CVE-2027-66478 Next.js 远程代码执行漏洞 - 5 // for 15

📅 2026-11-30 👤 拼多多助力营销技巧 📂 2027拼多多助力 👁️ 202 次阅读

CVSS评分:10.0(最高等级)

官方通报:https://nextjs.org/blog/CVE-2025-66478

CVE-2025-66478 Next.js 远程代码执行漏洞

1. 漏洞原理2. 漏洞危害3. 漏洞修复

1. 漏洞原理

该漏洞是 CVE-2025-55182 漏洞引发的下游关联漏洞, Next.js 只是其受影响其中之一

Next.js 是一个广受欢迎的 React 框架,它提供了一系列功能和优化,帮助开发者构建快速、可扩展且用户友好的应用程序。由于Next.js 15.x和16.x版本在使用App Router时,依赖了存在缺陷的React服务端DOM包,导致攻击者同样可以注入恶意代码远程执行命令

React Server Functions 是怎么工作的?

当浏览器要调用一个服务器函数(Server Action / Server Function),流程如下:

浏览器 ->发送一个 Flight payload ->Next.js/React 服务端 ->React 解码 ->调用对应的服务器函数 ->返回结果

漏洞引发的关键点是 Flight payload,这是 React RSC 自己的序列化格式,服务器会用 react-server 包来解析

React 在处理 Flight payload 时,没有严格验证其结构、数据类型、字段关系,导致攻击者可以放入恶意的反序列化数据,当服务器进入解码流程时,就会执行攻击者控制的代码

┌────────────────────────┐ ┌─────────────────────────────┐

│ 1. 攻击者构造 RSC │ HTTP 请求 │ 2. Next.js Server Functions │

│ Payload(恶意信封) ├──────────────►│ 端点接收请求 │

└────────────────────────┘ └──────────────┬─────────────┘

│

▼

┌────────────────────────────┐

│ 3. react-server 解析 Flight │

│ Payload(没有严格校验❌) │

└──────────────┬─────────────┘

│

▼

┌────────────────────────────┐

│ 4. 恶意字段进入逻辑路径 │

│ 触发 JS 执行(攻击者代码) │

└──────────────┬─────────────┘

│

▼

┌────────────────────────────┐

│ 5. 服务器端 RCE: │

│ - 文件读写 │

│ - 任意指令执行 │

│ - 服务横向移动 │

└────────────────────────────┘

2. 漏洞危害

该漏洞目前已有公开的 POC 和 EXP 信息,测试证实,即使是create-next-app为生产环境构建的新生成的 Next.js 应用程序()也存在漏洞,无需任何代码修改

同时,攻击者无需认证即可触发此漏洞,在漏洞影响的版本内,危害巨大,但影响面较小

公开 poc:

https://github.com/abtonc/next-cve-2025-66478https://github.com/BankkRoll/Quickcheck-CVE-2025-55182-React-and-CVE-2025-66478-Next.jshttps://github.com/xkillbit/cve-2025-55182-scanner

cve-2025-55182-scanner.py:

#!/usr/bin/env python3

"""

CVE-2025-55182 / CVE-2025-66478 Vulnerability Scanner

React Server Components (RSC) Flight Protocol RCE Detection

This tool scans targets for potential vulnerability to the critical

deserialization flaw in React Server Components.

CVSS: 10.0 Critical

Affected: React 19.0-19.2.0, Next.js 14.3.0-canary.77 through 16.x

Patched: React 19.0.1, 19.1.2, 19.2.1 | Next.js 15.0.5+, 16.0.7

Author: Hyperdrive Security

Usage: python3 cve-2025-55182-scanner.py -t[options]

DISCLAIMER: Only use against systems you own or have explicit authorization to test.

"""

import argparse

import requests

import re

import json

import sys

import urllib3

from urllib.parse import urljoin, urlparse

from concurrent.futures import ThreadPoolExecutor, as_completed

from dataclasses import dataclass

from typing import Optional, List, Dict, Tuple

from enum import Enum

# Suppress SSL warnings for testing

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

class VulnStatus(Enum):

VULNERABLE = "VULNERABLE"

LIKELY_VULNERABLE = "LIKELY_VULNERABLE"

POTENTIALLY_VULNERABLE = "POTENTIALLY_VULNERABLE"

NOT_VULNERABLE = "NOT_VULNERABLE"

UNKNOWN = "UNKNOWN"

ERROR = "ERROR"

@dataclass

class ScanResult:

target: str

status: VulnStatus

framework: Optional[str] = None

version: Optional[str] = None

rsc_endpoints: List[str] = None

evidence: List[str] = None

recommendations: List[str] = None

def __post_init__(self):

if self.rsc_endpoints is None:

self.rsc_endpoints = []

if self.evidence is None:

self.evidence = []

if self.recommendations is None:

self.recommendations = []

class CVE202555182Scanner:

"""Scanner for CVE-2025-55182 React RSC Deserialization RCE"""

# Vulnerable version ranges

VULNERABLE_REACT_VERSIONS = [

"19.0.0", "19.1.0", "19.1.1", "19.2.0"

]

PATCHED_REACT_VERSIONS = [

"19.0.1", "19.1.2", "19.2.1"

]

# Next.js vulnerable version patterns

VULNERABLE_NEXTJS_PATTERNS = [

r"14\.3\.0-canary\.(7[7-9]|[89]\d|[1-9]\d{2,})", # 14.3.0-canary.77+

r"15\.[0-4]\.\d+", # 15.0.x - 15.4.x (before patches)

r"16\.0\.[0-6]", # 16.0.0 - 16.0.6

]

PATCHED_NEXTJS_VERSIONS = [

"15.0.5", "15.1.9", "15.2.6", "15.3.6", "15.4.8", "15.5.7", "16.0.7"

]

# Common RSC endpoint paths

RSC_ENDPOINT_PATHS = [

"/",

"/_next/data",

"/api",

"/__rsc",

"/_rsc",

"/rsc",

]

# RSC-specific headers and indicators

RSC_HEADERS = {

"RSC": "1",

"Next-Router-State-Tree": "",

"Next-Router-Prefetch": "1",

}

FLIGHT_CONTENT_TYPE = "text/x-component"

def __init__(self, timeout: int = 10, verify_ssl: bool = False,

user_agent: str = None, threads: int = 5):

self.timeout = timeout

self.verify_ssl = verify_ssl

self.threads = threads

self.session = requests.Session()

self.session.headers.update({

"User-Agent": user_agent or "Mozilla/5.0 (compatible; SecurityScanner/1.0)"

})

def _normalize_url(self, url: str) ->str:

"""Ensure URL has proper scheme"""

if not url.startswith(('http://', 'https://')):

url = f"https://{url}"

return url.rstrip('/')

def _make_request(self, url: str, method: str = "GET",

headers: Dict = None, data: str = None) ->Optional[requests.Response]:

"""Make HTTP request with error handling"""

try:

if method.upper() == "GET":

resp = self.session.get(

url,

headers=headers,

timeout=self.timeout,

verify=self.verify_ssl,

allow_redirects=True

)

else:

resp = self.session.post(

url,

headers=headers,

data=data,

timeout=self.timeout,

verify=self.verify_ssl,

allow_redirects=True

)

return resp

except requests.exceptions.RequestException as e:

return None

def detect_framework(self, url: str) ->Tuple[Optional[str], Optional[str], List[str]]:

"""Detect React/Next.js framework and version"""

framework = None

version = None

evidence = []

resp = self._make_request(url)

if not resp:

return None, None, ["Failed to connect to target"]

headers = resp.headers

body = resp.text

# Check for Next.js indicators

if "x-powered-by" in headers:

powered_by = headers["x-powered-by"].lower()

if "next.js" in powered_by:

framework = "Next.js"

evidence.append(f"X-Powered-By header: {headers['x-powered-by']}")

# Try to extract version

version_match = re.search(r"next\.js\s*([\d.]+)", powered_by, re.I)

if version_match:

version = version_match.group(1)

# Check for Next.js build manifest

if "/_next/" in body or "__NEXT_DATA__" in body:

framework = framework or "Next.js"

evidence.append("Next.js build artifacts detected in page source")

# Check for React indicators

if "react" in body.lower() or "__REACT" in body:

if not framework:

framework = "React"

evidence.append("React framework detected in page source")

# Check for RSC indicators

if "react-server" in body.lower() or "server component" in body.lower():

evidence.append("React Server Components references found")

# Try to get build ID for Next.js

build_id_match = re.search(r'"buildId"\s*:\s*"([^"]+)"', body)

if build_id_match:

evidence.append(f"Next.js Build ID: {build_id_match.group(1)}")

# Check meta tags and scripts for version info

version_patterns = [

r'react@([\d.]+)',

r'react-dom@([\d.]+)',

r'next@([\d.]+)',

r'"version"\s*:\s*"(19\.[0-2]\.\d+)"',

]

for pattern in version_patterns:

match = re.search(pattern, body)

if match:

detected_ver = match.group(1)

if detected_ver.startswith("19."):

version = detected_ver

evidence.append(f"React version detected: {detected_ver}")

break

return framework, version, evidence

def check_rsc_endpoint(self, url: str, path: str) ->Tuple[bool, List[str]]:

"""Check if an endpoint supports RSC Flight protocol"""

full_url = urljoin(url, path)

evidence = []

is_rsc = False

# Test with RSC headers

headers = {

**self.RSC_HEADERS,

"Accept": self.FLIGHT_CONTENT_TYPE,

"Content-Type": "text/plain;charset=UTF-8",

}

# GET request with RSC headers

resp = self._make_request(full_url, headers=headers)

if resp:

# Check response content type

content_type = resp.headers.get("content-type", "")

if self.FLIGHT_CONTENT_TYPE in content_type or "text/x-component" in content_type:

is_rsc = True

evidence.append(f"RSC Flight response at {path} (Content-Type: {content_type})")

# Check for Flight protocol markers in response

if resp.text:

# Flight protocol uses specific serialization format

flight_markers = [

r'^\d+:', # Chunk format: "0:..."

r'\["?\$', # Reference format

r'"\$undefined"', # Undefined marker

r'"\$Infinity"', # Special values

]

for marker in flight_markers:

if re.search(marker, resp.text[:1000]):

is_rsc = True

evidence.append(f"Flight protocol markers detected at {path}")

break

# POST request test (RSC actions use POST)

post_headers = {

**headers,

"Next-Action": "test",

}

# Send minimal Flight payload probe

probe_payload = '["$undefined"]'

resp = self._make_request(full_url, method="POST",

headers=post_headers, data=probe_payload)

if resp:

if resp.status_code in [200, 400, 500]:

# Server processed the request (even errors indicate RSC handling)

if "text/x-component" in resp.headers.get("content-type", ""):

is_rsc = True

evidence.append(f"RSC POST endpoint responsive at {path}")

# Check for RSC error responses (indicates processing)

if "Unexpected" in resp.text or "Invalid" in resp.text:

evidence.append(f"RSC endpoint shows deserialization processing at {path}")

return is_rsc, evidence

def discover_rsc_endpoints(self, url: str) ->List[Tuple[str, List[str]]]:

"""Discover all RSC endpoints on target"""

discovered = []

with ThreadPoolExecutor(max_workers=self.threads) as executor:

futures = {

executor.submit(self.check_rsc_endpoint, url, path): path

for path in self.RSC_ENDPOINT_PATHS

}

for future in as_completed(futures):

path = futures[future]

try:

is_rsc, evidence = future.result()

if is_rsc:

discovered.append((path, evidence))

except Exception as e:

pass

return discovered

def assess_vulnerability(self, framework: str, version: str,

rsc_endpoints: List[str]) ->VulnStatus:

"""Assess vulnerability status based on collected evidence"""

if not rsc_endpoints:

# No RSC endpoints found

if framework in ["Next.js", "React"]:

return VulnStatus.UNKNOWN

return VulnStatus.NOT_VULNERABLE

# If we have version info, check against known vulnerable versions

if version:

# Check React versions

if version in self.VULNERABLE_REACT_VERSIONS:

return VulnStatus.VULNERABLE

if version in self.PATCHED_REACT_VERSIONS:

return VulnStatus.NOT_VULNERABLE

# Check Next.js version patterns

for pattern in self.VULNERABLE_NEXTJS_PATTERNS:

if re.match(pattern, version):

return VulnStatus.VULNERABLE

# Check if patched

if version in self.PATCHED_NEXTJS_VERSIONS:

return VulnStatus.NOT_VULNERABLE

# Version 19.x but not in known lists

if version.startswith("19."):

return VulnStatus.LIKELY_VULNERABLE

# RSC endpoints exist but version unknown

if rsc_endpoints:

return VulnStatus.POTENTIALLY_VULNERABLE

return VulnStatus.UNKNOWN

def generate_recommendations(self, result: ScanResult) ->List[str]:

"""Generate remediation recommendations"""

recommendations = []

if result.status in [VulnStatus.VULNERABLE, VulnStatus.LIKELY_VULNERABLE]:

recommendations.append("CRITICAL: Immediate patching required!")

recommendations.append("Upgrade React to 19.0.1, 19.1.2, or 19.2.1")

recommendations.append("Upgrade Next.js to latest patched version (15.0.5+, 16.0.7)")

recommendations.append("Enable WAF rules to block malicious RSC payloads")

recommendations.append("Monitor for anomalous POST requests to RSC endpoints")

recommendations.append("Review server logs for exploitation attempts")

elif result.status == VulnStatus.POTENTIALLY_VULNERABLE:

recommendations.append("Verify React/Next.js versions in package.json")

recommendations.append("Check if RSC is enabled in framework configuration")

recommendations.append("Apply patches as precautionary measure")

if result.rsc_endpoints:

recommendations.append(f"RSC endpoints identified: {', '.join(result.rsc_endpoints)}")

recommendations.append("Consider implementing authentication on server actions")

return recommendations

def scan(self, target: str) ->ScanResult:

"""Perform full vulnerability scan on target"""

url = self._normalize_url(target)

result = ScanResult(

target=url,

status=VulnStatus.UNKNOWN

)

# Step 1: Detect framework and version

framework, version, evidence = self.detect_framework(url)

result.framework = framework

result.version = version

result.evidence.extend(evidence)

if not framework:

result.status = VulnStatus.UNKNOWN

result.evidence.append("Could not detect React/Next.js framework")

return result

# Step 2: Discover RSC endpoints

rsc_results = self.discover_rsc_endpoints(url)

for path, path_evidence in rsc_results:

result.rsc_endpoints.append(path)

result.evidence.extend(path_evidence)

# Step 3: Assess vulnerability status

result.status = self.assess_vulnerability(

framework, version, result.rsc_endpoints

)

# Step 4: Generate recommendations

result.recommendations = self.generate_recommendations(result)

return result

def scan_multiple(self, targets: List[str]) ->List[ScanResult]:

"""Scan multiple targets"""

results = []

with ThreadPoolExecutor(max_workers=self.threads) as executor:

futures = {executor.submit(self.scan, t): t for t in targets}

for future in as_completed(futures):

target = futures[future]

try:

result = future.result()

results.append(result)

except Exception as e:

results.append(ScanResult(

target=target,

status=VulnStatus.ERROR,

evidence=[f"Scan error: {str(e)}"]

))

return results

def print_banner():

"""Print tool banner"""

banner = """

╔══════════════════════════════════════════════════════════════════════╗

║ CVE-2025-55182 / CVE-2025-66478 Scanner ║

║ React Server Components Flight Protocol RCE Detection ║

║ ║

║ CVSS: 10.0 Critical | Unauthenticated RCE ║

║ Affected: React 19.0-19.2.0 | Next.js 14.3.0-canary.77 - 16.x ║

╚══════════════════════════════════════════════════════════════════════╝

"""

print(banner)

def print_result(result: ScanResult, verbose: bool = False):

"""Print scan result with formatting"""

status_colors = {

VulnStatus.VULNERABLE: "\033[91m", # Red

VulnStatus.LIKELY_VULNERABLE: "\033[91m", # Red

VulnStatus.POTENTIALLY_VULNERABLE: "\033[93m", # Yellow

VulnStatus.NOT_VULNERABLE: "\033[92m", # Green

VulnStatus.UNKNOWN: "\033[94m", # Blue

VulnStatus.ERROR: "\033[95m", # Magenta

}

reset = "\033[0m"

color = status_colors.get(result.status, "")

print(f"\n{'='*70}")

print(f"Target: {result.target}")

print(f"Status: {color}{result.status.value}{reset}")

if result.framework:

print(f"Framework: {result.framework}")

if result.version:

print(f"Version: {result.version}")

if result.rsc_endpoints:

print(f"RSC Endpoints: {', '.join(result.rsc_endpoints)}")

if verbose and result.evidence:

print("\nEvidence:")

for e in result.evidence:

print(f" - {e}")

if result.recommendations:

print("\nRecommendations:")

for r in result.recommendations:

print(f" → {r}")

print(f"{'='*70}")

def output_json(results: List[ScanResult], output_file: str):

"""Output results as JSON"""

data = []

for r in results:

data.append({

"target": r.target,

"status": r.status.value,

"framework": r.framework,

"version": r.version,

"rsc_endpoints": r.rsc_endpoints,

"evidence": r.evidence,

"recommendations": r.recommendations

})

with open(output_file, 'w') as f:

json.dump(data, f, indent=2)

print(f"\n[+] Results saved to {output_file}")

def main():

parser = argparse.ArgumentParser(

description="CVE-2025-55182 React RSC Vulnerability Scanner",

formatter_class=argparse.RawDescriptionHelpFormatter,

epilog="""

Examples:

python3 %(prog)s -t https://example.com

python3 %(prog)s -t example.com -v

python3 %(prog)s -f targets.txt -o results.json

python3 %(prog)s -t 192.168.1.100 --timeout 15 --threads 10

"""

)

target_group = parser.add_mutually_exclusive_group(required=True)

target_group.add_argument("-t", "--target", help="Single target URL or hostname")

target_group.add_argument("-f", "--file", help="File containing list of targets")

parser.add_argument("-o", "--output", help="Output results to JSON file")

parser.add_argument("-v", "--verbose", action="store_true", help="Verbose output")

parser.add_argument("--timeout", type=int, default=10, help="Request timeout (default: 10)")

parser.add_argument("--threads", type=int, default=5, help="Number of threads (default: 5)")

parser.add_argument("--verify-ssl", action="store_true", help="Verify SSL certificates")

parser.add_argument("--user-agent", help="Custom User-Agent string")

parser.add_argument("--no-banner", action="store_true", help="Suppress banner")

args = parser.parse_args()

if not args.no_banner:

print_banner()

# Initialize scanner

scanner = CVE202555182Scanner(

timeout=args.timeout,

verify_ssl=args.verify_ssl,

user_agent=args.user_agent,

threads=args.threads

)

# Get targets

targets = []

if args.target:

targets = [args.target]

elif args.file:

try:

with open(args.file, 'r') as f:

targets = [line.strip() for line in f if line.strip()]

except FileNotFoundError:

print(f"[-] Error: File not found: {args.file}")

sys.exit(1)

if not targets:

print("[-] No targets specified")

sys.exit(1)

print(f"[*] Scanning {len(targets)} target(s)...")

# Run scans

if len(targets) == 1:

results = [scanner.scan(targets[0])]

else:

results = scanner.scan_multiple(targets)

# Print results

for result in results:

print_result(result, verbose=args.verbose)

# Summary

vuln_count = sum(1 for r in results if r.status in [

VulnStatus.VULNERABLE, VulnStatus.LIKELY_VULNERABLE

])

potential_count = sum(1 for r in results if r.status == VulnStatus.POTENTIALLY_VULNERABLE)

print(f"\n[*] Scan Complete")

print(f" Vulnerable/Likely Vulnerable: {vuln_count}")

print(f" Potentially Vulnerable: {potential_count}")

print(f" Total Scanned: {len(results)}")

# Output to file if specified

if args.output:

output_json(results, args.output)

# Exit code based on findings

if vuln_count > 0:

sys.exit(2) # Critical findings

elif potential_count > 0:

sys.exit(1) # Potential findings

sys.exit(0)

if __name__ == "__main__":

main()

rsc_analyzer.py:

#!/usr/bin/env python3

"""

Advanced RSC Flight Protocol Analyzer

Supplementary module for CVE-2025-55182 detection

This module provides deeper analysis of React Server Components

endpoints and Flight protocol responses.

"""

import re

import json

import requests

from dataclasses import dataclass, field

from typing import Optional, List, Dict, Any

from urllib.parse import urljoin

@dataclass

class FlightAnalysis:

"""Results from Flight protocol analysis"""

is_flight_response: bool = False

protocol_version: Optional[str] = None

chunk_count: int = 0

has_server_actions: bool = False

has_form_state: bool = False

detected_components: List[str] = field(default_factory=list)

raw_chunks: List[str] = field(default_factory=list)

warnings: List[str] = field(default_factory=list)

class RSCProtocolAnalyzer:

"""

Analyzer for React Server Components Flight Protocol

The Flight protocol serializes React trees for streaming from server to client.

Format typically follows: "chunk_id:chunk_type:payload"

Reference types:

- $: Reference marker

- @: Promise reference

- S: Symbol

- F: Server function reference

- T: Template

- $undefined: undefined value

- $Infinity: Infinity

- $NaN: NaN

- $-0: Negative zero

"""

# Flight protocol markers

FLIGHT_MARKERS = {

'reference': r'"\$[A-Za-z@]?\d*"',

'undefined': r'"\$undefined"',

'infinity': r'"\$Infinity"',

'nan': r'"\$NaN"',

'neg_zero': r'"\$-0"',

'symbol': r'"\$S[^"]*"',

'function_ref': r'"\$F\d+"',

'lazy': r'"\$L\d+"',

'chunk_start': r'^\d+:',

'promise': r'"\$@\d+"',

}

# Common RSC action paths

ACTION_PATHS = [

"",

"/actions",

"/api/actions",

"/_next/action",

]

def __init__(self, session: requests.Session = None, timeout: int = 10):

self.session = session or requests.Session()

self.timeout = timeout

def analyze_response(self, content: str) ->FlightAnalysis:

"""Analyze a response for Flight protocol characteristics"""

analysis = FlightAnalysis()

if not content:

return analysis

# Check for Flight chunk format

lines = content.strip().split('\n')

for line in lines:

# Flight chunks start with chunk_id:

chunk_match = re.match(r'^(\d+):(.*)$', line, re.DOTALL)

if chunk_match:

analysis.is_flight_response = True

analysis.chunk_count += 1

analysis.raw_chunks.append(line[:200]) # Store truncated

chunk_content = chunk_match.group(2)

self._analyze_chunk(chunk_content, analysis)

# Check for Flight markers in content

for marker_name, pattern in self.FLIGHT_MARKERS.items():

if re.search(pattern, content):

analysis.is_flight_response = True

if marker_name == 'function_ref':

analysis.has_server_actions = True

return analysis

def _analyze_chunk(self, chunk: str, analysis: FlightAnalysis):

"""Analyze individual Flight chunk"""

# Look for component references

component_patterns = [

r'"([A-Z][a-zA-Z0-9]+)"', # PascalCase component names

r'\$L(\d+)', # Lazy component references

]

for pattern in component_patterns:

matches = re.findall(pattern, chunk)

for match in matches:

if match not in analysis.detected_components:

analysis.detected_components.append(match)

# Check for form state (indicates server actions)

if '$SF' in chunk or 'formState' in chunk:

analysis.has_form_state = True

analysis.has_server_actions = True

def probe_rsc_endpoint(self, base_url: str, path: str = "") ->Dict[str, Any]:

"""

Probe an endpoint to detect RSC capabilities

Returns detailed information about RSC behavior

"""

url = urljoin(base_url, path) if path else base_url 拼多多帮助力入口

result = {

'url': url,

'supports_rsc': False,

'accepts_flight_post': False,

'has_server_actions': False,

'flight_analysis': None,

'headers_received': {},

'status_code': None,

'error': None

}

# Test 1: GET with RSC headers

headers = {

'RSC': '1',

'Accept': 'text/x-component',

'Next-Router-State-Tree': '%5B%22%22%2C%7B%22children%22%3A%5B%22__PAGE__%22%2C%7B%7D%5D%7D%5D',

}

try:

resp = self.session.get(url, headers=headers, timeout=self.timeout, verify=False)

result['status_code'] = resp.status_code

result['headers_received'] = dict(resp.headers)

content_type = resp.headers.get('content-type', '')

if 'text/x-component' in content_type:

result['supports_rsc'] = True

# Analyze response

analysis = self.analyze_response(resp.text)

result['flight_analysis'] = analysis

if analysis.is_flight_response:

result['supports_rsc'] = True

if analysis.has_server_actions:

result['has_server_actions'] = True

except requests.RequestException as e:

result['error'] = str(e)

return result

# Test 2: POST probe for server actions

if result['supports_rsc']:

result['accepts_flight_post'] = self._probe_post_endpoint(url)

return result

def _probe_post_endpoint(self, url: str) ->bool:

"""Test if endpoint accepts POST for server actions"""

headers = {

'Content-Type': 'text/plain;charset=UTF-8',

'Accept': 'text/x-component',

'RSC': '1',

'Next-Action': 'probe', # Dummy action ID

}

# Minimal Flight payload

payload = '[]'

try:

resp = self.session.post(

url,

headers=headers,

data=payload,

timeout=self.timeout,

verify=False

)

# Any response indicates the server processes RSC POST

# 400/500 errors still mean it's parsing the payload

if resp.status_code in [200, 400, 500]:

return True

except requests.RequestException:

pass

return False

def enumerate_server_actions(self, base_url: str) ->List[Dict]:

"""

Attempt to enumerate exposed server action endpoints

This is useful for understanding attack surface

"""

discovered = []

for path in self.ACTION_PATHS:

full_url = urljoin(base_url, path) if path else base_url

probe = self.probe_rsc_endpoint(full_url)

if probe['has_server_actions'] or probe['accepts_flight_post']:

discovered.append({

'url': full_url,

'path': path or '/',

'accepts_post': probe['accepts_flight_post'],

'has_actions': probe['has_server_actions']

})

return discovered

class VersionFingerprinter:

"""

Attempt to fingerprint exact React/Next.js versions

from observable characteristics

"""

# Build manifest paths

MANIFEST_PATHS = [

'/_next/static/chunks/main-app.js',

'/_next/static/chunks/webpack.js',

'/_next/static/chunks/framework.js',

'/build-manifest.json',

'/_buildManifest.js',

]

# Version signatures in JS bundles

VERSION_SIGNATURES = {

# React version patterns

'react_19_0': [r'19\.0\.0', r'react@19\.0\.0'],

'react_19_1': [r'19\.1\.[01]', r'react@19\.1\.[01]'],

'react_19_2': [r'19\.2\.0', r'react@19\.2\.0'],

# Patched versions

'react_19_0_1': [r'19\.0\.1', r'react@19\.0\.1'],

'react_19_1_2': [r'19\.1\.2', r'react@19\.1\.2'],

'react_19_2_1': [r'19\.2\.1', r'react@19\.2\.1'],

}

def __init__(self, session: requests.Session = None, timeout: int = 10):

self.session = session or requests.Session()

self.timeout = timeout

def fingerprint(self, base_url: str) ->Dict[str, Any]:

"""Attempt to fingerprint exact version"""

result = {

'detected_versions': [],

'is_patched': None,

'confidence': 'low',

'evidence': []

}

# Check main page first

try:

resp = self.session.get(base_url, timeout=self.timeout, verify=False)

self._check_content_for_versions(resp.text, result)

except requests.RequestException:

pass

# Check manifest/bundle files

for path in self.MANIFEST_PATHS:

url = urljoin(base_url, path)

try:

resp = self.session.get(url, timeout=self.timeout, verify=False)

if resp.status_code == 200:

self._check_content_for_versions(resp.text, result)

except requests.RequestException:

continue

# Determine if patched

if result['detected_versions']:

patched_versions = ['19.0.1', '19.1.2', '19.2.1']

vulnerable_versions = ['19.0.0', '19.1.0', '19.1.1', '19.2.0']

for ver in result['detected_versions']:

if ver in patched_versions:

result['is_patched'] = True

result['confidence'] = 'high'

break

elif ver in vulnerable_versions:

result['is_patched'] = False

result['confidence'] = 'high'

return result

def _check_content_for_versions(self, content: str, result: Dict):

"""Check content for version signatures"""

for version_key, patterns in self.VERSION_SIGNATURES.items():

for pattern in patterns:

if re.search(pattern, content):

# Extract clean version

ver_match = re.search(r'19\.\d+\.\d+', version_key.replace('_', '.'))

if ver_match:

version = ver_match.group(0)

if version not in result['detected_versions']:

result['detected_versions'].append(version)

result['evidence'].append(f"Found version pattern: {pattern}")

def create_detection_report(target: str, analyzer: RSCProtocolAnalyzer = None,

fingerprinter: VersionFingerprinter = None) ->Dict:

"""

Generate comprehensive detection report for a target

"""

if analyzer is None:

analyzer = RSCProtocolAnalyzer()

if fingerprinter is None:

fingerprinter = VersionFingerprinter()

report = {

'target': target,

'rsc_analysis': {},

'version_info': {},

'server_actions': [],

'vulnerability_assessment': {}

}

# Run analyses

probe_result = analyzer.probe_rsc_endpoint(target)

report['rsc_analysis'] = {

'supports_rsc': probe_result['supports_rsc'],

'accepts_post': probe_result['accepts_flight_post'],

'has_server_actions': probe_result['has_server_actions'],

}

if probe_result['flight_analysis']:

analysis = probe_result['flight_analysis']

report['rsc_analysis']['flight_details'] = {

'is_flight_response': analysis.is_flight_response,

'chunk_count': analysis.chunk_count,

'detected_components': analysis.detected_components[:10], # Limit

}

# Enumerate server actions

actions = analyzer.enumerate_server_actions(target)

report['server_actions'] = actions

# Version fingerprinting

version_result = fingerprinter.fingerprint(target)

report['version_info'] = version_result

# Vulnerability assessment

if version_result.get('is_patched') is False:

report['vulnerability_assessment'] = {

'status': 'VULNERABLE',

'confidence': version_result['confidence'],

'reason': f"Detected vulnerable version(s): {version_result['detected_versions']}"

}

elif version_result.get('is_patched') is True:

report['vulnerability_assessment'] = {

'status': 'PATCHED',

'confidence': version_result['confidence'],

'reason': f"Detected patched version(s): {version_result['detected_versions']}"

}

elif probe_result['supports_rsc'] and probe_result['accepts_flight_post']:

report['vulnerability_assessment'] = {

'status': 'POTENTIALLY_VULNERABLE',

'confidence': 'medium',

'reason': 'RSC endpoints detected but version could not be determined'

}

else:

report['vulnerability_assessment'] = {

'status': 'UNKNOWN',

'confidence': 'low',

'reason': 'Could not determine RSC status or version'

}

return report

if __name__ == "__main__":

import sys

if len(sys.argv) < 2:

print("Usage: python rsc_analyzer.py")

sys.exit(1)

target = sys.argv[1]

if not target.startswith(('http://', 'https://')):

target = f"https://{target}"

print(f"[*] Analyzing RSC configuration for: {target}")

print("-" * 60)

report = create_detection_report(target)

print(json.dumps(report, indent=2, default=str))

批量检测命令:

python3 cve-2025-55182-scanner.py -f targets.txt -o results.json

3. 漏洞修复

可参考:https://react.dev/blog/2025/12/03/critical-security-vulnerability-in-react-server-components

升级版本:

npm install next@15.0.5 // for 15.0.x

npm install next@15.1.9 // for 15.1.x

npm install next@15.2.6 // for 15.2.x

npm install next@15.3.6 // for 15.3.x

npm install next@15.4.8 // for 15.4.x

npm install next@15.5.7 // for 15.5.x

npm install next@16.0.7 // for 16.0.x

如果使用的是 Next.js 14.3.0-canary.77 或更高版本的 canary 版本,需要降级到最新的稳定版 14.x:

npm install next@14

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧