Exploit databaseDownload repository ZIP
GH-8c672a0790e043d04bd591599c679d42
cropnet/ni8mare
Sources for CVE-2026-21858
8 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files7
cropnet/ni8mareRevision 85f057951257
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
scripts/modules/utils.py
Python · 15,041 bytes"""
Utility Functions for Ni8mare Security Scanner
===============================================
Helper functions for logging, validation, rate limiting, and common operations.
"""
import ipaddress
import logging
import re
import time
import functools
from datetime import datetime
from typing import Optional, List, Callable, Any, Generator
from urllib.parse import urlparse
import json
# ============================================================================
# Logging Configuration
# ============================================================================
class JSONFormatter(logging.Formatter):
"""JSON log formatter for machine-readable output."""
def format(self, record: logging.LogRecord) -> str:
log_entry = {
"timestamp": datetime.utcnow().isoformat() + "Z",
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
"module": record.module,
"function": record.funcName,
"line": record.lineno,
}
# Add exception info if present
if record.exc_info:
log_entry["exception"] = self.formatException(record.exc_info)
# Add extra fields if present
if hasattr(record, "extra"):
log_entry.update(record.extra)
return json.dumps(log_entry)
def setup_logging(
level: str = "INFO",
json_output: bool = False,
log_file: Optional[str] = None,
name: str = "ni8mare_scanner"
) -> logging.Logger:
"""
Configure structured logging for the scanner.
Args:
level: Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
json_output: Use JSON format for machine parsing
log_file: Optional file path for log output
name: Logger name
Returns:
Configured logger instance
"""
logger = logging.getLogger(name)
logger.setLevel(getattr(logging, level.upper(), logging.INFO))
# Remove existing handlers
logger.handlers.clear()
# Create formatter
if json_output:
formatter = JSONFormatter()
else:
formatter = logging.Formatter(
"[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
# Console handler
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
# File handler if specified
if log_file:
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger
# ============================================================================
# Rate Limiting
# ============================================================================
class RateLimiter:
"""Thread-safe rate limiter with exponential backoff."""
def __init__(
self,
delay: float = 2.0,
max_delay: float = 60.0,
backoff_factor: float = 2.0
):
self.base_delay = delay
self.current_delay = delay
self.max_delay = max_delay
self.backoff_factor = backoff_factor
self.last_request = 0.0
self._consecutive_errors = 0
def wait(self) -> None:
"""Wait for the appropriate delay before next request."""
elapsed = time.time() - self.last_request
if elapsed < self.current_delay:
time.sleep(self.current_delay - elapsed)
self.last_request = time.time()
def on_success(self) -> None:
"""Reset delay on successful request."""
self._consecutive_errors = 0
self.current_delay = self.base_delay
def on_error(self) -> None:
"""Apply exponential backoff on error."""
self._consecutive_errors += 1
self.current_delay = min(
self.base_delay * (self.backoff_factor ** self._consecutive_errors),
self.max_delay
)
def on_rate_limit(self, retry_after: Optional[int] = None) -> None:
"""Handle HTTP 429 rate limit response."""
if retry_after:
self.current_delay = min(retry_after, self.max_delay)
else:
self.on_error()
def rate_limit(delay: float = 2.0) -> Callable:
"""
Decorator to apply rate limiting to functions.
Args:
delay: Minimum delay between calls in seconds
"""
limiter = RateLimiter(delay=delay)
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs) -> Any:
limiter.wait()
try:
result = func(*args, **kwargs)
limiter.on_success()
return result
except Exception as e:
limiter.on_error()
raise e
return wrapper
return decorator
# ============================================================================
# Input Validation & Sanitization
# ============================================================================
def sanitize_input(value: str, max_length: int = 1000) -> str:
"""
Sanitize user input to prevent injection attacks.
Args:
value: Input string to sanitize
max_length: Maximum allowed length
Returns:
Sanitized string
"""
if not isinstance(value, str):
value = str(value)
# Truncate to max length
value = value[:max_length]
# Remove null bytes and control characters (except newlines/tabs)
value = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]', '', value)
return value.strip()
def validate_url(url: str) -> bool:
"""
Validate URL format.
Args:
url: URL string to validate
Returns:
True if valid URL format
"""
try:
result = urlparse(url)
return all([result.scheme in ('http', 'https'), result.netloc])
except Exception:
return False
def validate_target(
target: str,
require_confirmation: bool = True,
allowed_networks: Optional[List[str]] = None
) -> tuple[bool, str, Optional[str]]:
"""
Validate a scan target with security checks.
Args:
target: Target URL to validate
require_confirmation: Whether to require explicit confirmation
allowed_networks: List of allowed CIDR ranges for IP validation
Returns:
Tuple of (is_valid, normalized_url, error_message)
"""
target = sanitize_input(target)
if not validate_url(target):
return False, "", "Invalid URL format. Expected http:// or https://"
parsed = urlparse(target)
host = parsed.hostname
if not host:
return False, "", "Could not extract hostname from URL"
# Check for localhost/private IPs if restrictions apply
try:
ip = ipaddress.ip_address(host)
if allowed_networks:
allowed = False
for network in allowed_networks:
try:
if ip in ipaddress.ip_network(network, strict=False):
allowed = True
break
except ValueError:
continue
if not allowed:
return False, "", f"IP {ip} not in allowed networks"
except ValueError:
# Host is a domain name, not an IP
pass
# Normalize URL
normalized = f"{parsed.scheme}://{parsed.netloc}"
if parsed.path:
normalized += parsed.path.rstrip('/')
return True, normalized, None
def parse_cidr(cidr: str) -> Generator[str, None, None]:
"""
Parse CIDR notation and yield individual IP addresses.
Args:
cidr: CIDR notation string (e.g., "192.168.1.0/24")
Yields:
Individual IP addresses as strings
"""
try:
network = ipaddress.ip_network(cidr, strict=False)
for ip in network.hosts():
yield str(ip)
except ValueError as e:
raise ValueError(f"Invalid CIDR notation: {cidr}") from e
def validate_port(port: int) -> bool:
"""Validate port number is in valid range."""
return isinstance(port, int) and 1 <= port <= 65535
# ============================================================================
# Version Parsing
# ============================================================================
def parse_version(version_string: str) -> tuple[int, int, int]:
"""
Parse a semantic version string.
Args:
version_string: Version string like "1.121.0"
Returns:
Tuple of (major, minor, patch)
"""
match = re.match(r'(\d+)\.(\d+)\.(\d+)', version_string)
if match:
return int(match.group(1)), int(match.group(2)), int(match.group(3))
# Try simpler patterns
match = re.match(r'(\d+)\.(\d+)', version_string)
if match:
return int(match.group(1)), int(match.group(2)), 0
return 0, 0, 0
def is_version_vulnerable(version: str, fixed_version: str = "1.121.0") -> bool:
"""
Check if a version is vulnerable to CVE-2026-21858.
Args:
version: Version to check
fixed_version: First patched version
Returns:
True if version is vulnerable
"""
current = parse_version(version)
fixed = parse_version(fixed_version)
return current < fixed
def get_version_info(version: str) -> dict:
"""
Get detailed version information including vulnerability status.
Args:
version: Version string to analyze
Returns:
Dictionary with version details
"""
major, minor, patch = parse_version(version)
vulnerable = is_version_vulnerable(version)
return {
"version": version,
"major": major,
"minor": minor,
"patch": patch,
"vulnerable_to_cve_2026_21858": vulnerable,
"fixed_version": "1.121.0",
"recommendation": "Upgrade to version 1.121.0 or later" if vulnerable else "Version is patched"
}
# ============================================================================
# Timing & Performance
# ============================================================================
class Timer:
"""Context manager for timing operations."""
def __init__(self, name: str = "operation"):
self.name = name
self.start_time = 0.0
self.end_time = 0.0
self.duration = 0.0
def __enter__(self):
self.start_time = time.perf_counter()
return self
def __exit__(self, *args):
self.end_time = time.perf_counter()
self.duration = self.end_time - self.start_time
def timing_decorator(func: Callable) -> Callable:
"""Decorator to measure function execution time."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
duration = time.perf_counter() - start
logger = logging.getLogger("ni8mare_scanner")
logger.debug(f"{func.__name__} executed in {duration:.3f}s")
return result
return wrapper
# ============================================================================
# HTTP Helpers
# ============================================================================
def get_default_headers() -> dict:
"""Get default headers for HTTP requests."""
return {
"User-Agent": "Ni8mare-Security-Scanner/1.0 (Ethical Security Research)",
"Accept": "application/json, text/html, */*",
"Accept-Language": "en-US,en;q=0.9",
"Connection": "keep-alive",
}
def parse_retry_after(value: str) -> Optional[int]:
"""Parse Retry-After header value."""
try:
return int(value)
except ValueError:
# Could be a date format, but we'll just use default
return None
def is_n8n_response(headers: dict, body: str = "") -> bool:
"""
Check if HTTP response appears to be from n8n.
Args:
headers: Response headers
body: Response body content
Returns:
True if response appears to be from n8n
"""
# Check for n8n-specific headers
n8n_headers = ['x-n8n-version', 'x-n8n-deployment']
for header in n8n_headers:
if header in {k.lower(): v for k, v in headers.items()}:
return True
# Check for n8n in body
n8n_indicators = ['n8n', 'workflow', 'nodes', 'n8n-nodes-base']
body_lower = body.lower()
return any(indicator in body_lower for indicator in n8n_indicators)
# ============================================================================
# File Helpers
# ============================================================================
def ensure_directory(path: str) -> None:
"""Ensure a directory exists, creating it if necessary."""
import os
os.makedirs(path, exist_ok=True)
def safe_filename(name: str) -> str:
"""Convert a string to a safe filename."""
# Remove or replace unsafe characters
safe = re.sub(r'[<>:"/\\|?*]', '_', name)
safe = re.sub(r'\s+', '_', safe)
safe = safe.strip('._')
return safe[:200] # Limit length
# ============================================================================
# Constants
# ============================================================================
# CVE Information
CVE_2026_21858 = {
"id": "CVE-2026-21858",
"name": "Ni8mare",
"cvss_score": 10.0,
"severity": "CRITICAL",
"cwe": "CWE-434",
"description": "Content-Type confusion vulnerability allowing arbitrary file read",
"fixed_version": "1.121.0",
"discovered_by": "Dor Attias",
"research_lab": "Cyera Research Labs",
"disclosure_date": "2026-01-07",
"advisory_url": "https://github.com/n8n-io/n8n/security/advisories/GHSA-v4pr-fm98-w9pg",
}
# Common n8n paths to check
N8N_PATHS = [
"/",
"/rest/settings",
"/rest/workflows",
"/healthz",
"/form/",
"/webhook/",
"/webhook-test/",
]
# Common form paths for discovery
FORM_PATHS = [
"/form/",
"/form/upload",
"/form/submit",
"/form/file",
"/form/document",
"/webhook/",
"/webhook/form",
"/webhook/upload",
]
# Sensitive files that should not be accessible
SENSITIVE_PATHS = [
".env",
"config.json",
"database.sqlite",
".n8n/config",
".n8n/database.sqlite",
]