Zum Inhalt

Nessus Cheatsheet

- :material-content-copy: **[Kopieren auf Clipboard](https://__LINK_0_____** - :material-file-pdf-box:*[PDF herunterladen](__LINK_0____**

Überblick

Nessus ist eine umfassende Sicherheitsbewertungslösung, die von Tenable entwickelt wurde. Es ist einer der am weitesten verbreiteten kommerziellen Sicherheitsscanner, bietet umfangreiche Sicherheitserkennungsfunktionen, Compliance-Check und detaillierte Berichterstattung für Unternehmensumgebungen.

Schlüsselmerkmale

  • ** Umfassende Schwachstellenerkennung*: 150.000+ Sicherheitskontrollen
  • *Compliance Scanning: PCI DSS, HIPAA, SOX, NIST, CIS Benchmarks
  • Web Application Scanning: OWASP Top 10 und benutzerdefinierte Web App Tests
  • *Konfiguration Auditing: Systemkonfiguration und -konformität
  • *Credentialed Scanning: Authentifizierte Scans für tiefere Analysen
  • Cloud Security: AWS, Azure, GCP Sicherheitsbewertungen
  • *Mobile Device Scanning: iOS und Android-Sicherheitsbewertung
  • *Industrial Control Systems: SCADA und ICS Security Scannen

Installation

Nessus Essentials (kostenlos)

```bash

Download Nessus Essentials (free for up to 16 IPs)

Visit: https://www.tenable.com/products/nessus/nessus-essentials

Linux installation

wget https://www.tenable.com/downloads/api/v1/public/pages/nessus/downloads/[VERSION]/Nessus-[VERSION]-ubuntu1404_amd64.deb sudo dpkg -i Nessus-[VERSION]-ubuntu1404_amd64.deb

Start Nessus service

sudo systemctl start nessusd sudo systemctl enable nessusd

Access web interface

https://localhost:8834

```_

Nessus Professional

```bash

Download Nessus Professional

Requires license key from Tenable

Ubuntu/Debian installation

wget https://www.tenable.com/downloads/api/v1/public/pages/nessus/downloads/[VERSION]/Nessus-[VERSION]-ubuntu1404_amd64.deb sudo dpkg -i Nessus-[VERSION]-ubuntu1404_amd64.deb

CentOS/RHEL installation

wget https://www.tenable.com/downloads/api/v1/public/pages/nessus/downloads/[VERSION]/Nessus-[VERSION]-es8.x86_64.rpm sudo rpm -ivh Nessus-[VERSION]-es8.x86_64.rpm

Start services

sudo systemctl start nessusd sudo systemctl enable nessusd

Check service status

sudo systemctl status nessusd ```_

Docker Installation

```bash

Pull Nessus Docker image (requires license)

docker pull tenable/nessus:latest

Run Nessus container

docker run -d \ --name nessus \ -p 8834:8834 \ -e NESSUS_LICENSE_KEY="your-license-key" \ -e NESSUS_ADMIN_USER="admin" \ -e NESSUS_ADMIN_PASSWORD="password" \ -v nessus-data:/opt/nessus/var/nessus \ tenable/nessus:latest

Check container status

docker ps docker logs nessus

Access web interface

https://localhost:8834

```_

Windows Installation

```powershell

Download Windows installer

https://www.tenable.com/downloads/nessus

Silent installation

Nessus-[VERSION]-x64.msi /quiet

Start Nessus service

net start "Tenable Nessus"

Configure Windows Firewall

netsh advfirewall firewall add rule name="Nessus" dir=in action=allow protocol=TCP localport=8834 ```_

Erstkonfiguration

Web Interface Setup

```bash

Access Nessus web interface

https://localhost:8834

Initial setup steps:

1. Create admin account

2. Enter license key (if applicable)

3. Download and install plugins

4. Configure scanner settings

```_

Konfiguration der Befehlszeile

```bash

Nessus CLI commands

sudo /opt/nessus/sbin/nessuscli

Add user

sudo /opt/nessus/sbin/nessuscli adduser username

Change password

sudo /opt/nessus/sbin/nessuscli chpasswd username

List users

sudo /opt/nessus/sbin/nessuscli lsuser

Remove user

sudo /opt/nessus/sbin/nessuscli rmuser username

Update plugins

sudo /opt/nessus/sbin/nessuscli update

Fix plugin database

sudo /opt/nessus/sbin/nessuscli fix

Show plugin feed info

sudo /opt/nessus/sbin/nessuscli feed ```_

Lizenzverwaltung

```bash

Register Nessus with activation code

sudo /opt/nessus/sbin/nessuscli fetch --register XXXX-XXXX-XXXX-XXXX

Register with challenge code

sudo /opt/nessus/sbin/nessuscli fetch --challenge

Show current license

sudo /opt/nessus/sbin/nessuscli fetch --check

Offline registration

sudo /opt/nessus/sbin/nessuscli fetch --register-offline nessus.license ```_

Basic Scanning

Quick Network Scan

```bash

Basic network discovery scan

Target: 192.168.1.0/24

Policy: Basic Network Scan

Via web interface:

1. New Scan → Basic Network Scan

2. Enter target: 192.168.1.0/24

3. Configure credentials (optional)

4. Launch scan

```_

Host Discovery

```bash

Ping sweep scan

Policy: Host Discovery

Target: 192.168.1.1-254

Advanced settings:

- Port scan range: 1-1000

- Ping methods: TCP, UDP, ICMP

- Performance: Normal

```_

Web Application Scan

```bash

Web application vulnerability scan

Target: https://example.com

Policy: Web Application Tests

Configuration:

- Enable web app tests

- Configure authentication

- Set crawling depth

- Enable OWASP Top 10 checks

```_

Erweitertes Scannen

Erstelltes Scannen

Windows Credentials

```bash

Windows SMB credentials

Username: DOMAIN\username or username

Password: password

Domain: DOMAIN (optional)

Registry settings for credentialed scans:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

LocalAccountTokenFilterPolicy = 1 (DWORD)

Enable WMI and disable UAC for better results

```_

Linux/Unix Credentials

```bash

SSH credentials

Username: scanuser

Password: password

Private key: (optional)

Sudo configuration for Nessus user

echo "scanuser ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers

SSH key-based authentication

ssh-keygen -t rsa -b 2048 -f nessus_key ssh-copy-id -i nessus_key.pub scanuser@target

Use private key in Nessus credential configuration

```_

Datenbank-Erfassungen

```bash

MySQL credentials

Username: nessus_user

Password: password

Port: 3306

PostgreSQL credentials

Username: postgres

Password: password

Database: postgres

Port: 5432

Oracle credentials

Username: system

Password: password

SID: ORCL

Port: 1521

```_

Kundenspezifische Scan-Policies

```bash

Create custom scan policy

1. Policies → New Policy

2. Advanced Scan template

3. Configure settings:

Discovery settings:

- Port scan range: 1-65535

- Port scan type: SYN scan

- Network ping type: ICMP & TCP

Assessment settings:

- Accuracy: Show potential false alarms

- Thoroughness: Perform thorough tests

- Scan for malware: Yes

Report settings:

- Output: Verbose

- Process scan time details: Yes

- Scan type: Normal

```_

Compliance Scannen

```bash

PCI DSS compliance scan

Policy: PCI DSS Audit

Requirements: PCI DSS v3.2.1

NIST compliance scan

Policy: NIST Cybersecurity Framework

Controls: NIST 800-53

CIS benchmark scan

Policy: CIS Benchmark

Operating system: Windows/Linux

Benchmark version: Latest

Custom compliance audit

Upload .audit file

Configure compliance checks

Set remediation priorities

```_

API Integration

REST API Basics

```python

!/usr/bin/env python3

nessus-api.py

import requests import json import time import urllib3 from urllib3.exceptions import InsecureRequestWarning

Disable SSL warnings

urllib3.disable_warnings(InsecureRequestWarning)

class NessusAPI: def init(self, host, port=8834, verify_ssl=False): self.host = host self.port = port self.verify_ssl = verify_ssl self.base_url = f"https://{host}:{port}" self.token = None self.session = requests.Session() self.session.verify = verify_ssl

def login(self, username, password):
    """Authenticate with Nessus"""
    url = f"{self.base_url}/session"
    data = {
        'username': username,
        'password': password
    }

    try:
        response = self.session.post(url, json=data)
        response.raise_for_status()

        self.token = response.json()['token']
        self.session.headers.update({'X-Cookie': f'token={self.token}'})
        print("✅ Successfully authenticated with Nessus")
        return True

    except requests.exceptions.RequestException as e:
        print(f"❌ Authentication failed: {e}")
        return False

def logout(self):
    """Logout from Nessus"""
    if self.token:
        url = f"{self.base_url}/session"
        try:
            self.session.delete(url)
            print("👋 Logged out from Nessus")
        except:
            pass
        finally:
            self.token = None

def get_scanners(self):
    """Get list of available scanners"""
    url = f"{self.base_url}/scanners"
    response = self.session.get(url)
    response.raise_for_status()
    return response.json()['scanners']

def get_policies(self):
    """Get list of scan policies"""
    url = f"{self.base_url}/policies"
    response = self.session.get(url)
    response.raise_for_status()
    return response.json()['policies']

def create_scan(self, name, targets, policy_id, folder_id=None):
    """Create a new scan"""
    url = f"{self.base_url}/scans"

    data = {
        'uuid': policy_id,
        'settings': {
            'name': name,
            'text_targets': targets,
            'folder_id': folder_id or 0
        }
    }

    response = self.session.post(url, json=data)
    response.raise_for_status()

    scan_id = response.json()['scan']['id']
    print(f"✅ Scan created with ID: {scan_id}")
    return scan_id

def launch_scan(self, scan_id):
    """Launch a scan"""
    url = f"{self.base_url}/scans/{scan_id}/launch"
    response = self.session.post(url)
    response.raise_for_status()

    scan_uuid = response.json()['scan_uuid']
    print(f"🚀 Scan launched with UUID: {scan_uuid}")
    return scan_uuid

def get_scan_status(self, scan_id):
    """Get scan status"""
    url = f"{self.base_url}/scans/{scan_id}"
    response = self.session.get(url)
    response.raise_for_status()

    scan_info = response.json()['info']
    return {
        'status': scan_info['status'],
        'progress': scan_info.get('progress', 0),
        'start_time': scan_info.get('scan_start'),
        'end_time': scan_info.get('scan_end')
    }

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

    while True:
        status_info = self.get_scan_status(scan_id)
        status = status_info['status']
        progress = status_info['progress']

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

        if status in ['completed', 'canceled', 'aborted']:
            print(f"✅ Scan finished with status: {status}")
            return status

        time.sleep(check_interval)

def get_scan_results(self, scan_id):
    """Get scan results"""
    url = f"{self.base_url}/scans/{scan_id}"
    response = self.session.get(url)
    response.raise_for_status()
    return response.json()

def export_scan(self, scan_id, format_type='nessus'):
    """Export scan results"""
    url = f"{self.base_url}/scans/{scan_id}/export"

    data = {
        'format': format_type  # nessus, pdf, html, csv, db
    }

    response = self.session.post(url, json=data)
    response.raise_for_status()

    file_id = response.json()['file']
    print(f"📄 Export initiated with file ID: {file_id}")
    return file_id

def download_export(self, scan_id, file_id, filename):
    """Download exported scan results"""
    # Check export status
    while True:
        url = f"{self.base_url}/scans/{scan_id}/export/{file_id}/status"
        response = self.session.get(url)
        response.raise_for_status()

        status = response.json()['status']
        if status == 'ready':
            break
        elif status == 'error':
            raise Exception("Export failed")

        print(f"⏳ Export status: {status}")
        time.sleep(5)

    # Download file
    url = f"{self.base_url}/scans/{scan_id}/export/{file_id}/download"
    response = self.session.get(url)
    response.raise_for_status()

    with open(filename, 'wb') as f:
        f.write(response.content)

    print(f"💾 Results saved to: {filename}")

def get_vulnerabilities(self, scan_id, severity_filter=None):
    """Get vulnerabilities from scan results"""
    results = self.get_scan_results(scan_id)
    vulnerabilities = []

    if 'vulnerabilities' in results:
        for vuln in results['vulnerabilities']:
            if severity_filter is None or vuln['severity'] >= severity_filter:
                vulnerabilities.append({
                    'plugin_id': vuln['plugin_id'],
                    'plugin_name': vuln['plugin_name'],
                    'severity': vuln['severity'],
                    'count': vuln['count']
                })

    return vulnerabilities

def get_host_vulnerabilities(self, scan_id, host_id):
    """Get vulnerabilities for specific host"""
    url = f"{self.base_url}/scans/{scan_id}/hosts/{host_id}"
    response = self.session.get(url)
    response.raise_for_status()
    return response.json()

def analyze_scan_results(self, scan_id):
    """Analyze and summarize scan results"""
    results = self.get_scan_results(scan_id)

    print("\n=== Scan Results Analysis ===")
    print(f"Scan Name: {results['info']['name']}")
    print(f"Target: {results['info']['targets']}")
    print(f"Status: {results['info']['status']}")

    # Vulnerability summary
    if 'vulnerabilities' in results:
        severity_counts = {'Critical': 0, 'High': 0, 'Medium': 0, 'Low': 0, 'Info': 0}

        for vuln in results['vulnerabilities']:
            severity = vuln['severity']
            if severity == 4:
                severity_counts['Critical'] += vuln['count']
            elif severity == 3:
                severity_counts['High'] += vuln['count']
            elif severity == 2:
                severity_counts['Medium'] += vuln['count']
            elif severity == 1:
                severity_counts['Low'] += vuln['count']
            else:
                severity_counts['Info'] += vuln['count']

        total_vulns = sum(severity_counts.values())
        print(f"\n📊 Total vulnerabilities: {total_vulns}")
        print(f"🔴 Critical: {severity_counts['Critical']}")
        print(f"🟠 High: {severity_counts['High']}")
        print(f"🟡 Medium: {severity_counts['Medium']}")
        print(f"🟢 Low: {severity_counts['Low']}")
        print(f"ℹ️  Info: {severity_counts['Info']}")

    # Host summary
    if 'hosts' in results:
        print(f"\n🖥️  Hosts scanned: {len(results['hosts'])}")

        for host in results['hosts'][:5]:  # Show first 5 hosts
            print(f"   - {host['hostname']} ({host.get('operating_system', 'Unknown OS')})")

    return results

def main(): # Configuration NESSUS_HOST = "localhost" NESSUS_PORT = 8834 USERNAME = "admin" PASSWORD = "password"

# Initialize API client
nessus = NessusAPI(NESSUS_HOST, NESSUS_PORT)

try:
    # Login
    if not nessus.login(USERNAME, PASSWORD):
        return

    # Get available policies
    policies = nessus.get_policies()
    print("\n📋 Available policies:")
    for policy in policies:
        print(f"   - {policy['name']} (ID: {policy['template_uuid']})")

    # Use Basic Network Scan policy
    basic_scan_uuid = "731a8e52-3ea6-a291-ec0a-d2ff0619c19d7bd788d6"

    # Create and launch scan
    scan_name = "API Automated Scan"
    targets = "192.168.1.0/24"

    scan_id = nessus.create_scan(scan_name, targets, basic_scan_uuid)
    scan_uuid = nessus.launch_scan(scan_id)

    # Wait for completion
    final_status = nessus.wait_for_scan_completion(scan_id)

    if final_status == 'completed':
        # Analyze results
        nessus.analyze_scan_results(scan_id)

        # Export results
        file_id = nessus.export_scan(scan_id, 'pdf')
        nessus.download_export(scan_id, file_id, f"scan_results_{scan_id}.pdf")

        # Export as Nessus format
        file_id = nessus.export_scan(scan_id, 'nessus')
        nessus.download_export(scan_id, file_id, f"scan_results_{scan_id}.nessus")

except Exception as e:
    print(f"❌ Error: {e}")
finally:
    nessus.logout()

if name == "main": main() ```_

Bulk Scanning Skript

```python

!/usr/bin/env python3

nessus-bulk-scan.py

import csv import json import time from datetime import datetime from nessus_api import NessusAPI # Import from previous script

class NessusBulkScanner: def init(self, host, port=8834): self.nessus = NessusAPI(host, port) self.scan_results = []

def login(self, username, password):
    return self.nessus.login(username, password)

def load_targets_from_csv(self, csv_file):
    """Load scan targets from CSV file"""
    targets = []

    with open(csv_file, 'r') as f:
        reader = csv.DictReader(f)
        for row in reader:
            targets.append({
                'name': row['name'],
                'targets': row['targets'],
                'policy': row.get('policy', 'basic'),
                'credentials': row.get('credentials', ''),
                'priority': int(row.get('priority', 1))
            })

    # Sort by priority
    targets.sort(key=lambda x: x['priority'])
    return targets

def create_scan_batch(self, targets_list, max_concurrent=3):
    """Create multiple scans with concurrency control"""
    scan_jobs = []

    for target in targets_list:
        # Select policy based on target configuration
        policy_uuid = self.get_policy_uuid(target['policy'])

        # Create scan
        scan_id = self.nessus.create_scan(
            name=target['name'],
            targets=target['targets'],
            policy_id=policy_uuid
        )

        scan_jobs.append({
            'scan_id': scan_id,
            'name': target['name'],
            'targets': target['targets'],
            'status': 'created'
        })

    return scan_jobs

def get_policy_uuid(self, policy_name):
    """Get policy UUID by name"""
    policy_mapping = {
        'basic': '731a8e52-3ea6-a291-ec0a-d2ff0619c19d7bd788d6',
        'advanced': 'ad629e16-03b6-8c1d-cef6-ef8c9dd3c658d24bd260',
        'web': '4be40e2d-a9b8-4e3e-8e9f-1b2c3d4e5f6g',
        'compliance': '5cf50f3e-b0c9-5f4f-9f0g-2c3d4e5f6g7h'
    }

    return policy_mapping.get(policy_name, policy_mapping['basic'])

def launch_scans_with_throttling(self, scan_jobs, max_concurrent=3, delay=60):
    """Launch scans with throttling to avoid overloading"""
    active_scans = []
    completed_scans = []
    pending_scans = scan_jobs.copy()

    print(f"🚀 Starting bulk scan with max {max_concurrent} concurrent scans")

    while pending_scans or active_scans:
        # Launch new scans if under limit
        while len(active_scans) < max_concurrent and pending_scans:
            scan_job = pending_scans.pop(0)

            try:
                scan_uuid = self.nessus.launch_scan(scan_job['scan_id'])
                scan_job['scan_uuid'] = scan_uuid
                scan_job['status'] = 'running'
                scan_job['start_time'] = datetime.now()
                active_scans.append(scan_job)

                print(f"▶️  Launched: {scan_job['name']}")

                # Delay between launches
                if pending_scans:
                    time.sleep(delay)

            except Exception as e:
                print(f"❌ Failed to launch {scan_job['name']}: {e}")
                scan_job['status'] = 'failed'
                completed_scans.append(scan_job)

        # Check status of active scans
        for scan_job in active_scans.copy():
            try:
                status_info = self.nessus.get_scan_status(scan_job['scan_id'])
                scan_job['progress'] = status_info['progress']

                if status_info['status'] in ['completed', 'canceled', 'aborted']:
                    scan_job['status'] = status_info['status']
                    scan_job['end_time'] = datetime.now()
                    active_scans.remove(scan_job)
                    completed_scans.append(scan_job)

                    print(f"✅ Completed: {scan_job['name']} ({scan_job['status']})")

            except Exception as e:
                print(f"❌ Error checking {scan_job['name']}: {e}")

        # Status update
        if active_scans:
            print(f"📊 Active: {len(active_scans)}, Pending: {len(pending_scans)}, Completed: {len(completed_scans)}")
            for scan in active_scans:
                print(f"   - {scan['name']}: {scan['progress']}%")

        time.sleep(30)  # Check every 30 seconds

    return completed_scans

def generate_bulk_report(self, completed_scans, output_dir="./bulk_scan_results"):
    """Generate comprehensive report for all scans"""
    import os
    os.makedirs(output_dir, exist_ok=True)

    summary_data = []

    for scan_job in completed_scans:
        if scan_job['status'] == 'completed':
            try:
                # Analyze scan results
                results = self.nessus.analyze_scan_results(scan_job['scan_id'])

                # Extract summary data
                vuln_summary = self.extract_vulnerability_summary(results)

                summary_data.append({
                    'scan_name': scan_job['name'],
                    'targets': scan_job['targets'],
                    'start_time': scan_job['start_time'].isoformat(),
                    'end_time': scan_job['end_time'].isoformat(),
                    'duration': str(scan_job['end_time'] - scan_job['start_time']),
                    **vuln_summary
                })

                # Export individual reports
                file_id = self.nessus.export_scan(scan_job['scan_id'], 'pdf')
                filename = f"{output_dir}/scan_{scan_job['scan_id']}.pdf"
                self.nessus.download_export(scan_job['scan_id'], file_id, filename)

            except Exception as e:
                print(f"❌ Error processing {scan_job['name']}: {e}")

    # Generate summary CSV
    summary_file = f"{output_dir}/bulk_scan_summary.csv"
    with open(summary_file, 'w', newline='') as f:
        if summary_data:
            writer = csv.DictWriter(f, fieldnames=summary_data[0].keys())
            writer.writeheader()
            writer.writerows(summary_data)

    print(f"📊 Bulk scan summary saved to: {summary_file}")
    return summary_data

def extract_vulnerability_summary(self, results):
    """Extract vulnerability summary from scan results"""
    summary = {
        'total_hosts': 0,
        'critical_vulns': 0,
        'high_vulns': 0,
        'medium_vulns': 0,
        'low_vulns': 0,
        'info_vulns': 0
    }

    if 'hosts' in results:
        summary['total_hosts'] = len(results['hosts'])

    if 'vulnerabilities' in results:
        for vuln in results['vulnerabilities']:
            severity = vuln['severity']
            count = vuln['count']

            if severity == 4:
                summary['critical_vulns'] += count
            elif severity == 3:
                summary['high_vulns'] += count
            elif severity == 2:
                summary['medium_vulns'] += count
            elif severity == 1:
                summary['low_vulns'] += count
            else:
                summary['info_vulns'] += count

    return summary

def main(): # Configuration NESSUS_HOST = "localhost" USERNAME = "admin" PASSWORD = "password" TARGETS_CSV = "scan_targets.csv"

# Create sample CSV file
sample_targets = [
    {
        'name': 'DMZ Network Scan',
        'targets': '10.0.1.0/24',
        'policy': 'advanced',
        'priority': 1
    },
    {
        'name': 'Internal Network Scan',
        'targets': '192.168.1.0/24',
        'policy': 'basic',
        'priority': 2
    },
    {
        'name': 'Web Servers Scan',
        'targets': '10.0.2.10-20',
        'policy': 'web',
        'priority': 1
    }
]

# Create CSV file
with open(TARGETS_CSV, 'w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=['name', 'targets', 'policy', 'priority'])
    writer.writeheader()
    writer.writerows(sample_targets)

print(f"📄 Sample targets file created: {TARGETS_CSV}")

# Initialize bulk scanner
bulk_scanner = NessusBulkScanner(NESSUS_HOST)

try:
    # Login
    if not bulk_scanner.login(USERNAME, PASSWORD):
        return

    # Load targets
    targets = bulk_scanner.load_targets_from_csv(TARGETS_CSV)
    print(f"📋 Loaded {len(targets)} scan targets")

    # Create scan jobs
    scan_jobs = bulk_scanner.create_scan_batch(targets)

    # Launch scans with throttling
    completed_scans = bulk_scanner.launch_scans_with_throttling(
        scan_jobs, 
        max_concurrent=2,
        delay=30
    )

    # Generate reports
    summary_data = bulk_scanner.generate_bulk_report(completed_scans)

    print(f"\n🎉 Bulk scanning completed!")
    print(f"📊 Processed {len(completed_scans)} scans")

except Exception as e:
    print(f"❌ Error: {e}")
finally:
    bulk_scanner.nessus.logout()

if name == "main": main() ```_

CI/CD Integration

Jenkins Pipeline

```groovy // Jenkinsfile for Nessus security scanning pipeline { agent any

parameters {
    string(name: 'TARGET_HOSTS', defaultValue: '192.168.1.0/24', description: 'Target hosts to scan')
    choice(name: 'SCAN_TYPE', choices: ['basic', 'advanced', 'web', 'compliance'], description: 'Type of scan to perform')
    booleanParam(name: 'FAIL_ON_HIGH', defaultValue: true, description: 'Fail build on high severity vulnerabilities')
}

environment {
    NESSUS_HOST = 'nessus.internal.com'
    NESSUS_CREDS = credentials('nessus-credentials')
    SCAN_NAME = "Jenkins-${env.BUILD_NUMBER}-${params.SCAN_TYPE}"
}

stages {
    stage('Setup') {
        steps {
            script {
                // Install Python dependencies
                sh '''
                    pip3 install requests urllib3
                    python3 --version
                '''
            }
        }
    }

    stage('Nessus Scan') {
        steps {
            script {
                // Run Nessus scan
                def scanResult = sh(
                    script: """
                        python3 << 'EOF'

import os import sys sys.path.append('${WORKSPACE}') from nessus_api import NessusAPI

Configuration

nessus = NessusAPI('${NESSUS_HOST}')

try: # Login if not nessus.login('${NESSUS_CREDS_USR}', '${NESSUS_CREDS_PSW}'): sys.exit(1)

# Get policy UUID
policy_mapping = {
    'basic': '731a8e52-3ea6-a291-ec0a-d2ff0619c19d7bd788d6',
    'advanced': 'ad629e16-03b6-8c1d-cef6-ef8c9dd3c658d24bd260',
    'web': '4be40e2d-a9b8-4e3e-8e9f-1b2c3d4e5f6g',
    'compliance': '5cf50f3e-b0c9-5f4f-9f0g-2c3d4e5f6g7h'
}

policy_uuid = policy_mapping.get('${params.SCAN_TYPE}', policy_mapping['basic'])

# Create and launch scan
scan_id = nessus.create_scan('${SCAN_NAME}', '${params.TARGET_HOSTS}', policy_uuid)
nessus.launch_scan(scan_id)

# Wait for completion
status = nessus.wait_for_scan_completion(scan_id)

if status == 'completed':
    # Analyze results
    results = nessus.analyze_scan_results(scan_id)

    # Export reports
    file_id = nessus.export_scan(scan_id, 'pdf')
    nessus.download_export(scan_id, file_id, 'nessus_report.pdf')

    file_id = nessus.export_scan(scan_id, 'csv')
    nessus.download_export(scan_id, file_id, 'nessus_results.csv')

    # Get vulnerability counts
    vulns = nessus.get_vulnerabilities(scan_id)
    critical_count = len([v for v in vulns if v['severity'] == 4])
    high_count = len([v for v in vulns if v['severity'] == 3])

    # Save results for Jenkins
    with open('scan_summary.txt', 'w') as f:
        f.write(f"CRITICAL_VULNS={critical_count}\\n")
        f.write(f"HIGH_VULNS={high_count}\\n")
        f.write(f"SCAN_STATUS={status}\\n")

    print(f"Scan completed: Critical={critical_count}, High={high_count}")

else:
    print(f"Scan failed with status: {status}")
    sys.exit(1)

except Exception as e: print(f"Error: {e}") sys.exit(1) finally: nessus.logout() EOF """, returnStatus: true )

                if (scanResult != 0) {
                    error("Nessus scan failed")
                }
            }
        }
    }

    stage('Process Results') {
        steps {
            script {
                // Read scan results
                def scanSummary = readFile('scan_summary.txt')
                def criticalVulns = (scanSummary =~ /CRITICAL_VULNS=(\d+)/)[0][1] as Integer
                def highVulns = (scanSummary =~ /HIGH_VULNS=(\d+)/)[0][1] as Integer

                // Set build description
                currentBuild.description = "Critical: ${criticalVulns}, High: ${highVulns}"

                // Archive reports
                archiveArtifacts artifacts: 'nessus_report.pdf,nessus_results.csv', fingerprint: true

                // Publish results
                publishHTML([
                    allowMissing: false,
                    alwaysLinkToLastBuild: true,
                    keepAll: true,
                    reportDir: '.',
                    reportFiles: 'nessus_report.pdf',
                    reportName: 'Nessus Security Report'
                ])

                // Check failure conditions

| if (params.FAIL_ON_HIGH && (criticalVulns > 0 | | highVulns > 0)) { | currentBuild.result = 'FAILURE' error("High severity vulnerabilities detected: Critical=${criticalVulns}, High=${highVulns}") }

                // Send notifications
                if (criticalVulns > 0) {
                    slackSend(
                        channel: '#security',
                        color: 'danger',
                        message: "🚨 Critical vulnerabilities detected in ${params.TARGET_HOSTS}: ${criticalVulns} critical, ${highVulns} high"
                    )
                }
            }
        }
    }
}

post {
    always {
        // Cleanup
        sh 'rm -f scan_summary.txt nessus_report.pdf nessus_results.csv'
    }

    success {
        echo "Security scan completed successfully"
    }

    failure {
        echo "Security scan failed or found critical vulnerabilities"
    }
}

} ```_

Fehlerbehebung

Gemeinsame Themen

```bash

Service not starting

sudo systemctl status nessusd sudo journalctl -u nessusd -f

Check Nessus logs

sudo tail -f /opt/nessus/var/nessus/logs/nessusd.messages

Plugin update issues

sudo /opt/nessus/sbin/nessuscli update sudo /opt/nessus/sbin/nessuscli fix

License issues

sudo /opt/nessus/sbin/nessuscli fetch --check sudo /opt/nessus/sbin/nessuscli fetch --register NEW-LICENSE-KEY

Port conflicts

sudo ss -tulpn | grep 8834 sudo netstat -tulpn | grep 8834

Reset admin password

sudo /opt/nessus/sbin/nessuscli chpasswd admin

Database corruption

sudo service nessusd stop sudo /opt/nessus/sbin/nessuscli fix sudo service nessusd start ```_

Leistungsoptimierung

```bash

Increase scan performance

Edit /opt/nessus/etc/nessus/nessusd.conf

Max hosts per scan

max_hosts = 100

Max checks per host

max_checks = 10

Scan timeout

checks_read_timeout = 300

Memory optimization

optimize_test = yes

Network timeout

network_receive_timeout = 5

Restart service after changes

sudo systemctl restart nessusd ```_

Speicher und Disk Management

```bash

Monitor Nessus resource usage

ps aux | grep nessus top -p $(pgrep nessusd)

Check disk space

df -h /opt/nessus du -sh /opt/nessus/var/nessus/logs

Clean old logs

sudo find /opt/nessus/var/nessus/logs -name "*.log" -mtime +30 -delete

Clean old scan results

sudo find /opt/nessus/var/nessus/users -name "*.db" -mtime +90 -delete

Backup configuration

sudo tar -czf nessus-backup-$(date +%Y%m%d).tar.gz /opt/nessus/etc/nessus/ ```_

Dieses umfassende Nessus-Catsheet bietet alles, was für eine professionelle Sicherheitsbewertung erforderlich ist, von der Grundinstallation bis hin zu fortschrittlichen Automatisierungs- und Unternehmensintegrationsszenarien.