Exploit database

GH-8c672a0790e043d04bd591599c679d42

cropnet/ni8mare

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-21858

8 sources

Preferred 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/build.py

Suggested starting filePython · 13,544 bytes
#!/usr/bin/env python3
"""
Ni8mare Security Scanner - Build Script
========================================
Maintained by CropNet on GitHub, by Schema.cx organisation research team

Build and package the Ni8mare Security Scanner.
Handles dependency management, testing, and distribution.

Usage:
    python scripts/build.py install     - Install dependencies
    python scripts/build.py test        - Run tests
    python scripts/build.py lint        - Run linters
    python scripts/build.py build       - Build distribution
    python scripts/build.py clean       - Clean build artifacts
    python scripts/build.py all         - Run all build steps
"""

import os
import sys
import subprocess
import shutil
import argparse
from pathlib import Path
from typing import List, Optional


# ============================================================================
# Configuration
# ============================================================================

PROJECT_ROOT = Path(__file__).parent.parent
SCRIPTS_DIR = PROJECT_ROOT / "scripts"
TESTS_DIR = SCRIPTS_DIR / "tests"
DOCS_DIR = PROJECT_ROOT / "docs"
DIST_DIR = PROJECT_ROOT / "dist"
BUILD_DIR = PROJECT_ROOT / "build"

# Dependencies
CORE_DEPENDENCIES = [
    "requests>=2.28.0",
    "urllib3>=1.26.0",
]

OPTIONAL_DEPENDENCIES = [
    "click>=8.0.0",       # CLI framework
    "pydantic>=1.10.0",   # Configuration validation
    "jinja2>=3.0.0",      # Report templates
    "pyyaml>=6.0",        # YAML configuration
]

DEV_DEPENDENCIES = [
    "pytest>=7.0.0",
    "pytest-cov>=4.0.0",
    "pytest-mock>=3.10.0",
    "responses>=0.22.0",  # Mock HTTP responses
    "black>=23.0.0",
    "flake8>=6.0.0",
    "mypy>=1.0.0",
    "isort>=5.12.0",
]


# ============================================================================
# Build Functions
# ============================================================================

def run_command(cmd: List[str], cwd: Optional[Path] = None, check: bool = True) -> int:
    """Run a shell command."""
    print(f"  Running: {' '.join(cmd)}")
    result = subprocess.run(cmd, cwd=cwd or PROJECT_ROOT)
    if check and result.returncode != 0:
        print(f"  [X] Command failed with exit code {result.returncode}")
    return result.returncode


def install_dependencies(dev: bool = False) -> int:
    """Install project dependencies."""
    print("\n[PKG] Installing dependencies...")
    
    # Core dependencies
    print("\n  Installing core dependencies...")
    deps = CORE_DEPENDENCIES + OPTIONAL_DEPENDENCIES
    result = run_command([sys.executable, "-m", "pip", "install"] + deps, check=False)
    
    if dev:
        print("\n  Installing development dependencies...")
        result = run_command([sys.executable, "-m", "pip", "install"] + DEV_DEPENDENCIES, check=False)
    
    if result == 0:
        print("\n  [OK] Dependencies installed successfully")
    else:
        print("\n  ⚠️ Some dependencies may have failed to install")
    
    return result


def run_tests(coverage: bool = True, verbose: bool = True) -> int:
    """Run the test suite."""
    print("\n[TEST] Running tests...")
    
    cmd = [sys.executable, "-m", "pytest"]
    
    if verbose:
        cmd.append("-v")
    
    if coverage:
        cmd.extend(["--cov=scripts/modules", "--cov-report=term-missing", "--cov-report=html"])
    
    cmd.append(str(TESTS_DIR))
    
    result = run_command(cmd, check=False)
    
    if result == 0:
        print("\n  [OK] All tests passed")
    else:
        print("\n  [X] Some tests failed")
    
    return result


def run_linters() -> int:
    """Run code linters."""
    print("\n[LINT] Running linters...")
    
    results = []
    
    # Black (formatting check)
    print("\n  Checking formatting with Black...")
    results.append(run_command(
        [sys.executable, "-m", "black", "--check", "--diff", str(SCRIPTS_DIR)],
        check=False
    ))
    
    # Flake8 (style guide)
    print("\n  Checking style with Flake8...")
    results.append(run_command(
        [sys.executable, "-m", "flake8", str(SCRIPTS_DIR), "--max-line-length=120", "--ignore=E501,W503"],
        check=False
    ))
    
    # isort (import sorting)
    print("\n  Checking imports with isort...")
    results.append(run_command(
        [sys.executable, "-m", "isort", "--check-only", "--diff", str(SCRIPTS_DIR)],
        check=False
    ))
    
    # MyPy (type checking)
    print("\n  Type checking with MyPy...")
    results.append(run_command(
        [sys.executable, "-m", "mypy", str(SCRIPTS_DIR / "modules"), "--ignore-missing-imports"],
        check=False
    ))
    
    if all(r == 0 for r in results):
        print("\n  [OK] All linters passed")
        return 0
    else:
        print("\n  ⚠️ Some linters reported issues")
        return 1


def format_code() -> int:
    """Format code with Black and isort."""
    print("\n[FMT] Formatting code...")
    
    # Black
    print("\n  Running Black...")
    run_command([sys.executable, "-m", "black", str(SCRIPTS_DIR)], check=False)
    
    # isort
    print("\n  Running isort...")
    run_command([sys.executable, "-m", "isort", str(SCRIPTS_DIR)], check=False)
    
    print("\n  [OK] Code formatted")
    return 0


def clean() -> int:
    """Clean build artifacts."""
    print("\n[CLEAN] Cleaning build artifacts...")
    
    dirs_to_clean = [
        DIST_DIR,
        BUILD_DIR,
        PROJECT_ROOT / "*.egg-info",
        PROJECT_ROOT / ".pytest_cache",
        PROJECT_ROOT / ".mypy_cache",
        PROJECT_ROOT / "htmlcov",
        PROJECT_ROOT / ".coverage",
    ]
    
    for pattern in dirs_to_clean:
        for path in PROJECT_ROOT.glob(str(pattern.name) if hasattr(pattern, 'name') else str(pattern)):
            if path.exists():
                if path.is_dir():
                    shutil.rmtree(path)
                    print(f"  Removed directory: {path}")
                else:
                    path.unlink()
                    print(f"  Removed file: {path}")
    
    # Clean __pycache__ directories
    for pycache in PROJECT_ROOT.rglob("__pycache__"):
        shutil.rmtree(pycache)
        print(f"  Removed: {pycache}")
    
    print("\n  [OK] Cleaned")
    return 0


def build_package() -> int:
    """Build the distribution package."""
    print("\n[PKG] Building distribution package...")
    
    # Create setup.py if it doesn't exist
    setup_py = PROJECT_ROOT / "setup.py"
    if not setup_py.exists():
        create_setup_py()
    
    # Build wheel and sdist
    result = run_command([sys.executable, "-m", "build"], check=False)
    
    if result == 0:
        print("\n  [OK] Package built successfully")
        print(f"  Distribution files in: {DIST_DIR}")
    
    return result


def create_setup_py():
    """Create a setup.py file."""
    setup_content = '''#!/usr/bin/env python3
"""Setup script for Ni8mare Security Scanner."""

from setuptools import setup, find_packages
from pathlib import Path

# Read README
readme_path = Path(__file__).parent / "docs" / "README.md"
long_description = readme_path.read_text() if readme_path.exists() else ""

setup(
    name="ni8mare-scanner",
    version="1.0.0",
    author="Security Research Team",
    author_email="[email protected]",
    description="Ethical security scanner for n8n workflow automation instances (CVE-2026-21858)",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/example/ni8mare-scanner",
    project_urls={
        "Bug Tracker": "https://github.com/example/ni8mare-scanner/issues",
        "Documentation": "https://github.com/example/ni8mare-scanner/docs",
    },
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Intended Audience :: Information Technology",
        "Intended Audience :: System Administrators",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
        "Programming Language :: Python :: 3.11",
        "Programming Language :: Python :: 3.12",
        "Topic :: Security",
        "Topic :: System :: Networking",
    ],
    package_dir={"": "scripts"},
    packages=find_packages(where="scripts"),
    python_requires=">=3.9",
    install_requires=[
        "requests>=2.28.0",
        "urllib3>=1.26.0",
        "click>=8.0.0",
        "pydantic>=1.10.0",
        "jinja2>=3.0.0",
        "pyyaml>=6.0",
    ],
    extras_require={
        "dev": [
            "pytest>=7.0.0",
            "pytest-cov>=4.0.0",
            "black>=23.0.0",
            "flake8>=6.0.0",
            "mypy>=1.0.0",
        ],
    },
    entry_points={
        "console_scripts": [
            "ni8mare-scanner=n8n_scanner:main",
        ],
    },
)
'''
    
    with open(PROJECT_ROOT / "setup.py", "w") as f:
        f.write(setup_content)
    print("  Created setup.py")


def create_requirements_txt():
    """Generate requirements.txt file."""
    print("\n📄 Generating requirements.txt...")
    
    with open(PROJECT_ROOT / "requirements.txt", "w") as f:
        f.write("# Ni8mare Security Scanner - Requirements\n")
        f.write("# Core dependencies\n")
        for dep in CORE_DEPENDENCIES:
            f.write(f"{dep}\n")
        f.write("\n# Optional dependencies\n")
        for dep in OPTIONAL_DEPENDENCIES:
            f.write(f"{dep}\n")
    
    with open(PROJECT_ROOT / "requirements-dev.txt", "w") as f:
        f.write("# Ni8mare Security Scanner - Development Requirements\n")
        f.write("-r requirements.txt\n\n")
        for dep in DEV_DEPENDENCIES:
            f.write(f"{dep}\n")
    
    print("  [OK] Generated requirements.txt and requirements-dev.txt")


def check_python_version() -> bool:
    """Check if Python version is compatible."""
    version = sys.version_info
    if version.major < 3 or (version.major == 3 and version.minor < 9):
        print(f"[X] Python 3.9+ required, found {version.major}.{version.minor}")
        return False
    print(f"[OK] Python {version.major}.{version.minor}.{version.micro}")
    return True


def show_help():
    """Show help message."""
    print(__doc__)


# ============================================================================
# Main Entry Point
# ============================================================================

def main():
    parser = argparse.ArgumentParser(
        description="Build script for Ni8mare Security Scanner",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Commands:
  install     Install project dependencies
  install-dev Install with development dependencies
  test        Run the test suite
  lint        Run code linters
  format      Format code with Black and isort
  build       Build distribution package
  clean       Clean build artifacts
  reqs        Generate requirements.txt files
  all         Run full build pipeline (lint, test, build)
        """
    )
    
    parser.add_argument("command", nargs="?", default="help",
                       choices=["install", "install-dev", "test", "lint", "format", 
                               "build", "clean", "reqs", "all", "help"])
    parser.add_argument("--no-coverage", action="store_true", help="Skip coverage during tests")
    parser.add_argument("-v", "--verbose", action="store_true", help="Verbose output")
    
    args = parser.parse_args()
    
    print("=" * 60)
    print("  Ni8mare Security Scanner - Build System")
    print("=" * 60)
    
    if not check_python_version():
        sys.exit(1)
    
    exit_code = 0
    
    if args.command == "help":
        show_help()
    elif args.command == "install":
        exit_code = install_dependencies(dev=False)
    elif args.command == "install-dev":
        exit_code = install_dependencies(dev=True)
    elif args.command == "test":
        exit_code = run_tests(coverage=not args.no_coverage, verbose=args.verbose)
    elif args.command == "lint":
        exit_code = run_linters()
    elif args.command == "format":
        exit_code = format_code()
    elif args.command == "build":
        exit_code = build_package()
    elif args.command == "clean":
        exit_code = clean()
    elif args.command == "reqs":
        create_requirements_txt()
    elif args.command == "all":
        print("\n[BUILD] Running full build pipeline...")
        
        exit_code = run_linters()
        if exit_code != 0:
            print("\n⚠️ Linting issues found, continuing anyway...")
        
        exit_code = run_tests(coverage=True)
        if exit_code != 0:
            print("\n[X] Tests failed, stopping build")
            sys.exit(exit_code)
        
        exit_code = build_package()
    
    print("\n" + "=" * 60)
    if exit_code == 0:
        print("  [OK] Build completed successfully!")
    else:
        print("  [X] Build completed with errors")
    print("=" * 60)
    
    sys.exit(exit_code)


if __name__ == "__main__":
    main()