Saltar a contenido

OpenVAS Cheatsheet

■/div titulada

Sinopsis

OpenVAS (Open Vulnerability Assessment System) es un escáner de vulnerabilidad integral y una solución de gestión de vulnerabilidad. Es parte del marco Greenbone Vulnerability Management (GVM) y proporciona capacidades poderosas para identificar vulnerabilidades de seguridad en redes, sistemas y aplicaciones.

Características clave

  • Escaneamiento amplio: detección y evaluación de la vulnerabilidad de la red
  • ** Base de datos NVT extensa**: más de 50.000 pruebas de vulnerabilidad de red (NVT)
  • ** Interfaz de Internet**: Asistente de Seguridad de Greenbone (GSA)
  • Flexible Reporting: Múltiples formatos de informe y opciones de personalización
  • Escáner de cumplimiento: Apoyo a diversos marcos de cumplimiento
  • Escaneos autenticados: Escaneos tripulados para un análisis más profundo
  • API Integration: REST API para automatización e integración

Instalación

Docker Instalación (recomendada)

# Pull the official Greenbone Community Edition container
docker pull greenbone/gvm

# Create persistent volumes
docker volume create gvm-data
docker volume create gvm-postgres-data

# Run OpenVAS with Docker Compose
cat > docker-compose.yml << EOF
version: '3.8'

services:
  gvm:
    image: greenbone/gvm:stable
    restart: unless-stopped
    ports:
      - "9392:9392"
      - "9390:9390"
    volumes:
      - gvm-data:/var/lib/gvm
      - gvm-postgres-data:/var/lib/postgresql
    environment:
      - POSTGRES_PASSWORD=mypassword
      - GVMD_PASSWORD=admin
    networks:
      - gvm-network

networks:
  gvm-network:
    driver: bridge

volumes:
  gvm-data:
  gvm-postgres-data:
EOF

# Start the services
docker-compose up -d

# Wait for initialization (can take 10-15 minutes)
docker-compose logs -f gvm

Instalación Ubuntu/Debian

# Add Greenbone repository
sudo apt update
sudo apt install -y software-properties-common
sudo add-apt-repository ppa:mrazavi/gvm

# Install OpenVAS components
sudo apt update
sudo apt install -y gvm

# Setup and start services
sudo gvm-setup

# Start services
sudo systemctl start gvmd
sudo systemctl start gsad
sudo systemctl start ospd-openvas

# Enable services at boot
sudo systemctl enable gvmd
sudo systemctl enable gsad
sudo systemctl enable ospd-openvas

# Create admin user
sudo gvmd --create-user=admin --password=admin

# Update NVT feed
sudo gvmd --update-nvt-cache
sudo greenbone-nvt-sync

CentOS/RHEL Instalación

# Install EPEL repository
sudo yum install -y epel-release

# Install dependencies
sudo yum install -y cmake gcc gcc-c++ git make pkg-config
sudo yum install -y glib2-devel libgcrypt-devel libgpgme-devel
sudo yum install -y libxml2-devel openssl-devel sqlite-devel

# Clone and build GVM
git clone https://github.com/greenbone/gvm-libs.git
cd gvm-libs
mkdir build && cd build
cmake ..
make -j$(nproc)
sudo make install

# Continue with other components
cd ../../
git clone https://github.com/greenbone/openvas.git
cd openvas
mkdir build && cd build
cmake ..
make -j$(nproc)
sudo make install

# Setup services (manual configuration required)
sudo ldconfig

Fuente: Instalación

# Install dependencies
sudo apt install -y cmake pkg-config gcc make
sudo apt install -y libglib2.0-dev libgpgme-dev libgnutls28-dev
sudo apt install -y uuid-dev libssh-gcrypt-dev libldap2-dev
sudo apt install -y libhiredis-dev libxml2-dev libradcli-dev

# Create GVM user
sudo useradd -r -M -U -G sudo -s /usr/sbin/nologin gvm

# Set installation directory
export INSTALL_PREFIX=/opt/gvm
export PATH=$PATH:$INSTALL_PREFIX/bin:$INSTALL_PREFIX/sbin
export PKG_CONFIG_PATH=$INSTALL_PREFIX/lib/pkgconfig:$PKG_CONFIG_PATH

# Build GVM libraries
git clone -b gvm-libs-20.08 https://github.com/greenbone/gvm-libs.git
cd gvm-libs
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=$INSTALL_PREFIX ..
make -j$(nproc)
sudo make install

# Build OpenVAS Scanner
cd ../../
git clone -b openvas-20.08 https://github.com/greenbone/openvas.git
cd openvas
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=$INSTALL_PREFIX ..
make -j$(nproc)
sudo make install

# Build GVM Daemon
cd ../../
git clone -b gvmd-20.08 https://github.com/greenbone/gvmd.git
cd gvmd
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=$INSTALL_PREFIX ..
make -j$(nproc)
sudo make install

# Build GSA (Web Interface)
cd ../../
git clone -b gsa-20.08 https://github.com/greenbone/gsa.git
cd gsa
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=$INSTALL_PREFIX ..
make -j$(nproc)
sudo make install

Configuración básica

Configuración inicial

# Update NVT feed
sudo greenbone-nvt-sync

# Update SCAP data
sudo greenbone-scapdata-sync

# Update CERT data
sudo greenbone-certdata-sync

# Rebuild NVT cache
sudo openvas --update-vt-info

# Create admin user
sudo gvmd --create-user=admin --password=StrongPassword123

# Set user role
sudo gvmd --modify-setting 78eceaec-3385-11ea-b237-28d24461215b --value admin

# Start services
sudo systemctl start gvmd
sudo systemctl start gsad
sudo systemctl start ospd-openvas

# Check service status
sudo systemctl status gvmd
sudo systemctl status gsad
sudo systemctl status ospd-openvas

Acceso a la interfaz web

# Default access
# URL: https://localhost:9392
# Username: admin
# Password: admin (or your set password)

# Check GSA status
sudo ss -tulpn | grep 9392

# View logs
sudo journalctl -u gsad -f
sudo journalctl -u gvmd -f
sudo journalctl -u ospd-openvas -f

Interfaz de línea de mando

# GVM CLI installation
pip3 install gvm-tools

# Connect to GVM daemon
gvm-cli socket --xml "<get_version/>"

# Connect via TLS
gvm-cli tls --hostname localhost --port 9390 --xml "<get_version/>"

# Interactive mode
gvm-cli socket --xml

Operaciones de exploración

Configuración de objetivos

# Create target via CLI
gvm-cli socket --xml '
<create_target>
  <name>Test Network</name>
  <hosts>192.168.1.0/24</hosts>
  <port_list id="730ef368-57e2-11e1-a90f-406186ea4fc5"/>
</create_target>'

# Create target with credentials
gvm-cli socket --xml '
<create_target>
  <name>Authenticated Scan Target</name>
  <hosts>192.168.1.100-110</hosts>
  <ssh_credential id="credential-uuid"/>
  <port_list id="730ef368-57e2-11e1-a90f-406186ea4fc5"/>
</create_target>'

# List existing targets
gvm-cli socket --xml '<get_targets/>'

Configuración de exploración

# Create scan configuration
gvm-cli socket --xml '
<create_config>
  <name>Custom Full Scan</name>
  <copy>daba56c8-73ec-11df-a475-002264764cea</copy>
</create_config>'

# Modify scan configuration
gvm-cli socket --xml '
<modify_config config_id="config-uuid">
  <name>Modified Scan Config</name>
  <nvt_selection>
    <family>Service detection</family>
    <nvt oid="1.3.6.1.4.1.25623.1.0.14259"/>
  </nvt_selection>
</modify_config>'

# List scan configurations
gvm-cli socket --xml '<get_configs/>'

Gestión de tareas

# Create scan task
gvm-cli socket --xml '
<create_task>
  <name>Network Security Scan</name>
  <target id="target-uuid"/>
  <config id="config-uuid"/>
  <scanner id="08b69003-5fc2-4037-a479-93b440211c73"/>
</create_task>'

# Start scan task
gvm-cli socket --xml '
<start_task task_id="task-uuid"/>'

# Stop scan task
gvm-cli socket --xml '
<stop_task task_id="task-uuid"/>'

# Resume scan task
gvm-cli socket --xml '
<resume_task task_id="task-uuid"/>'

# Delete scan task
gvm-cli socket --xml '
<delete_task task_id="task-uuid"/>'

# List all tasks
gvm-cli socket --xml '<get_tasks/>'

# Get task status
gvm-cli socket --xml '
<get_tasks task_id="task-uuid"/>'

Credential Management

# Create SSH credential
gvm-cli socket --xml '
<create_credential>
  <name>SSH Login</name>
  <type>up</type>
  <login>username</login>
  <password>password</password>
</create_credential>'

# Create SSH key credential
gvm-cli socket --xml '
<create_credential>
  <name>SSH Key</name>
  <type>usk</type>
  <login>username</login>
  <key>
    <private>-----BEGIN PRIVATE KEY-----
    ...private key content...
    -----END PRIVATE KEY-----</private>
  </key>
</create_credential>'

# Create Windows credential
gvm-cli socket --xml '
<create_credential>
  <name>Windows Login</name>
  <type>up</type>
  <login>domain\\username</login>
  <password>password</password>
</create_credential>'

# List credentials
gvm-cli socket --xml '<get_credentials/>'

Escáner avanzado

Escaneado autentico

# Linux authenticated scan setup
gvm-cli socket --xml '
<create_credential>
  <name>Linux SSH</name>
  <type>up</type>
  <login>scanuser</login>
  <password>scanpassword</password>
</create_credential>'

# Windows authenticated scan setup
gvm-cli socket --xml '
<create_credential>
  <name>Windows SMB</name>
  <type>up</type>
  <login>DOMAIN\\scanuser</login>
  <password>scanpassword</password>
</create_credential>'

# Database credential setup
gvm-cli socket --xml '
<create_credential>
  <name>MySQL Database</name>
  <type>up</type>
  <login>dbuser</login>
  <password>dbpassword</password>
</create_credential>'

Listas de puertos personalizados

# Create custom port list
gvm-cli socket --xml '
<create_port_list>
  <name>Web Services</name>
  <port_range>80,443,8080,8443</port_range>
</create_port_list>'

# Create comprehensive port list
gvm-cli socket --xml '
<create_port_list>
  <name>Extended Scan</name>
  <port_range>1-1000,1433,1521,3306,3389,5432,5900-5910</port_range>
</create_port_list>'

# List port lists
gvm-cli socket --xml '<get_port_lists/>'

Tiempo de exploración y rendimiento

# Create performance-optimized config
gvm-cli socket --xml '
<create_config>
  <name>Fast Network Scan</name>
  <copy>daba56c8-73ec-11df-a475-002264764cea</copy>
  <preferences>
    <preference>
      <nvt oid="1.3.6.1.4.1.25623.1.0.100315">
        <id>1</id>
        <value>5</value>
      </nvt>
    </preference>
  </preferences>
</create_config>'

# Adjust scanner preferences
gvm-cli socket --xml '
<modify_config config_id="config-uuid">
  <preferences>
    <preference>
      <nvt oid="scanner">
        <id>max_hosts</id>
        <value>20</value>
      </nvt>
    </preference>
    <preference>
      <nvt oid="scanner">
        <id>max_checks</id>
        <value>5</value>
      </nvt>
    </preference>
  </preferences>
</modify_config>'

Gestión de informes

Report Generation

# Get scan results
gvm-cli socket --xml '
<get_results task_id="task-uuid"/>'

# Generate PDF report
gvm-cli socket --xml '
<get_reports report_id="report-uuid" format_id="c402cc3e-b531-11e1-9163-406186ea4fc5"/>'

# Generate XML report
gvm-cli socket --xml '
<get_reports report_id="report-uuid" format_id="a994b278-1f62-11e1-96ac-406186ea4fc5"/>'

# Generate CSV report
gvm-cli socket --xml '
<get_reports report_id="report-uuid" format_id="c1645568-627a-11e3-a660-406186ea4fc5"/>'

# Generate HTML report
gvm-cli socket --xml '
<get_reports report_id="report-uuid" format_id="6c248850-1f62-11e1-b082-406186ea4fc5"/>'

# List all reports
gvm-cli socket --xml '<get_reports/>'

Formatos de informe personalizado

# Create custom report format
gvm-cli socket --xml '
<create_report_format>
  <name>Custom Security Report</name>
  <extension>html</extension>
  <content_type>text/html</content_type>
  <summary>Custom HTML security report</summary>
  <description>Detailed security assessment report</description>
  <file name="report.xsl">
    <!-- XSL transformation content -->
  </file>
</create_report_format>'

# List report formats
gvm-cli socket --xml '<get_report_formats/>'

Report Filtering

# Filter results by severity
gvm-cli socket --xml '
<get_results task_id="task-uuid" filter="severity>7.0"/>'

# Filter by host
gvm-cli socket --xml '
<get_results task_id="task-uuid" filter="host=192.168.1.100"/>'

# Filter by NVT family
gvm-cli socket --xml '
<get_results task_id="task-uuid" filter="nvt_family=&quot;Web application abuses&quot;"/>'

# Complex filtering
gvm-cli socket --xml '
<get_results task_id="task-uuid" filter="severity>5.0 and host~192.168.1"/>'

Scripts de automatización

Python Automation Script

#!/usr/bin/env python3
# openvas-automation.py

import time
import xml.etree.ElementTree as ET
from gvm.connections import UnixSocketConnection
from gvm.protocols.gmp import Gmp
from gvm.transforms import EtreeTransform

class OpenVASAutomation:
    def __init__(self, socket_path='/var/run/gvmd.sock'):
        self.connection = UnixSocketConnection(path=socket_path)
        self.transform = EtreeTransform()
        self.gmp = None

    def connect(self, username, password):
        """Connect to OpenVAS and authenticate"""
        try:
            self.gmp = Gmp(connection=self.connection, transform=self.transform)
            self.gmp.authenticate(username, password)
            print("✅ Connected to OpenVAS successfully")
            return True
        except Exception as e:
            print(f"❌ Connection failed: {e}")
            return False

    def create_target(self, name, hosts, port_list_id=None):
        """Create a scan target"""
        if not port_list_id:
            # Use default OpenVAS port list
            port_list_id = "730ef368-57e2-11e1-a90f-406186ea4fc5"

        try:
            resp = self.gmp.create_target(
                name=name,
                hosts=[hosts],
                port_list_id=port_list_id
            )
            target_id = resp.get('id')
            print(f"✅ Target '{name}' created with ID: {target_id}")
            return target_id
        except Exception as e:
            print(f"❌ Failed to create target: {e}")
            return None

    def create_task(self, name, target_id, config_id=None, scanner_id=None):
        """Create a scan task"""
        if not config_id:
            # Use Full and fast scan config
            config_id = "daba56c8-73ec-11df-a475-002264764cea"

        if not scanner_id:
            # Use default OpenVAS scanner
            scanner_id = "08b69003-5fc2-4037-a479-93b440211c73"

        try:
            resp = self.gmp.create_task(
                name=name,
                config_id=config_id,
                target_id=target_id,
                scanner_id=scanner_id
            )
            task_id = resp.get('id')
            print(f"✅ Task '{name}' created with ID: {task_id}")
            return task_id
        except Exception as e:
            print(f"❌ Failed to create task: {e}")
            return None

    def start_scan(self, task_id):
        """Start a scan task"""
        try:
            self.gmp.start_task(task_id)
            print(f"✅ Scan started for task: {task_id}")
            return True
        except Exception as e:
            print(f"❌ Failed to start scan: {e}")
            return False

    def wait_for_scan_completion(self, task_id, check_interval=30):
        """Wait for scan to complete"""
        print(f"⏳ Waiting for scan completion...")

        while True:
            try:
                task = self.gmp.get_task(task_id)
                status = task.find('task/status').text
                progress = task.find('task/progress').text

                print(f"📊 Status: {status}, Progress: {progress}%")

                if status in ['Done', 'Stopped', 'Interrupted']:
                    print(f"✅ Scan completed with status: {status}")
                    return status

                time.sleep(check_interval)

            except Exception as e:
                print(f"❌ Error checking scan status: {e}")
                return None

    def get_scan_results(self, task_id):
        """Get scan results"""
        try:
            task = self.gmp.get_task(task_id)
            reports = task.xpath('task/last_report/report/@id')

            if reports:
                report_id = reports[0]
                results = self.gmp.get_results(task_id=task_id)
                return results, report_id
            else:
                print("❌ No reports found for task")
                return None, None

        except Exception as e:
            print(f"❌ Failed to get results: {e}")
            return None, None

    def generate_report(self, report_id, format_id="c402cc3e-b531-11e1-9163-406186ea4fc5"):
        """Generate and download report"""
        try:
            # PDF format by default
            report = self.gmp.get_report(
                report_id=report_id,
                report_format_id=format_id
            )
            return report
        except Exception as e:
            print(f"❌ Failed to generate report: {e}")
            return None

    def analyze_results(self, results):
        """Analyze scan results"""
        if not results:
            return

        print("\n=== Scan Results Analysis ===")

        # Count vulnerabilities by severity
        severity_counts = {'High': 0, 'Medium': 0, 'Low': 0, 'Log': 0}
        total_vulns = 0

        for result in results.xpath('result'):
            severity = result.find('severity').text
            threat = result.find('threat').text

            if threat in severity_counts:
                severity_counts[threat] += 1
            total_vulns += 1

        print(f"📊 Total vulnerabilities found: {total_vulns}")
        print(f"🔴 High severity: {severity_counts.get('High', 0)}")
        print(f"🟡 Medium severity: {severity_counts.get('Medium', 0)}")
        print(f"🟢 Low severity: {severity_counts.get('Low', 0)}")
        print(f"ℹ️  Log entries: {severity_counts.get('Log', 0)}")

        # Show top vulnerabilities
        print("\n--- Top High Severity Vulnerabilities ---")
        high_vulns = results.xpath('result[threat="High"]')[:10]

        for vuln in high_vulns:
            name = vuln.find('name').text
            host = vuln.find('host').text
            port = vuln.find('port').text
            print(f"🔴 {name} on {host}:{port}")

    def automated_scan_workflow(self, target_name, target_hosts, scan_name=None):
        """Complete automated scan workflow"""
        if not scan_name:
            scan_name = f"Automated Scan - {target_name}"

        print(f"🚀 Starting automated scan workflow for {target_name}")

        # Create target
        target_id = self.create_target(target_name, target_hosts)
        if not target_id:
            return False

        # Create task
        task_id = self.create_task(scan_name, target_id)
        if not task_id:
            return False

        # Start scan
        if not self.start_scan(task_id):
            return False

        # Wait for completion
        status = self.wait_for_scan_completion(task_id)
        if status != 'Done':
            print(f"⚠️  Scan completed with status: {status}")

        # Get and analyze results
        results, report_id = self.get_scan_results(task_id)
        if results:
            self.analyze_results(results)

            # Generate PDF report
            report = self.generate_report(report_id)
            if report:
                filename = f"scan_report_{target_name}_{int(time.time())}.pdf"
                with open(filename, 'wb') as f:
                    f.write(report)
                print(f"📄 Report saved as: {filename}")

        return True

    def disconnect(self):
        """Disconnect from OpenVAS"""
        if self.connection:
            self.connection.disconnect()
            print("👋 Disconnected from OpenVAS")

def main():
    # Configuration
    USERNAME = "admin"
    PASSWORD = "admin"
    TARGET_NAME = "Test Network"
    TARGET_HOSTS = "192.168.1.0/24"

    # Initialize automation
    scanner = OpenVASAutomation()

    try:
        # Connect to OpenVAS
        if not scanner.connect(USERNAME, PASSWORD):
            return

        # Run automated scan
        scanner.automated_scan_workflow(TARGET_NAME, TARGET_HOSTS)

    except KeyboardInterrupt:
        print("\n⏹️  Scan interrupted by user")
    except Exception as e:
        print(f"❌ Unexpected error: {e}")
    finally:
        scanner.disconnect()

if __name__ == "__main__":
    main()

Bash Automation Script

#!/bin/bash
# openvas-scan.sh

set -e

# Configuration
GVM_USER="${GVM_USER:-admin}"
GVM_PASSWORD="${GVM_PASSWORD:-admin}"
TARGET_HOSTS="${TARGET_HOSTS:-192.168.1.0/24}"
SCAN_NAME="${SCAN_NAME:-Automated Security Scan}"
OUTPUT_DIR="${OUTPUT_DIR:-./scan-results}"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Logging function
log() {
    echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
}

success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

# Check if gvm-cli is available
check_dependencies() {
    if ! command -v gvm-cli &> /dev/null; then
        error "gvm-cli not found. Please install gvm-tools: pip3 install gvm-tools"
        exit 1
    fi

    if ! command -v xmllint &> /dev/null; then
        warning "xmllint not found. Install libxml2-utils for better XML parsing"
    fi
}

# Test connection to OpenVAS
test_connection() {
    log "Testing connection to OpenVAS..."

    local response=$(gvm-cli socket --xml "<get_version/>" 2>/dev/null || echo "ERROR")

    if [[ "$response" == "ERROR" ]]; then
        error "Cannot connect to OpenVAS. Check if services are running."
        return 1
    fi

    success "Connected to OpenVAS successfully"
    return 0
}

# Create scan target
create_target() {
    local target_name="$1"
    local target_hosts="$2"

    log "Creating target: $target_name"

    local xml_request="<create_target>
        <name>$target_name</name>
        <hosts>$target_hosts</hosts>
        <port_list id=\"730ef368-57e2-11e1-a90f-406186ea4fc5\"/>
    </create_target>"

    local response=$(gvm-cli socket --xml "$xml_request")
    local target_id=$(echo "$response" | grep -oP 'id="\K[^"]*' | head -1)

    if [[ -n "$target_id" ]]; then
        success "Target created with ID: $target_id"
        echo "$target_id"
    else
        error "Failed to create target"
        echo "$response"
        return 1
    fi
}

# Create scan task
create_task() {
    local task_name="$1"
    local target_id="$2"

    log "Creating scan task: $task_name"

    local xml_request="<create_task>
        <name>$task_name</name>
        <target id=\"$target_id\"/>
        <config id=\"daba56c8-73ec-11df-a475-002264764cea\"/>
        <scanner id=\"08b69003-5fc2-4037-a479-93b440211c73\"/>
    </create_task>"

    local response=$(gvm-cli socket --xml "$xml_request")
    local task_id=$(echo "$response" | grep -oP 'id="\K[^"]*' | head -1)

    if [[ -n "$task_id" ]]; then
        success "Task created with ID: $task_id"
        echo "$task_id"
    else
        error "Failed to create task"
        echo "$response"
        return 1
    fi
}

# Start scan
start_scan() {
    local task_id="$1"

    log "Starting scan for task: $task_id"

    local xml_request="<start_task task_id=\"$task_id\"/>"
    local response=$(gvm-cli socket --xml "$xml_request")

    if echo "$response" | grep -q "start_task_response"; then
        success "Scan started successfully"
        return 0
    else
        error "Failed to start scan"
        echo "$response"
        return 1
    fi
}

# Monitor scan progress
monitor_scan() {
    local task_id="$1"
    local check_interval="${2:-30}"

    log "Monitoring scan progress..."

    while true; do
        local xml_request="<get_tasks task_id=\"$task_id\"/>"
        local response=$(gvm-cli socket --xml "$xml_request")

        local status=$(echo "$response" | grep -oP '<status>\K[^<]*' | head -1)
        local progress=$(echo "$response" | grep -oP '<progress>\K[^<]*' | head -1)

        log "Status: $status, Progress: $progress%"

        case "$status" in
            "Done")
                success "Scan completed successfully"
                return 0
                ;;
            "Stopped"|"Interrupted")
                warning "Scan stopped with status: $status"
                return 1
                ;;
            "Running")
                sleep "$check_interval"
                ;;
            *)
                error "Unknown scan status: $status"
                return 1
                ;;
        esac
    done
}

# Generate and save report
generate_report() {
    local task_id="$1"
    local output_dir="$2"

    log "Generating scan report..."

    # Get report ID
    local xml_request="<get_tasks task_id=\"$task_id\"/>"
    local response=$(gvm-cli socket --xml "$xml_request")
    local report_id=$(echo "$response" | grep -oP 'last_report.*?id="\K[^"]*' | head -1)

    if [[ -z "$report_id" ]]; then
        error "No report found for task"
        return 1
    fi

    mkdir -p "$output_dir"

    # Generate PDF report
    log "Generating PDF report..."
    local pdf_request="<get_reports report_id=\"$report_id\" format_id=\"c402cc3e-b531-11e1-9163-406186ea4fc5\"/>"
    local pdf_response=$(gvm-cli socket --xml "$pdf_request")

    if echo "$pdf_response" | grep -q "get_reports_response"; then
        echo "$pdf_response" | grep -oP '<report.*?</report>' | \
        sed 's/<report[^>]*>//; s/<\/report>//' | \
        base64 -d > "$output_dir/scan_report.pdf"
        success "PDF report saved to: $output_dir/scan_report.pdf"
    fi

    # Generate XML report
    log "Generating XML report..."
    local xml_report_request="<get_reports report_id=\"$report_id\" format_id=\"a994b278-1f62-11e1-96ac-406186ea4fc5\"/>"
    local xml_report_response=$(gvm-cli socket --xml "$xml_report_request")

    echo "$xml_report_response" > "$output_dir/scan_report.xml"
    success "XML report saved to: $output_dir/scan_report.xml"

    # Generate summary
    generate_summary "$output_dir/scan_report.xml" "$output_dir/scan_summary.txt"
}

# Generate scan summary
generate_summary() {
    local xml_file="$1"
    local summary_file="$2"

    log "Generating scan summary..."

    cat > "$summary_file" << EOF
OpenVAS Scan Summary
===================
Scan Date: $(date)
Target: $TARGET_HOSTS
Scan Name: $SCAN_NAME

EOF

    if command -v xmllint &> /dev/null; then
        # Count vulnerabilities by severity
        local high_count=$(xmllint --xpath "count(//result[threat='High'])" "$xml_file" 2>/dev/null || echo "0")
        local medium_count=$(xmllint --xpath "count(//result[threat='Medium'])" "$xml_file" 2>/dev/null || echo "0")
        local low_count=$(xmllint --xpath "count(//result[threat='Low'])" "$xml_file" 2>/dev/null || echo "0")
        local total_count=$((high_count + medium_count + low_count))

        cat >> "$summary_file" << EOF
Vulnerability Summary:
- Total vulnerabilities: $total_count
- High severity: $high_count
- Medium severity: $medium_count
- Low severity: $low_count

EOF

        if [[ $high_count -gt 0 ]]; then
            echo "High Severity Vulnerabilities:" >> "$summary_file"
            xmllint --xpath "//result[threat='High']/name/text()" "$xml_file" 2>/dev/null | \
            head -10 | sed 's/^/- /' >> "$summary_file" 2>/dev/null || true
            echo "" >> "$summary_file"
        fi
    else
        echo "Install xmllint for detailed vulnerability analysis" >> "$summary_file"
    fi

    success "Summary saved to: $summary_file"
}

# Cleanup function
cleanup() {
    local task_id="$1"
    local target_id="$2"

    if [[ "$CLEANUP" == "true" ]]; then
        log "Cleaning up scan artifacts..."

        if [[ -n "$task_id" ]]; then
            gvm-cli socket --xml "<delete_task task_id=\"$task_id\"/>" >/dev/null 2>&1 || true
        fi

        if [[ -n "$target_id" ]]; then
            gvm-cli socket --xml "<delete_target target_id=\"$target_id\"/>" >/dev/null 2>&1 || true
        fi

        success "Cleanup completed"
    fi
}

# Main execution function
main() {
    log "Starting OpenVAS automated scan"
    log "Target: $TARGET_HOSTS"
    log "Scan Name: $SCAN_NAME"

    # Check dependencies
    check_dependencies

    # Test connection
    if ! test_connection; then
        exit 1
    fi

    # Create target
    local target_id
    target_id=$(create_target "$SCAN_NAME Target" "$TARGET_HOSTS")
    if [[ $? -ne 0 ]]; then
        exit 1
    fi

    # Create task
    local task_id
    task_id=$(create_task "$SCAN_NAME" "$target_id")
    if [[ $? -ne 0 ]]; then
        cleanup "" "$target_id"
        exit 1
    fi

    # Start scan
    if ! start_scan "$task_id"; then
        cleanup "$task_id" "$target_id"
        exit 1
    fi

    # Monitor scan
    if ! monitor_scan "$task_id"; then
        cleanup "$task_id" "$target_id"
        exit 1
    fi

    # Generate report
    generate_report "$task_id" "$OUTPUT_DIR"

    # Cleanup if requested
    cleanup "$task_id" "$target_id"

    success "Scan completed successfully!"
    log "Results available in: $OUTPUT_DIR"
}

# Handle script interruption
trap 'error "Script interrupted"; exit 1' INT TERM

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -t|--target)
            TARGET_HOSTS="$2"
            shift 2
            ;;
        -n|--name)
            SCAN_NAME="$2"
            shift 2
            ;;
        -o|--output)
            OUTPUT_DIR="$2"
            shift 2
            ;;
        -c|--cleanup)
            CLEANUP="true"
            shift
            ;;
        -h|--help)
            echo "Usage: $0 [OPTIONS]"
            echo "Options:"
            echo "  -t, --target    Target hosts (default: 192.168.1.0/24)"
            echo "  -n, --name      Scan name (default: Automated Security Scan)"
            echo "  -o, --output    Output directory (default: ./scan-results)"
            echo "  -c, --cleanup   Cleanup scan artifacts after completion"
            echo "  -h, --help      Show this help message"
            exit 0
            ;;
        *)
            error "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Run main function
main

CI/CD Integration

GitHub Actions

# .github/workflows/security-scan.yml
name: Security Vulnerability Scan

on:
  schedule:
    - cron: '0 2 * * 1'  # Weekly on Monday at 2 AM
  workflow_dispatch:
    inputs:
      target_hosts:
        description: 'Target hosts to scan'
        required: true
        default: '192.168.1.0/24'
      scan_type:
        description: 'Type of scan'
        required: true
        default: 'full'
        type: choice
        options:
          - full
          - quick
          - custom

jobs:
  security-scan:
    runs-on: ubuntu-latest

    services:
      openvas:
        image: greenbone/gvm:stable
        ports:
          - 9392:9392
        env:
          GVMD_PASSWORD: ${{ secrets.OPENVAS_PASSWORD }}
        options: >-
          --health-cmd "gvmd --get-users"
          --health-interval 30s
          --health-timeout 10s
          --health-retries 5

    steps:
    - name: Checkout code
      uses: actions/checkout@v3

    - name: Setup Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.9'

    - name: Install dependencies
      run: |
        pip install gvm-tools python-gvm

    - name: Wait for OpenVAS initialization
      run: |
        echo "Waiting for OpenVAS to initialize..."
        sleep 300  # Wait 5 minutes for full initialization

    - name: Configure scan parameters
      run: |
        case "${{ github.event.inputs.scan_type }}" in
          "quick")
            echo "SCAN_CONFIG=085569ce-73ed-11df-83c3-002264764cea" >> $GITHUB_ENV
            ;;
          "custom")
            echo "SCAN_CONFIG=708f25c4-7489-11df-8094-002264764cea" >> $GITHUB_ENV
            ;;
          *)
            echo "SCAN_CONFIG=daba56c8-73ec-11df-a475-002264764cea" >> $GITHUB_ENV
            ;;
        esac

    - name: Run security scan
      env:
        TARGET_HOSTS: ${{ github.event.inputs.target_hosts || '192.168.1.0/24' }}
        OPENVAS_PASSWORD: ${{ secrets.OPENVAS_PASSWORD }}
      run: |
        python3 << 'EOF'
        import os
        import time
        from gvm.connections import TLSConnection
        from gvm.protocols.gmp import Gmp
        from gvm.transforms import EtreeTransform

        # Connection setup
        connection = TLSConnection(hostname='localhost', port=9390)
        transform = EtreeTransform()

        with Gmp(connection=connection, transform=transform) as gmp:
            # Authenticate
            gmp.authenticate('admin', os.environ['OPENVAS_PASSWORD'])

            # Create target
            target_resp = gmp.create_target(
                name=f"CI/CD Scan Target - {os.environ['GITHUB_RUN_ID']}",
                hosts=[os.environ['TARGET_HOSTS']]
            )
            target_id = target_resp.get('id')
            print(f"Created target: {target_id}")

            # Create task
            task_resp = gmp.create_task(
                name=f"CI/CD Security Scan - {os.environ['GITHUB_RUN_ID']}",
                config_id=os.environ['SCAN_CONFIG'],
                target_id=target_id,
                scanner_id="08b69003-5fc2-4037-a479-93b440211c73"
            )
            task_id = task_resp.get('id')
            print(f"Created task: {task_id}")

            # Start scan
            gmp.start_task(task_id)
            print("Scan started")

            # Monitor progress
            while True:
                task = gmp.get_task(task_id)
                status = task.find('task/status').text
                progress = task.find('task/progress').text

                print(f"Status: {status}, Progress: {progress}%")

                if status in ['Done', 'Stopped', 'Interrupted']:
                    break

                time.sleep(60)  # Check every minute

            # Get results
            results = gmp.get_results(task_id=task_id)

            # Count vulnerabilities
            high_count = len(results.xpath('result[threat="High"]'))
            medium_count = len(results.xpath('result[threat="Medium"]'))
            low_count = len(results.xpath('result[threat="Low"]'))

            print(f"Scan completed:")
            print(f"High: {high_count}, Medium: {medium_count}, Low: {low_count}")

            # Save results to environment
            with open(os.environ['GITHUB_ENV'], 'a') as f:
                f.write(f"HIGH_VULNS={high_count}\n")
                f.write(f"MEDIUM_VULNS={medium_count}\n")
                f.write(f"LOW_VULNS={low_count}\n")
                f.write(f"TASK_ID={task_id}\n")
        EOF

    - name: Generate reports
      if: always()
      run: |
        mkdir -p scan-reports

        # Generate summary report
        cat > scan-reports/summary.md << EOF
        # Security Scan Results

        **Scan Date:** $(date)
        **Target:** ${{ github.event.inputs.target_hosts || '192.168.1.0/24' }}
        **Scan Type:** ${{ github.event.inputs.scan_type || 'full' }}
        **Workflow:** ${{ github.workflow }}
        **Run ID:** ${{ github.run_id }}

        ## Vulnerability Summary

        - 🔴 **High Severity:** ${HIGH_VULNS:-0}
        - 🟡 **Medium Severity:** ${MEDIUM_VULNS:-0}
        - 🟢 **Low Severity:** ${LOW_VULNS:-0}

        ## Recommendations

        $(if [ "${HIGH_VULNS:-0}" -gt 0 ]; then
            echo "⚠️ **CRITICAL:** High severity vulnerabilities detected. Immediate action required."
        elif [ "${MEDIUM_VULNS:-0}" -gt 5 ]; then
            echo "⚠️ **WARNING:** Multiple medium severity vulnerabilities detected."
        else
            echo "✅ **GOOD:** No critical vulnerabilities detected."
        fi)
        EOF

    - name: Upload scan results
      uses: actions/upload-artifact@v3
      if: always()
      with:
        name: security-scan-results
        path: scan-reports/

    - name: Create issue for high severity vulnerabilities
      if: env.HIGH_VULNS > 0
      uses: actions/github-script@v6
      with:
        script: |
          const fs = require('fs');
          const summary = fs.readFileSync('scan-reports/summary.md', 'utf8');

          github.rest.issues.create({
            owner: context.repo.owner,
            repo: context.repo.repo,
            title: `🚨 High Severity Vulnerabilities Detected - ${process.env.HIGH_VULNS} issues`,
            body: summary,
            labels: ['security', 'vulnerability', 'high-priority']
          });

    - name: Fail workflow on high severity vulnerabilities
      if: env.HIGH_VULNS > 0
      run: |
        echo "❌ High severity vulnerabilities detected: $HIGH_VULNS"
        echo "Security scan failed due to critical vulnerabilities"
        exit 1

Solución de problemas

Cuestiones comunes

# Service startup issues
sudo systemctl status gvmd
sudo systemctl status gsad
sudo systemctl status ospd-openvas

# Check logs
sudo journalctl -u gvmd -f
sudo journalctl -u gsad -f
sudo journalctl -u ospd-openvas -f

# Database issues
sudo -u gvm gvmd --rebuild

# Feed synchronization issues
sudo greenbone-nvt-sync
sudo greenbone-scapdata-sync
sudo greenbone-certdata-sync

# Permission issues
sudo chown -R gvm:gvm /var/lib/gvm
sudo chown -R gvm:gvm /var/log/gvm

# Port conflicts
sudo ss -tulpn | grep 9392
sudo ss -tulpn | grep 9390

Optimización del rendimiento

# Increase scanner performance
sudo systemctl edit ospd-openvas
# Add:
[Service]
ExecStart=
ExecStart=/usr/bin/ospd-openvas --pid-file /var/run/ospd-openvas.pid --log-file /var/log/gvm/ospd-openvas.log --lock-file-dir /var/lib/openvas --socket-mode 0o770 --mqtt-broker-address localhost --mqtt-broker-port 1883 --notus-feed-dir /var/lib/notus/advisories --max-scans 3

# Database optimization
sudo -u postgres psql gvmd -c "VACUUM ANALYZE;"

# Disk space management
sudo find /var/lib/gvm -name "*.log" -mtime +30 -delete

This comprehensive OpenVAS ofrece todo lo necesario para la evaluación de la vulnerabilidad profesional, desde la instalación básica hasta escenarios de automatización avanzada y de integración CI/CD.