Absortio

Email → Summary → Bookmark → Email

GitHub - IHATEGIVINGAUSERNAME/theProtector: Linux Bash Script for the Paranoid Admin on a Budget - real-time monitoring and active threat response

Extracto

Linux Bash Script for the Paranoid Admin on a Budget - real-time monitoring and active threat response - IHATEGIVINGAUSERNAME/theProtector

Resumen

Resumen Principal

theProtector v2.3 es un exhaustivo framework de monitorización de seguridad host-based diseñado para sistemas Linux, ofreciendo detección de amenazas en tiempo real. Su arquitectura se distingue por una aproximación multi-capa, combinando mecanismos de detección tanto en el espacio de usuario como en el espacio del kernel para una cobertura de seguridad ininterrumpida. Implementa tecnologías avanzadas como la monitorización del kernel mediante eBPF para el seguimiento de la ejecución de procesos y el análisis de llamadas al sistema, y YARA para la detección de malware basada en patrones, identificando específicamente webshells, reverse shells y criptomineros. Además, incorpora honeypots de red para la implementación automatizada de escuchas en puertos comúnmente atacados y sofisticadas técnicas anti-evasión para descubrir procesos y conexiones ocultas. El framework mantiene una operatividad continua con un mínimo impacto en el rendimiento del sistema, proporcionando una defensa robusta y detallada contra actividades sospechosas, malware y tentativas de evasión.

Elementos Clave

  • Capacidades de Detección Multi-Capa: theProtector v2.3 integra una combinación única de herramientas de seguridad. Utiliza eBPF para la visibilidad profunda a nivel del kernel, permitiendo el análisis de llamadas al sistema y el seguimiento de procesos en tiempo real, lo que es crucial para detectar actividades maliciosas que intentan operar bajo el radar del sistema operativo. Simultáneamente, emplea YARA para el escaneo basado en firmas de malware conocido, y despliega honeypots de red que actúan como señuelos en puertos vulnerables, registrando y alertando sobre intentos de acceso no autorizados. A esto se suma la detección anti-evasión, que busca identificar elementos ocultos que podrían eludir las herramientas de monitoreo estándar.

  • Flexibilidad Operacional y Configuración Detallada: El framework ofrece una amplia gama de comandos para su uso, desde escaneos básicos hasta monitoreo mejorado con todas las funciones activadas, pasando por modos de rendimiento o la ejecución de módulos específicos (YARA, honeypot, eBPF). La configuración se gestiona a través de un archivo sentinel.conf que permite personalizar módulos de monitoreo (red, procesos, archivos, usuarios, rootkits, memoria), activar funciones avanzadas (anti-evasión, eBPF, honeypots, API), ajustar el rendimiento, configurar notificaciones (correo electrónico, webhooks) e integrar claves API para inteligencia de amenazas.

  • Integración de Inteligencia de Amenazas y API REST: theProtector v2.3 va más allá de la detección local al integrar actualizaciones automatizadas de inteligencia de amenazas que incluyen la verificación de reputación de IP, utilizando APIs como AbuseIPDB y VirusTotal. Esto proporciona un contexto crucial para las alertas generadas. Además, cuenta con una interfaz REST API que habilita un panel de control web (http://127.0.0.1:8080 por defecto) y permite el acceso programático a los datos de monitoreo, facilitando la integración con otras plataformas de seguridad y la automatización de respuestas.

  • Soporte Forense Robusto y Gestión de Whitelists: Para las investigaciones post-incidente, el framework ofrece capacidades forenses detalladas, incluyendo un registro exhaustivo de actividad (`sentinel.

Contenido

theProtector v2.3

A comprehensive host-based security monitoring framework that implements real-time threat detection through eBPF kernel monitoring, YARA pattern matching, network honeypots, and anti-evasion techniques.

Overview

theProtector provides multi-layer security monitoring for Linux systems by combining user-space and kernel-space detection mechanisms. The framework operates continuously to detect suspicious activities, malware, and evasion attempts while maintaining minimal system overhead.

Features

  • eBPF Kernel Monitoring: Real-time process execution tracking and system call analysis
  • YARA Malware Detection: Pattern-based scanning for webshells, reverse shells, and crypto miners
  • Network Honeypots: Automated deployment of listeners on commonly targeted ports
  • Anti-Evasion Detection: Cross-validation techniques to identify hidden processes and connections
  • Threat Intelligence Integration: Automated updates with IP reputation checking
  • REST API Interface: Web dashboard and programmatic access to monitoring data
  • Forensic Capabilities: Detailed logging with integrity verification and quarantine functions
  • Container Support: Optimized monitoring for containerized environments

Requirements

System Requirements

  • Linux kernel 4.9+ (for eBPF functionality)
  • Bash 4.0+
  • Root privileges (required for kernel monitoring and honeypots)

Optional Dependencies

# Ubuntu/Debian
sudo apt update
sudo apt install yara jq inotify-tools bcc-tools netcat-openbsd python3

# Fedora/RHEL
sudo dnf install yara jq inotify-tools bcc-tools nmap-ncat python3

# Arch Linux
sudo pacman -S yara jq inotify-tools bcc netcat python

Dependency Functions

  • yara: Advanced malware detection rules
  • jq: Enhanced JSON processing and output formatting
  • inotify-tools: Real-time file system monitoring
  • bcc-tools: eBPF kernel instrumentation
  • netcat: Network honeypot implementation
  • python3: API server and advanced monitoring features

Installation

Quick Start

# Download
git clone https://github.com/yourusername/theprotector.git
cd theprotector
chmod +x the_protector.sh

# Test installation
sudo ./the_protector.sh test

# Run basic scan
sudo ./the_protector.sh

# Run enhanced monitoring
sudo ./the_protector.sh enhanced

Automated Installation

# Install scheduled monitoring (hourly cron job)
sudo ./the_protector.sh install

# Install systemd service (recommended for servers)
sudo ./the_protector.sh systemd

Usage

Basic Commands

# Run standard security scan
sudo ./the_protector.sh

# Run enhanced monitoring with all features
sudo ./the_protector.sh enhanced

# Test installation and show capabilities
sudo ./the_protector.sh test

# Check system status
sudo ./the_protector.sh status

Advanced Features

# Start web dashboard
sudo ./the_protector.sh dashboard
# Access at http://127.0.0.1:8080

# Run specific monitoring modules
sudo ./the_protector.sh yara        # YARA scanning only
sudo ./the_protector.sh honeypot    # Network honeypots only
sudo ./the_protector.sh ebpf        # eBPF monitoring only

# Performance mode (reduced overhead)
sudo ./the_protector.sh performance

Maintenance Commands

# View real-time logs
sudo ./the_protector.sh logs

# View today's alerts
sudo ./the_protector.sh alerts

# View JSON output
sudo ./the_protector.sh json

# Update threat intelligence
sudo ./the_protector.sh enhanced  # Automatic during scan

# Create new baseline
sudo ./the_protector.sh baseline

# Clean up processes and fix issues
sudo ./the_protector.sh cleanup

Configuration

Configuration File

Create sentinel.conf in the same directory as the script:

# Monitoring modules
MONITOR_NETWORK=true
MONITOR_PROCESSES=true
MONITOR_FILES=true
MONITOR_USERS=true
MONITOR_ROOTKITS=true
MONITOR_MEMORY=true

# Advanced features
ENABLE_ANTI_EVASION=true
ENABLE_EBPF=true
ENABLE_HONEYPOTS=true
ENABLE_API_SERVER=true
ENABLE_YARA=true
ENABLE_THREAT_INTEL=true

# Performance tuning
PERFORMANCE_MODE=false
MAX_FIND_DEPTH=2
SCAN_TIMEOUT=180
PARALLEL_JOBS=2

# Notifications
SEND_EMAIL=false
EMAIL_RECIPIENT=""
WEBHOOK_URL=""
SLACK_WEBHOOK_URL=""
SYSLOG_ENABLED=true

# Threat intelligence
ABUSEIPDB_API_KEY=""
VIRUSTOTAL_API_KEY=""
THREAT_INTEL_UPDATE_HOURS=6

# Network settings
API_PORT=8080
HONEYPOT_PORTS=("2222" "8080" "23" "21" "3389")

Environment Variables

# Override API port
export DASHBOARD_PORT=8081

# Custom log directory
export GHOST_SENTINEL_LOG_DIR="/custom/log/path"

Whitelisting

Edit the configuration to whitelist known-good processes and connections:

# Process whitelist (exact matching)
WHITELIST_PROCESSES=("firefox" "chrome" "docker" "systemd" "ssh")

# Network whitelist
WHITELIST_CONNECTIONS=("127.0.0.1" "8.8.8.8" "1.1.1.1")

# Path exclusions
EXCLUDE_PATHS=("/opt/tools" "/var/lib/docker" "/snap")

Output and Logging

Log Locations

# Root user
/var/log/ghost-sentinel/

# Non-root user
$HOME/.ghost-sentinel/logs/

Log Files

  • sentinel.log - General activity log
  • alerts/YYYYMMDD.log - Daily alert files
  • latest_scan.json - Structured scan results
  • honeypot.log - Network connection attempts
  • ebpf_events.log - Kernel-level events
  • quarantine/ - Quarantined files with forensic data

JSON Output Format

{
  "version": "2.3",
  "scan_start": "2025-01-15T10:30:00Z",
  "scan_end": "2025-01-15T10:32:15Z",
  "hostname": "server-01",
  "summary": {
    "total_alerts": 3,
    "critical": 0,
    "high": 1,
    "medium": 2,
    "low": 0
  },
  "alerts": [
    {
      "level": 2,
      "message": "Suspicious process detected",
      "timestamp": "2025-01-15T10:31:22Z"
    }
  ]
}

API Interface

Starting API Server

sudo ./the_protector.sh api
# Access dashboard at http://127.0.0.1:8080

API Endpoints

# System status
curl http://127.0.0.1:8080/api/status

# Recent alerts
curl http://127.0.0.1:8080/api/alerts

# Latest scan results
curl http://127.0.0.1:8080/api/scan

# Honeypot activity
curl http://127.0.0.1:8080/api/honeypot

Integration Examples

SIEM Integration

# Syslog output (automatic if SYSLOG_ENABLED=true)
logger -t "theprotector" -p security.alert "Alert message"

# JSON log parsing
tail -f /var/log/ghost-sentinel/latest_scan.json | jq '.alerts[]'

Webhook Notifications

# Configure webhook URL in sentinel.conf
WEBHOOK_URL="https://your-siem.com/webhook"
SLACK_WEBHOOK_URL="https://hooks.slack.com/services/..."

Cron Scheduling

# Manual cron entry (automatic with 'install' command)
0 * * * * /path/to/the_protector.sh enhanced >/dev/null 2>&1

Troubleshooting

Common Issues

Permission Denied

chmod +x the_protector.sh
sudo ./the_protector.sh test

eBPF Not Working

# Check kernel version
uname -r  # Should be 4.9+

# Install BCC tools
sudo apt install bcc-tools  # Ubuntu
sudo dnf install bcc-tools  # Fedora

Port Already in Use

# Check what's using the port
sudo ss -tulnp | grep :8080

# Use different port
export DASHBOARD_PORT=8081
sudo ./the_protector.sh api

High Resource Usage

# Enable performance mode
sudo ./the_protector.sh performance

# Or configure limits in sentinel.conf
PERFORMANCE_MODE=true
MAX_FIND_DEPTH=1
PARALLEL_JOBS=1

Debug Mode

# Enable verbose output
sudo ./the_protector.sh --verbose enhanced

Reset and Cleanup

# Fix common issues
sudo ./the_protector.sh cleanup

# Reset integrity checks after updates
sudo ./the_protector.sh reset-integrity

# Recreate baseline
sudo ./the_protector.sh baseline

Performance Considerations

Resource Usage

  • CPU: 2-5% during normal operation, 8-12% during active scanning
  • Memory: 15-40MB resident memory
  • Disk: 1-3MB/hour log generation
  • Network: 500KB every 6 hours for threat intelligence updates

Optimization Settings

# Production environments
PERFORMANCE_MODE=true
MAX_FIND_DEPTH=1
SCAN_TIMEOUT=60
PARALLEL_JOBS=1

# High-security environments
MAX_FIND_DEPTH=3
SCAN_TIMEOUT=300
ENABLE_ANTI_EVASION=true
ENABLE_EBPF=true

Security Considerations

Privilege Requirements

  • Root access required for eBPF monitoring and honeypots
  • Non-root operation available with limited functionality
  • API server binds to localhost only by default

Log Security

  • Alert logs include integrity checksums
  • Quarantined files preserve forensic metadata
  • Structured logging enables SIEM integration

Network Security

  • Honeypots bind to localhost by default
  • API authentication can be implemented for remote access
  • Threat intelligence uses HTTPS with timeout controls

Contributing

Development Setup

git clone https://github.com/yourusername/theprotector.git
cd theprotector

# Run shellcheck for code quality
shellcheck the_protector.sh

# Test across environments
sudo ./the_protector.sh test

Adding Detection Rules

Edit YARA rules in the init_yara_rules() function or add new rule files to the YARA rules directory.

Extending Functionality

The modular design allows for easy extension:

  • Add new monitoring modules in the main detection loop
  • Implement additional API endpoints in the Python server
  • Create new alert notification methods

License

This project is released under the MIT License. See LICENSE file for details.

Changelog

v2.3

  • Added eBPF kernel monitoring
  • Implemented network honeypots
  • Enhanced anti-evasion detection
  • Added REST API and web dashboard
  • Improved threat intelligence integration
  • Added forensic quarantine capabilities

v2.2

  • YARA integration for malware detection
  • Performance optimizations
  • Container environment support

v2.1

  • Multi-environment detection
  • Enhanced logging and JSON output
  • Baseline comparison system

v2.0

  • Complete rewrite with modular architecture
  • Advanced configuration system
  • Comprehensive alert management

Support

For issues, questions, or contributions:

  • Create GitHub issues for bug reports
  • Submit pull requests for improvements
  • Review documentation for common solutions

Acknowledgments

This project incorporates techniques and patterns from various open-source security tools and research papers in the host-based monitoring field.

Fuente: GitHub