OpenVAS Cheatsheet
%20Überblick
OpenVAS%20(Open%20Vulnerability%20Assessment%20System) ist eine umfassende Lösung für Sicherheitsscanner und Sicherheitsmanagement. Es ist Teil des Greenbone Vulnerability Management (GVM) Frameworks und bietet leistungsstarke Fähigkeiten zur Erkennung von Sicherheitslücken in Netzwerken, Systemen und Anwendungen.
Schlüsselmerkmale
- *Comprehensive Scanning: Netzwerklückenerkennung und -bewertung
- *Extensive NVT Datenbank: Über 50.000 Netzwerk-Verwundbarkeitstests (NVT)
- Web Interface: Benutzerfreundlicher Greenbone Security Assistant (GSA)
- Flexible Reporting: Mehrere Berichtsformate und Anpassungsmöglichkeiten
- *Compliance Scanning: Unterstützung verschiedener Compliance-Frames
- *Authenticated Scanning: Erstellen von Scans für tiefere Analysen
- API Integration: REST API für Automatisierung und Integration
Installation
Docker Installation (empfohlen)
```bash
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 ```_
Ubuntu/Debian Installation
```bash
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 Installation
```bash
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 ```_
Quelle Installation
```bash
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 ```_
Grundkonfiguration
Erster Setup
```bash
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 ```_
Web Interface Zugriff
```bash
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 ```_
Kommandozeilenschnittstelle
```bash
GVM CLI installation
pip3 install gvm-tools
Connect to GVM daemon
gvm-cli socket --xml "
Connect via TLS
gvm-cli tls --hostname localhost --port 9390 --xml "
Interactive mode
gvm-cli socket --xml ```_
Scannen von Operationen
Zielkonfiguration
```bash
Create target via CLI
gvm-cli socket --xml '
Create target with credentials
gvm-cli socket --xml '
List existing targets
gvm-cli socket --xml '
Scan-Konfiguration
```bash
Create scan configuration
gvm-cli socket --xml '
Modify scan configuration
gvm-cli socket --xml '
List scan configurations
gvm-cli socket --xml '
Aufgabenmanagement
```bash
Create scan task
gvm-cli socket --xml '
Start scan task
gvm-cli socket --xml '
Stop scan task
gvm-cli socket --xml '
Resume scan task
gvm-cli socket --xml '
Delete scan task
gvm-cli socket --xml '
List all tasks
gvm-cli socket --xml '
Get task status
gvm-cli socket --xml '
Gründungsmanagement
```bash
Create SSH credential
gvm-cli socket --xml '
Create SSH key credential
gvm-cli socket --xml '
Create Windows credential
gvm-cli socket --xml '
List credentials
gvm-cli socket --xml '
Erweitertes Scannen
Authenticed Scanning
```bash
Linux authenticated scan setup
gvm-cli socket --xml '
Windows authenticated scan setup
gvm-cli socket --xml '
Database credential setup
gvm-cli socket --xml '
Individuelle Portlisten
```bash
Create custom port list
gvm-cli socket --xml '
Create comprehensive port list
gvm-cli socket --xml '
List port lists
gvm-cli socket --xml '
Scannen von Timing und Performance
```bash
Create performance-optimized config
gvm-cli socket --xml '
Adjust scanner preferences
gvm-cli socket --xml '
Bericht Management
Bericht Generation
```bash
Get scan results
gvm-cli socket --xml '
Generate PDF report
gvm-cli socket --xml '
Generate XML report
gvm-cli socket --xml '
Generate CSV report
gvm-cli socket --xml '
Generate HTML report
gvm-cli socket --xml '
List all reports
gvm-cli socket --xml '
Kundenspezifische Berichtsformate
```bash
Create custom report format
gvm-cli socket --xml '
List report formats
gvm-cli socket --xml '
Filtern melden
```bash
Filter results by severity
gvm-cli socket --xml '
gvm-cli socket --xml '
gvm-cli socket --xml '
gvm-cli socket --xml '
```python 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 main():
# Configuration
USERNAME = "admin"
PASSWORD = "admin"
TARGET_NAME = "Test Network"
TARGET_HOSTS = "192.168.1.0/24" if name == "main":
main()
```_ ```bash set -e 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}" RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color 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_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 } test_connection() {
log "Testing connection to OpenVAS..." | local response=$(gvm-cli socket --xml " } create_target() {
local target_name="$1"
local target_hosts="$2" | local target_id=$(echo "$response" | grep -oP 'id="\K[^"]*' | head -1) | } create_task() {
local task_name="$1"
local target_id="$2" | local task_id=$(echo "$response" | grep -oP 'id="\K[^"]*' | head -1) | } start_scan() {
local task_id="$1" } monitor_scan() {
local task_id="$1"
local check_interval="${2:-30}" | local status=$(echo "$response" | grep -oP ' } generate_report() {
local task_id="$1"
local output_dir="$2" | local report_id=$(echo "$response" | grep -oP 'last_report.?id="\K[^"]' | head -1) | | echo "$pdf_response" | grep -oP ' } generate_summary() {
local xml_file="$1"
local summary_file="$2" Scan Date: $(date)
Target: $TARGET_HOSTS
Scan Name: $SCAN_NAME EOF | 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)) Vulnerability Summary:
- Total vulnerabilities: $total_count
- High severity: $high_count
- Medium severity: $medium_count
- Low severity: $low_count EOF | 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 } cleanup() {
local task_id="$1"
local target_id="$2" | gvm-cli socket --xml " | gvm-cli socket --xml " } main() {
log "Starting OpenVAS automated scan"
log "Target: $TARGET_HOSTS"
log "Scan Name: $SCAN_NAME" } trap 'error "Script interrupted"; exit 1' INT TERM 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 main
```_ ```yaml 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 | 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 | 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 }} ```_ ```bash sudo systemctl status gvmd
sudo systemctl status gsad
sudo systemctl status ospd-openvas sudo journalctl -u gvmd -f
sudo journalctl -u gsad -f
sudo journalctl -u ospd-openvas -f sudo -u gvm gvmd --rebuild sudo greenbone-nvt-sync
sudo greenbone-scapdata-sync
sudo greenbone-certdata-sync sudo chown -R gvm:gvm /var/lib/gvm
sudo chown -R gvm:gvm /var/log/gvm sudo ss -tulpn | grep 9392
sudo ss -tulpn | grep 9390
```_ ```bash sudo systemctl edit ospd-openvas [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 sudo -u postgres psql gvmd -c "VACUUM ANALYZE;" sudo find /var/lib/gvm -name "*.log" -mtime +30 -delete
```_ Diese umfassende OpenVAS cheatsheet bietet alles, was für eine professionelle Sicherheitsbewertung erforderlich ist, von der Grundinstallation bis hin zu fortschrittlichen Automatisierungs- und CI/CD-Integrationsszenarien.Filter by host
Filter by NVT family
Complex filtering
Automatisierungsskripte
Python Automation Script
!/usr/bin/env python3
openvas-automation.py
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")
# 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()
Bash Automation Script
!/bin/bash
openvas-scan.sh
Configuration
Colors for output
Logging function
Check if gvm-cli is available
if ! command -v xmllint &> /dev/null; then
warning "xmllint not found. Install libxml2-utils for better XML parsing"
fi
Test connection to OpenVAS
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
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")
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
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")
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
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
log "Monitoring scan progress..."
while true; do
local xml_request="<get_tasks task_id=\"$task_id\"/>"
local response=$(gvm-cli socket --xml "$xml_request")
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
log "Generating scan report..."
# Get report ID
local xml_request="<get_tasks task_id=\"$task_id\"/>"
local response=$(gvm-cli socket --xml "$xml_request")
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
# 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
log "Generating scan summary..."
cat > "$summary_file" << EOF
OpenVAS Scan Summary
if command -v xmllint &> /dev/null; then
# Count vulnerabilities by severity
cat >> "$summary_file" << 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 | \
success "Summary saved to: $summary_file"
Cleanup function
if [[ "$CLEANUP" == "true" ]]; then
log "Cleaning up scan artifacts..."
if [[ -n "$task_id" ]]; then
if [[ -n "$target_id" ]]; then
success "Cleanup completed"
fi
Main execution function
# 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
Parse command line arguments
Run main function
CI/CD Integration
GitHub Aktionen
.github/workflows/security-scan.yml
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:
# 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)
## 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
Fehlerbehebung
Gemeinsame Themen
Service startup issues
Check logs
Database issues
Feed synchronization issues
Permission issues
Port conflicts
Leistungsoptimierung
Increase scanner performance
Add:
Database optimization
Disk space management