From 262e39031f4941806e8071006ae18a1f11000806 Mon Sep 17 00:00:00 2001 From: NullSpace-BitCradle <216858096+NullSpace-BitCradle@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:09:24 -0700 Subject: [PATCH 1/9] Stop silent data loss and take paths on the command line Shared nessus_common.py holds the one 106-column spec and a streaming parser. Repeated CWE/BID values are kept, over-long XLSX cells are truncated with a visible note, every host reaches the SQL path, and formula-leading cells are neutralised. The converters accept file paths and only fall back to the picker when none are given, so they run unattended. nessus_to_sql.py now creates tables as the README says, validates existing ones, escapes identifiers and values, keeps TLS validation on, and runs one transaction per file with --dry-run to preview. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi --- nessus_common.py | 397 +++++++++++++++++++ nessus_to_csv.py | 388 +++++------------- nessus_to_sql.py | 976 ++++++++++++++++++++++------------------------ nessus_to_xlsx.py | 405 +++++++------------ 4 files changed, 1099 insertions(+), 1067 deletions(-) create mode 100644 nessus_common.py diff --git a/nessus_common.py b/nessus_common.py new file mode 100644 index 0000000..8be0dce --- /dev/null +++ b/nessus_common.py @@ -0,0 +1,397 @@ +""" +Shared code for the Nessus conversion scripts. + +Holds the one definition of the 106 output columns, the .nessus parser, the +row de-duplication, the spreadsheet-safety helper and the optional file +pickers. nessus_to_csv.py, nessus_to_xlsx.py and nessus_to_sql.py all use it, +so a fix to parsing lands in all three. + +Note: column names (e.g. pluginName, Credentialed_Scan) mirror the Nessus XML +element and attribute names for traceability back to the source format. +""" + +import hashlib +import os +import re +import sys +import xml.etree.ElementTree as ET +from datetime import datetime + +# Severity constants. +SEVERITY_MAPPING = {0: 4, 1: 3, 2: 2, 3: 1, 4: 0} +SEVERITY_RATING = {0: "Critical", 1: "High", 2: "Medium", 3: "Low", 4: "Informational"} + +# Exit codes shared by the converters. +EXIT_OK = 0 +EXIT_FAILED = 1 # bad usage, nothing to do, or every input failed +EXIT_PARTIAL = 2 # output written, but at least one input could not be read + +# Column spec: csv_name | xlsx_header | kind | key +# host first under HostProperties +# attr attribute of +# item text of the first child element named key +# multi every child element named key, joined with ", " +# output text of , stripped +# derived computed from the item/host (key names the value) +_COLUMN_SPEC = """ +host_ip|IP Address|host|host-ip +mac_address|MAC Address|host|mac-address +virtual_mac_address|Virtual MAC Address|host|virtual-mac-address +hostname|Hostname|host|hostname +netbios_name|NETBIOS|host|netbios-name +host_fqdn|FQDN|host|host-fqdn +host_rdns|RDNS|host|host-rdns +system_type|System Type|host|system-type +cpe|CPE|item|cpe +operating_system_id|OS Family|host|os +operating_system|Operating System|host|operating-system +severity_rating|Severity Rating|derived|severity_rating +risk_factor|Risk Factor|item|risk_factor +severity_reversed|Severity Number|derived|severity_reversed +pluginName|Plugin Name|attr|pluginName +synopsis|Synopsis|item|synopsis +description|Description|item|description +solution|Solution|item|solution +port|Port|attr|port +protocol|Protocol|attr|protocol +svc_name|Service Name|attr|svc_name +plugin_output|Plugin Output|output|plugin_output +plugin_type|Plugin Type|item|plugin_type +plugin_publication_date|Plugin Publication Date|item|plugin_publication_date +plugin_modification_date|Plugin Modification Date|item|plugin_modification_date +stig_severity|STIG Severity|item|stig_severity +cvss_base_score|CVSS Score|item|cvss_base_score +cvss_vector|CVSS Vector|item|cvss_vector +cvss_score_rationale|CVSS Score Rationale|item|cvss_score_rationale +cvss_score_source|CVSS Score Source|item|cvss_score_source +cvss_temporal_score|CVSS Temporal Score|item|cvss_temporal_score +cvss_temporal_vector|CVSS Temporal Vector|item|cvss_temporal_vector +cvss3_base_score|CVSS3 Score|item|cvss3_base_score +cvss3_vector|CVSS3 Vector|item|cvss3_vector +cvss3_score_source|CVSS3 Score Source|item|cvss3_score_source +cvss3_temporal_score|CVSS3 Temporal Score|item|cvss3_temporal_score +cvss3_temporal_vector|CVSS3 Temporal Vector|item|cvss3_temporal_vector +cvssV3_impactScore|CVSS3 Impact Score|item|cvssV3_impactScore +vpr_score|VPR Score|item|vpr_score +patch_publication_date|Patch Publication Date|item|patch_publication_date +patch_summary_total_cves|Patch Summary CVE Count|host|patch-summary-total-cves +vuln_publication_date|Vulnerability Publication Date|item|vuln_publication_date +age_of_vuln|Vulnerability Age|item|age_of_vuln +product_coverage|Product Coverage|item|product_coverage +exploit_available|Exploit Available|item|exploit_available +exploitability_ease|Exploitability Ease|item|exploitability_ease +exploit_code_maturity|Exploit Code Maturity|item|exploit_code_maturity +exploit_framework_canvas|Exploitable with CANVAS|item|exploit_framework_canvas +canvas_package|CANVAS Package|item|canvas_package +exploit_framework_core|Exploitable with Core Impact|item|exploit_framework_core +exploit_framework_metasploit|Exploitable with Metasploit|item|exploit_framework_metasploit +metasploit_name|Metasploit Module|item|metasploit_name +exploited_by_malware|Exploitable by Malware|item|exploited_by_malware +exploited_by_nessus|Exploitable by Nessus|item|exploited_by_nessus +edb_id|Exploit DB ID|multi|edb-id +threat_recency|Threat Recency|item|threat_recency +threat_intensity_last_28|Threat Intensity Last 28 Days|item|threat_intensity_last_28 +threat_sources_last_28|Threat Sources Last 28 Days|item|threat_sources_last_28 +local_checks_proto|Local Checks Protocol|host|local-checks-proto +smb_login_used|SMB Login Used|host|smb-login-used +wmi_domain|WMI Domain|host|wmi-domain +thorough_tests|Thorough Tests Used|item|thorough_tests +Credentialed_Scan|Credentialed Scan Used|host|Credentialed_Scan +LastAuthenticatedResults|Authentication Issues|host|LastAuthenticatedResults +policy_used|Policy Used|host|policy-used +host_start|Host Scan Started|host|HOST_START +host_start_timestamp|Host Scan Started Timestamp|host|HOST_START_TIMESTAMP +host_end|Host Scan Ended|host|HOST_END +host_end_timestamp|Host Scan Ended Timestamp|host|HOST_END_TIMESTAMP +os_identification|OS Identified|item|os_identification +operating_system_conf|Operating System Confidence|host|operating-system-conf +operating_system_method|OS Identification Method|host|operating-system-method +sinfp_signature|SinFP Signature|host|sinfp-signature +pluginID|Plugin ID|attr|pluginID +pluginFamily|Plugin Family|attr|pluginFamily +script_version|Script Version|item|script_version +agent|Agent Used|item|agent +always_run|Always Run|item|always_run +asset_inventory|Asset Inventory|item|asset_inventory +asset_inventory_category|Asset Inventory Category|item|asset_inventory_category +asset_categories|Asset Categories|item|asset_categories +hardware_inventory|Hardware Inventory|item|hardware_inventory +bid|BugtraqID|multi|bid +cea_id|CEA Id|multi|cea-id +cert|CERT|multi|cert +cisa_known_exploited|CISA Known Exploited|item|cisa-known-exploited +cisa_ncas|CISA NCAS|multi|cisa-ncas +cisco_bug_id|Cisco Bug ID|multi|cisco-bug-id +cisco_sa|Cisco Security Advisory|multi|cisco-sa +cve|CVE|multi|cve +cwe|CWE|multi|cwe +iava|IAVA|multi|iava +iavb|IAVB|multi|iavb +iavt|IAVT|multi|iavt +icsa|ICSA|multi|icsa +msft|MSFT|multi|msft +mskb|MSKB|multi|mskb +tra|Trust Research Advisory|multi|tra +vmsa|VMWare Security Advisory|multi|vmsa +secunia|Secunia Security Advisory|multi|secunia +unsupported_by_vendor|Unsupported by Vendor|item|unsupported_by_vendor +see_also|See Also|item|see_also +in_the_news|In The News|item|in_the_news +generated_plugin|Generated Plugin|item|generated_plugin +file_name|File Name|derived|file_name +scan_date|Scan Date|derived|scan_date +""" + +COLUMNS = [tuple(line.split("|")) for line in _COLUMN_SPEC.strip().splitlines()] +COLUMN_NAMES = [c[0] for c in COLUMNS] +XLSX_HEADERS = [c[1] for c in COLUMNS] +assert len(COLUMNS) == 106 and len(set(COLUMN_NAMES)) == 106 + +HOST_DATE_FORMAT = "%a %b %d %H:%M:%S %Y" +XLSX_MAX_ROWS = 1_048_576 +XLSX_MAX_CELL = 32_767 + + +class NessusParseError(Exception): + """A .nessus file could not be read or is not shaped like a Nessus report.""" + + +class RunStats: + """Counters for one conversion run.""" + + def __init__(self): + self.files_seen = 0 + self.files_ok = 0 + self.hosts = 0 + self.findings = 0 # rows read, before de-duplication + self.duplicates = 0 + self.failures = [] # list of (path, message) + + +def _text(el): + return el.text if el is not None and el.text is not None else "" + + +def parse_scan_date(host_start): + """Turn a Nessus HOST_START string into YYYY-MM-DD, or None if it will not parse.""" + if not host_start: + return None + try: + return datetime.strptime(host_start, HOST_DATE_FORMAT).strftime("%Y-%m-%d") + except ValueError: + return None + + +def _host_tags(host): + """Map HostProperties tag name -> text. The first tag of a name wins.""" + tags = {} + props = host.find("HostProperties") + if props is not None: + for tag in props.findall("tag"): + name = tag.get("name") + if name is not None and name not in tags: + tags[name] = _text(tag) + return tags + + +def _item_severity(item): + try: + severity = int(item.attrib["severity"]) + reversed_ = SEVERITY_MAPPING[severity] + except (KeyError, ValueError) as exc: + raise NessusParseError( + f"ReportItem pluginID={item.attrib.get('pluginID', '?')} has a missing or " + f"invalid severity attribute ({exc!r})" + ) from None + return SEVERITY_RATING[reversed_], reversed_ + + +def build_row(host_tags, item, file_name, scan_date): + """Build one 106-column row from a host's tags and one ReportItem.""" + rating, reversed_ = _item_severity(item) + derived = { + "severity_rating": rating, + "severity_reversed": reversed_, + "file_name": file_name, + "scan_date": scan_date, + } + row = [] + for _name, _header, kind, key in COLUMNS: + if kind == "host": + row.append(host_tags.get(key, "")) + elif kind == "attr": + row.append(item.attrib.get(key, "")) + elif kind == "item": + row.append(_text(item.find(key))) + elif kind == "multi": + row.append(", ".join(t for t in (_text(el) for el in item.findall(key)) if t)) + elif kind == "output": + row.append(_text(item.find(key)).strip()) + else: + row.append(derived[key]) + return row + + +def parse_nessus_file(path, stats=None): + """ + Parse one .nessus file and return its rows (a list of 106-column lists). + + Hosts are read one at a time and released as they are done, so the whole XML + tree is never held in memory; the rows of this one file are. Raises + NessusParseError if the file cannot be read, so the caller can skip it and + report it instead of treating the run as a success. + """ + file_name = os.path.basename(path) + rows = [] + hosts = 0 + try: + for _event, elem in ET.iterparse(path, events=("end",)): + if elem.tag != "ReportHost": + continue + hosts += 1 + tags = _host_tags(elem) + scan_date = parse_scan_date(tags.get("HOST_START", "")) + for item in elem.iter("ReportItem"): + rows.append(build_row(tags, item, file_name, scan_date)) + elem.clear() + except ET.ParseError as exc: + raise NessusParseError(f"XML error: {exc}") from None + except OSError as exc: + raise NessusParseError(f"cannot read file: {exc}") from None + if stats is not None: + stats.hosts += hosts + stats.findings += len(rows) + return rows + + +def _row_digest(row): + joined = "\x1f".join("" if v is None else str(v) for v in row) + return hashlib.blake2b(joined.encode("utf-8", "surrogatepass"), digest_size=16).digest() + + +def iter_unique_rows(files, stats, seen=None): + """ + Yield the rows of every file in order, skipping exact duplicate rows. + + A row is a duplicate only if all 106 columns match, which includes the file + name, so the same finding in two differently named files is kept. Rows come + out in file order, then host order, then finding order. Files that fail to + parse are recorded in stats.failures and skipped whole. Pass the same `seen` + set to several calls to de-duplicate across them. + """ + if seen is None: + seen = set() + for path in files: + stats.files_seen += 1 + print(f"Processing {path}") + try: + rows = parse_nessus_file(path, stats) + except NessusParseError as exc: + print(f"Error processing {path}: {exc}", file=sys.stderr) + stats.failures.append((path, str(exc))) + continue + stats.files_ok += 1 + for row in rows: + digest = _row_digest(row) + if digest in seen: + stats.duplicates += 1 + continue + seen.add(digest) + yield row + + +def collect_nessus_files(paths): + """Expand a mix of files and folders into a sorted list of .nessus files.""" + files = [] + for path in paths: + if os.path.isdir(path): + found = [] + for root_dir, dirs, names in os.walk(path): + dirs.sort() + for name in sorted(names): + if name.lower().endswith(".nessus"): + found.append(os.path.join(root_dir, name)) + files.extend(found) + elif os.path.isfile(path): + files.append(path) + else: + raise FileNotFoundError(f"No such file or folder: {path}") + return files + + +# Cells that a spreadsheet would read as a formula. +_FORMULA_LEADERS = ("=", "+", "-", "@", "\t", "\r") +_PLAIN_NUMBER = re.compile(r"[+-]?\d+(\.\d+)?") + + +def neutralize_cell(value): + """ + Stop a spreadsheet from running a text cell as a formula. + + A text value that starts with = + - @ tab or CR gets a leading apostrophe. + Plain numbers such as -5 are left alone. Plugin output, hostnames and banners + come from scanned hosts, so they can hold anything. + """ + if isinstance(value, str) and value.startswith(_FORMULA_LEADERS): + if _PLAIN_NUMBER.fullmatch(value): + return value + return "'" + value + return value + + +def format_run_metrics(start_time): + """Return the 'Elapsed time ... Peak memory ...' line.""" + import time + import psutil + elapsed = time.time() - start_time + hours = int(elapsed // 3600) + minutes = int((elapsed % 3600) // 60) + seconds = elapsed % 60 + mem_info = psutil.Process().memory_info() + peak_mb = getattr(mem_info, "peak_wset", mem_info.rss) / 1024 / 1024 + return (f"Elapsed time: {hours} hours {minutes} minutes {seconds:.2f} seconds. " + f"Peak memory usage: {peak_mb:.2f} MB.") + + +def report_failures(stats): + """Print a summary of files that failed. Returns True if there were any.""" + if not stats.failures: + return False + print(f"\n{len(stats.failures)} of {stats.files_seen} file(s) could not be processed:", + file=sys.stderr) + for path, message in stats.failures: + print(f" {path}: {message}", file=sys.stderr) + return True + + +# ---- Optional file pickers: used only when no path is given on the command line ---- + +def pick_inputs_gui(allow_files=True): + """ + Ask for input with tkinter dialogs. Fallback for when no path was given. + + Returns a list of file/folder paths, or [] if the user cancelled. + """ + import tkinter as tk + from tkinter import filedialog + root = tk.Tk() + root.withdraw() + if allow_files: + choice = input("Select (1) for files or (2) for folder: ").strip() + else: + choice = "2" + if choice == "2": + folder = filedialog.askdirectory(title="Select folder containing .nessus files") + return [folder] if folder else [] + return list(filedialog.askopenfilenames( + title="Select .nessus files to process", filetypes=[("Nessus files", "*.nessus")])) + + +def pick_output_gui(default_name, extension): + """Ask where to save the output. Returns '' if cancelled.""" + import tkinter as tk + from tkinter import filedialog + root = tk.Tk() + root.withdraw() + return filedialog.asksaveasfilename( + defaultextension=extension, initialfile=default_name, title="Save output file as...") diff --git a/nessus_to_csv.py b/nessus_to_csv.py index 0eb306e..d353624 100644 --- a/nessus_to_csv.py +++ b/nessus_to_csv.py @@ -1,9 +1,8 @@ """ Nessus to CSV Conversion Script -This script converts .nessus (XML) vulnerability scan files into CSV format for -easier analysis in spreadsheet applications. It processes one or more .nessus files -and extracts comprehensive vulnerability data including: +Converts .nessus (XML) vulnerability scan files into CSV for analysis in +spreadsheet applications. It extracts 106 fields per finding: - Host information (IP, hostname, FQDN, MAC address, OS details) - Vulnerability details (plugin name, severity, CVSS scores, CVE IDs) @@ -11,309 +10,116 @@ - Scan metadata (scan dates, policy used, credentialed scan status) - Additional security references (CISA, STIG, vendor advisories) +Usage: + python nessus_to_csv.py [-o OUTPUT.csv] PATH [PATH ...] + +Each PATH is a .nessus file or a folder (searched recursively). With no PATH the +script falls back to file pickers, which need a desktop session. + Features: -- Supports processing individual files or entire folders -- Removes duplicate findings automatically -- Provides progress tracking and performance metrics -- Handles large files efficiently with memory management +- Repeated reference elements (CWE, BID, MSKB, ...) are all kept, joined with ", " +- Exact duplicate findings are removed and the original row order is kept +- Each host is released from memory once read; one file's rows are held at a time +- Cells that start with = + - @ are prefixed with ' so Excel does not run them +- Exit code 0 on success, 1 if nothing could be converted, 2 if some files failed -Note: Variable names (e.g., pluginName, Credentialed_Scan) mirror the Nessus XML -element and attribute names for traceability back to the source format. +The output is UTF-8 with a byte order mark so Excel opens it correctly. """ -import os -import xml.etree.ElementTree as ET +import argparse import csv +import os +import sys import time -import tkinter as tk -from tkinter import filedialog -import psutil -from datetime import datetime - -# Severity constants (defined once, not per iteration) -SEVERITY_MAPPING = {0: 4, 1: 3, 2: 2, 3: 1, 4: 0} -SEVERITY_RATING = {0: "Critical", 1: "High", 2: "Medium", 3: "Low", 4: "Informational"} +import nessus_common as nc -def get_text(parent, xpath, default=""): - """Extract text from an XML element by XPath, returning default if not found.""" - el = parent.find(xpath) - return el.text if el is not None else default +DEFAULT_OUTPUT = "nessus_conversion.csv" -# Create a file dialog window for the user to select .nessus files or folder -root = tk.Tk() -root.withdraw() +def parse_args(argv): + parser = argparse.ArgumentParser(description="Convert .nessus files to CSV.") + parser.add_argument("paths", nargs="*", help=".nessus files or folders (recursive)") + parser.add_argument("-o", "--output", help=f"output CSV path (default: {DEFAULT_OUTPUT})") + return parser.parse_args(argv) -# Ask user if they want to select files or a folder -choice = input("Select (1) for files or (2) for folder: ").strip() -if choice == "2": - folder_path = filedialog.askdirectory(title="Select folder containing .nessus files") - if not folder_path: - print("No folder selected. Exiting.") - exit() - # Collect all .nessus files from folder - nessus_files = [] - for root_dir, dirs, files in os.walk(folder_path): - for file in files: - if file.endswith('.nessus'): - nessus_files.append(os.path.join(root_dir, file)) -else: - nessus_files = list(filedialog.askopenfilenames(title="Select .nessus files to process", filetypes=[("Nessus files", "*.nessus")])) - if not nessus_files: - print("No files selected. Exiting.") - exit() - -# Start run timer. -start_time = time.time() - -# Create an empty list to store the data. -data = [] - -# Function to process a single .nessus file -def process_nessus_file(file_path): +def write_csv(files, output_path, stats): """ - Processes a single .nessus XML file and extracts all vulnerability data. - - Parses the XML structure to extract: - - Host properties (IP, hostname, OS, scan metadata) - - Report items (vulnerabilities, findings, plugins) - - Vulnerability details (CVSS scores, CVE IDs, descriptions, solutions) - - Exploit and threat intelligence data + Write the unique rows of `files` to `output_path`. - The extracted data is added to the global 'data' list for later CSV export. - - Args: - file_path: Path to the .nessus file to process + Writes to a temporary file and moves it into place only if at least one input + file was read, so a failed run does not replace an existing good CSV. + Returns the number of rows written. """ - # Extract just the file name from the file path for tracking purposes - file_name = os.path.basename(file_path) - - # Parse the XML file. + tmp_path = output_path + ".tmp" + written = 0 try: - tree = ET.parse(file_path) - except ET.ParseError as e: - print(f"Error parsing {file_path}: {e}") - return - - xml_root = tree.getroot() - print(f"Processing {file_path}") - - # Process each host. - for host in xml_root.iter("ReportHost"): - host_cpe = get_text(host, "HostProperties/tag[@name='cpe']") - Credentialed_Scan = get_text(host, "HostProperties/tag[@name='Credentialed_Scan']") - host_end = get_text(host, "HostProperties/tag[@name='HOST_END']") - host_end_timestamp = get_text(host, "HostProperties/tag[@name='HOST_END_TIMESTAMP']") - host_start = get_text(host, "HostProperties/tag[@name='HOST_START']") - host_start_timestamp = get_text(host, "HostProperties/tag[@name='HOST_START_TIMESTAMP']") - host_fqdn = get_text(host, "HostProperties/tag[@name='host-fqdn']") - host_ip = get_text(host, "HostProperties/tag[@name='host-ip']") - hostname = get_text(host, "HostProperties/tag[@name='hostname']") - host_rdns = get_text(host, "HostProperties/tag[@name='host-rdns']") - LastAuthenticatedResults = get_text(host, "HostProperties/tag[@name='LastAuthenticatedResults']") - local_checks_proto = get_text(host, "HostProperties/tag[@name='local-checks-proto']") - mac_address = get_text(host, "HostProperties/tag[@name='mac-address']") - netbios_name = get_text(host, "HostProperties/tag[@name='netbios-name']") - operating_system = get_text(host, "HostProperties/tag[@name='operating-system']") - operating_system_conf = get_text(host, "HostProperties/tag[@name='operating-system-conf']") - operating_system_method = get_text(host, "HostProperties/tag[@name='operating-system-method']") - operating_system_id = get_text(host, "HostProperties/tag[@name='os']") - patch_summary_total_cves = get_text(host, "HostProperties/tag[@name='patch-summary-total-cves']") - policy_used = get_text(host, "HostProperties/tag[@name='policy-used']") - sinfp_signature = get_text(host, "HostProperties/tag[@name='sinfp-signature']") - smb_login_used = get_text(host, "HostProperties/tag[@name='smb-login-used']") - system_type = get_text(host, "HostProperties/tag[@name='system-type']") - virtual_mac_address = get_text(host, "HostProperties/tag[@name='virtual-mac-address']") - wmi_domain = get_text(host, "HostProperties/tag[@name='wmi-domain']") - - # Extract scan_date from host_start - scan_date = None - host_start_tag = host.find('HostProperties/tag[@name="HOST_START"]') - if host_start_tag is not None: - host_start = host_start_tag.text - if host_start: - try: - scan_date = datetime.strptime(host_start, "%a %b %d %H:%M:%S %Y").strftime("%Y-%m-%d") - except ValueError: - pass - - # Loop through each report item. - for item in host.iter("ReportItem"): - pluginFamily = item.attrib["pluginFamily"] - pluginID = item.attrib["pluginID"] - port = item.attrib["port"] - protocol = item.attrib["protocol"] - severity = item.attrib["severity"] - - severity_reversed = SEVERITY_MAPPING[int(severity)] - severity_rating = SEVERITY_RATING[severity_reversed] - - svc_name = item.attrib["svc_name"] - age_of_vuln = get_text(item, "age_of_vuln") - agent = get_text(item, "agent") - always_run = get_text(item, "always_run") - asset_categories = get_text(item, "asset_categories") - asset_inventory = get_text(item, "asset_inventory") - asset_inventory_category = get_text(item, "asset_inventory_category") - bid = get_text(item, "bid") - canvas_package = get_text(item, "canvas_package") - cea_id = get_text(item, "cea-id") - cert = get_text(item, "cert") - cisa_known_exploited = get_text(item, "cisa-known-exploited") - cisa_ncas = get_text(item, "cisa-ncas") - cisco_bug_id = get_text(item, "cisco-bug-id") - cisco_sa = get_text(item, "cisco-sa") - cpe = get_text(item, "cpe") - cve_elements = item.findall('cve') - cve = ', '.join(c.text for c in cve_elements) if cve_elements else '' - cvss_base_score = get_text(item, "cvss_base_score") - cvss_score_rationale = get_text(item, "cvss_score_rationale") - cvss_score_source = get_text(item, "cvss_score_source") - cvss_temporal_score = get_text(item, "cvss_temporal_score") - cvss_temporal_vector = get_text(item, "cvss_temporal_vector") - cvss_vector = get_text(item, "cvss_vector") - cvss3_base_score = get_text(item, "cvss3_base_score") - cvss3_score_source = get_text(item, "cvss3_score_source") - cvss3_temporal_score = get_text(item, "cvss3_temporal_score") - cvss3_temporal_vector = get_text(item, "cvss3_temporal_vector") - cvss3_vector = get_text(item, "cvss3_vector") - cvssV3_impactScore = get_text(item, "cvssV3_impactScore") - cwe = get_text(item, "cwe") - description = get_text(item, "description") - edb_id = get_text(item, "edb-id") - exploit_available = get_text(item, "exploit_available") - exploit_code_maturity = get_text(item, "exploit_code_maturity") - exploit_framework_canvas = get_text(item, "exploit_framework_canvas") - exploit_framework_core = get_text(item, "exploit_framework_core") - exploit_framework_metasploit = get_text(item, "exploit_framework_metasploit") - exploitability_ease = get_text(item, "exploitability_ease") - exploited_by_malware = get_text(item, "exploited_by_malware") - exploited_by_nessus = get_text(item, "exploited_by_nessus") - generated_plugin = get_text(item, "generated_plugin") - hardware_inventory = get_text(item, "hardware_inventory") - iava = get_text(item, "iava") - iavb = get_text(item, "iavb") - iavt = get_text(item, "iavt") - icsa = get_text(item, "icsa") - in_the_news = get_text(item, "in_the_news") - metasploit_name = get_text(item, "metasploit_name") - msft = get_text(item, "msft") - mskb = get_text(item, "mskb") - os_identification = get_text(item, "os_identification") - patch_publication_date = get_text(item, "patch_publication_date") - plugin_modification_date = get_text(item, "plugin_modification_date") - pluginName = item.attrib.get("pluginName") - plugin_output_element = item.find('plugin_output') - plugin_output = plugin_output_element.text.strip() if plugin_output_element is not None and plugin_output_element.text else "" - plugin_publication_date = get_text(item, "plugin_publication_date") - plugin_type = get_text(item, "plugin_type") - product_coverage = get_text(item, "product_coverage") - risk_factor = get_text(item, "risk_factor") - script_version = get_text(item, "script_version") - secunia = get_text(item, "secunia") - see_also = get_text(item, "see_also") - solution = get_text(item, "solution") - stig_severity = get_text(item, "stig_severity") - synopsis = get_text(item, "synopsis") - thorough_tests = get_text(item, "thorough_tests") - threat_intensity_last_28 = get_text(item, "threat_intensity_last_28") - threat_recency = get_text(item, "threat_recency") - threat_sources_last_28 = get_text(item, "threat_sources_last_28") - tra = get_text(item, "tra") - unsupported_by_vendor = get_text(item, "unsupported_by_vendor") - vmsa = get_text(item, "vmsa") - vpr_score = get_text(item, "vpr_score") - vuln_publication_date = get_text(item, "vuln_publication_date") - - # Column order: 106 fields matching CSV headers - data.append([host_ip, mac_address, virtual_mac_address, hostname, netbios_name, host_fqdn, host_rdns, system_type, cpe, operating_system_id, operating_system, severity_rating, risk_factor, severity_reversed, pluginName, synopsis, description, solution, port, protocol, svc_name, plugin_output, plugin_type, plugin_publication_date, plugin_modification_date, stig_severity, cvss_base_score, cvss_vector, cvss_score_rationale, cvss_score_source, cvss_temporal_score, cvss_temporal_vector, cvss3_base_score, cvss3_vector, cvss3_score_source, cvss3_temporal_score, cvss3_temporal_vector, cvssV3_impactScore, vpr_score, patch_publication_date, patch_summary_total_cves, vuln_publication_date, age_of_vuln, product_coverage, exploit_available, exploitability_ease, exploit_code_maturity, exploit_framework_canvas, canvas_package, exploit_framework_core, exploit_framework_metasploit, metasploit_name, exploited_by_malware, exploited_by_nessus, edb_id, threat_recency, threat_intensity_last_28, threat_sources_last_28, local_checks_proto, smb_login_used, wmi_domain, thorough_tests, Credentialed_Scan, LastAuthenticatedResults, policy_used, host_start, host_start_timestamp, host_end, host_end_timestamp, os_identification, operating_system_conf, operating_system_method, sinfp_signature, pluginID, pluginFamily, script_version, agent, always_run, asset_inventory, asset_inventory_category, asset_categories, hardware_inventory, bid, cea_id, cert, cisa_known_exploited, cisa_ncas, cisco_bug_id, cisco_sa, cve, cwe, iava, iavb, iavt, icsa, msft, mskb, tra, vmsa, secunia, unsupported_by_vendor, see_also, in_the_news, generated_plugin, file_name, scan_date]) - -# Process all .nessus files -total_hosts = 0 -for nessus_file in nessus_files: - # Count hosts before processing + with open(tmp_path, "w", newline="", encoding="utf-8-sig") as csvfile: + writer = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL) + writer.writerow(nc.COLUMN_NAMES) + for row in nc.iter_unique_rows(files, stats): + writer.writerow(["" if v is None else nc.neutralize_cell(v) for v in row]) + written += 1 + if written % 1000 == 0: + print(f"\rWrote {written} rows...", end="", flush=True) + if stats.files_ok == 0: + os.remove(tmp_path) + return 0 + os.replace(tmp_path, output_path) + except BaseException: + if os.path.exists(tmp_path): + os.remove(tmp_path) + raise + return written + + +def main(argv=None): + args = parse_args(sys.argv[1:] if argv is None else argv) + start_time = time.time() + + paths = args.paths + if not paths: + paths = nc.pick_inputs_gui() + if not paths: + print("No files or folder selected. Exiting.") + return nc.EXIT_FAILED try: - tree = ET.parse(nessus_file) - xml_root = tree.getroot() - total_hosts += len(list(xml_root.iter("ReportHost"))) - except Exception: - pass - process_nessus_file(nessus_file) - -# Define remove duplicates function. -def remove_duplicates(data): - """ - Removes duplicate rows from the extracted vulnerability data. - - Duplicates can occur when the same vulnerability is found on the same host - in multiple scans or when processing overlapping scan results. This function - uses a set to identify and remove exact duplicate rows. - - Args: - data: List of data rows (each row is a list of values) - - Returns: - A tuple containing: - - List of unique rows (duplicates removed) - - Count of duplicates that were removed - """ - unique_rows = set() - duplicates_removed = 0 - for row in data: - row_tuple = tuple(row) - if row_tuple not in unique_rows: - unique_rows.add(row_tuple) + files = nc.collect_nessus_files(paths) + except FileNotFoundError as exc: + print(exc, file=sys.stderr) + return nc.EXIT_FAILED + if not files: + print("No .nessus files found. Exiting.", file=sys.stderr) + return nc.EXIT_FAILED + + output_path = args.output + if not output_path: + if args.paths: + output_path = DEFAULT_OUTPUT else: - duplicates_removed += 1 - return [list(row_tuple) for row_tuple in unique_rows], duplicates_removed - -# Remove duplicates from the data. -data, duplicates_removed = remove_duplicates(data) - -# Print a message displaying the number of removed duplicates. -if duplicates_removed > 0: - print(f"Removed {duplicates_removed} duplicate rows from the data.") -else: - print("No duplicate rows found.") - -# Define the default filename -csv_filename = "nessus_conversion.csv" - -# Open a file dialog to choose the output filename and directory -csv_filename = filedialog.asksaveasfilename(defaultextension=".csv", initialfile=csv_filename, title="Save CSV File As...") - -if not csv_filename: - print("No output file selected. Exiting.") - exit() - -# Define CSV headers matching the column order -headers = ["host_ip", "mac_address", "virtual_mac_address", "hostname", "netbios_name", "host_fqdn", "host_rdns", "system_type", "cpe", "operating_system_id", "operating_system", "severity_rating", "risk_factor", "severity_reversed", "pluginName", "synopsis", "description", "solution", "port", "protocol", "svc_name", "plugin_output", "plugin_type", "plugin_publication_date", "plugin_modification_date", "stig_severity", "cvss_base_score", "cvss_vector", "cvss_score_rationale", "cvss_score_source", "cvss_temporal_score", "cvss_temporal_vector", "cvss3_base_score", "cvss3_vector", "cvss3_score_source", "cvss3_temporal_score", "cvss3_temporal_vector", "cvssV3_impactScore", "vpr_score", "patch_publication_date", "patch_summary_total_cves", "vuln_publication_date", "age_of_vuln", "product_coverage", "exploit_available", "exploitability_ease", "exploit_code_maturity", "exploit_framework_canvas", "canvas_package", "exploit_framework_core", "exploit_framework_metasploit", "metasploit_name", "exploited_by_malware", "exploited_by_nessus", "edb_id", "threat_recency", "threat_intensity_last_28", "threat_sources_last_28", "local_checks_proto", "smb_login_used", "wmi_domain", "thorough_tests", "Credentialed_Scan", "LastAuthenticatedResults", "policy_used", "host_start", "host_start_timestamp", "host_end", "host_end_timestamp", "os_identification", "operating_system_conf", "operating_system_method", "sinfp_signature", "pluginID", "pluginFamily", "script_version", "agent", "always_run", "asset_inventory", "asset_inventory_category", "asset_categories", "hardware_inventory", "bid", "cea_id", "cert", "cisa_known_exploited", "cisa_ncas", "cisco_bug_id", "cisco_sa", "cve", "cwe", "iava", "iavb", "iavt", "icsa", "msft", "mskb", "tra", "vmsa", "secunia", "unsupported_by_vendor", "see_also", "in_the_news", "generated_plugin", "file_name", "scan_date"] - -# Write the data to a CSV file with a progress indicator. -print(f"Processed {len(nessus_files)} files, {total_hosts} hosts, and {len(data)} findings.\nNow writing to CSV: {csv_filename}.") -with open(csv_filename, 'w', newline='', encoding='utf-8') as csvfile: - writer = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL) - writer.writerow(headers) - for progress, row in enumerate(data, start=1): - percent_complete = (progress / len(data)) * 100 - if progress % 1000 == 0 or progress == len(data): - print(f"\rWriting data to CSV: {percent_complete:.2f}% complete ({progress}/{len(data)} rows).", end="", flush=True) - writer.writerow(row) -print("\rWriting data to CSV: 100.00% complete.") - -# Confirm completion and provide elapsed run time, peak CPU usage and peak memory usage. -print("Processing complete.") -end_time = time.time() -elapsed_time = end_time - start_time - -# Calculate hours, minutes and seconds -hours = int(elapsed_time // 3600) -minutes = int((elapsed_time % 3600) // 60) -seconds = elapsed_time % 60 - -peak_cpu_usage = psutil.Process().cpu_percent() -mem_info = psutil.Process().memory_info() -peak_mem_usage = getattr(mem_info, 'peak_wset', mem_info.rss) / 1024 / 1024 -print(f"Elapsed time: {hours} hours {minutes} minutes {seconds:.2f} seconds. Peak CPU usage: {peak_cpu_usage}%. Peak memory usage: {peak_mem_usage:.2f} MB.") + output_path = nc.pick_output_gui(DEFAULT_OUTPUT, ".csv") + if not output_path: + print("No output file selected. Exiting.") + return nc.EXIT_FAILED + + stats = nc.RunStats() + written = write_csv(files, output_path, stats) + print() + failed = nc.report_failures(stats) + if stats.files_ok == 0: + print("No file could be read. No CSV was written.", file=sys.stderr) + return nc.EXIT_FAILED + + if stats.duplicates: + print(f"Removed {stats.duplicates} duplicate rows from the data.") + else: + print("No duplicate rows found.") + print(f"Processed {stats.files_ok} of {stats.files_seen} files, {stats.hosts} hosts, " + f"and {written} findings. Wrote {output_path}.") + print(nc.format_run_metrics(start_time)) + return nc.EXIT_PARTIAL if failed else nc.EXIT_OK + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/nessus_to_sql.py b/nessus_to_sql.py index fdebd2e..ee02b3c 100644 --- a/nessus_to_sql.py +++ b/nessus_to_sql.py @@ -1,568 +1,504 @@ """ -Nessus to SQL Server Database Import Script - -This script converts .nessus (XML) vulnerability scan files and imports them into -a SQL Server database. It processes .nessus files from a selected folder and: - -- Extracts comprehensive vulnerability data from XML structure -- Connects to SQL Server (with interactive server/database/table selection) -- Creates the target table if it doesn't exist -- Imports data in batches for efficient processing of large datasets -- Handles all vulnerability fields including host info, CVSS scores, CVE IDs, etc. - -Features: -- Interactive SQL Server connection setup (queries available servers/databases/tables) -- Automatic table creation with proper schema -- Batch processing for memory efficiency (500,000 rows per batch) -- Progress tracking and performance metrics -- Processes all .nessus files in selected folder recursively - -Note: Variable names (e.g., pluginName, Credentialed_Scan) mirror the Nessus XML -element and attribute names for traceability back to the source format. +Nessus to SQL Server Import Script + +Imports .nessus (XML) vulnerability scan files into a SQL Server table, 106 +columns per finding. + +Usage: + python nessus_to_sql.py [PATH ...] [--server S] [--database D] [--table T] + [--create-table] [--trust-server-certificate] + [--dry-run] + +Each PATH is a .nessus file or a folder (searched recursively). Anything you do +not give on the command line is asked for at the prompt; with no PATH the script +falls back to a folder picker, which needs a desktop session. + +Tables: +- Name an existing table with --table, or choose one from the menu. The script + checks that it has every column it needs and stops if it does not. +- To make a new table, pass --create-table with --table NEW_NAME, or choose + "Create a new table" in the menu. The new table gets a unique index on + (host_ip, pluginID, port, protocol, scan_date, file_path) that ignores + duplicate rows, so importing the same file twice does not add rows twice. + Existing tables made by another tool or an older version of this script do not + have that index, and re-importing into them adds the rows again. +- The file_path column holds the file's base name, not a full path. + +Each file is imported in one transaction: if any batch of a file fails, nothing +from that file is kept. A file that cannot be parsed is skipped and reported. + +Connection: Windows authentication (Trusted_Connection) through ODBC Driver 18. +The server certificate is validated. If your server uses a self-signed +certificate, install it as trusted, or pass --trust-server-certificate to accept +any certificate (this lets someone in the network path impersonate the server). + +--dry-run reads the files and prints the SQL it would run, without connecting. """ -import os +import argparse import re -import xml.etree.ElementTree as ET +import sys import time -import tkinter as tk -from tkinter import filedialog -import psutil -import pyodbc # type: ignore[import-not-found] -from datetime import datetime +from datetime import date, datetime -# Severity constants (defined once, not per iteration) -SEVERITY_MAPPING = {0: 4, 1: 3, 2: 2, 3: 1, 4: 0} -SEVERITY_RATING = {0: "Critical", 1: "High", 2: "Medium", 3: "Low", 4: "Informational"} +import nessus_common as nc +BATCH_SIZE = 500_000 +DEFAULT_TABLE = "nessus_findings" +EXAMPLE_SERVER = "sqlserver.example.com" -def get_text(parent, xpath, default=""): - """Extract text from an XML element by XPath, returning default if not found.""" - el = parent.find(xpath) - return el.text if el is not None else default +# ---- Column types ------------------------------------------------------------ +_INT_COLUMNS = {"severity_reversed", "port", "pluginID"} +_BIGINT_COLUMNS = {"host_start_timestamp", "host_end_timestamp"} +_DATE_COLUMNS = { + "plugin_publication_date", "plugin_modification_date", "patch_publication_date", + "vuln_publication_date", "scan_date", +} +# Short fixed-vocabulary fields. +_SHORT_TEXT_COLUMNS = { + "severity_rating", "risk_factor", "plugin_type", "exploit_available", + "exploit_framework_canvas", "exploit_framework_core", "exploit_framework_metasploit", + "exploited_by_malware", "exploited_by_nessus", "local_checks_proto", "Credentialed_Scan", + "always_run", "agent", "cisa_known_exploited", "thorough_tests", "unsupported_by_vendor", + "in_the_news", +} +# Columns that make up the unique index; they cannot be MAX. +_KEY_TYPES = {"host_ip": "NVARCHAR(64)", "protocol": "NVARCHAR(15)", "file_path": "NVARCHAR(255)"} +UNIQUE_KEY_COLUMNS = ["host_ip", "pluginID", "port", "protocol", "scan_date", "file_path"] + + +def sql_column_name(column): + """The SQL name for an output column. The CSV's file_name is stored as file_path.""" + return "file_path" if column == "file_name" else column + + +def sql_type(column): + name = sql_column_name(column) + if name in _KEY_TYPES: + return _KEY_TYPES[name] + if name in _INT_COLUMNS: + return "INT" + if name in _BIGINT_COLUMNS: + return "BIGINT" + if name in _DATE_COLUMNS: + return "DATE" + if name in _SHORT_TEXT_COLUMNS: + return "NVARCHAR(100)" + return "NVARCHAR(MAX)" + + +SQL_COLUMNS = [(sql_column_name(c), sql_type(c)) for c in nc.COLUMN_NAMES] +SQL_COLUMN_NAMES = [c for c, _ in SQL_COLUMNS] + + +# ---- Names and connection strings -------------------------------------------- def sanitize_table_name(name): - """Validate and sanitize a SQL Server table name to prevent injection.""" - # Only allow alphanumeric, underscores, and hyphens - if not re.match(r'^[A-Za-z_][A-Za-z0-9_]*$', name): - raise ValueError(f"Invalid table name: {name}") + """ + Validate a NEW table name typed by the user: letters, digits, underscore and + hyphen, starting with a letter or underscore, at most 100 characters. + """ + if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_-]{0,99}", name): + raise ValueError( + f"Invalid table name: {name!r}. Use letters, digits, underscore or hyphen, " + "starting with a letter or underscore (100 characters at most).") return name -# Create a file dialog window for the user to select a folder. -root_window = tk.Tk() -root_window.withdraw() -folder_path = filedialog.askdirectory(title="Select folder containing .nessus files") +def quote_identifier(name): + """ + Bracket-quote a SQL Server identifier, doubling any ']'. Safe for any name that + came back from the server's own table list, including names with hyphens or spaces. + """ + if not isinstance(name, str) or not name or len(name) > 128 or any( + ord(ch) < 32 or ch == "\x7f" for ch in name): + raise ValueError(f"Invalid identifier: {name!r}") + return "[" + name.replace("]", "]]") + "]" -# Start run timer. -start_time = time.time() -def get_databases(server): - """ - Queries SQL Server for available user databases. +def _odbc_value(value): + """Escape a connection-string value so ';' and braces in it cannot add options.""" + if not value or any(ord(ch) < 32 for ch in value): + raise ValueError(f"Invalid connection value: {value!r}") + if any(ch in value for ch in ";{}"): + return "{" + value.replace("}", "}}") + "}" + return value - Connects to the specified SQL Server instance and retrieves a list of - all user databases (excluding system databases like master, model, etc.). - This allows users to select which database to import data into. - Args: - server: SQL Server address (hostname, IP, or FQDN) +def build_connection_string(server, database=None, trust_server_certificate=False): + parts = [ + "DRIVER={ODBC Driver 18 for SQL Server}", + f"SERVER={_odbc_value(server)}", + ] + if database: + parts.append(f"DATABASE={_odbc_value(database)}") + parts.append("Trusted_Connection=yes") + if trust_server_certificate: + parts.append("TrustServerCertificate=yes") + return ";".join(parts) + ";" - Returns: - List of database names, or None if connection fails - """ - conn_str = ( - r'DRIVER={ODBC Driver 18 for SQL Server};' - f'SERVER={server};' - r'Trusted_Connection=yes;' - r'TrustServerCertificate=yes;' - ) + +# ---- SQL text ---------------------------------------------------------------- + +def build_create_table_sql(table): + """Return (CREATE TABLE statement, CREATE UNIQUE INDEX statement) for a new table.""" + quoted = quote_identifier(table) + columns = ",\n ".join(f"{name} {typ}" for name, typ in SQL_COLUMNS) + create_table = f"CREATE TABLE dbo.{quoted} (\n {columns}\n)" + index_name = quote_identifier(f"UX_{table}_finding") + key = ", ".join(UNIQUE_KEY_COLUMNS) + create_index = (f"CREATE UNIQUE INDEX {index_name} ON dbo.{quoted} ({key}) " + "WITH (IGNORE_DUP_KEY = ON)") + return create_table, create_index + + +def build_insert_sql(table): + columns = ", ".join(SQL_COLUMN_NAMES) + marks = ", ".join("?" for _ in SQL_COLUMN_NAMES) + return f"INSERT INTO dbo.{quote_identifier(table)} ({columns}) VALUES ({marks})" + + +# ---- Value conversion -------------------------------------------------------- + +_DATE_FORMATS = ("%Y/%m/%d", "%Y-%m-%d") + + +def _to_date(value): + """Parse a Nessus date to a date, or None. Done here so SQL Server's language setting + cannot change how 2024/03/05 is read.""" + if not value: + return None + if isinstance(value, date): + return value + text = value.strip() + for fmt in _DATE_FORMATS: + try: + return datetime.strptime(text[:10], fmt).date() + except ValueError: + continue + return None + + +def _to_int(value): + if value is None or value == "": + return None try: - conn = pyodbc.connect(conn_str) - cursor = conn.cursor() - cursor.execute("SELECT name FROM sys.databases WHERE database_id > 4 ORDER BY name") - databases = [row[0] for row in cursor.fetchall()] - cursor.close() - conn.close() - return databases - except Exception as e: - print(f"Error connecting to server: {e}") + return int(value) + except (TypeError, ValueError): return None -def get_tables(server, database): - """ - Queries a SQL Server database for available tables in the dbo schema. - Retrieves a list of all user tables in the specified database, allowing - users to select an existing table or create a new one for the import. +def to_sql_row(row): + """Convert one 106-column row to values for the INSERT: ints, dates and NULLs where typed.""" + out = [] + for (name, _typ), value in zip(SQL_COLUMNS, row): + if name in _INT_COLUMNS or name in _BIGINT_COLUMNS: + out.append(_to_int(value)) + elif name in _DATE_COLUMNS: + out.append(_to_date(value)) + else: + out.append("" if value is None else value) + return out - Args: - server: SQL Server address - database: Name of the database to query - Returns: - List of table names, or None if query fails - """ - conn_str = ( - r'DRIVER={ODBC Driver 18 for SQL Server};' - f'SERVER={server};' - f'DATABASE={database};' - r'Trusted_Connection=yes;' - r'TrustServerCertificate=yes;' - ) +# ---- Database helpers (take a connection so they can be tested without a server) ---- + +def connect(conn_str): + """Open an ODBC connection. pyodbc is imported here so --dry-run and the tests do not need it.""" try: - conn = pyodbc.connect(conn_str) - cursor = conn.cursor() - cursor.execute(""" - SELECT TABLE_NAME - FROM INFORMATION_SCHEMA.TABLES - WHERE TABLE_TYPE = 'BASE TABLE' - AND TABLE_SCHEMA = 'dbo' - ORDER BY TABLE_NAME - """) - tables = [row[0] for row in cursor.fetchall()] + import pyodbc # type: ignore[import-not-found] + except ImportError: + raise SystemExit("pyodbc is not installed. Run: pip install -r requirements.txt") + return pyodbc.connect(conn_str) + + +def list_databases(conn): + cursor = conn.cursor() + cursor.execute("SELECT name FROM sys.databases WHERE database_id > 4 ORDER BY name") + names = [row[0] for row in cursor.fetchall()] + cursor.close() + return names + + +def list_tables(conn): + cursor = conn.cursor() + cursor.execute( + "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES " + "WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = 'dbo' ORDER BY TABLE_NAME") + names = [row[0] for row in cursor.fetchall()] + cursor.close() + return names + + +def get_table_columns(conn, table): + cursor = conn.cursor() + cursor.execute( + "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS " + "WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION", (table,)) + names = [row[0] for row in cursor.fetchall()] + cursor.close() + return names + + +def missing_columns(existing_columns): + """Columns the import needs that the table does not have (names compared ignoring case).""" + have = {c.lower() for c in existing_columns} + return [c for c in SQL_COLUMN_NAMES if c.lower() not in have] + + +def create_table(conn, table): + create_table_sql, create_index_sql = build_create_table_sql(table) + cursor = conn.cursor() + try: + cursor.execute(create_table_sql) + cursor.execute(create_index_sql) + conn.commit() + except Exception: + conn.rollback() + raise + finally: cursor.close() - conn.close() - return tables - except Exception as e: - print(f"Error querying tables: {e}") - return None -def select_from_list(items, item_type="item"): + +def prepare_table(conn, table, create): + """ + Make sure `table` can take the import. + + Returns "existing" or "created". Raises ValueError if the table is missing and + create is False, or if an existing table lacks required columns. + """ + existing = get_table_columns(conn, table) + if existing: + missing = missing_columns(existing) + if missing: + raise ValueError( + f"Table dbo.{table} does not look like a Nessus findings table. " + f"Missing columns: {', '.join(missing)}") + return "existing" + if not create: + raise ValueError( + f"Table dbo.{table} does not exist. Pass --create-table to create it.") + sanitize_table_name(table) + create_table(conn, table) + return "created" + + +def import_rows(conn, table, rows, batch_size=BATCH_SIZE): """ - Provides an interactive selection interface from a list of items. + Insert `rows` into `table` in batches inside one transaction. + + Commits at the end; any error rolls back everything inserted by this call. + Returns the number of rows sent. + """ + insert_sql = build_insert_sql(table) + cursor = conn.cursor() + sent = 0 + try: + for start in range(0, len(rows), batch_size): + batch = [to_sql_row(r) for r in rows[start:start + batch_size]] + cursor.executemany(insert_sql, batch) + sent += len(batch) + conn.commit() + except Exception: + conn.rollback() + raise + finally: + cursor.close() + return sent - Displays numbered options and prompts user to select one, with validation - and confirmation to prevent accidental selections. Used for selecting - databases and tables. - Args: - items: List of items to choose from - item_type: Type name for display purposes (e.g., "database", "table") +# ---- Prompts ----------------------------------------------------------------- - Returns: - The selected item, or None if selection is cancelled +def select_from_list(items, item_type="item", input_fn=input, extra=None): """ - if not items: + Numbered menu. `extra` is an optional extra choice shown last; if picked, the + function returns the `extra` string itself. Returns None if there is nothing to pick. + """ + options = list(items) + ([extra] if extra else []) + if not options: print(f"No {item_type}s found.") return None print(f"\nAvailable {item_type}s:") - for idx, item in enumerate(items, 1): + for idx, item in enumerate(options, 1): print(f"{idx}. {item}") while True: try: - choice = input(f"\nEnter the number of your choice (1-{len(items)}): ").strip() - choice_num = int(choice) - if 1 <= choice_num <= len(items): - selected = items[choice_num - 1] - confirmation = input(f"You have selected '{selected}'. Is this correct? (Y/N): ").strip().lower() - if confirmation == 'y': - return selected - else: - print("Let's try again.\n") - else: - print(f"Invalid selection. Please enter a number between 1 and {len(items)}.\n") + choice_num = int(input_fn(f"\nEnter the number of your choice (1-{len(options)}): ").strip()) except ValueError: print("Invalid input. Please enter a number.\n") + continue + if not 1 <= choice_num <= len(options): + print(f"Invalid selection. Please enter a number between 1 and {len(options)}.\n") + continue + selected = options[choice_num - 1] + if input_fn(f"You have selected '{selected}'. Is this correct? (Y/N): ").strip().lower() == "y": + return selected + print("Let's try again.\n") + + +NEW_TABLE_CHOICE = "[Create a new table]" + + +def choose_table(conn, input_fn=input): + """Interactive table choice. Returns (table_name, create_flag) or (None, False).""" + tables = list_tables(conn) + picked = select_from_list(tables, "table", input_fn, extra=NEW_TABLE_CHOICE) + if picked is None: + return None, False + if picked != NEW_TABLE_CHOICE: + return picked, False + while True: + name = input_fn("Name for the new table: ").strip() + try: + return sanitize_table_name(name), True + except ValueError as exc: + print(f"{exc}\n") + + +# ---- Main -------------------------------------------------------------------- + +def parse_args(argv): + parser = argparse.ArgumentParser(description="Import .nessus files into SQL Server.") + parser.add_argument("paths", nargs="*", help=".nessus files or folders (recursive)") + parser.add_argument("--server", help=f"SQL Server address, e.g. localhost or {EXAMPLE_SERVER}") + parser.add_argument("--database", help="database to import into") + parser.add_argument("--table", help="target table in the dbo schema") + parser.add_argument("--create-table", action="store_true", + help="create the table if it does not exist") + parser.add_argument("--trust-server-certificate", action="store_true", + help="accept any server certificate (not recommended)") + parser.add_argument("--dry-run", action="store_true", + help="parse the files and print the SQL, without connecting") + return parser.parse_args(argv) + + +def _dry_run(args, files): + table = sanitize_table_name(args.table or DEFAULT_TABLE) + create_table_sql, create_index_sql = build_create_table_sql(table) + print("-- Would run, if the table did not exist:") + print(create_table_sql + ";") + print(create_index_sql + ";") + print("\n-- Would insert each row with:") + print(build_insert_sql(table) + ";\n") + stats = nc.RunStats() + total = sum(1 for _ in nc.iter_unique_rows(files, stats)) + failed = nc.report_failures(stats) + print(f"Dry run: {stats.files_ok} of {stats.files_seen} files read, {stats.hosts} hosts, " + f"{total} rows would be inserted ({stats.duplicates} duplicates removed). " + "Nothing was sent to a server.") + if stats.files_ok == 0: + return nc.EXIT_FAILED + return nc.EXIT_PARTIAL if failed else nc.EXIT_OK + + +def main(argv=None, connect_fn=None, input_fn=input): + args = parse_args(sys.argv[1:] if argv is None else argv) + connect_fn = connect_fn or connect + start_time = time.time() + + paths = args.paths + if not paths: + paths = nc.pick_inputs_gui(allow_files=False) + if not paths: + print("No folder selected. Exiting.") + return nc.EXIT_FAILED + try: + files = nc.collect_nessus_files(paths) + except FileNotFoundError as exc: + print(exc, file=sys.stderr) + return nc.EXIT_FAILED + if not files: + print("No .nessus files found. Exiting.", file=sys.stderr) + return nc.EXIT_FAILED -# Get server information -print("=" * 60) -print("SQL Server Connection Setup") -print("=" * 60) -server = input("Enter SQL Server address (e.g., localhost, 10.10.30.20, or server.domain.com): ").strip() -if not server: - print("Server address is required. Exiting.") - exit(1) - -# Query and select database -print(f"\nConnecting to server '{server}' to retrieve databases...") -databases = get_databases(server) -if databases is None: - print("Failed to retrieve databases. Exiting.") - exit(1) - -database = select_from_list(databases, "database") -if not database: - print("No database selected. Exiting.") - exit(1) - -# Query and select table -print(f"\nConnecting to database '{database}' to retrieve tables...") -tables = get_tables(server, database) -if tables is None: - print("Failed to retrieve tables. Exiting.") - exit(1) - -table_name = select_from_list(tables, "table") -if not table_name: - print("No table selected. Exiting.") - exit(1) - -# Validate table name to prevent SQL injection -table_name = sanitize_table_name(table_name) - -print(f"\nProceeding with:") -print(f" Server: {server}") -print(f" Database: {database}") -print(f" Table: {table_name}") -print("=" * 60) - -# Establish database connection -conn_str = ( - r'DRIVER={ODBC Driver 18 for SQL Server};' - f'SERVER={server};' - f'DATABASE={database};' - r'Trusted_Connection=yes;' - r'TrustServerCertificate=yes;' -) - -conn = pyodbc.connect(conn_str) -cursor = conn.cursor() - -def create_table_if_not_exists(): - """ - Creates the target table in SQL Server if it doesn't already exist. - - Defines a comprehensive schema with all vulnerability data fields including: - - Host information (IP, hostname, MAC, OS details) - - Vulnerability details (plugin info, severity, CVSS scores) - - CVE and security reference IDs - - Exploit and threat intelligence data - - Scan metadata (dates, policy, credentials) - - Uses IF NOT EXISTS to avoid errors if the table already exists. - """ - # Table name is validated by sanitize_table_name() — safe for bracket-quoting - create_table_query = f''' - IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES - WHERE TABLE_SCHEMA = 'dbo' - AND TABLE_NAME = ?) - BEGIN - CREATE TABLE [{table_name}] ( - host_ip VARCHAR(200), - mac_address NVARCHAR(MAX), - virtual_mac_address NVARCHAR(1000), - hostname VARCHAR(100), - netbios_name VARCHAR(100), - host_fqdn VARCHAR(150), - host_rdns VARCHAR(150), - system_type VARCHAR(25), - cpe VARCHAR(1000), - operating_system_id VARCHAR(150), - operating_system VARCHAR(200), - severity_rating VARCHAR(15), - risk_factor VARCHAR(15), - severity_reversed INT, - pluginName VARCHAR(MAX), - synopsis VARCHAR(255), - description VARCHAR(MAX), - solution VARCHAR(MAX), - port INT, - protocol VARCHAR(15), - svc_name VARCHAR(150), - plugin_output VARCHAR(MAX), - plugin_type VARCHAR(15), - plugin_publication_date DATE, - plugin_modification_date DATE, - stig_severity VARCHAR(100), - cvss_base_score VARCHAR(100), - cvss_vector VARCHAR(150), - cvss_score_rationale VARCHAR(500), - cvss_score_source VARCHAR(100), - cvss_temporal_score VARCHAR(100), - cvss_temporal_vector VARCHAR(100), - cvss3_base_score VARCHAR(100), - cvss3_vector VARCHAR(150), - cvss3_score_source VARCHAR(100), - cvss3_temporal_score VARCHAR(100), - cvss3_temporal_vector VARCHAR(100), - cvssV3_impactScore VARCHAR(100), - vpr_score VARCHAR(100), - patch_publication_date DATE, - patch_summary_total_cves VARCHAR(150), - vuln_publication_date DATE, - age_of_vuln VARCHAR(100), - product_coverage VARCHAR(150), - exploit_available VARCHAR(15), - exploitability_ease VARCHAR(150), - exploit_code_maturity VARCHAR(150), - exploit_framework_canvas VARCHAR(15), - canvas_package VARCHAR(150), - exploit_framework_core VARCHAR(15), - exploit_framework_metasploit VARCHAR(15), - metasploit_name VARCHAR(150), - exploited_by_malware VARCHAR(15), - exploited_by_nessus VARCHAR(15), - edb_id VARCHAR(150), - threat_recency VARCHAR(150), - threat_intensity_last_28 VARCHAR(150), - threat_sources_last_28 VARCHAR(150), - local_checks_proto VARCHAR(15), - smb_login_used VARCHAR(150), - wmi_domain VARCHAR(150), - thorough_tests VARCHAR(150), - Credentialed_Scan VARCHAR(15), - LastAuthenticatedResults VARCHAR(50), - policy_used VARCHAR(150), - host_start VARCHAR(150), - host_start_timestamp INT, - host_end VARCHAR(150), - host_end_timestamp INT, - os_identification VARCHAR(150), - operating_system_conf VARCHAR(150), - operating_system_method VARCHAR(150), - sinfp_signature VARCHAR(250), - pluginID INT, - pluginFamily VARCHAR(150), - script_version VARCHAR(150), - agent VARCHAR(150), - always_run VARCHAR(150), - asset_inventory VARCHAR(150), - asset_inventory_category VARCHAR(150), - asset_categories VARCHAR(150), - hardware_inventory VARCHAR(150), - bid VARCHAR(150), - cea_id VARCHAR(150), - cert VARCHAR(150), - cisa_known_exploited VARCHAR(150), - cisa_ncas VARCHAR(150), - cisco_bug_id VARCHAR(150), - cisco_sa VARCHAR(150), - cve NVARCHAR(4000), - cwe VARCHAR(150), - iava VARCHAR(150), - iavb VARCHAR(150), - iavt VARCHAR(150), - icsa VARCHAR(150), - msft VARCHAR(150), - mskb VARCHAR(150), - tra VARCHAR(150), - vmsa VARCHAR(150), - secunia VARCHAR(150), - unsupported_by_vendor VARCHAR(15), - see_also VARCHAR(MAX), - in_the_news VARCHAR(15), - generated_plugin VARCHAR(150), - file_path VARCHAR(255), - scan_date DATE - ) - END - ''' - cursor.execute(create_table_query, (table_name,)) - conn.commit() - -create_table_if_not_exists() - -def process_nessus_file(nessus_file_path): - """ - Processes a single .nessus XML file and prepares data for database import. - - Parses the XML structure to extract all vulnerability data, then batches - the data for efficient database insertion. Uses batch processing to handle - large files without consuming excessive memory. - - Args: - nessus_file_path: Path to the .nessus file to process - """ - # Extract just the file name from the file path for tracking in database - file_name = os.path.basename(nessus_file_path) + try: + if args.dry_run: + return _dry_run(args, files) + + server = args.server + if not server: + print("=" * 60) + print("SQL Server Connection Setup") + print("=" * 60) + server = input_fn(f"Enter SQL Server address (e.g., localhost or {EXAMPLE_SERVER}): ").strip() + if not server: + print("Server address is required. Exiting.", file=sys.stderr) + return nc.EXIT_FAILED + + trust = args.trust_server_certificate + database = args.database + if not database: + print(f"\nConnecting to server '{server}' to retrieve databases...") + conn = connect_fn(build_connection_string(server, None, trust)) + try: + database = select_from_list(list_databases(conn), "database", input_fn) + finally: + conn.close() + if not database: + print("No database selected. Exiting.", file=sys.stderr) + return nc.EXIT_FAILED + + print(f"\nConnecting to database '{database}'...") + conn = connect_fn(build_connection_string(server, database, trust)) + except ValueError as exc: + print(exc, file=sys.stderr) + return nc.EXIT_FAILED + except EOFError: + print("Input ended before all required values were given. Pass them as arguments.", + file=sys.stderr) + return nc.EXIT_FAILED + except Exception as exc: # connection errors from the ODBC driver + print(f"Error connecting to SQL Server: {exc}", file=sys.stderr) + if "certificate" in str(exc).lower(): + print("The server certificate was not trusted. Install it as trusted, or pass " + "--trust-server-certificate to accept any certificate.", file=sys.stderr) + return nc.EXIT_FAILED - # Parse the XML file. try: - tree = ET.parse(nessus_file_path) - except ET.ParseError as e: - print(f"Error parsing {nessus_file_path}: {e}") - return - - root = tree.getroot() - print(f"Processing {nessus_file_path}") - - batch = [] - batch_size = 500000 # Process 500,000 rows per batch for memory efficiency - - # Process each host. - for host in root.iter("ReportHost"): - host_cpe = get_text(host, "HostProperties/tag[@name='cpe']") - Credentialed_Scan = get_text(host, "HostProperties/tag[@name='Credentialed_Scan']") - host_end = get_text(host, "HostProperties/tag[@name='HOST_END']") - host_end_timestamp = get_text(host, "HostProperties/tag[@name='HOST_END_TIMESTAMP']") - host_start = get_text(host, "HostProperties/tag[@name='HOST_START']") - host_start_timestamp = get_text(host, "HostProperties/tag[@name='HOST_START_TIMESTAMP']") - host_fqdn = get_text(host, "HostProperties/tag[@name='host-fqdn']") - host_ip = get_text(host, "HostProperties/tag[@name='host-ip']") - hostname = get_text(host, "HostProperties/tag[@name='hostname']") - host_rdns = get_text(host, "HostProperties/tag[@name='host-rdns']") - LastAuthenticatedResults = get_text(host, "HostProperties/tag[@name='LastAuthenticatedResults']") - local_checks_proto = get_text(host, "HostProperties/tag[@name='local-checks-proto']") - mac_address = get_text(host, "HostProperties/tag[@name='mac-address']") - netbios_name = get_text(host, "HostProperties/tag[@name='netbios-name']") - operating_system = get_text(host, "HostProperties/tag[@name='operating-system']") - operating_system_conf = get_text(host, "HostProperties/tag[@name='operating-system-conf']") - operating_system_method = get_text(host, "HostProperties/tag[@name='operating-system-method']") - operating_system_id = get_text(host, "HostProperties/tag[@name='os']") - patch_summary_total_cves = get_text(host, "HostProperties/tag[@name='patch-summary-total-cves']") - policy_used = get_text(host, "HostProperties/tag[@name='policy-used']") - sinfp_signature = get_text(host, "HostProperties/tag[@name='sinfp-signature']") - smb_login_used = get_text(host, "HostProperties/tag[@name='smb-login-used']") - system_type = get_text(host, "HostProperties/tag[@name='system-type']") - virtual_mac_address = get_text(host, "HostProperties/tag[@name='virtual-mac-address']") - wmi_domain = get_text(host, "HostProperties/tag[@name='wmi-domain']") - - scan_date = None - host_start_tag = host.find('HostProperties/tag[@name="HOST_START"]') - if host_start_tag is not None: - host_start = host_start_tag.text - if host_start: - try: - scan_date = datetime.strptime(host_start, "%a %b %d %H:%M:%S %Y").strftime("%Y-%m-%d") - except ValueError: - print(f"Invalid date format for host_start: {host_start}") - continue - - # Loop through each report item. - for item in host.iter("ReportItem"): - pluginFamily = item.attrib["pluginFamily"] - pluginID = item.attrib["pluginID"] - port = item.attrib["port"] - protocol = item.attrib["protocol"] - severity = item.attrib["severity"] - - severity_reversed = SEVERITY_MAPPING[int(severity)] - severity_rating = SEVERITY_RATING[severity_reversed] - - svc_name = item.attrib["svc_name"] - age_of_vuln = get_text(item, "age_of_vuln") - agent = get_text(item, "agent") - always_run = get_text(item, "always_run") - asset_categories = get_text(item, "asset_categories") - asset_inventory = get_text(item, "asset_inventory") - asset_inventory_category = get_text(item, "asset_inventory_category") - bid = get_text(item, "bid") - canvas_package = get_text(item, "canvas_package") - cea_id = get_text(item, "cea-id") - cert = get_text(item, "cert") - cisa_known_exploited = get_text(item, "cisa-known-exploited") - cisa_ncas = get_text(item, "cisa-ncas") - cisco_bug_id = get_text(item, "cisco-bug-id") - cisco_sa = get_text(item, "cisco-sa") - cpe = get_text(item, "cpe") - cve_elements = item.findall('cve') - cve = ', '.join(c.text for c in cve_elements) if cve_elements else '' - cvss_base_score = get_text(item, "cvss_base_score") - cvss_score_rationale = get_text(item, "cvss_score_rationale") - cvss_score_source = get_text(item, "cvss_score_source") - cvss_temporal_score = get_text(item, "cvss_temporal_score") - cvss_temporal_vector = get_text(item, "cvss_temporal_vector") - cvss_vector = get_text(item, "cvss_vector") - cvss3_base_score = get_text(item, "cvss3_base_score") - cvss3_score_source = get_text(item, "cvss3_score_source") - cvss3_temporal_score = get_text(item, "cvss3_temporal_score") - cvss3_temporal_vector = get_text(item, "cvss3_temporal_vector") - cvss3_vector = get_text(item, "cvss3_vector") - cvssV3_impactScore = get_text(item, "cvssV3_impactScore") - cwe = get_text(item, "cwe") - description = get_text(item, "description") - edb_id = get_text(item, "edb-id") - exploit_available = get_text(item, "exploit_available") - exploit_code_maturity = get_text(item, "exploit_code_maturity") - exploit_framework_canvas = get_text(item, "exploit_framework_canvas") - exploit_framework_core = get_text(item, "exploit_framework_core") - exploit_framework_metasploit = get_text(item, "exploit_framework_metasploit") - exploitability_ease = get_text(item, "exploitability_ease") - exploited_by_malware = get_text(item, "exploited_by_malware") - exploited_by_nessus = get_text(item, "exploited_by_nessus") - generated_plugin = get_text(item, "generated_plugin") - hardware_inventory = get_text(item, "hardware_inventory") - iava = get_text(item, "iava") - iavb = get_text(item, "iavb") - iavt = get_text(item, "iavt") - icsa = get_text(item, "icsa") - in_the_news = get_text(item, "in_the_news") - metasploit_name = get_text(item, "metasploit_name") - msft = get_text(item, "msft") - mskb = get_text(item, "mskb") - os_identification = get_text(item, "os_identification") - patch_publication_date = get_text(item, "patch_publication_date") - plugin_modification_date = get_text(item, "plugin_modification_date") - pluginName = item.attrib.get("pluginName") - plugin_output_element = item.find('plugin_output') - plugin_output = plugin_output_element.text.strip() if plugin_output_element is not None and plugin_output_element.text else "" - plugin_publication_date = get_text(item, "plugin_publication_date") - plugin_type = get_text(item, "plugin_type") - product_coverage = get_text(item, "product_coverage") - risk_factor = get_text(item, "risk_factor") - script_version = get_text(item, "script_version") - secunia = get_text(item, "secunia") - see_also = get_text(item, "see_also") - solution = get_text(item, "solution") - stig_severity = get_text(item, "stig_severity") - synopsis = get_text(item, "synopsis") - thorough_tests = get_text(item, "thorough_tests") - threat_intensity_last_28 = get_text(item, "threat_intensity_last_28") - threat_recency = get_text(item, "threat_recency") - threat_sources_last_28 = get_text(item, "threat_sources_last_28") - tra = get_text(item, "tra") - unsupported_by_vendor = get_text(item, "unsupported_by_vendor") - vmsa = get_text(item, "vmsa") - vpr_score = get_text(item, "vpr_score") - vuln_publication_date = get_text(item, "vuln_publication_date") - - # Column order: 106 fields matching CREATE TABLE and INSERT column order - batch.append([host_ip, mac_address, virtual_mac_address, hostname, netbios_name, host_fqdn, host_rdns, system_type, cpe, operating_system_id, operating_system, severity_rating, risk_factor, severity_reversed, pluginName, synopsis, description, solution, port, protocol, svc_name, plugin_output, plugin_type, plugin_publication_date, plugin_modification_date, stig_severity, cvss_base_score, cvss_vector, cvss_score_rationale, cvss_score_source, cvss_temporal_score, cvss_temporal_vector, cvss3_base_score, cvss3_vector, cvss3_score_source, cvss3_temporal_score, cvss3_temporal_vector, cvssV3_impactScore, vpr_score, patch_publication_date, patch_summary_total_cves, vuln_publication_date, age_of_vuln, product_coverage, exploit_available, exploitability_ease, exploit_code_maturity, exploit_framework_canvas, canvas_package, exploit_framework_core, exploit_framework_metasploit, metasploit_name, exploited_by_malware, exploited_by_nessus, edb_id, threat_recency, threat_intensity_last_28, threat_sources_last_28, local_checks_proto, smb_login_used, wmi_domain, thorough_tests, Credentialed_Scan, LastAuthenticatedResults, policy_used, host_start, host_start_timestamp, host_end, host_end_timestamp, os_identification, operating_system_conf, operating_system_method, sinfp_signature, pluginID, pluginFamily, script_version, agent, always_run, asset_inventory, asset_inventory_category, asset_categories, hardware_inventory, bid, cea_id, cert, cisa_known_exploited, cisa_ncas, cisco_bug_id, cisco_sa, cve, cwe, iava, iavb, iavt, icsa, msft, mskb, tra, vmsa, secunia, unsupported_by_vendor, see_also, in_the_news, generated_plugin, file_name, scan_date]) - - # If the batch is full, insert it into the database - if len(batch) >= batch_size: - insert_batch(batch) - batch = [] - - # Insert any remaining items in the batch - if batch: - insert_batch(batch) - -def insert_batch(batch): - """ - Inserts a batch of vulnerability data rows into the SQL Server database. + table, create = args.table, args.create_table + if not table: + table, create = choose_table(conn, input_fn) + if not table: + print("No table selected. Exiting.", file=sys.stderr) + return nc.EXIT_FAILED + try: + state = prepare_table(conn, table, create) + except ValueError as exc: + print(exc, file=sys.stderr) + return nc.EXIT_FAILED + print(f"\nProceeding with:\n Server: {server}\n Database: {database}\n" + f" Table: dbo.{table} ({state})\n" + "=" * 60) + + stats = nc.RunStats() + seen = set() + imported = 0 + for path in files: + failures_before = len(stats.failures) + rows = list(nc.iter_unique_rows([path], stats, seen)) + if len(stats.failures) > failures_before: + continue + try: + imported += import_rows(conn, table, rows) + except Exception as exc: + print(f"Error importing {path}: {exc}\nNothing from this file was kept " + "(rolled back). Stopping.", file=sys.stderr) + nc.report_failures(stats) + return nc.EXIT_FAILED + print(f"Imported {len(rows)} rows from {path}") + finally: + conn.close() - Uses parameterized queries with executemany() for efficient bulk insertion. - This method is much faster than inserting rows one at a time. + failed = nc.report_failures(stats) + print(f"Processed {stats.files_ok} of {stats.files_seen} files, {stats.hosts} hosts, " + f"{imported} rows sent ({stats.duplicates} duplicates removed before sending).") + print(nc.format_run_metrics(start_time)) + if stats.files_ok == 0: + return nc.EXIT_FAILED + return nc.EXIT_PARTIAL if failed else nc.EXIT_OK - Args: - batch: List of data rows to insert (each row is a list of values) - """ - # Table name validated by sanitize_table_name() — safe for bracket-quoting - insert_query = f''' - INSERT INTO [{table_name}] ( - host_ip, mac_address, virtual_mac_address, hostname, netbios_name, host_fqdn, host_rdns, system_type, cpe, operating_system_id, operating_system, severity_rating, risk_factor, severity_reversed, pluginName, synopsis, description, solution, port, protocol, svc_name, plugin_output, plugin_type, plugin_publication_date, plugin_modification_date, stig_severity, cvss_base_score, cvss_vector, cvss_score_rationale, cvss_score_source, cvss_temporal_score, cvss_temporal_vector, cvss3_base_score, cvss3_vector, cvss3_score_source, cvss3_temporal_score, cvss3_temporal_vector, cvssV3_impactScore, vpr_score, patch_publication_date, patch_summary_total_cves, vuln_publication_date, age_of_vuln, product_coverage, exploit_available, exploitability_ease, exploit_code_maturity, exploit_framework_canvas, canvas_package, exploit_framework_core, exploit_framework_metasploit, metasploit_name, exploited_by_malware, exploited_by_nessus, edb_id, threat_recency, threat_intensity_last_28, threat_sources_last_28, local_checks_proto, smb_login_used, wmi_domain, thorough_tests, Credentialed_Scan, LastAuthenticatedResults, policy_used, host_start, host_start_timestamp, host_end, host_end_timestamp, os_identification, operating_system_conf, operating_system_method, sinfp_signature, pluginID, pluginFamily, script_version, agent, always_run, asset_inventory, asset_inventory_category, asset_categories, hardware_inventory, bid, cea_id, cert, cisa_known_exploited, cisa_ncas, cisco_bug_id, cisco_sa, cve, cwe, iava, iavb, iavt, icsa, msft, mskb, tra, vmsa, secunia, unsupported_by_vendor, see_also, in_the_news, generated_plugin, file_path, scan_date - ) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - ''' - cursor.executemany(insert_query, batch) - conn.commit() - -# Process all .nessus files in the selected folder and its subfolders -for root, dirs, files in os.walk(folder_path): - for file in files: - if file.endswith('.nessus'): - file_path = os.path.join(root, file) - process_nessus_file(file_path) - -# Confirm completion and provide elapsed run time and peak memory usage. -print("Processing complete.") -end_time = time.time() -elapsed_time = end_time - start_time - -# Calculate minutes and seconds -hours = int(elapsed_time // 3600) -minutes = int((elapsed_time % 3600) // 60) -seconds = elapsed_time % 60 - -mem_info = psutil.Process().memory_info() -peak_mem_usage = getattr(mem_info, 'peak_wset', mem_info.rss) / 1024 / 1024 -print(f"Elapsed time: {hours} hours {minutes} minutes {seconds:.2f} seconds. Peak memory usage: {peak_mem_usage:.2f} MB.") - -# Close the database connection -cursor.close() -conn.close() + +if __name__ == "__main__": + sys.exit(main()) diff --git a/nessus_to_xlsx.py b/nessus_to_xlsx.py index b1fff64..a2680a8 100644 --- a/nessus_to_xlsx.py +++ b/nessus_to_xlsx.py @@ -1,275 +1,168 @@ """ Nessus to Excel (XLSX) Conversion Script -This script converts .nessus (XML) vulnerability scan files into Microsoft Excel -format (.xlsx) with formatted tables for easy analysis. It processes .nessus files -and extracts comprehensive vulnerability data, then creates a formatted Excel -workbook with: - -- Formatted table with alternating row colors for readability -- All vulnerability data in structured columns -- Host information, vulnerability details, CVSS scores, CVE IDs -- Exploit information and security references - -Features: -- Creates formatted Excel tables with professional styling -- Supports processing multiple .nessus files -- Removes duplicate findings automatically -- Provides progress tracking and performance metrics - -Note: Variable names (e.g., pluginName, Credentialed_Scan) mirror the Nessus XML -element and attribute names for traceability back to the source format. +Converts .nessus (XML) vulnerability scan files into a formatted Excel workbook +with one table of 106 columns per finding: host information, vulnerability +details, CVSS scores, CVE IDs, exploit information and security references. + +Usage: + python nessus_to_xlsx.py [-o OUTPUT.xlsx] PATH [PATH ...] + +Each PATH is a .nessus file or a folder (searched recursively). With no PATH the +script falls back to file pickers, which need a desktop session. + +Things to know: +- Repeated reference elements (CWE, BID, MSKB, ...) are all kept, joined with ", " +- Exact duplicate findings are removed and the original row order is kept +- Excel cells hold at most 32,767 characters. A longer value is cut and ends with + a "[truncated ...]" note, and the script prints how many cells were cut. Use + nessus_to_csv.py if you need the full text. +- A sheet holds at most 1,048,576 rows. Larger inputs stop with an error; split + the input or use the CSV script. +- Cells that start with = + - @ are stored as text, never as formulas +- Exit code 0 on success, 1 if nothing could be converted, 2 if some files failed """ -# Import required libraries. +import argparse import os -import xml.etree.ElementTree as ET -from openpyxl import Workbook -from openpyxl.worksheet.table import Table, TableStyleInfo +import sys import time -import tkinter as tk -from tkinter import filedialog -import psutil -from datetime import datetime - -# Severity constants (defined once, not per iteration) -SEVERITY_MAPPING = {0: 4, 1: 3, 2: 2, 3: 1, 4: 0} -SEVERITY_RATING = {0: "Critical", 1: "High", 2: "Medium", 3: "Low", 4: "Informational"} - - -def get_text(parent, xpath, default=""): - """Extract text from an XML element by XPath, returning default if not found.""" - el = parent.find(xpath) - return el.text if el is not None else default - - -# Create a file dialog window for the user to select multiple XML files. -root = tk.Tk() -root.withdraw() -xml_files = filedialog.askopenfilenames(title="Select files to process",filetypes=[("Nessus files", "*.nessus")]) - -# Start run timer. -start_time = time.time() - -# Create an empty list to store the data. -data = [] - -# Loop through each XML file. -for xml_file in xml_files: - # Extract just the file name from the file path - file_name = os.path.basename(xml_file) - - # Parse the XML file. - try: - tree = ET.parse(xml_file) - except ET.ParseError as e: - print(f"Error parsing {xml_file}: {e}") - continue - - xml_root = tree.getroot() - print(f"Processing {xml_file}") - # Get the total number of hosts. - total_hosts = len(list(xml_root.iter("ReportHost"))) - - # Process each host. - for i, host in enumerate(xml_root.iter("ReportHost"), 1): - host_cpe = get_text(host, "HostProperties/tag[@name='cpe']") - Credentialed_Scan = get_text(host, "HostProperties/tag[@name='Credentialed_Scan']") - host_end = get_text(host, "HostProperties/tag[@name='HOST_END']") - host_end_timestamp = get_text(host, "HostProperties/tag[@name='HOST_END_TIMESTAMP']") - host_start = get_text(host, "HostProperties/tag[@name='HOST_START']") - host_start_timestamp = get_text(host, "HostProperties/tag[@name='HOST_START_TIMESTAMP']") - host_fqdn = get_text(host, "HostProperties/tag[@name='host-fqdn']") - host_ip = get_text(host, "HostProperties/tag[@name='host-ip']") - hostname = get_text(host, "HostProperties/tag[@name='hostname']") - host_rdns = get_text(host, "HostProperties/tag[@name='host-rdns']") - LastAuthenticatedResults = get_text(host, "HostProperties/tag[@name='LastAuthenticatedResults']") - local_checks_proto = get_text(host, "HostProperties/tag[@name='local-checks-proto']") - mac_address = get_text(host, "HostProperties/tag[@name='mac-address']") - netbios_name = get_text(host, "HostProperties/tag[@name='netbios-name']") - operating_system = get_text(host, "HostProperties/tag[@name='operating-system']") - operating_system_conf = get_text(host, "HostProperties/tag[@name='operating-system-conf']") - operating_system_method = get_text(host, "HostProperties/tag[@name='operating-system-method']") - operating_system_id = get_text(host, "HostProperties/tag[@name='os']") - patch_summary_total_cves = get_text(host, "HostProperties/tag[@name='patch-summary-total-cves']") - policy_used = get_text(host, "HostProperties/tag[@name='policy-used']") - sinfp_signature = get_text(host, "HostProperties/tag[@name='sinfp-signature']") - smb_login_used = get_text(host, "HostProperties/tag[@name='smb-login-used']") - system_type = get_text(host, "HostProperties/tag[@name='system-type']") - virtual_mac_address = get_text(host, "HostProperties/tag[@name='virtual-mac-address']") - wmi_domain = get_text(host, "HostProperties/tag[@name='wmi-domain']") +from openpyxl import Workbook +from openpyxl.worksheet.table import Table, TableStyleInfo - # Extract scan_date from host_start - scan_date = None - host_start_tag = host.find('HostProperties/tag[@name="HOST_START"]') - if host_start_tag is not None: - host_start = host_start_tag.text - if host_start: - try: - scan_date = datetime.strptime(host_start, "%a %b %d %H:%M:%S %Y").strftime("%Y-%m-%d") - except ValueError: - pass +import nessus_common as nc - # Loop through each report item - for item in host.iter("ReportItem"): - pluginFamily = item.attrib["pluginFamily"] - pluginID = item.attrib["pluginID"] - port = item.attrib["port"] - protocol = item.attrib["protocol"] - severity = item.attrib["severity"] +DEFAULT_OUTPUT = "nessus_conversion.xlsx" - severity_reversed = SEVERITY_MAPPING[int(severity)] - severity_rating = SEVERITY_RATING[severity_reversed] - svc_name = item.attrib["svc_name"] - age_of_vuln = get_text(item, "age_of_vuln") - agent = get_text(item, "agent") - always_run = get_text(item, "always_run") - asset_categories = get_text(item, "asset_categories") - asset_inventory = get_text(item, "asset_inventory") - asset_inventory_category = get_text(item, "asset_inventory_category") - bid = get_text(item, "bid") - canvas_package = get_text(item, "canvas_package") - cea_id = get_text(item, "cea-id") - cert = get_text(item, "cert") - cisa_known_exploited = get_text(item, "cisa-known-exploited") - cisa_ncas = get_text(item, "cisa-ncas") - cisco_bug_id = get_text(item, "cisco-bug-id") - cisco_sa = get_text(item, "cisco-sa") - cpe = get_text(item, "cpe") - cve_elements = item.findall('cve') - cve = ', '.join(c.text for c in cve_elements) if cve_elements else '' - cvss_base_score = get_text(item, "cvss_base_score") - cvss_score_rationale = get_text(item, "cvss_score_rationale") - cvss_score_source = get_text(item, "cvss_score_source") - cvss_temporal_score = get_text(item, "cvss_temporal_score") - cvss_temporal_vector = get_text(item, "cvss_temporal_vector") - cvss_vector = get_text(item, "cvss_vector") - cvss3_base_score = get_text(item, "cvss3_base_score") - cvss3_score_source = get_text(item, "cvss3_score_source") - cvss3_temporal_score = get_text(item, "cvss3_temporal_score") - cvss3_temporal_vector = get_text(item, "cvss3_temporal_vector") - cvss3_vector = get_text(item, "cvss3_vector") - cvssV3_impactScore = get_text(item, "cvssV3_impactScore") - cwe = get_text(item, "cwe") - description = get_text(item, "description") - edb_id = get_text(item, "edb-id") - exploit_available = get_text(item, "exploit_available") - exploit_code_maturity = get_text(item, "exploit_code_maturity") - exploit_framework_canvas = get_text(item, "exploit_framework_canvas") - exploit_framework_core = get_text(item, "exploit_framework_core") - exploit_framework_metasploit = get_text(item, "exploit_framework_metasploit") - exploitability_ease = get_text(item, "exploitability_ease") - exploited_by_malware = get_text(item, "exploited_by_malware") - exploited_by_nessus = get_text(item, "exploited_by_nessus") - generated_plugin = get_text(item, "generated_plugin") - hardware_inventory = get_text(item, "hardware_inventory") - iava = get_text(item, "iava") - iavb = get_text(item, "iavb") - iavt = get_text(item, "iavt") - icsa = get_text(item, "icsa") - in_the_news = get_text(item, "in_the_news") - metasploit_name = get_text(item, "metasploit_name") - msft = get_text(item, "msft") - mskb = get_text(item, "mskb") - os_identification = get_text(item, "os_identification") - patch_publication_date = get_text(item, "patch_publication_date") - plugin_modification_date = get_text(item, "plugin_modification_date") - pluginName = item.attrib.get("pluginName") - plugin_output_element = item.find('plugin_output') - plugin_output = plugin_output_element.text.strip() if plugin_output_element is not None and plugin_output_element.text else "" - plugin_publication_date = get_text(item, "plugin_publication_date") - plugin_type = get_text(item, "plugin_type") - product_coverage = get_text(item, "product_coverage") - risk_factor = get_text(item, "risk_factor") - script_version = get_text(item, "script_version") - secunia = get_text(item, "secunia") - see_also = get_text(item, "see_also") - solution = get_text(item, "solution") - stig_severity = get_text(item, "stig_severity") - synopsis = get_text(item, "synopsis") - thorough_tests = get_text(item, "thorough_tests") - threat_intensity_last_28 = get_text(item, "threat_intensity_last_28") - threat_recency = get_text(item, "threat_recency") - threat_sources_last_28 = get_text(item, "threat_sources_last_28") - tra = get_text(item, "tra") - unsupported_by_vendor = get_text(item, "unsupported_by_vendor") - vmsa = get_text(item, "vmsa") - vpr_score = get_text(item, "vpr_score") - vuln_publication_date = get_text(item, "vuln_publication_date") +class TooManyRowsError(Exception): + """The input has more findings than one Excel sheet can hold.""" - # Column order: 106 fields matching XLSX headers - data.append([host_ip, mac_address, virtual_mac_address, hostname, netbios_name, host_fqdn, host_rdns, system_type, cpe, operating_system_id, operating_system, severity_rating, risk_factor, severity_reversed, pluginName, synopsis, description, solution, port, protocol, svc_name, plugin_output, plugin_type, plugin_publication_date, plugin_modification_date, stig_severity, cvss_base_score, cvss_vector, cvss_score_rationale, cvss_score_source, cvss_temporal_score, cvss_temporal_vector, cvss3_base_score, cvss3_vector, cvss3_score_source, cvss3_temporal_score, cvss3_temporal_vector, cvssV3_impactScore, vpr_score, patch_publication_date, patch_summary_total_cves, vuln_publication_date, age_of_vuln, product_coverage, exploit_available, exploitability_ease, exploit_code_maturity, exploit_framework_canvas, canvas_package, exploit_framework_core, exploit_framework_metasploit, metasploit_name, exploited_by_malware, exploited_by_nessus, edb_id, threat_recency, threat_intensity_last_28, threat_sources_last_28, local_checks_proto, smb_login_used, wmi_domain, thorough_tests, Credentialed_Scan, LastAuthenticatedResults, policy_used, host_start, host_start_timestamp, host_end, host_end_timestamp, os_identification, operating_system_conf, operating_system_method, sinfp_signature, pluginID, pluginFamily, script_version, agent, always_run, asset_inventory, asset_inventory_category, asset_categories, hardware_inventory, bid, cea_id, cert, cisa_known_exploited, cisa_ncas, cisco_bug_id, cisco_sa, cve, cwe, iava, iavb, iavt, icsa, msft, mskb, tra, vmsa, secunia, unsupported_by_vendor, see_also, in_the_news, generated_plugin, file_name, scan_date]) -# Define remove duplicates function. -def remove_duplicates(data): +def fit_cell(value): """ - Removes duplicate rows from the extracted vulnerability data. - - Args: - data: List of data rows (each row is a list of values) + Return (value, was_truncated) for a cell value that must fit Excel's limit. - Returns: - A tuple containing: - - List of unique rows (duplicates removed) - - Count of duplicates that were removed + Text over 32,767 characters is cut so that the result, including a short + note saying how long the original was, is exactly at the limit. openpyxl + would otherwise cut it with no sign. """ - unique_rows = set() - duplicates_removed = 0 - for row in data: - row_tuple = tuple(row) - if row_tuple not in unique_rows: - unique_rows.add(row_tuple) + if isinstance(value, str) and len(value) > nc.XLSX_MAX_CELL: + note = f" [truncated, original was {len(value)} characters]" + return value[:nc.XLSX_MAX_CELL - len(note)] + note, True + return value, False + + +def prepare_cell(value): + """Neutralise formulas, then fit the Excel size limit. Returns (value, truncated).""" + if value is None: + return None, False + return fit_cell(nc.neutralize_cell(value)) + + +def build_workbook(files, stats): + """Read `files` into a new Workbook. Returns (workbook, rows_written, cells_truncated).""" + wb = Workbook() + ws = wb.active + assert ws is not None # a new Workbook always has an active worksheet + ws.append(nc.XLSX_HEADERS) + rows_written = 0 + truncated_cells = 0 + for row in nc.iter_unique_rows(files, stats): + if rows_written + 1 >= nc.XLSX_MAX_ROWS: + raise TooManyRowsError( + f"More than {nc.XLSX_MAX_ROWS - 1} findings do not fit on one Excel sheet. " + "Split the input or use nessus_to_csv.py.") + out_row = [] + for value in row: + cell, cut = prepare_cell(value) + truncated_cells += cut + out_row.append(cell) + ws.append(out_row) + rows_written += 1 + if rows_written % 1000 == 0: + print(f"\rRead {rows_written} rows...", end="", flush=True) + + if rows_written: + table_range = f"A1:{ws.cell(row=ws.max_row, column=ws.max_column).coordinate}" + table = Table(displayName="Table1", ref=table_range) + table.tableStyleInfo = TableStyleInfo( + name="TableStyleMedium2", showFirstColumn=False, showLastColumn=False, + showRowStripes=True, showColumnStripes=False) + ws.add_table(table) + return wb, rows_written, truncated_cells + + +def parse_args(argv): + parser = argparse.ArgumentParser(description="Convert .nessus files to Excel.") + parser.add_argument("paths", nargs="*", help=".nessus files or folders (recursive)") + parser.add_argument("-o", "--output", help=f"output XLSX path (default: {DEFAULT_OUTPUT})") + return parser.parse_args(argv) + + +def main(argv=None): + args = parse_args(sys.argv[1:] if argv is None else argv) + start_time = time.time() + + paths = args.paths + if not paths: + paths = nc.pick_inputs_gui() + if not paths: + print("No files or folder selected. Exiting.") + return nc.EXIT_FAILED + try: + files = nc.collect_nessus_files(paths) + except FileNotFoundError as exc: + print(exc, file=sys.stderr) + return nc.EXIT_FAILED + if not files: + print("No .nessus files found. Exiting.", file=sys.stderr) + return nc.EXIT_FAILED + + output_path = args.output + if not output_path: + if args.paths: + output_path = DEFAULT_OUTPUT else: - duplicates_removed += 1 - return [list(row_tuple) for row_tuple in unique_rows], duplicates_removed - -# Remove duplicates from the data. -data, duplicates_removed = remove_duplicates(data) - -# Print a message displaying the number of removed duplicates. -if duplicates_removed > 0: - print(f"Removed {duplicates_removed} duplicate rows from the data.") -else: - print("No duplicate rows found.") - -# Define the default filename -xlsx_filename = "nessus_conversion.xlsx" + output_path = nc.pick_output_gui(DEFAULT_OUTPUT, ".xlsx") + if not output_path: + print("No output file selected. Exiting.") + return nc.EXIT_FAILED -# Open a file dialog to choose the output filename and directory -xlsx_filename = filedialog.asksaveasfilename(defaultextension=".xlsx", initialfile=xlsx_filename, title="Save XLSX File As...") - -# Write the data to an XLSX file with a progress indicator. -print(f"Processed {len(xml_files)} files, {total_hosts} hosts, and {len(data)} findings.\nNow writing to XLSX: {xlsx_filename}.") -wb = Workbook() -ws = wb.active -assert ws is not None # New Workbook always has an active worksheet -ws.append(["IP Address", "MAC Address", "Virtual MAC Address", "Hostname", "NETBIOS", "FQDN", "RDNS", "System Type", "CPE", "OS Family", "Operating System", "Severity Rating", "Risk Factor", "Severity Number", "Plugin Name", "Synopsis", "Description", "Solution", "Port", "Protocol", "Service Name", "Plugin Output", "Plugin Type", "Plugin Publication Date", "Plugin Modification Date", "STIG Severity", "CVSS Score", "CVSS Vector", "CVSS Score Rationale", "CVSS Score Source", "CVSS Temporal Score", "CVSS Temporal Vector", "CVSS3 Score", "CVSS3 Vector", "CVSS3 Score Source", "CVSS3 Temporal Score", "CVSS3 Temporal Vector", "CVSS3 Impact Score", "VPR Score", "Patch Publication Date", "Patch Summary CVE Count", "Vulnerability Publication Date", "Vulnerability Age", "Product Coverage", "Exploit Available", "Exploitability Ease", "Exploit Code Maturity", "Exploitable with CANVAS", "CANVAS Package", "Exploitable with Core Impact", "Exploitable with Metasploit", "Metasploit Module", "Exploitable by Malware", "Exploitable by Nessus", "Exploit DB ID", "Threat Recency", "Threat Intensity Last 28 Days", "Threat Sources Last 28 Days", "Local Checks Protocol", "SMB Login Used", "WMI Domain", "Thorough Tests Used", "Credentialed Scan Used", "Authentication Issues", "Policy Used", "Host Scan Started", "Host Scan Started Timestamp", "Host Scan Ended", "Host Scan Ended Timestamp", "OS Identified", "Operating System Confidence", "OS Identification Method", "SinFP Signature", "Plugin ID", "Plugin Family", "Script Version", "Agent Used", "Always Run", "Asset Inventory", "Asset Inventory Category", "Asset Categories", "Hardware Inventory", "BugtraqID", "CEA Id", "CERT", "CISA Known Exploited", "CISA NCAS", "Cisco Bug ID", "Cisco Security Advisory", "CVE", "CWE", "IAVA", "IAVB", "IAVT", "ICSA", "MSFT", "MSKB", "Trust Research Advisory", "VMWare Security Advisory", "Secunia Security Advisory", "Unsupported by Vendor", "See Also", "In The News", "Generated Plugin", "File Name", "Scan Date"]) -for progress, row in enumerate(data, start=1): - percent_complete = (progress / len(data)) * 100 - print(f"\rWriting data to XLSX: {percent_complete:.2f}% complete.", end="", flush=True) - ws.append(row) -print("\rWriting data to XLSX: 100.00% complete.") - -# Define the table range and create the table -print("Converting XLSX data to table") -table_range = f"A1:{ws.cell(row=ws.max_row, column=ws.max_column).coordinate}" -table = Table(displayName="Table1", ref=table_range) - -# Define the table style -style = TableStyleInfo(name="TableStyleMedium2", showFirstColumn=False, showLastColumn=False, showRowStripes=True, showColumnStripes=False) - -# Apply the table style and save the file -table.tableStyleInfo = style -ws.add_table(table) -wb.save(xlsx_filename) - -# Confirm completion and provide elapsed run time, peak CPU usage and peak memory usage. -print("Processing complete.") -end_time = time.time() -elapsed_time = end_time - start_time -peak_cpu_usage = psutil.Process().cpu_percent() -mem_info = psutil.Process().memory_info() -peak_mem_usage = getattr(mem_info, 'peak_wset', mem_info.rss) / 1024 / 1024 -print(f"Elapsed time: {elapsed_time:.2f} seconds. Peak CPU usage: {peak_cpu_usage}%. Peak memory usage: {peak_mem_usage:.2f} MB.") + stats = nc.RunStats() + try: + wb, rows_written, truncated = build_workbook(files, stats) + except TooManyRowsError as exc: + print(f"\n{exc}", file=sys.stderr) + return nc.EXIT_FAILED + print() + failed = nc.report_failures(stats) + if stats.files_ok == 0: + print("No file could be read. No workbook was written.", file=sys.stderr) + return nc.EXIT_FAILED + + if stats.duplicates: + print(f"Removed {stats.duplicates} duplicate rows from the data.") + else: + print("No duplicate rows found.") + if truncated: + print(f"WARNING: {truncated} cell(s) were longer than Excel's 32,767 character limit " + "and were cut. Use nessus_to_csv.py for the full text.", file=sys.stderr) + + print(f"Processed {stats.files_ok} of {stats.files_seen} files, {stats.hosts} hosts, " + f"and {rows_written} findings.\nNow writing to XLSX: {output_path}.") + tmp_path = output_path + ".tmp" + try: + wb.save(tmp_path) + os.replace(tmp_path, output_path) + except BaseException: + if os.path.exists(tmp_path): + os.remove(tmp_path) + raise + print(nc.format_run_metrics(start_time)) + return nc.EXIT_PARTIAL if failed else nc.EXIT_OK + + +if __name__ == "__main__": + sys.exit(main()) From 938b2a85dbbf631b34fafb4b715b2ab22c7f2779 Mon Sep 17 00:00:00 2001 From: NullSpace-BitCradle <216858096+NullSpace-BitCradle@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:09:24 -0700 Subject: [PATCH 2/9] Harden the Tenable.io downloader Timeouts on every call, credentials from getpass or environment variables, safe output names, 429 retry, failed-export detection, partial-download check, and --all/--scan-id/--output-dir. No work runs at import time. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi --- tenable_scan_retrieval.py | 427 ++++++++++++++++++++++---------------- 1 file changed, 253 insertions(+), 174 deletions(-) diff --git a/tenable_scan_retrieval.py b/tenable_scan_retrieval.py index dc07761..35e19a5 100644 --- a/tenable_scan_retrieval.py +++ b/tenable_scan_retrieval.py @@ -1,199 +1,254 @@ """ Tenable.io Scan Retrieval Script -This script connects to Tenable.io (cloud vulnerability management platform) via API -to retrieve and download vulnerability scan results. It allows users to: -- Authenticate with Tenable.io using API keys -- View all available scans -- Select scans interactively (single, multiple, or all) -- Export selected scans in .nessus format -- Organize downloads in a date-based directory structure (Year/Month-Name/Week-XX) - -The script handles the full export workflow: -1. Initiates scan export requests -2. Monitors export status until ready -3. Downloads completed exports with progress tracking -4. Saves files with sanitized names in organized directories +Connects to Tenable.io (cloud vulnerability management platform) through its API +and downloads scan results in .nessus format. It lets you: +- Authenticate with API keys (environment variables, or a prompt that hides the secret key) +- List all available scans +- Pick scans interactively (single, multiple or all), or name them on the command line +- Save the files in a date-based directory structure (Year/MM-MonthName/Week-XX) + +Usage: + python tenable_scan_retrieval.py # interactive + python tenable_scan_retrieval.py --all # every scan, no prompts + python tenable_scan_retrieval.py --scan-id 12 --scan-id 34 + python tenable_scan_retrieval.py --all --output-dir D:\\scans + +Credentials: set TENABLE_ACCESS_KEY and TENABLE_SECRET_KEY, or you are asked for +them (the secret key is not shown as you type). They are never written to disk. + +Set TENABLE_URL to use another Tenable cloud, for example https://fedcloud.tenable.com. + +Each download goes to a .part file and is renamed only when it is complete, so +an interrupted download never leaves a truncated .nessus behind. Files are named +-.nessus so two scans with the same name do not overwrite +each other. The exit code is 0 if every selected scan downloaded, 1 otherwise. """ -import requests +import argparse import datetime -import time +import getpass import logging import os import re import sys +import time + +import requests # Setup logging to track script execution and errors logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") +DEFAULT_BASE_URL = "https://cloud.tenable.com" +# (connect timeout, read timeout) in seconds. Every request uses it so a stalled +# connection cannot hang the script. +TIMEOUT = (10, 60) +MAX_RATE_LIMIT_RETRIES = 3 +MAX_RETRY_AFTER = 60 + +_FAILED_EXPORT_STATUSES = {"error", "failed", "cancelled", "canceled"} + + +def get_base_url(): + """Tenable API base URL: TENABLE_URL if set (must be https), else Tenable.io.""" + url = os.environ.get("TENABLE_URL", DEFAULT_BASE_URL).strip().rstrip("/") + if not url.lower().startswith("https://"): + logging.error("TENABLE_URL must start with https://") + sys.exit(1) + return url + + def get_api_credentials(): - """Prompt user for Tenable.io API credentials at runtime.""" + """Get Tenable.io API keys from the environment, or prompt for them at runtime.""" + access_key = os.environ.get("TENABLE_ACCESS_KEY", "").strip() + secret_key = os.environ.get("TENABLE_SECRET_KEY", "").strip() + if access_key and secret_key: + return access_key, secret_key + print("=" * 60) print("Tenable.io API Credentials") print("=" * 60) print("Enter your Tenable.io API credentials.") print("You can find these in Tenable.io under Settings > My Account > API Keys") + print("(Or set TENABLE_ACCESS_KEY and TENABLE_SECRET_KEY.)") print() - - access_key = input("Enter Access Key: ").strip() + + if not access_key: + access_key = input("Enter Access Key: ").strip() if not access_key: logging.error("Access Key is required. Exiting.") sys.exit(1) - - secret_key = input("Enter Secret Key: ").strip() + + if not secret_key: + secret_key = getpass.getpass("Enter Secret Key (hidden): ").strip() if not secret_key: logging.error("Secret Key is required. Exiting.") sys.exit(1) - + print() return access_key, secret_key -# Get current date info -current_date = datetime.datetime.now() -year = current_date.strftime("%Y") # Four-digit year (e.g., "2025") -month_num = current_date.strftime("%m") # Two-digit month (e.g., "03") -month_name = current_date.strftime("%B") # Full month name (e.g., "March") -week_number = current_date.isocalendar().week # ISO week number (correct calendar week) -# Construct dynamic directory structure -OUTPUT_DIR = os.path.join(year, f"{month_num}-{month_name}", f"Week-{week_number:02d}") +def build_output_dir(now=None, base=""): + """ + Build the Year/MM-MonthName/Week-XX path for a date. Does not create it. + + The year and week are both ISO values, so 2027-01-01 (ISO week 53 of 2026) + lands in 2026/01-January/Week-53 rather than a Week-53 folder under 2027. + """ + now = now or datetime.datetime.now() + iso = now.isocalendar() + return os.path.join( + base, str(iso.year), f"{now.strftime('%m')}-{now.strftime('%B')}", f"Week-{iso.week:02d}") -# Ensure all directories exist -os.makedirs(OUTPUT_DIR, exist_ok=True) -# Print output directory path for verification -print(f"Output directory set to: {OUTPUT_DIR}") +_RESERVED_NAMES = {"CON", "PRN", "AUX", "NUL"} | {f"COM{i}" for i in range(1, 10)} | { + f"LPT{i}" for i in range(1, 10)} + def sanitize_filename(filename): """ - Sanitizes filenames by removing invalid characters that could cause OS issues. - - Replaces characters that are not allowed in Windows/Linux filenames with underscores. - This prevents file system errors when saving downloaded scan files. - - Args: - filename: The original filename that may contain invalid characters - - Returns: - A sanitized filename safe for use in file systems + Turn a scan name into a safe single file name component. + + Replaces path separators (both kinds), drive colons, wildcard and control + characters with underscores, strips trailing dots and spaces, avoids + Windows reserved device names and caps the length. The result can never + contain a path separator or be '.' or '..'. + """ + name = re.sub(r'[\\/:*?"<>|\x00-\x1f]', "_", str(filename)) + name = name.strip().rstrip(". ") + if not name: + name = "scan" + if name.split(".")[0].upper() in _RESERVED_NAMES: + name = "_" + name + return name[:150].rstrip(". ") or "scan" + + +def request_with_retry(method, url, **kwargs): """ - return re.sub(r'[\/:*?"<>|]', '_', filename) # Replace special characters with "_" + Call requests.get/post with the module timeout, waiting and retrying on HTTP 429. + + Honours Retry-After (capped), up to MAX_RATE_LIMIT_RETRIES retries. Returns the + final response; the caller still calls raise_for_status(). + """ + kwargs.setdefault("timeout", TIMEOUT) + func = requests.get if method == "get" else requests.post + response = func(url, **kwargs) + retries = 0 + while response.status_code == 429 and retries < MAX_RATE_LIMIT_RETRIES: + try: + delay = float(response.headers.get("Retry-After", 5)) + except (TypeError, ValueError): + delay = 5.0 + delay = min(max(delay, 1.0), MAX_RETRY_AFTER) + logging.warning(f"Rate limited (HTTP 429). Waiting {delay:.0f}s before retrying.") + time.sleep(delay) + retries += 1 + response = func(url, **kwargs) + return response + def get_all_scans(headers): """ Fetches all available vulnerability scans from Tenable.io. - Connects to the Tenable.io API to retrieve a list of all scans accessible - with the provided API credentials. This includes all scan types (scheduled, - on-demand, etc.) that the authenticated user has access to. - Args: headers: HTTP headers dict with API authentication keys Returns: - A list of scan dictionaries containing scan metadata (id, name, etc.) - Returns an empty list if the API call fails + A list of scan dictionaries (id, name, ...), possibly empty, or None if the + API call failed. """ - scans_url = "https://cloud.tenable.com/scans" + scans_url = f"{get_base_url()}/scans" try: - response = requests.get(scans_url, headers=headers) - response.raise_for_status() # Raise an exception for bad status codes - scans = response.json().get("scans", []) # Extract scans array from JSON response + response = request_with_retry("get", scans_url, headers=headers) + response.raise_for_status() + scans = response.json().get("scans") or [] # the API may send "scans": null logging.info(f"Found {len(scans)} scans.") return scans - except requests.exceptions.RequestException as e: + except (requests.exceptions.RequestException, ValueError) as e: logging.error(f"Error fetching scans: {e}") - return [] + return None + def initiate_export(scan_id, headers): """ Initiates an export request for a specific scan in .nessus format. - Tenable.io exports are asynchronous - this function starts the export process - and returns a file_id that can be used to check status and download the file - once the export is complete. - - Args: - scan_id: The unique identifier of the scan to export - headers: HTTP headers dict with API authentication keys - Returns: The file_id string if export was initiated successfully, None otherwise """ - export_url = f"https://cloud.tenable.com/scans/{scan_id}/export" + export_url = f"{get_base_url()}/scans/{scan_id}/export" try: - # Request export in .nessus format (XML format used by Nessus/Tenable) - response = requests.post(export_url, headers=headers, json={"format": "nessus"}) + response = request_with_retry("post", export_url, headers=headers, json={"format": "nessus"}) response.raise_for_status() - file_id = response.json().get("file") # Extract file_id from response + file_id = response.json().get("file") if file_id: logging.info(f"Export initiated for scan {scan_id}. File ID: {file_id}") return file_id - else: - logging.error(f"Failed to retrieve file ID for scan {scan_id}.") - except requests.exceptions.RequestException as e: + logging.error(f"Failed to retrieve file ID for scan {scan_id}.") + except (requests.exceptions.RequestException, ValueError) as e: logging.error(f"Error initiating export for scan {scan_id}: {e}") return None + def wait_for_export(scan_id, file_id, headers, max_retries=30, wait_time=5): """ Polls the export status until the scan export is ready for download. - Since Tenable.io exports are asynchronous, this function periodically checks - the export status until it becomes "ready". This prevents attempting to download - a file that hasn't finished exporting yet. - - Args: - scan_id: The unique identifier of the scan being exported - file_id: The file identifier returned from initiate_export() - headers: HTTP headers dict with API authentication keys - max_retries: Maximum number of status check attempts (default: 30) - wait_time: Seconds to wait between status checks (default: 5) - Returns: - True if export is ready, False if timeout is reached + True if the export is ready. False if Tenable reports a failed export or + max_retries * wait_time seconds pass without it becoming ready. """ - status_url = f"https://cloud.tenable.com/scans/{scan_id}/export/{file_id}/status" + status_url = f"{get_base_url()}/scans/{scan_id}/export/{file_id}/status" for attempt in range(max_retries): try: - response = requests.get(status_url, headers=headers) + response = request_with_retry("get", status_url, headers=headers) response.raise_for_status() status = response.json().get("status") if status == "ready": logging.info(f"Export ready for scan {scan_id}. File ID: {file_id}") return True + if status and str(status).lower() in _FAILED_EXPORT_STATUSES: + logging.error(f"Export for scan {scan_id} failed with status '{status}'. Skipping.") + return False logging.info(f"Waiting for export {scan_id}... (Attempt {attempt + 1}/{max_retries})") - except requests.exceptions.RequestException as e: + except (requests.exceptions.RequestException, ValueError) as e: logging.error(f"Error checking export status for scan {scan_id}: {e}") - time.sleep(wait_time) # Wait before next status check + time.sleep(wait_time) logging.error(f"Export did not complete for scan {scan_id}. Skipping.") return False -def download_scan(scan_id, scan_name, file_id, headers): + +def scan_output_path(output_dir, scan_name, scan_id): + """Full path for a scan's .nessus file, guaranteed to sit directly inside output_dir.""" + safe_name = sanitize_filename(scan_name) + safe_id = sanitize_filename(scan_id) + path = os.path.join(output_dir, f"{safe_name}-{safe_id}.nessus") + if os.path.dirname(os.path.abspath(path)) != os.path.abspath(output_dir): + raise ValueError(f"Refusing to write outside {output_dir}: {path}") + return path + + +def download_scan(scan_id, scan_name, file_id, headers, output_dir): """ Downloads the exported .nessus scan file with progress tracking. - Downloads the completed export file in chunks to handle large files efficiently. - Displays real-time progress including percentage complete and download speed. - Files are saved to the date-organized output directory. - - Args: - scan_id: The unique identifier of the scan - scan_name: The name of the scan (used for filename) - file_id: The file identifier from the export process - headers: HTTP headers dict with API authentication keys + The data goes to '.part' and is renamed to '' only after the whole + body arrived (and matched Content-Length when the server gave one), so a failed + or interrupted download leaves no .nessus file. Returns: The path to the downloaded file if successful, None otherwise """ - download_url = f"https://cloud.tenable.com/scans/{scan_id}/export/{file_id}/download" - safe_scan_name = sanitize_filename(scan_name) # Ensure valid filename - output_file = os.path.join(OUTPUT_DIR, f"{safe_scan_name}.nessus") + download_url = f"{get_base_url()}/scans/{scan_id}/export/{file_id}/download" + output_file = scan_output_path(output_dir, scan_name, scan_id) + part_file = output_file + ".part" try: - start_time = time.time() # Start timing - response = requests.get(download_url, headers=headers, stream=True) + os.makedirs(output_dir, exist_ok=True) + start_time = time.time() + response = request_with_retry("get", download_url, headers=headers, stream=True) response.raise_for_status() total_size = int(response.headers.get("Content-Length", 0)) @@ -201,86 +256,81 @@ def download_scan(scan_id, scan_name, file_id, headers): chunk_size = 1024 * 1024 # 1MB chunks last_update_time = start_time - with open(output_file, "wb") as f: + with open(part_file, "wb") as f: for chunk in response.iter_content(chunk_size=chunk_size): if chunk: f.write(chunk) downloaded_size += len(chunk) - # Calculate percentage percent_done = (downloaded_size / total_size) * 100 if total_size else 0 - - # Calculate speed current_time = time.time() elapsed_chunk_time = current_time - last_update_time last_update_time = current_time - if elapsed_chunk_time > 0: speed_mb_s = (len(chunk) / (1024 * 1024)) / elapsed_chunk_time else: speed_mb_s = 0 - # Update progress in the same line (stdout instead of logging) sys.stdout.write(f"\rDownloading {output_file}: {percent_done:.2f}% - Speed: {speed_mb_s:.2f} MB/s") sys.stdout.flush() - end_time = time.time() # End timing - elapsed_time = end_time - start_time # Total time taken + if total_size and downloaded_size != total_size: + raise requests.exceptions.ChunkedEncodingError( + f"incomplete download: got {downloaded_size} of {total_size} bytes") + os.replace(part_file, output_file) + + elapsed_time = time.time() - start_time file_size_mb = downloaded_size / (1024 * 1024) avg_speed = file_size_mb / elapsed_time if elapsed_time > 0 else 0 - logging.info(f"\nDownload complete: {output_file} | Size: {file_size_mb:.2f} MB | Avg Speed: {avg_speed:.2f} MB/s") return output_file - except requests.exceptions.RequestException as e: + except (requests.exceptions.RequestException, OSError) as e: logging.error(f"Error downloading scan {scan_id}: {e}") + if os.path.exists(part_file): + try: + os.remove(part_file) + except OSError: + pass return None + def select_scans_interactive(scans): """ Displays available scans and provides interactive selection interface. - - Shows all available scans in a numbered list and allows the user to: - - Select a single scan by entering its number - - Select multiple scans by entering comma-separated numbers (e.g., 1,3,5) - - Select all scans by entering "all" - - Includes validation and confirmation prompts to prevent accidental selections. - - Args: - scans: List of scan dictionaries from get_all_scans() - + + Lets the user select one scan (a number), several (comma-separated numbers) + or all ("all"), with a confirmation prompt. + Returns: List of selected scan dictionaries, or empty list if none selected """ if not scans: logging.info("No scans available to select.") return [] - + print("\n" + "=" * 60) print("Available Scans") print("=" * 60) - - # Display all scans with numbers + for idx, scan in enumerate(scans, 1): scan_id = scan.get("id") scan_name = scan.get("name", "Unknown Scan") print(f"{idx:3d}. {scan_name} (ID: {scan_id})") - + print("=" * 60) print("\nSelection Options:") print(" - Enter a single number (e.g., 1) to select one scan") print(" - Enter multiple numbers separated by commas (e.g., 1,3,5) to select multiple scans") print(" - Enter 'all' to select all scans") print() - + while True: selection = input("Enter your selection: ").strip().lower() - + if not selection: print("Please enter a selection.\n") continue - - # Handle "all" selection + if selection == "all": confirmation = input(f"Select all {len(scans)} scans? (Y/N): ").strip().lower() if confirmation == 'y': @@ -288,61 +338,78 @@ def select_scans_interactive(scans): else: print("Selection cancelled. Please try again.\n") continue - - # Handle numeric selections + try: - # Split by comma and strip whitespace selected_numbers = [num.strip() for num in selection.split(',')] selected_indices = [] - + for num_str in selected_numbers: num = int(num_str) if 1 <= num <= len(scans): - selected_indices.append(num - 1) # Convert to 0-based index + selected_indices.append(num - 1) else: print(f"Invalid number: {num}. Please enter numbers between 1 and {len(scans)}.\n") break else: - # All numbers were valid if not selected_indices: print("No valid selections made. Please try again.\n") continue - - # Remove duplicates while preserving order + selected_indices = list(dict.fromkeys(selected_indices)) selected_scans = [scans[idx] for idx in selected_indices] - - # Display selected scans for confirmation + print("\nSelected scans:") for idx in selected_indices: scan = scans[idx] - scan_name = scan.get("name", "Unknown Scan") - print(f" - {scan_name}") - + print(f" - {scan.get('name', 'Unknown Scan')}") + confirmation = input(f"\nProceed with {len(selected_scans)} scan(s)? (Y/N): ").strip().lower() if confirmation == 'y': return selected_scans else: print("Selection cancelled. Please try again.\n") continue - + except ValueError: print("Invalid input. Please enter numbers separated by commas, or 'all'.\n") continue -def main(): + +def select_scans_from_args(scans, args): + """Pick scans named by --all / --scan-id. Returns the list, or None if an id is unknown.""" + if args.all: + return scans + by_id = {str(s.get("id")): s for s in scans} + missing = [i for i in args.scan_id if str(i) not in by_id] + if missing: + logging.error(f"Scan id(s) not found: {', '.join(map(str, missing))}") + return None + return [by_id[str(i)] for i in dict.fromkeys(args.scan_id)] + + +def parse_args(argv): + parser = argparse.ArgumentParser(description="Download Tenable.io scans as .nessus files.") + parser.add_argument("--all", action="store_true", help="download every scan, no prompts") + parser.add_argument("--scan-id", action="append", default=[], + help="scan id to download (repeat for more), no prompts") + parser.add_argument("--output-dir", default="", + help="base folder for the Year/Month/Week folders (default: current folder)") + return parser.parse_args(argv) + + +def main(argv=None): """ Main execution function that orchestrates the scan retrieval workflow. - - Workflow: + 1. Fetches all available scans from Tenable.io - 2. Displays scans and allows user to select which ones to download - 3. For each selected scan: - - Initiates export request - - Waits for export to complete - - Downloads the exported .nessus file + 2. Selects scans (from --all / --scan-id, or interactively) + 3. For each selected scan: initiates the export, waits, downloads the .nessus file + + Returns the process exit code: 0 if every selected scan downloaded, else 1. """ - # Get API credentials at runtime (inside main to avoid prompting on import) + args = parse_args(sys.argv[1:] if argv is None else argv) + + # Credentials are read here, not at import time. access_key, secret_key = get_api_credentials() headers = { "X-ApiKeys": f"accessKey={access_key}; secretKey={secret_key};", @@ -354,36 +421,48 @@ def main(): print("Fetching Scans from Tenable.io") print("=" * 60) scans = get_all_scans(headers) - + if scans is None: + return 1 if not scans: logging.info("No scans found. Exiting.") - return - - # Interactive scan selection - user chooses which scans to download - selected_scans = select_scans_interactive(scans) - + return 0 + + if args.all or args.scan_id: + selected_scans = select_scans_from_args(scans, args) + if selected_scans is None: + return 1 + else: + selected_scans = select_scans_interactive(scans) + if not selected_scans: logging.info("No scans selected. Exiting.") - return - - print(f"\nProcessing {len(selected_scans)} selected scan(s)...\n") - - # Process each selected scan through the export and download workflow + return 0 + + output_dir = build_output_dir(base=args.output_dir) + print(f"\nOutput directory: {output_dir}") + print(f"Processing {len(selected_scans)} selected scan(s)...\n") + + failures = 0 for scan in selected_scans: scan_id = scan.get("id") scan_name = scan.get("name", "Unknown Scan") - + logging.info(f"Processing scan: {scan_name} (ID: {scan_id})") - - # Step 1: Initiate export request + file_id = initiate_export(scan_id, headers) if not file_id: - continue # Skip to next scan if export initiation failed + failures += 1 + continue + + if not wait_for_export(scan_id, file_id, headers) \ + or not download_scan(scan_id, scan_name, file_id, headers, output_dir): + failures += 1 + + if failures: + logging.error(f"{failures} of {len(selected_scans)} scan(s) were not downloaded.") + return 1 + return 0 - # Step 2: Wait for export to complete - if wait_for_export(scan_id, file_id, headers): - # Step 3: Download the completed export - download_scan(scan_id, scan_name, file_id, headers) if __name__ == "__main__": - main() \ No newline at end of file + sys.exit(main()) From f52ab898436609e39cfe41a115c2d007016a05c2 Mon Sep 17 00:00:00 2001 From: NullSpace-BitCradle <216858096+NullSpace-BitCradle@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:09:24 -0700 Subject: [PATCH 3/9] Add a pytest suite and CI 111 tests built on synthetic .nessus files and fake SQL and HTTP layers. The workflow runs them on every push and pull request. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi --- .github/workflows/tests.yml | 20 ++ pytest.ini | 3 + requirements-dev.txt | 3 + tests/helpers.py | 38 ++++ tests/test_common.py | 185 +++++++++++++++++++ tests/test_converters.py | 208 +++++++++++++++++++++ tests/test_sql.py | 357 ++++++++++++++++++++++++++++++++++++ tests/test_tenable.py | 254 +++++++++++++++++++++++++ 8 files changed, 1068 insertions(+) create mode 100644 .github/workflows/tests.yml create mode 100644 pytest.ini create mode 100644 requirements-dev.txt create mode 100644 tests/helpers.py create mode 100644 tests/test_common.py create mode 100644 tests/test_converters.py create mode 100644 tests/test_sql.py create mode 100644 tests/test_tenable.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..2bebee7 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,20 @@ +name: tests + +on: + push: + pull_request: + +jobs: + pytest: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, windows-latest] + python-version: ["3.9", "3.13"] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - run: python -m pip install -r requirements-dev.txt + - run: python -m pytest diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..c7b23ec --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +pythonpath = . +testpaths = tests diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..2e9f5e9 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,3 @@ +# Test dependencies. The tests do not need pyodbc or a display. +-r requirements.txt +pytest>=7.0,<10 diff --git a/tests/helpers.py b/tests/helpers.py new file mode 100644 index 0000000..788792d --- /dev/null +++ b/tests/helpers.py @@ -0,0 +1,38 @@ +"""Builders for small synthetic .nessus files. No real scan data is used anywhere in the tests.""" + +from xml.sax.saxutils import escape, quoteattr + + +def report_item(plugin_id="1000", name="Test plugin", severity=2, port="0", protocol="tcp", + svc_name="general", family="General", children=()): + """One . `children` is a list of (tag, text) pairs; a tag may repeat.""" + attrs = (f'port="{port}" svc_name="{svc_name}" protocol="{protocol}" severity="{severity}" ' + f'pluginID="{plugin_id}" pluginName={quoteattr(name)} pluginFamily="{family}"') + inner = "".join( + f"<{tag}/>" if text is None else f"<{tag}>{escape(text)}" for tag, text in children) + return f"{inner}" + + +def report_host(name, tags=(), items=()): + """One . `tags` is a list of (name, text) pairs.""" + tag_xml = "".join(f'{escape(v)}' for n, v in tags) + return (f'{tag_xml}' + f'{"".join(items)}') + + +def nessus_xml(hosts): + return ('' + f'{"".join(hosts)}') + + +def write_nessus(path, hosts): + path.write_text(nessus_xml(hosts), encoding="utf-8") + return str(path) + + +HOST_START = "Thu Apr 4 10:23:11 2024" + + +def basic_host(name="10.0.0.1", items=(), start=HOST_START, extra_tags=()): + tags = [("host-ip", name), ("HOST_START", start)] + list(extra_tags) + return report_host(name, tags, items) diff --git a/tests/test_common.py b/tests/test_common.py new file mode 100644 index 0000000..8af0739 --- /dev/null +++ b/tests/test_common.py @@ -0,0 +1,185 @@ +import pytest + +import nessus_common as nc +from helpers import basic_host, report_host, report_item, write_nessus + + +def col(row, name): + return row[nc.COLUMN_NAMES.index(name)] + + +def test_there_are_106_unique_columns_and_headers(): + assert len(nc.COLUMN_NAMES) == 106 + assert len(set(nc.COLUMN_NAMES)) == 106 + assert len(nc.XLSX_HEADERS) == 106 + assert nc.COLUMN_NAMES[0] == "host_ip" and nc.COLUMN_NAMES[-2:] == ["file_name", "scan_date"] + + +def test_every_row_is_106_wide(tmp_path): + path = write_nessus(tmp_path / "a.nessus", [basic_host(items=[report_item()])]) + rows = nc.parse_nessus_file(path) + assert [len(r) for r in rows] == [106] + + +def test_repeated_reference_elements_are_all_kept(tmp_path): + """Audit M2: only the first CWE/BID/... used to survive.""" + item = report_item(children=[ + ("cwe", "CWE-79"), ("cwe", "CWE-89"), + ("bid", "111"), ("bid", "222"), + ("cve", "CVE-2024-0001"), ("cve", "CVE-2024-0002"), + ("edb-id", "5"), ("edb-id", "6"), + ("cert", "A"), ("cert", "B"), + ("msft", "MS1"), ("msft", "MS2"), + ("mskb", "KB1"), ("mskb", "KB2"), + ]) + path = write_nessus(tmp_path / "a.nessus", [basic_host(items=[item])]) + (row,) = nc.parse_nessus_file(path) + assert col(row, "cwe") == "CWE-79, CWE-89" + assert col(row, "bid") == "111, 222" + assert col(row, "cve") == "CVE-2024-0001, CVE-2024-0002" + assert col(row, "edb_id") == "5, 6" + assert col(row, "cert") == "A, B" + assert col(row, "msft") == "MS1, MS2" + assert col(row, "mskb") == "KB1, KB2" + + +def test_empty_cve_element_does_not_crash(tmp_path): + """Audit M3: raised TypeError and lost the whole run.""" + item = report_item(children=[("cve", None), ("cve", "CVE-2024-1"), ("cwe", None)]) + path = write_nessus(tmp_path / "a.nessus", [basic_host(items=[item])]) + (row,) = nc.parse_nessus_file(path) + assert col(row, "cve") == "CVE-2024-1" + assert col(row, "cwe") == "" + + +def test_bad_host_start_keeps_the_host_with_no_scan_date(tmp_path): + """Audit M6: the SQL path used to drop the host's findings.""" + hosts = [ + basic_host("10.0.0.1", items=[report_item("1")]), + basic_host("10.0.0.2", items=[report_item("2"), report_item("3")], start="garbage date"), + ] + path = write_nessus(tmp_path / "a.nessus", hosts) + rows = nc.parse_nessus_file(path) + assert len(rows) == 3 + assert col(rows[0], "scan_date") == "2024-04-04" + assert col(rows[1], "scan_date") is None and col(rows[1], "host_ip") == "10.0.0.2" + assert col(rows[1], "host_start") == "garbage date" + + +def test_multiple_hosts_are_counted_and_keep_their_own_tags(tmp_path): + hosts = [ + basic_host("10.0.0.1", items=[report_item("1")], extra_tags=[("hostname", "alpha")]), + basic_host("10.0.0.2", items=[report_item("1")], extra_tags=[("hostname", "beta")]), + report_host("10.0.0.3", [("host-ip", "10.0.0.3")], []), # no findings + ] + path = write_nessus(tmp_path / "a.nessus", hosts) + stats = nc.RunStats() + rows = nc.parse_nessus_file(path, stats) + assert stats.hosts == 3 and stats.findings == 2 + assert [col(r, "hostname") for r in rows] == ["alpha", "beta"] + + +def test_severity_mapping_and_plugin_output_is_stripped(tmp_path): + items = [ + report_item("1", severity=0), + report_item("2", severity=4, children=[("plugin_output", " out \n")]), + ] + path = write_nessus(tmp_path / "a.nessus", [basic_host(items=items)]) + rows = nc.parse_nessus_file(path) + assert (col(rows[0], "severity_rating"), col(rows[0], "severity_reversed")) == ("Informational", 4) + assert (col(rows[1], "severity_rating"), col(rows[1], "severity_reversed")) == ("Critical", 0) + assert col(rows[1], "plugin_output") == "out" + + +def test_invalid_severity_is_a_parse_error(tmp_path): + path = write_nessus(tmp_path / "a.nessus", [basic_host(items=[report_item(severity="x")])]) + with pytest.raises(nc.NessusParseError): + nc.parse_nessus_file(path) + + +def test_first_host_tag_wins_and_item_cpe_is_used(tmp_path): + host = basic_host(items=[report_item(children=[("cpe", "cpe:/a:item")])], + extra_tags=[("cpe", "cpe:/o:host"), ("cpe", "cpe:/o:second")]) + path = write_nessus(tmp_path / "a.nessus", [host]) + (row,) = nc.parse_nessus_file(path) + assert col(row, "cpe") == "cpe:/a:item" + + +def test_malformed_xml_raises_parse_error(tmp_path): + bad = tmp_path / "bad.nessus" + bad.write_text("", encoding="utf-8") + with pytest.raises(nc.NessusParseError): + nc.parse_nessus_file(str(bad)) + + +def test_external_entity_is_not_resolved(tmp_path): + secret = tmp_path / "marker.txt" + secret.write_text("MARKER-TEXT", encoding="utf-8") + xml = (f']>' + '' + '&e;' + '') + bad = tmp_path / "xxe.nessus" + bad.write_text(xml, encoding="utf-8") + try: + rows = nc.parse_nessus_file(str(bad)) + except nc.NessusParseError: + return + assert "MARKER-TEXT" not in "".join(str(v) for r in rows for v in r) + + +def test_missing_file_is_a_parse_error(tmp_path): + with pytest.raises(nc.NessusParseError): + nc.parse_nessus_file(str(tmp_path / "nope.nessus")) + + +def test_dedupe_keeps_first_seen_order_and_counts(tmp_path): + items = [report_item(str(i)) for i in (3000, 1000, 2000, 1000, 3000, 4000)] + path = write_nessus(tmp_path / "a.nessus", [basic_host(items=items)]) + stats = nc.RunStats() + rows = list(nc.iter_unique_rows([path], stats)) + assert [col(r, "pluginID") for r in rows] == ["3000", "1000", "2000", "4000"] + assert stats.duplicates == 2 + + +def test_same_finding_in_two_differently_named_files_is_kept(tmp_path): + a = write_nessus(tmp_path / "a.nessus", [basic_host(items=[report_item("1")])]) + b = write_nessus(tmp_path / "b.nessus", [basic_host(items=[report_item("1")])]) + stats = nc.RunStats() + assert len(list(nc.iter_unique_rows([a, b], stats))) == 2 + assert stats.duplicates == 0 + + +def test_failed_file_is_recorded_and_others_continue(tmp_path): + good = write_nessus(tmp_path / "good.nessus", [basic_host(items=[report_item()])]) + bad = tmp_path / "bad.nessus" + bad.write_text("", encoding="utf-8") + out = tmp_path / "out.csv" + assert nessus_to_csv.main(["-o", str(out), str(bad), good]) == nc.EXIT_PARTIAL + assert len(read_csv(out)) == 2 + + +def test_csv_all_files_failed_is_an_error_and_writes_nothing(tmp_path): + bad = tmp_path / "bad.nessus" + bad.write_text("not xml", encoding="utf-8") + out = tmp_path / "out.csv" + out.write_text("previous good output", encoding="utf-8") + assert nessus_to_csv.main(["-o", str(out), str(bad)]) == nc.EXIT_FAILED + assert out.read_text(encoding="utf-8") == "previous good output" + assert not (tmp_path / "out.csv.tmp").exists() + + +def test_csv_missing_path_and_empty_folder_are_errors(tmp_path): + assert nessus_to_csv.main([str(tmp_path / "nope.nessus")]) == nc.EXIT_FAILED + empty = tmp_path / "empty" + empty.mkdir() + assert nessus_to_csv.main([str(empty)]) == nc.EXIT_FAILED + + +def test_csv_gui_fallback_cancel_is_clean(monkeypatch): + monkeypatch.setattr(nc, "pick_inputs_gui", lambda *a, **k: []) + assert nessus_to_csv.main([]) == nc.EXIT_FAILED + + +def test_csv_gui_fallback_is_used_only_without_paths(tmp_path, monkeypatch): + scan = write_nessus(tmp_path / "s.nessus", [basic_host(items=[report_item()])]) + out = tmp_path / "picked.csv" + monkeypatch.setattr(nc, "pick_inputs_gui", lambda *a, **k: [scan]) + monkeypatch.setattr(nc, "pick_output_gui", lambda *a, **k: str(out)) + assert nessus_to_csv.main([]) == nc.EXIT_OK + assert len(read_csv(out)) == 2 + + +# ---- XLSX ---- + +def test_xlsx_end_to_end(tmp_path): + scan = synthetic_scan(tmp_path) + out = tmp_path / "out.xlsx" + assert nessus_to_xlsx.main(["-o", str(out), scan]) == nc.EXIT_OK + ws = load_workbook(out).active + assert [c.value for c in ws[1]] == nc.XLSX_HEADERS + assert ws.max_row == 5 and ws.max_column == 106 + assert len(ws.tables) == 1 + idx = nc.COLUMN_NAMES.index + first = [c for c in ws[2]] + # A formula-looking value must be stored as a string, not a formula (audit M1). + for name, expected in (("pluginName", "'=1+1"), ("plugin_output", "'@SUM(1+1)")): + cell = first[idx(name)] + assert cell.data_type == "s" and cell.value == expected + assert first[idx("cwe")].value == "CWE-79, CWE-89" + assert ws.cell(row=5, column=idx("scan_date") + 1).value in (None, "") + + +def test_xlsx_long_cell_is_cut_with_a_note_and_a_warning(tmp_path, capsys): + long_text = "x" * 40_000 + scan = write_nessus(tmp_path / "s.nessus", [basic_host(items=[ + report_item("1", children=[("plugin_output", long_text)]), + report_item("2", children=[("plugin_output", "y" * nc.XLSX_MAX_CELL)])])]) + out = tmp_path / "out.xlsx" + assert nessus_to_xlsx.main(["-o", str(out), scan]) == nc.EXIT_OK + ws = load_workbook(out).active + col = nc.COLUMN_NAMES.index("plugin_output") + 1 + cut = ws.cell(row=2, column=col).value + assert len(cut) == nc.XLSX_MAX_CELL + assert cut.endswith("[truncated, original was 40000 characters]") + # A value that exactly fits is left whole. + assert ws.cell(row=3, column=col).value == "y" * nc.XLSX_MAX_CELL + captured = capsys.readouterr() + assert "1 cell(s)" in captured.err + + +def test_fit_cell_boundaries(): + assert nessus_to_xlsx.fit_cell("a" * nc.XLSX_MAX_CELL) == ("a" * nc.XLSX_MAX_CELL, False) + value, cut = nessus_to_xlsx.fit_cell("a" * (nc.XLSX_MAX_CELL + 1)) + assert cut and len(value) == nc.XLSX_MAX_CELL + assert nessus_to_xlsx.fit_cell(5) == (5, False) + + +def test_xlsx_counts_hosts_across_files(tmp_path, capsys): + a = write_nessus(tmp_path / "a.nessus", [basic_host("10.0.0.1", items=[report_item("1")]), + basic_host("10.0.0.2", items=[report_item("1")])]) + b = write_nessus(tmp_path / "b.nessus", [basic_host("10.0.0.3", items=[report_item("1")])]) + out = tmp_path / "out.xlsx" + assert nessus_to_xlsx.main(["-o", str(out), a, b]) == nc.EXIT_OK + assert "3 hosts" in capsys.readouterr().out + + +def test_xlsx_no_findings_still_makes_a_valid_file(tmp_path): + scan = write_nessus(tmp_path / "s.nessus", [basic_host(items=[])]) + out = tmp_path / "out.xlsx" + assert nessus_to_xlsx.main(["-o", str(out), scan]) == nc.EXIT_OK + ws = load_workbook(out).active + assert ws.max_row == 1 and len(ws.tables) == 0 + + +def test_xlsx_failure_modes_exit_nonzero(tmp_path): + bad = tmp_path / "bad.nessus" + bad.write_text("nope", encoding="utf-8") + out = tmp_path / "out.xlsx" + assert nessus_to_xlsx.main(["-o", str(out), str(bad)]) == nc.EXIT_FAILED + assert not out.exists() + assert nessus_to_xlsx.main(["-o", str(out), str(tmp_path / "missing.nessus")]) == nc.EXIT_FAILED + + +def test_xlsx_gui_fallback_cancel_is_clean(monkeypatch): + monkeypatch.setattr(nc, "pick_inputs_gui", lambda *a, **k: []) + assert nessus_to_xlsx.main([]) == nc.EXIT_FAILED + + +def test_xlsx_cancelled_save_dialog_is_clean(tmp_path, monkeypatch): + scan = write_nessus(tmp_path / "s.nessus", [basic_host(items=[report_item()])]) + monkeypatch.setattr(nc, "pick_inputs_gui", lambda *a, **k: [scan]) + monkeypatch.setattr(nc, "pick_output_gui", lambda *a, **k: "") + assert nessus_to_xlsx.main([]) == nc.EXIT_FAILED diff --git a/tests/test_sql.py b/tests/test_sql.py new file mode 100644 index 0000000..3e2bf2a --- /dev/null +++ b/tests/test_sql.py @@ -0,0 +1,357 @@ +""" +nessus_to_sql.py without a SQL Server: the SQL text is built and checked as text, and the +database calls run against a small in-memory fake of a pyodbc connection. +""" + +import re +from datetime import date + +import pytest + +import nessus_common as nc +import nessus_to_sql as sql +from helpers import basic_host, report_item, write_nessus + + +class FakeCursor: + def __init__(self, conn): + self.conn = conn + + def execute(self, query, params=()): + self.conn.executed.append((query, tuple(params))) + if self.conn.fail_on and self.conn.fail_on in query: + raise RuntimeError("boom") + self._rows = [] + if "FROM sys.databases" in query: + self._rows = [(d,) for d in self.conn.databases] + elif "INFORMATION_SCHEMA.TABLES" in query: + self._rows = [(t,) for t in self.conn.tables] + elif "INFORMATION_SCHEMA.COLUMNS" in query: + self._rows = [(c,) for c in self.conn.table_columns.get(params[0], [])] + elif query.lstrip().startswith("CREATE TABLE"): + name = re.match(r"CREATE TABLE dbo\.\[(.+?)\]", query.lstrip()).group(1) + self.conn.table_columns[name] = list(sql.SQL_COLUMN_NAMES) + self.conn.tables.append(name) + + def executemany(self, query, batch): + if self.conn.fail_on_insert_after is not None and \ + len(self.conn.inserted) + len(self.conn.pending) + len(batch) > self.conn.fail_on_insert_after: + raise RuntimeError("String or binary data would be truncated") + self.conn.batches.append((query, len(batch))) + self.conn.pending.extend(batch) + + def fetchall(self): + return self._rows + + def close(self): + pass + + +class FakeConn: + def __init__(self, databases=("scans",), tables=(), table_columns=None): + self.databases = list(databases) + self.tables = list(tables) + self.table_columns = dict(table_columns or {}) + self.executed, self.batches = [], [] + self.pending, self.inserted = [], [] + self.commits = self.rollbacks = 0 + self.closed = False + self.fail_on = None + self.fail_on_insert_after = None + + def cursor(self): + return FakeCursor(self) + + def commit(self): + self.commits += 1 + self.inserted.extend(self.pending) + self.pending = [] + + def rollback(self): + self.rollbacks += 1 + self.pending = [] + + def close(self): + self.closed = True + + +def good_columns(): + return list(sql.SQL_COLUMN_NAMES) + + +# ---- SQL text ---- + +def test_create_table_has_106_columns_in_order_and_matches_the_insert(): + create, index = sql.build_create_table_sql("nessus_findings") + names = re.findall(r"^\s{4}(\w+) [A-Z]+", create, re.M) + assert len(names) == 106 + insert = sql.build_insert_sql("nessus_findings") + cols = re.search(r"\(([^)]*)\) VALUES", insert).group(1).split(", ") + assert names == cols + assert insert.count("?") == 106 + # CSV column file_name is the SQL column file_path. + assert cols[-2:] == ["file_path", "scan_date"] and "file_name" not in cols + assert cols == [("file_path" if c == "file_name" else c) for c in nc.COLUMN_NAMES] + + +def test_create_table_text_is_for_a_new_table_with_a_dedupe_index(): + create, index = sql.build_create_table_sql("my_scans") + assert create.startswith("CREATE TABLE dbo.[my_scans] (") + assert "IF NOT EXISTS" not in create + assert index == ("CREATE UNIQUE INDEX [UX_my_scans_finding] ON dbo.[my_scans] " + "(host_ip, pluginID, port, protocol, scan_date, file_path) " + "WITH (IGNORE_DUP_KEY = ON)") + + +def test_column_types_avoid_the_truncation_traps(): + types = dict(sql.SQL_COLUMNS) + for wide in ("synopsis", "cve", "cwe", "bid", "pluginName", "plugin_output", "hostname", + "operating_system", "system_type", "see_also", "description"): + assert types[wide] == "NVARCHAR(MAX)", wide + assert not any(t.startswith("VARCHAR") for t in types.values()) + assert types["port"] == "INT" and types["host_start_timestamp"] == "BIGINT" + assert types["scan_date"] == "DATE" + # The index key must stay under the 900 byte clustered / 1700 byte limit. + key_bytes = 0 + for c in sql.UNIQUE_KEY_COLUMNS: + t = types[c] + m = re.match(r"NVARCHAR\((\d+)\)", t) + key_bytes += int(m.group(1)) * 2 if m else {"INT": 4, "DATE": 3}[t] + assert key_bytes < 900 + + +# ---- Names ---- + +@pytest.mark.parametrize("name", ["scans", "_x", "my-scans", "A1_b-2"]) +def test_sanitize_accepts_valid_new_names(name): + assert sql.sanitize_table_name(name) == name + + +@pytest.mark.parametrize("name", ["", "1abc", "a b", "a]b", "a;drop", "x\n", "a" * 101, "a.b", None]) +def test_sanitize_rejects_bad_new_names(name): + with pytest.raises(ValueError): + sql.sanitize_table_name(name) + + +def test_trailing_newline_is_rejected(): + """Audit L8: re.match with $ accepted 'name\\n'.""" + with pytest.raises(ValueError): + sql.sanitize_table_name("scans\n") + + +def test_quote_identifier_handles_hyphens_spaces_and_brackets(): + assert sql.quote_identifier("my-scans") == "[my-scans]" + assert sql.quote_identifier("a b") == "[a b]" + assert sql.quote_identifier("a]b") == "[a]]b]" + for bad in ("", "x\n", "a\x00b", "a" * 129): + with pytest.raises(ValueError): + sql.quote_identifier(bad) + + +def test_connection_string_validates_certificate_by_default(): + cs = sql.build_connection_string("localhost", "scans") + assert "TrustServerCertificate" not in cs + assert "Trusted_Connection=yes" in cs and "DATABASE=scans" in cs + assert "TrustServerCertificate=yes" in sql.build_connection_string("h", "d", True) + + +def test_connection_string_escapes_semicolons_and_braces(): + cs = sql.build_connection_string("host;Encrypt=no", "db}x;y") + assert "SERVER={host;Encrypt=no};" in cs + assert "DATABASE={db}}x;y};" in cs + assert "Encrypt=no;" not in cs.replace("{host;Encrypt=no}", "") + for bad in ("", "a\nb"): + with pytest.raises(ValueError): + sql.build_connection_string(bad) + + +# ---- Values ---- + +def test_to_sql_row_types_ints_dates_and_nulls(tmp_path): + path = write_nessus(tmp_path / "s.nessus", [basic_host(items=[report_item( + "1234", port="445", children=[("plugin_publication_date", "2024/03/05"), + ("vuln_publication_date", "")])], + extra_tags=[("HOST_START_TIMESTAMP", "1712226191")])]) + (row,) = nc.parse_nessus_file(path) + out = dict(zip(sql.SQL_COLUMN_NAMES, sql.to_sql_row(row))) + assert out["pluginID"] == 1234 and out["port"] == 445 and out["severity_reversed"] == 2 + assert out["host_start_timestamp"] == 1712226191 and out["host_end_timestamp"] is None + assert out["plugin_publication_date"] == date(2024, 3, 5) + assert out["vuln_publication_date"] is None # '' would otherwise become 1900-01-01 + assert out["scan_date"] == date(2024, 4, 4) + assert out["file_path"] == "s.nessus" + assert out["hostname"] == "" + + +# ---- Database flow ---- + +def test_prepare_table_existing_good_table(): + conn = FakeConn(tables=["t"], table_columns={"t": good_columns()}) + assert sql.prepare_table(conn, "t", create=False) == "existing" + assert not any(q.lstrip().startswith("CREATE") for q, _ in conn.executed) + + +def test_prepare_table_rejects_an_unrelated_table(): + conn = FakeConn(tables=["other"], table_columns={"other": ["id", "name"]}) + with pytest.raises(ValueError, match="Missing columns"): + sql.prepare_table(conn, "other", create=True) + + +def test_prepare_table_missing_without_create_flag(): + with pytest.raises(ValueError, match="--create-table"): + sql.prepare_table(FakeConn(), "new_table", create=False) + + +def test_prepare_table_creates_a_new_table_and_its_index(): + conn = FakeConn() + assert sql.prepare_table(conn, "new_table", create=True) == "created" + statements = [q.lstrip() for q, _ in conn.executed if q.lstrip().startswith("CREATE")] + assert statements[0].startswith("CREATE TABLE dbo.[new_table]") + assert statements[1].startswith("CREATE UNIQUE INDEX") + assert conn.commits == 1 + + +def test_prepare_table_validates_a_new_name(): + with pytest.raises(ValueError): + sql.prepare_table(FakeConn(), "bad name", create=True) + + +def test_import_rows_batches_in_one_transaction(tmp_path): + path = write_nessus(tmp_path / "s.nessus", [basic_host(items=[report_item(str(i)) for i in range(5)])]) + rows = nc.parse_nessus_file(path) + conn = FakeConn() + assert sql.import_rows(conn, "t", rows, batch_size=2) == 5 + assert [n for _, n in conn.batches] == [2, 2, 1] + assert conn.commits == 1 and conn.rollbacks == 0 and len(conn.inserted) == 5 + + +def test_import_rows_rolls_back_on_error(tmp_path): + path = write_nessus(tmp_path / "s.nessus", [basic_host(items=[report_item(str(i)) for i in range(5)])]) + rows = nc.parse_nessus_file(path) + conn = FakeConn() + conn.fail_on_insert_after = 3 + with pytest.raises(RuntimeError): + sql.import_rows(conn, "t", rows, batch_size=2) + assert conn.rollbacks == 1 and conn.commits == 0 and conn.inserted == [] + + +# ---- main() ---- + +def folder_with_scans(tmp_path): + folder = tmp_path / "scans" + folder.mkdir() + write_nessus(folder / "a.nessus", [ + basic_host("10.0.0.1", items=[report_item("1"), report_item("1")]), + basic_host("10.0.0.2", items=[report_item("2")], start="garbage date")]) + (folder / "bad.nessus").write_text("= 1 + assert "rolled back" in capsys.readouterr().err + + +def test_main_connection_error_mentions_the_certificate_flag(tmp_path, capsys): + folder = folder_with_scans(tmp_path) + + def connect_fn(cs): + raise RuntimeError("SSL Provider: certificate verify failed") + + code = sql.main(["--server", "s", "--database", "d", "--table", "t", str(folder / "a.nessus")], + connect_fn=connect_fn) + assert code == nc.EXIT_FAILED + assert "--trust-server-certificate" in capsys.readouterr().err + + +def test_main_dry_run_never_connects_and_prints_sql(tmp_path, capsys): + folder = folder_with_scans(tmp_path) + + def connect_fn(cs): + raise AssertionError("dry run must not connect") + + code = sql.main(["--dry-run", "--table", "dry", str(folder)], connect_fn=connect_fn) + out = capsys.readouterr().out + assert code == nc.EXIT_PARTIAL + assert "CREATE TABLE dbo.[dry]" in out and "INSERT INTO dbo.[dry]" in out + assert "2 rows would be inserted" in out + + +def test_main_no_server_and_no_input_is_a_clean_error(tmp_path): + folder = folder_with_scans(tmp_path) + + def eof(prompt): + raise EOFError + + assert sql.main([str(folder / "a.nessus")], connect_fn=lambda cs: FakeConn(), input_fn=eof) == nc.EXIT_FAILED diff --git a/tests/test_tenable.py b/tests/test_tenable.py new file mode 100644 index 0000000..ea0cfc0 --- /dev/null +++ b/tests/test_tenable.py @@ -0,0 +1,254 @@ +"""tenable_scan_retrieval.py against a fake `requests`. No network, no tenant.""" + +import datetime +import importlib +import os +import sys + +import pytest +import requests + +import tenable_scan_retrieval as tsr + + +class FakeResponse: + def __init__(self, status=200, json_data=None, chunks=(), headers=None): + self.status_code = status + self._json = json_data + self._chunks = list(chunks) + self.headers = headers or {} + + def raise_for_status(self): + if self.status_code >= 400: + raise requests.exceptions.HTTPError(f"HTTP {self.status_code}") + + def json(self): + return self._json + + def iter_content(self, chunk_size=None): + for c in self._chunks: + if isinstance(c, Exception): + raise c + yield c + + +class Recorder: + """Stands in for requests.get/post; returns queued responses and records the kwargs.""" + + def __init__(self, responses): + self.responses = list(responses) + self.calls = [] + + def __call__(self, url, **kwargs): + self.calls.append((url, kwargs)) + return self.responses.pop(0) + + +@pytest.fixture(autouse=True) +def fast(monkeypatch): + monkeypatch.setattr(tsr.time, "sleep", lambda s: None) + monkeypatch.delenv("TENABLE_URL", raising=False) + + +def patch_http(monkeypatch, get=(), post=()): + g, p = Recorder(get), Recorder(post) + monkeypatch.setattr(tsr.requests, "get", g) + monkeypatch.setattr(tsr.requests, "post", p) + return g, p + + +# ---- import side effects (audit L2) ---- + +def test_importing_the_module_creates_no_directories_and_asks_nothing(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.setattr("builtins.input", lambda *a: pytest.fail("prompted on import")) + importlib.reload(tsr) + assert os.listdir(tmp_path) == [] + + +# ---- timeouts (audit M10) ---- + +def test_every_request_carries_a_timeout(monkeypatch, tmp_path): + get, post = patch_http( + monkeypatch, + get=[FakeResponse(json_data={"scans": [{"id": 1, "name": "s"}]}), + FakeResponse(json_data={"status": "ready"}), + FakeResponse(chunks=[b"abc"], headers={"Content-Length": "3"})], + post=[FakeResponse(json_data={"file": 99})]) + h = {"X-ApiKeys": "k"} + assert tsr.get_all_scans(h) + assert tsr.initiate_export(1, h) == 99 + assert tsr.wait_for_export(1, 99, h) + assert tsr.download_scan(1, "s", 99, h, str(tmp_path)) + for url, kwargs in get.calls + post.calls: + assert kwargs.get("timeout") == tsr.TIMEOUT, url + assert tsr.TIMEOUT[0] and tsr.TIMEOUT[1] + + +# ---- credentials (audit M11) ---- + +def test_credentials_come_from_the_environment(monkeypatch): + monkeypatch.setenv("TENABLE_ACCESS_KEY", "AK") + monkeypatch.setenv("TENABLE_SECRET_KEY", "SK") + monkeypatch.setattr("builtins.input", lambda *a: pytest.fail("prompted")) + monkeypatch.setattr(tsr.getpass, "getpass", lambda *a: pytest.fail("prompted")) + assert tsr.get_api_credentials() == ("AK", "SK") + + +def test_secret_key_is_read_with_getpass_not_input(monkeypatch): + monkeypatch.delenv("TENABLE_ACCESS_KEY", raising=False) + monkeypatch.delenv("TENABLE_SECRET_KEY", raising=False) + prompts = [] + monkeypatch.setattr("builtins.input", lambda p="": prompts.append(p) or "AK") + monkeypatch.setattr(tsr.getpass, "getpass", lambda p="": "SK") + assert tsr.get_api_credentials() == ("AK", "SK") + assert not any("Secret" in p for p in prompts) + + +def test_missing_credentials_exit(monkeypatch): + monkeypatch.delenv("TENABLE_ACCESS_KEY", raising=False) + monkeypatch.delenv("TENABLE_SECRET_KEY", raising=False) + monkeypatch.setattr("builtins.input", lambda p="": "") + with pytest.raises(SystemExit): + tsr.get_api_credentials() + + +# ---- file names and folders (audit L1, L11) ---- + +@pytest.mark.parametrize("raw", ["a\\b..\\..\\x:y/z", "..", "../../etc/passwd", "C:\\Windows\\x", "a\x00b"]) +def test_sanitize_filename_never_yields_a_path(raw): + out = tsr.sanitize_filename(raw) + assert out and out not in (".", "..") + assert not any(ch in out for ch in '\\/:*?"<>|\x00') + + +def test_sanitize_filename_reserved_names_and_trailing_dots(): + assert tsr.sanitize_filename("CON") == "_CON" + assert tsr.sanitize_filename("nul.txt") == "_nul.txt" + assert tsr.sanitize_filename("name. . ") == "name" + assert tsr.sanitize_filename("") == "scan" + assert len(tsr.sanitize_filename("x" * 500)) <= 150 + + +def test_same_named_scans_get_different_files(tmp_path): + a = tsr.scan_output_path(str(tmp_path), "Weekly", 1) + b = tsr.scan_output_path(str(tmp_path), "Weekly", 2) + assert a != b and a.endswith("Weekly-1.nessus") and b.endswith("Weekly-2.nessus") + + +def test_scan_output_path_stays_inside_the_folder(tmp_path): + p = tsr.scan_output_path(str(tmp_path), "..\\..\\evil", "1/../2") + assert os.path.dirname(os.path.abspath(p)) == os.path.abspath(str(tmp_path)) + + +def test_year_boundary_uses_the_iso_year(): + """2027-01-01 is ISO week 53 of 2026, so it belongs under 2026.""" + path = tsr.build_output_dir(datetime.datetime(2027, 1, 1)) + assert path.replace("\\", "/") == "2026/01-January/Week-53" + assert tsr.build_output_dir(datetime.datetime(2026, 11, 18), base="out").replace("\\", "/") == \ + "out/2026/11-November/Week-47" + + +# ---- API robustness (audit L12) ---- + +def test_scans_null_is_an_empty_list(monkeypatch): + patch_http(monkeypatch, get=[FakeResponse(json_data={"scans": None})]) + assert tsr.get_all_scans({}) == [] + + +def test_fetch_error_is_none_not_empty(monkeypatch): + patch_http(monkeypatch, get=[FakeResponse(status=500)]) + assert tsr.get_all_scans({}) is None + + +def test_rate_limit_is_retried_with_retry_after(monkeypatch): + sleeps = [] + monkeypatch.setattr(tsr.time, "sleep", sleeps.append) + get, _ = patch_http(monkeypatch, get=[ + FakeResponse(status=429, headers={"Retry-After": "7"}), + FakeResponse(json_data={"scans": [{"id": 1}]})]) + assert tsr.get_all_scans({}) == [{"id": 1}] + assert sleeps == [7.0] and len(get.calls) == 2 + + +def test_rate_limit_gives_up_after_the_retry_budget(monkeypatch): + get, _ = patch_http(monkeypatch, get=[FakeResponse(status=429)] * (tsr.MAX_RATE_LIMIT_RETRIES + 1)) + assert tsr.get_all_scans({}) is None + assert len(get.calls) == tsr.MAX_RATE_LIMIT_RETRIES + 1 + + +def test_failed_export_status_stops_polling_early(monkeypatch): + get, _ = patch_http(monkeypatch, get=[FakeResponse(json_data={"status": "error"})]) + assert tsr.wait_for_export(1, 2, {}) is False + assert len(get.calls) == 1 + + +def test_export_that_never_finishes_times_out(monkeypatch): + get, _ = patch_http(monkeypatch, get=[FakeResponse(json_data={"status": "loading"})] * 3) + assert tsr.wait_for_export(1, 2, {}, max_retries=3, wait_time=0) is False + + +def test_download_writes_part_then_renames(monkeypatch, tmp_path): + patch_http(monkeypatch, get=[FakeResponse(chunks=[b"ab", b"cd"], headers={"Content-Length": "4"})]) + out = tsr.download_scan(5, "Scan", 9, {}, str(tmp_path / "x" / "y")) + assert out.endswith("Scan-5.nessus") + assert open(out, "rb").read() == b"abcd" + assert not os.path.exists(out + ".part") + + +def test_interrupted_download_leaves_no_nessus_file(monkeypatch, tmp_path): + patch_http(monkeypatch, get=[FakeResponse( + chunks=[b"ab", requests.exceptions.ChunkedEncodingError("cut")], headers={"Content-Length": "10"})]) + assert tsr.download_scan(5, "Scan", 9, {}, str(tmp_path)) is None + assert os.listdir(tmp_path) == [] + + +def test_short_download_is_rejected(monkeypatch, tmp_path): + patch_http(monkeypatch, get=[FakeResponse(chunks=[b"ab"], headers={"Content-Length": "10"})]) + assert tsr.download_scan(5, "Scan", 9, {}, str(tmp_path)) is None + assert os.listdir(tmp_path) == [] + + +def test_tenable_url_must_be_https(monkeypatch): + monkeypatch.setenv("TENABLE_URL", "http://example.com") + with pytest.raises(SystemExit): + tsr.get_base_url() + monkeypatch.setenv("TENABLE_URL", "https://fedcloud.tenable.com/") + assert tsr.get_base_url() == "https://fedcloud.tenable.com" + + +# ---- main ---- + +def test_main_unattended_all(monkeypatch, tmp_path): + monkeypatch.setenv("TENABLE_ACCESS_KEY", "AK") + monkeypatch.setenv("TENABLE_SECRET_KEY", "SK") + monkeypatch.setattr("builtins.input", lambda *a: pytest.fail("prompted")) + get, post = patch_http( + monkeypatch, + get=[FakeResponse(json_data={"scans": [{"id": 1, "name": "A"}, {"id": 2, "name": "A"}]}), + FakeResponse(json_data={"status": "ready"}), + FakeResponse(chunks=[b"1"], headers={"Content-Length": "1"}), + FakeResponse(json_data={"status": "ready"}), + FakeResponse(chunks=[b"2"], headers={"Content-Length": "1"})], + post=[FakeResponse(json_data={"file": 10}), FakeResponse(json_data={"file": 11})]) + assert tsr.main(["--all", "--output-dir", str(tmp_path)]) == 0 + names = sorted(f for _, _, files in os.walk(tmp_path) for f in files) + assert names == ["A-1.nessus", "A-2.nessus"] + assert post.calls[0][1]["headers"]["X-ApiKeys"] == "accessKey=AK; secretKey=SK;" + + +def test_main_unknown_scan_id_is_an_error(monkeypatch, tmp_path): + monkeypatch.setenv("TENABLE_ACCESS_KEY", "AK") + monkeypatch.setenv("TENABLE_SECRET_KEY", "SK") + patch_http(monkeypatch, get=[FakeResponse(json_data={"scans": [{"id": 1, "name": "A"}]})]) + assert tsr.main(["--scan-id", "5", "--output-dir", str(tmp_path)]) == 1 + assert os.listdir(tmp_path) == [] + + +def test_main_failed_download_gives_nonzero_exit(monkeypatch, tmp_path): + monkeypatch.setenv("TENABLE_ACCESS_KEY", "AK") + monkeypatch.setenv("TENABLE_SECRET_KEY", "SK") + patch_http(monkeypatch, + get=[FakeResponse(json_data={"scans": [{"id": 1, "name": "A"}]})], + post=[FakeResponse(status=403)]) + assert tsr.main(["--all", "--output-dir", str(tmp_path)]) == 1 From 13ecf6dcd2ca7d37b83ae679d705293711ecf48c Mon Sep 17 00:00:00 2001 From: NullSpace-BitCradle <216858096+NullSpace-BitCradle@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:09:24 -0700 Subject: [PATCH 4/9] Bring the README in line with the code Document command-line use, exit codes, the SQL options and their limits, and bound dependency versions. Replace the old example server address. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi --- CONTRIBUTING.md | 20 +++++++++++ README.md | 90 ++++++++++++++++++++++++++++++++---------------- requirements.txt | 10 +++--- 3 files changed, 85 insertions(+), 35 deletions(-) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..d0f9253 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,20 @@ +# Contributing + +Issues and pull requests are welcome. + +## Setup + +```bash +python -m venv venv +venv\Scripts\activate # Linux/macOS: source venv/bin/activate +pip install -r requirements-dev.txt +pytest +``` + +## Ground rules + +- Run `pytest` before you send a change. Add a test for any bug you fix; the tests in `tests/` show the style (small synthetic `.nessus` files built in code). +- Never commit real scan files or output. `.gitignore` already excludes `*.nessus`, `*.csv` and `*.xlsx`. Use synthetic data in tests. +- The 106-column list lives in one place, `nessus_common.py`. If you add a field, add it there, then update the SQL types in `nessus_to_sql.py`, the field list in the README, and the column count checks in the tests. +- Scripts take paths on the command line. The file pickers are only a fallback when no path is given, and tests must never open one. +- Plain, direct wording in docs and messages. diff --git a/README.md b/README.md index 63a5800..1b54128 100644 --- a/README.md +++ b/README.md @@ -10,13 +10,14 @@ A collection of Python scripts for processing and converting Tenable Nessus vuln | `nessus_to_csv.py` | Convert .nessus files to CSV | | `nessus_to_xlsx.py` | Convert .nessus files to formatted Excel (.xlsx) | | `nessus_to_sql.py` | Import .nessus files into SQL Server | +| `nessus_common.py` | Shared parser and column list used by the three converters. Keep it next to them. | -All conversion scripts support multiple input files, automatic duplicate removal, progress tracking, and performance metrics. +All three converters accept files or folders on the command line, support multiple input files, remove duplicate findings, and print performance metrics. Each also has a file-picker fallback that runs only when you give no path. ## Requirements - Python 3.9+ -- A graphical display (tkinter file dialogs require a desktop environment or X11 forwarding) +- A graphical display only if you run a converter with no path (tkinter file dialogs need a desktop environment or X11 forwarding) ```bash pip install -r requirements.txt @@ -24,7 +25,7 @@ pip install -r requirements.txt | Dependency | Used By | |------------|---------| -| `psutil` | All scripts (performance metrics) | +| `psutil` | The converters (performance metrics) | | `requests` | `tenable_scan_retrieval.py` (Tenable.io API) | | `openpyxl` | `nessus_to_xlsx.py` (Excel output) | | `pyodbc` | `nessus_to_sql.py` (SQL Server via ODBC Driver 18) | @@ -34,52 +35,67 @@ pip install -r requirements.txt `nessus_to_sql.py` requires: - Windows with ODBC Driver 18 for SQL Server installed - Windows Authentication (Trusted Connection) to the target SQL Server -- Permissions to create tables and insert data +- Permission to insert data, and to create a table and index if you want the script to create the table ## Usage +Exit codes for the converters: `0` success, `1` nothing could be converted (bad usage, no files, or every file failed), `2` output was written but at least one file could not be read. A file that fails to parse is skipped and listed at the end. + ### Download Scans from Tenable.io ```bash -python tenable_scan_retrieval.py +python tenable_scan_retrieval.py # pick scans from a list +python tenable_scan_retrieval.py --all # every scan, no prompts +python tenable_scan_retrieval.py --scan-id 12 --scan-id 34 +python tenable_scan_retrieval.py --all --output-dir D:\scans ``` -1. Enter your API credentials (find them in Tenable.io: Settings > My Account > API Keys) -2. Select scans to download (single number, comma-separated, or "all") -3. Files are saved in a date-organized directory: `Year/MM-MonthName/Week-XX/` +1. Provide your API credentials (Tenable.io: Settings > My Account > API Keys). Set `TENABLE_ACCESS_KEY` and `TENABLE_SECRET_KEY`, or type them at the prompt. The secret key is not shown as you type. +2. Select scans: with no options, enter a single number, comma-separated numbers, or "all". `--all` and `--scan-id` skip the prompt. +3. Files are saved as `-.nessus` in `Year/MM-MonthName/Week-XX/` under `--output-dir` (default: the current folder). Year and week are both ISO values, so 2027-01-01 goes in `2026/01-January/Week-53`. + +Every request has a timeout (10 s to connect, 60 s to read). A rate-limited request (HTTP 429) is retried up to 3 times. Each download goes to a `.part` file and is renamed only when complete. To use another Tenable cloud, set `TENABLE_URL` (https only), for example `https://fedcloud.tenable.com`. The exit code is `1` if any selected scan failed. ### Convert to CSV ```bash -python nessus_to_csv.py +python nessus_to_csv.py -o findings.csv scan1.nessus scan2.nessus +python nessus_to_csv.py -o findings.csv D:\scans # folders are searched recursively +python nessus_to_csv.py # no path: file pickers ``` -1. Choose file selection (1) or folder selection (2) -2. Select .nessus files or folder -3. Choose output location -4. Produces a UTF-8 CSV with 106 columns +Produces a CSV with 106 columns, UTF-8 with a byte order mark so Excel reads non-ASCII text correctly. Without `-o` the output is `nessus_conversion.csv` in the current folder. The CSV is written to a temporary file first, so a run where every input fails does not overwrite an existing CSV. ### Convert to Excel ```bash -python nessus_to_xlsx.py +python nessus_to_xlsx.py -o findings.xlsx D:\scans +python nessus_to_xlsx.py # no path: file pickers ``` -1. Select one or more .nessus files -2. Choose output location -3. Produces a formatted Excel workbook with alternating row colors, table filters, and TableStyleMedium2 styling +Produces a formatted Excel workbook with alternating row colors, table filters, and TableStyleMedium2 styling. + +- An Excel cell holds at most 32,767 characters. A longer value (usually Plugin Output) is cut, ends with `[truncated, original was N characters]`, and the script prints how many cells were cut. Use the CSV script when you need the full text. +- A sheet holds at most 1,048,576 rows. A larger input stops with an error; split it or use the CSV script. ### Import to SQL Server ```bash -python nessus_to_sql.py +python nessus_to_sql.py D:\scans --server sqlserver.example.com --database Scans --table nessus_findings --create-table +python nessus_to_sql.py D:\scans # prompts for server, database and table +python nessus_to_sql.py D:\scans --dry-run # print the SQL and row count, no connection ``` -1. Select folder containing .nessus files -2. Enter SQL Server address (e.g., `localhost`, `10.10.30.20`, `server.domain.com`) -3. Select database and table from interactive menus -4. Table is auto-created if it doesn't exist -5. Data is inserted in batches of 500,000 rows for memory efficiency +1. Give a folder or files (or none, to get a folder picker). +2. Give the server, database and table on the command line, or answer the prompts. The table menu lists the existing `dbo` tables and a "Create a new table" choice that asks for a name. +3. An existing table must already have all the script's columns, or the script stops before inserting. To create a table, use `--create-table` with `--table NAME`, or choose it in the menu. A new table gets a unique index on `(host_ip, pluginID, port, protocol, scan_date, file_path)` that ignores duplicate rows, so importing the same file twice does not add its rows twice. A table made some other way has no such index, and importing the same file again adds the rows again. +4. Each file is imported in one transaction, in batches of 500,000 rows. If a batch fails, nothing from that file is kept and the run stops. + +The `file_path` column holds the file's base name (for example `scan1.nessus`), not a full path. The CSV and Excel outputs call the same value File Name. + +The connection uses Windows Authentication and validates the server certificate. If your server uses a self-signed certificate, install it as trusted. `--trust-server-certificate` accepts any certificate, which lets someone in the network path impersonate the server, so use it only on a network you control. + +Dates are read in Python and sent as dates, empty numbers and dates are stored as NULL, and text columns are `NVARCHAR`, so non-Latin text is stored as is. This script has been tested against a fake connection only; it has not been run against a real SQL Server. ## Extracted Data Fields (106 per finding) @@ -90,7 +106,7 @@ python nessus_to_sql.py - IP Address, MAC Address, Virtual MAC Address - Hostname, NetBIOS Name, FQDN, RDNS - System Type, Operating System (name, family, confidence, detection method) -- CPE (Common Platform Enumeration) +- CPE (Common Platform Enumeration): the finding's own CPE from its plugin, not the host-level OS CPE ### Vulnerability Details - Plugin ID, Plugin Family, Plugin Name @@ -113,6 +129,8 @@ python nessus_to_sql.py - Bug IDs: BID, EDB-ID, CEA-ID, CERT - IAVA, IAVB, IAVT, ICSA, TRA +When a finding lists the same kind of reference more than once (two CWEs, several MSKB numbers), all of them are kept, joined with `, `. + ### Exploit Intelligence - Exploit Available, Exploitability Ease, Exploit Code Maturity - Framework availability: Metasploit, Canvas, Core Impact @@ -129,12 +147,24 @@ python nessus_to_sql.py -## Platform Notes +Newer Nessus fields (such as CVSS v4 and EPSS) are not extracted. + +## Notes + +- **Spreadsheet safety**: in CSV and Excel output, a text cell that starts with `=`, `+`, `-` or `@` (or a tab or carriage return) gets a leading `'` so Excel does not run it as a formula. Plugin output and hostnames come from scanned hosts, so they can contain anything. Plain numbers such as `-5` are left alone. The leading `'` is visible in the cell; strip it if you load the CSV into something other than Excel. +- **Duplicate removal**: the CSV, Excel and SQL scripts drop a row only when all 106 columns match another row. The file name is one of the columns, so the same finding in two differently named files is kept. Rows stay in the order they appear in the input. +- **Memory**: each host is released after it is read and only one file's rows are held at a time, but a single very large file is still held in memory as rows. +- **Windows-optimized**: the SQL script uses Windows Authentication (Trusted Connection). The memory metric uses `peak_wset` on Windows and falls back to `rss` on Linux/macOS. +- **API credentials**: read from the environment or prompted at runtime, never stored to disk. + +## Tests + +```bash +pip install -r requirements-dev.txt +pytest +``` -- **GUI required**: All scripts use tkinter file dialogs for file/folder selection. They will not work over SSH without X11 forwarding or on headless servers. -- **Windows-optimized**: The SQL script uses Windows Authentication (Trusted Connection). The memory metric uses `peak_wset` on Windows and falls back to `rss` on Linux/macOS. -- **API credentials**: Prompted at runtime, never stored to disk. -- **Duplicate removal**: CSV and XLSX scripts automatically deduplicate findings before writing output. +The tests build small synthetic `.nessus` files and run the scripts through their command-line interface, so no scan data, GUI, SQL Server or Tenable account is needed. ## License @@ -142,7 +172,7 @@ MIT License. See [LICENSE](LICENSE) for details. ## Contributing -Contributions, issues, and feature requests are welcome. +Contributions, issues, and feature requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md). ## Disclaimer diff --git a/requirements.txt b/requirements.txt index ab296cf..3a438cd 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,15 +1,15 @@ # Python dependencies for Tenable Nessus Scripts # Install with: pip install -r requirements.txt +# Each entry has a floor and a ceiling at the next major version. # System and process monitoring -psutil>=5.9.0 +psutil>=5.9.0,<8 # SQL Server database connectivity (for nessus_to_sql.py) -pyodbc>=4.0.39 +pyodbc>=4.0.39,<6 # Excel file creation (for nessus_to_xlsx.py) -openpyxl>=3.1.0 +openpyxl>=3.1.0,<4 # HTTP requests for Tenable.io API (for tenable_scan_retrieval.py) -requests>=2.31.0 - +requests>=2.31.0,<3 From cb26c0392f662bccbbb63831bdee991972374df8 Mon Sep 17 00:00:00 2001 From: NullSpace-BitCradle <216858096+NullSpace-BitCradle@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:09:38 -0700 Subject: [PATCH 5/9] Pin CI actions to commit SHAs Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi --- .github/workflows/tests.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 2bebee7..1a4b44e 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -4,6 +4,9 @@ on: push: pull_request: +permissions: + contents: read + jobs: pytest: runs-on: ${{ matrix.os }} @@ -12,8 +15,8 @@ jobs: os: [ubuntu-latest, windows-latest] python-version: ["3.9", "3.13"] steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: ${{ matrix.python-version }} - run: python -m pip install -r requirements-dev.txt From 4ad21f64e56e34ba0a937af6f29dd4e67c6986fe Mon Sep 17 00:00:00 2001 From: NullSpace-BitCradle <216858096+NullSpace-BitCradle@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:40:26 -0700 Subject: [PATCH 6/9] Never drop distinct findings on SQL import The unique index with IGNORE_DUP_KEY keyed on six columns, coarser than the 106-column dedupe, so distinct compliance results and hosts without a host-ip collapsed to one row with only a server warning. Remove it and make re-imports idempotent per file instead: a _import_log keyed by file name and SHA-256, written in the same transaction, with logged files skipped. The summary now reports rows inserted, not rows sent, and existing tables with columns too narrow for joined CWE/BID/MSKB values get a warning with the ALTER statements to run. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi --- nessus_to_sql.py | 191 ++++++++++++++++++++++++++++++++++++++-------- tests/test_sql.py | 185 +++++++++++++++++++++++++++++++++++++++----- 2 files changed, 326 insertions(+), 50 deletions(-) diff --git a/nessus_to_sql.py b/nessus_to_sql.py index ee02b3c..d6ea6bd 100644 --- a/nessus_to_sql.py +++ b/nessus_to_sql.py @@ -17,15 +17,21 @@ - Name an existing table with --table, or choose one from the menu. The script checks that it has every column it needs and stops if it does not. - To make a new table, pass --create-table with --table NEW_NAME, or choose - "Create a new table" in the menu. The new table gets a unique index on - (host_ip, pluginID, port, protocol, scan_date, file_path) that ignores - duplicate rows, so importing the same file twice does not add rows twice. - Existing tables made by another tool or an older version of this script do not - have that index, and re-importing into them adds the rows again. + "Create a new table" in the menu. - The file_path column holds the file's base name, not a full path. -Each file is imported in one transaction: if any batch of a file fails, nothing -from that file is kept. A file that cannot be parsed is skipped and reported. +Re-importing: next to the findings table the script keeps a log table named +
_import_log (created on first use, also for existing tables). It holds +one row per imported file: the file's base name, the SHA-256 of its bytes and the +row count. A file whose name and SHA-256 are already in the log is skipped, so +running the same folder twice adds nothing. A file with the same name but +different content is imported again in full. No findings table or index drops a +row by key: a finding is skipped only when all 106 columns equal an earlier row +in the same run. + +Each file is imported in one transaction, rows and log entry together: if any +batch of a file fails, nothing from that file is kept and it is not logged. A +file that cannot be parsed is skipped and reported. Connection: Windows authentication (Trusted_Connection) through ODBC Driver 18. The server certificate is validated. If your server uses a self-signed @@ -36,6 +42,8 @@ """ import argparse +import hashlib +import os import re import sys import time @@ -63,9 +71,10 @@ "always_run", "agent", "cisa_known_exploited", "thorough_tests", "unsupported_by_vendor", "in_the_news", } -# Columns that make up the unique index; they cannot be MAX. -_KEY_TYPES = {"host_ip": "NVARCHAR(64)", "protocol": "NVARCHAR(15)", "file_path": "NVARCHAR(255)"} -UNIQUE_KEY_COLUMNS = ["host_ip", "pluginID", "port", "protocol", "scan_date", "file_path"] +# Columns with a fixed, bounded size (the file name is at most 255 characters on Windows). +_KEY_TYPES = {"host_ip": "NVARCHAR(255)", "protocol": "NVARCHAR(100)", "file_path": "NVARCHAR(255)"} +# Columns that can hold several values joined with ", ". +MULTI_VALUE_COLUMNS = [c[0] for c in nc.COLUMNS if c[2] == "multi"] def sql_column_name(column): @@ -142,15 +151,40 @@ def build_connection_string(server, database=None, trust_server_certificate=Fals # ---- SQL text ---------------------------------------------------------------- def build_create_table_sql(table): - """Return (CREATE TABLE statement, CREATE UNIQUE INDEX statement) for a new table.""" + """CREATE TABLE statement for a new findings table. It has no unique key on purpose.""" quoted = quote_identifier(table) columns = ",\n ".join(f"{name} {typ}" for name, typ in SQL_COLUMNS) - create_table = f"CREATE TABLE dbo.{quoted} (\n {columns}\n)" - index_name = quote_identifier(f"UX_{table}_finding") - key = ", ".join(UNIQUE_KEY_COLUMNS) - create_index = (f"CREATE UNIQUE INDEX {index_name} ON dbo.{quoted} ({key}) " - "WITH (IGNORE_DUP_KEY = ON)") - return create_table, create_index + return f"CREATE TABLE dbo.{quoted} (\n {columns}\n)" + + +def log_table_name(table): + return f"{table}_import_log" + + +LOG_COLUMN_NAMES = ["file_name", "file_sha256", "row_count", "imported_at"] + + +def build_create_log_table_sql(table): + """CREATE TABLE statement for the import log that sits next to a findings table.""" + log = quote_identifier(log_table_name(table)) + pk = quote_identifier(f"PK_{log_table_name(table)}") + return (f"CREATE TABLE dbo.{log} (\n" + " file_name NVARCHAR(255) NOT NULL,\n" + " file_sha256 CHAR(64) NOT NULL,\n" + " row_count INT NOT NULL,\n" + " imported_at DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME(),\n" + f" CONSTRAINT {pk} PRIMARY KEY (file_sha256, file_name)\n" + ")") + + +def build_log_insert_sql(table): + return (f"INSERT INTO dbo.{quote_identifier(log_table_name(table))} " + "(file_name, file_sha256, row_count) VALUES (?, ?, ?)") + + +def build_log_lookup_sql(table): + return (f"SELECT COUNT(*) FROM dbo.{quote_identifier(log_table_name(table))} " + "WHERE file_sha256 = ? AND file_name = ?") def build_insert_sql(table): @@ -247,12 +281,72 @@ def missing_columns(existing_columns): return [c for c in SQL_COLUMN_NAMES if c.lower() not in have] +def narrow_multi_value_columns(conn, table): + """ + Names of multi-value columns (cwe, bid, mskb, cve, ...) in an existing table that + have a fixed length. Several values joined with ", " can be longer than that, and + SQL Server then rejects the whole batch with "String or binary data would be truncated". + """ + cursor = conn.cursor() + cursor.execute( + "SELECT COLUMN_NAME, CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS " + "WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = ?", (table,)) + rows = cursor.fetchall() + cursor.close() + lengths = {name.lower(): length for name, length in rows} + return [c for c in MULTI_VALUE_COLUMNS + if lengths.get(c.lower()) not in (None, -1)] + + +def alter_multi_value_columns_sql(table, columns): + quoted = quote_identifier(table) + return "\n".join(f"ALTER TABLE dbo.{quoted} ALTER COLUMN {c} NVARCHAR(MAX) NULL;" for c in columns) + + +def file_sha256(path): + digest = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def ensure_log_table(conn, table): + """Create
_import_log if it is missing; refuse a table of that name that has other columns.""" + log = log_table_name(table) + existing = get_table_columns(conn, log) + if existing: + have = {c.lower() for c in existing} + missing = [c for c in LOG_COLUMN_NAMES if c not in have] + if missing: + raise ValueError(f"Table dbo.{log} exists but is not an import log " + f"(missing columns: {', '.join(missing)}).") + return + cursor = conn.cursor() + try: + cursor.execute(build_create_log_table_sql(table)) + conn.commit() + except Exception: + conn.rollback() + raise + finally: + cursor.close() + + +def is_already_imported(conn, table, file_name, sha256): + cursor = conn.cursor() + try: + cursor.execute(build_log_lookup_sql(table), (sha256, file_name)) + return cursor.fetchone()[0] > 0 + finally: + cursor.close() + + def create_table(conn, table): - create_table_sql, create_index_sql = build_create_table_sql(table) + create_table_sql = build_create_table_sql(table) cursor = conn.cursor() try: cursor.execute(create_table_sql) - cursor.execute(create_index_sql) conn.commit() except Exception: conn.rollback() @@ -284,12 +378,15 @@ def prepare_table(conn, table, create): return "created" -def import_rows(conn, table, rows, batch_size=BATCH_SIZE): +def import_rows(conn, table, rows, batch_size=BATCH_SIZE, log=None): """ Insert `rows` into `table` in batches inside one transaction. - Commits at the end; any error rolls back everything inserted by this call. - Returns the number of rows sent. + `log` is an optional (file_name, sha256) pair; its import-log row is written in the + same transaction, so the rows and the log entry land together or not at all. + Commits at the end; any error rolls back everything done by this call. + Returns the number of rows inserted (no row is skipped by key, so this equals + the rows that landed once the commit succeeded). """ insert_sql = build_insert_sql(table) cursor = conn.cursor() @@ -299,6 +396,8 @@ def import_rows(conn, table, rows, batch_size=BATCH_SIZE): batch = [to_sql_row(r) for r in rows[start:start + batch_size]] cursor.executemany(insert_sql, batch) sent += len(batch) + if log is not None: + cursor.execute(build_log_insert_sql(table), (log[0], log[1], sent)) conn.commit() except Exception: conn.rollback() @@ -377,12 +476,14 @@ def parse_args(argv): def _dry_run(args, files): table = sanitize_table_name(args.table or DEFAULT_TABLE) - create_table_sql, create_index_sql = build_create_table_sql(table) print("-- Would run, if the table did not exist:") - print(create_table_sql + ";") - print(create_index_sql + ";") + print(build_create_table_sql(table) + ";") + print("\n-- Would run, if the import log did not exist:") + print(build_create_log_table_sql(table) + ";") print("\n-- Would insert each row with:") - print(build_insert_sql(table) + ";\n") + print(build_insert_sql(table) + ";") + print("\n-- And, per file, in the same transaction:") + print(build_log_insert_sql(table) + ";\n") stats = nc.RunStats() total = sum(1 for _ in nc.iter_unique_rows(files, stats)) failed = nc.report_failures(stats) @@ -465,37 +566,63 @@ def main(argv=None, connect_fn=None, input_fn=input): print("No table selected. Exiting.", file=sys.stderr) return nc.EXIT_FAILED try: + quote_identifier(f"PK_{log_table_name(table)}") # name must fit; fail before any change state = prepare_table(conn, table, create) + ensure_log_table(conn, table) + narrow = narrow_multi_value_columns(conn, table) if state == "existing" else [] except ValueError as exc: print(exc, file=sys.stderr) return nc.EXIT_FAILED print(f"\nProceeding with:\n Server: {server}\n Database: {database}\n" - f" Table: dbo.{table} ({state})\n" + "=" * 60) + f" Table: dbo.{table} ({state})\n Import log: dbo.{log_table_name(table)}\n" + + "=" * 60) + if narrow: + print("WARNING: these columns can hold several joined values but have a fixed length, " + "so a long list (many CVEs, CWEs or MSKB numbers) can make SQL Server reject a " + "batch with 'String or binary data would be truncated':\n " + + ", ".join(narrow) + "\nWiden them with:\n" + + alter_multi_value_columns_sql(table, narrow) + "\n", file=sys.stderr) stats = nc.RunStats() seen = set() - imported = 0 + landed = 0 # rows committed to the table by this run + imported_files = 0 + skipped_files = [] # already in the import log for path in files: + file_name = os.path.basename(path) + try: + sha256 = file_sha256(path) + except OSError as exc: + stats.files_seen += 1 + print(f"Error reading {path}: {exc}", file=sys.stderr) + stats.failures.append((path, f"cannot read file: {exc}")) + continue + if is_already_imported(conn, table, file_name, sha256): + print(f"Skipping {path}: this file (same name and SHA-256) was already imported.") + skipped_files.append(path) + continue failures_before = len(stats.failures) rows = list(nc.iter_unique_rows([path], stats, seen)) if len(stats.failures) > failures_before: continue try: - imported += import_rows(conn, table, rows) + landed += import_rows(conn, table, rows, log=(file_name, sha256)) except Exception as exc: print(f"Error importing {path}: {exc}\nNothing from this file was kept " "(rolled back). Stopping.", file=sys.stderr) nc.report_failures(stats) return nc.EXIT_FAILED + imported_files += 1 print(f"Imported {len(rows)} rows from {path}") finally: conn.close() failed = nc.report_failures(stats) - print(f"Processed {stats.files_ok} of {stats.files_seen} files, {stats.hosts} hosts, " - f"{imported} rows sent ({stats.duplicates} duplicates removed before sending).") + print(f"{imported_files} file(s) imported, {len(skipped_files)} skipped as already imported, " + f"{len(stats.failures)} failed. {landed} rows inserted " + f"({stats.duplicates} exact duplicate rows were removed before sending).") print(nc.format_run_metrics(start_time)) - if stats.files_ok == 0: + if imported_files == 0 and not skipped_files: return nc.EXIT_FAILED return nc.EXIT_PARTIAL if failed else nc.EXIT_OK diff --git a/tests/test_sql.py b/tests/test_sql.py index 3e2bf2a..e6c1734 100644 --- a/tests/test_sql.py +++ b/tests/test_sql.py @@ -26,12 +26,25 @@ def execute(self, query, params=()): self._rows = [(d,) for d in self.conn.databases] elif "INFORMATION_SCHEMA.TABLES" in query: self._rows = [(t,) for t in self.conn.tables] + elif "CHARACTER_MAXIMUM_LENGTH" in query: + lengths = self.conn.column_lengths.get(params[0], {}) + self._rows = [(c, lengths.get(c, -1)) for c in self.conn.table_columns.get(params[0], [])] elif "INFORMATION_SCHEMA.COLUMNS" in query: self._rows = [(c,) for c in self.conn.table_columns.get(params[0], [])] elif query.lstrip().startswith("CREATE TABLE"): name = re.match(r"CREATE TABLE dbo\.\[(.+?)\]", query.lstrip()).group(1) - self.conn.table_columns[name] = list(sql.SQL_COLUMN_NAMES) + is_log = name.endswith("_import_log") + self.conn.table_columns[name] = list(sql.LOG_COLUMN_NAMES if is_log else sql.SQL_COLUMN_NAMES) self.conn.tables.append(name) + elif "_import_log]" in query and query.lstrip().startswith("SELECT COUNT"): + sha, name = params + self._rows = [(1 if (sha, name) in self.conn.log_keys else 0,)] + elif "_import_log]" in query and query.lstrip().startswith("INSERT"): + name, sha, count = params + if (sha, name) in self.conn.log_keys or (sha, name) in self.conn.pending_log: + raise RuntimeError("Violation of PRIMARY KEY constraint") + self.conn.pending_log.append((sha, name)) + self.conn.log_counts[(sha, name)] = count def executemany(self, query, batch): if self.conn.fail_on_insert_after is not None and \ @@ -43,6 +56,9 @@ def executemany(self, query, batch): def fetchall(self): return self._rows + def fetchone(self): + return self._rows[0] + def close(self): pass @@ -54,6 +70,8 @@ def __init__(self, databases=("scans",), tables=(), table_columns=None): self.table_columns = dict(table_columns or {}) self.executed, self.batches = [], [] self.pending, self.inserted = [], [] + self.pending_log, self.log_keys, self.log_counts = [], set(), {} + self.column_lengths = {} self.commits = self.rollbacks = 0 self.closed = False self.fail_on = None @@ -66,10 +84,13 @@ def commit(self): self.commits += 1 self.inserted.extend(self.pending) self.pending = [] + self.log_keys.update(self.pending_log) + self.pending_log = [] def rollback(self): self.rollbacks += 1 self.pending = [] + self.pending_log = [] def close(self): self.closed = True @@ -82,7 +103,7 @@ def good_columns(): # ---- SQL text ---- def test_create_table_has_106_columns_in_order_and_matches_the_insert(): - create, index = sql.build_create_table_sql("nessus_findings") + create = sql.build_create_table_sql("nessus_findings") names = re.findall(r"^\s{4}(\w+) [A-Z]+", create, re.M) assert len(names) == 106 insert = sql.build_insert_sql("nessus_findings") @@ -94,13 +115,21 @@ def test_create_table_has_106_columns_in_order_and_matches_the_insert(): assert cols == [("file_path" if c == "file_name" else c) for c in nc.COLUMN_NAMES] -def test_create_table_text_is_for_a_new_table_with_a_dedupe_index(): - create, index = sql.build_create_table_sql("my_scans") +def test_findings_table_has_no_key_that_could_drop_a_finding(): + """Audit review B1: a unique index on 6 columns merged distinct findings.""" + create = sql.build_create_table_sql("my_scans") assert create.startswith("CREATE TABLE dbo.[my_scans] (") - assert "IF NOT EXISTS" not in create - assert index == ("CREATE UNIQUE INDEX [UX_my_scans_finding] ON dbo.[my_scans] " - "(host_ip, pluginID, port, protocol, scan_date, file_path) " - "WITH (IGNORE_DUP_KEY = ON)") + for word in ("UNIQUE", "PRIMARY KEY", "IGNORE_DUP_KEY", "INDEX", "IF NOT EXISTS"): + assert word not in create + assert not hasattr(sql, "UNIQUE_KEY_COLUMNS") + + +def test_import_log_table_is_keyed_on_sha256_and_name(): + ddl = sql.build_create_log_table_sql("my_scans") + assert ddl.startswith("CREATE TABLE dbo.[my_scans_import_log] (") + assert "PRIMARY KEY (file_sha256, file_name)" in ddl + assert "file_sha256 CHAR(64) NOT NULL" in ddl + assert re.findall(r"^\s{4}(\w+) ", ddl, re.M)[:4] == sql.LOG_COLUMN_NAMES def test_column_types_avoid_the_truncation_traps(): @@ -111,13 +140,10 @@ def test_column_types_avoid_the_truncation_traps(): assert not any(t.startswith("VARCHAR") for t in types.values()) assert types["port"] == "INT" and types["host_start_timestamp"] == "BIGINT" assert types["scan_date"] == "DATE" - # The index key must stay under the 900 byte clustered / 1700 byte limit. - key_bytes = 0 - for c in sql.UNIQUE_KEY_COLUMNS: - t = types[c] - m = re.match(r"NVARCHAR\((\d+)\)", t) - key_bytes += int(m.group(1)) * 2 if m else {"INT": 4, "DATE": 3}[t] - assert key_bytes < 900 + # Every multi-value column must be able to hold a long joined list. + for c in sql.MULTI_VALUE_COLUMNS: + assert types[sql.sql_column_name(c)] == "NVARCHAR(MAX)", c + assert "cwe" in sql.MULTI_VALUE_COLUMNS and "mskb" in sql.MULTI_VALUE_COLUMNS # ---- Names ---- @@ -202,15 +228,35 @@ def test_prepare_table_missing_without_create_flag(): sql.prepare_table(FakeConn(), "new_table", create=False) -def test_prepare_table_creates_a_new_table_and_its_index(): +def test_prepare_table_creates_a_new_table_without_an_index(): conn = FakeConn() assert sql.prepare_table(conn, "new_table", create=True) == "created" statements = [q.lstrip() for q, _ in conn.executed if q.lstrip().startswith("CREATE")] - assert statements[0].startswith("CREATE TABLE dbo.[new_table]") - assert statements[1].startswith("CREATE UNIQUE INDEX") + assert len(statements) == 1 and statements[0].startswith("CREATE TABLE dbo.[new_table]") assert conn.commits == 1 +def test_ensure_log_table_creates_once_and_rejects_a_lookalike(): + conn = FakeConn() + sql.ensure_log_table(conn, "t") + sql.ensure_log_table(conn, "t") + creates = [q for q, _ in conn.executed if q.lstrip().startswith("CREATE")] + assert len(creates) == 1 and "[t_import_log]" in creates[0] + other = FakeConn(tables=["t_import_log"], table_columns={"t_import_log": ["id"]}) + with pytest.raises(ValueError, match="not an import log"): + sql.ensure_log_table(other, "t") + + +def test_narrow_multi_value_columns_are_found_and_the_alter_text_is_built(): + cols = good_columns() + conn = FakeConn(tables=["old"], table_columns={"old": cols}) + conn.column_lengths["old"] = {"cwe": 150, "bid": 150, "cve": 4000, "mskb": -1} + narrow = sql.narrow_multi_value_columns(conn, "old") + assert set(narrow) >= {"cwe", "bid", "cve"} and "mskb" not in narrow + alter = sql.alter_multi_value_columns_sql("old", ["cwe"]) + assert alter == "ALTER TABLE dbo.[old] ALTER COLUMN cwe NVARCHAR(MAX) NULL;" + + def test_prepare_table_validates_a_new_name(): with pytest.raises(ValueError): sql.prepare_table(FakeConn(), "bad name", create=True) @@ -355,3 +401,106 @@ def eof(prompt): raise EOFError assert sql.main([str(folder / "a.nessus")], connect_fn=lambda cs: FakeConn(), input_fn=eof) == nc.EXIT_FAILED + + +# ---- Findings that look alike must all land (review B1) ---- + +def compliance_folder(tmp_path): + """Three compliance ReportItems under one plugin on one host, differing only in the text, + plus a host with no host-ip tag whose two items also differ only in the text.""" + from helpers import report_host + items = [report_item("21156", "Windows Compliance Checks", sev, port="0", + children=[("description", f'"1.1.{n} check" : [{res}]')]) + for n, sev, res in ((1, 3, "FAILED"), (2, 1, "PASSED"), (3, 3, "FAILED"))] + no_ip = [report_item("21156", "Windows Compliance Checks", 3, port="0", + children=[("description", f"no ip check {n}")]) for n in (1, 2)] + folder = tmp_path / "compliance" + folder.mkdir() + write_nessus(folder / "compliance.nessus", [ + basic_host("10.0.0.5", items=items), + report_host("noip-host", [("HOST_START", "Thu Apr 4 10:23:11 2024")], no_ip)]) + return folder + + +def run_import(folder, conn, *extra): + return sql.main(["--server", "s", "--database", "d", "--table", "findings", "--create-table", + *extra, str(folder)], connect_fn=lambda cs: conn, + input_fn=lambda p: pytest.fail("should not prompt")) + + +def test_all_compliance_findings_land_and_the_message_counts_rows_that_landed(tmp_path, capsys): + conn = FakeConn() + assert run_import(compliance_folder(tmp_path), conn) == nc.EXIT_OK + assert len(conn.inserted) == 5 + descriptions = [r[sql.SQL_COLUMN_NAMES.index("description")] for r in conn.inserted] + assert len(set(descriptions)) == 5 + out = capsys.readouterr().out + assert "5 rows inserted" in out and "1 file(s) imported" in out + + +def test_importing_the_same_folder_twice_adds_nothing(tmp_path, capsys): + folder = compliance_folder(tmp_path) + conn = FakeConn() + assert run_import(folder, conn) == nc.EXIT_OK + capsys.readouterr() + assert run_import(folder, conn) == nc.EXIT_OK + assert len(conn.inserted) == 5 + out = capsys.readouterr().out + assert "already imported" in out and "0 file(s) imported, 1 skipped" in out and "0 rows inserted" in out + + +def test_a_changed_file_with_the_same_name_is_imported_again(tmp_path): + folder = compliance_folder(tmp_path) + conn = FakeConn() + run_import(folder, conn) + write_nessus(folder / "compliance.nessus", [basic_host("10.0.0.9", items=[report_item("1")])]) + assert run_import(folder, conn) == nc.EXIT_OK + assert len(conn.inserted) == 6 + assert len(conn.log_keys) == 2 + + +def test_same_content_under_another_name_is_a_separate_import(tmp_path): + folder = compliance_folder(tmp_path) + (folder / "copy.nessus").write_bytes((folder / "compliance.nessus").read_bytes()) + conn = FakeConn() + assert run_import(folder, conn) == nc.EXIT_OK + assert len(conn.inserted) == 10 # file_path differs, so these are different rows + + +def test_a_failed_import_is_not_logged_so_a_rerun_retries_it(tmp_path): + folder = compliance_folder(tmp_path) + conn = FakeConn() + conn.fail_on_insert_after = 0 + assert run_import(folder, conn) == nc.EXIT_FAILED + assert conn.inserted == [] and conn.log_keys == set() + conn.fail_on_insert_after = None + assert run_import(folder, conn) == nc.EXIT_OK + assert len(conn.inserted) == 5 + + +def test_a_failing_log_write_rolls_the_rows_back_too(tmp_path): + folder = compliance_folder(tmp_path) + conn = FakeConn() + # Make the log INSERT fail; the findings batch before it must not stay. + conn.fail_on = "INSERT INTO dbo.[findings_import_log]" + assert run_import(folder, conn) == nc.EXIT_FAILED + assert conn.inserted == [] and conn.rollbacks >= 1 + + +def test_main_warns_about_narrow_columns_in_an_old_table(tmp_path, capsys): + folder = compliance_folder(tmp_path) + conn = FakeConn(tables=["findings"], table_columns={"findings": good_columns()}) + conn.column_lengths["findings"] = {"cwe": 150, "mskb": 150} + code = sql.main(["--server", "s", "--database", "d", "--table", "findings", str(folder)], + connect_fn=lambda cs: conn) + assert code == nc.EXIT_OK + err = capsys.readouterr().err + assert "ALTER TABLE dbo.[findings] ALTER COLUMN cwe NVARCHAR(MAX) NULL;" in err + assert "String or binary data would be truncated" in err + + +def test_dry_run_shows_the_import_log_sql(tmp_path, capsys): + folder = compliance_folder(tmp_path) + assert sql.main(["--dry-run", "--table", "dry", str(folder)]) == nc.EXIT_OK + out = capsys.readouterr().out + assert "CREATE TABLE dbo.[dry_import_log]" in out and "5 rows would be inserted" in out From 5748b29194f44f5e3cfbbbbd7f036936d37d4eed Mon Sep 17 00:00:00 2001 From: NullSpace-BitCradle <216858096+NullSpace-BitCradle@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:40:26 -0700 Subject: [PATCH 7/9] Downloader: handle gzip responses and long exports Skip the Content-Length size check when the response is content-encoded, tolerate a non-numeric Content-Length, and make the export wait configurable (--export-timeout, default 900 s; --poll-interval). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi --- tenable_scan_retrieval.py | 40 +++++++++++++++++++++++++----- tests/test_tenable.py | 52 +++++++++++++++++++++++++++++++++++++-- 2 files changed, 84 insertions(+), 8 deletions(-) diff --git a/tenable_scan_retrieval.py b/tenable_scan_retrieval.py index 35e19a5..e65a4f8 100644 --- a/tenable_scan_retrieval.py +++ b/tenable_scan_retrieval.py @@ -19,6 +19,9 @@ Set TENABLE_URL to use another Tenable cloud, for example https://fedcloud.tenable.com. +Each scan's export is polled every 5 seconds for up to 900 seconds. Change that with +--export-timeout SECONDS and --poll-interval SECONDS for very large scans. + Each download goes to a .part file and is renamed only when it is complete, so an interrupted download never leaves a truncated .nessus behind. Files are named -.nessus so two scans with the same name do not overwrite @@ -29,6 +32,7 @@ import datetime import getpass import logging +import math import os import re import sys @@ -45,6 +49,8 @@ TIMEOUT = (10, 60) MAX_RATE_LIMIT_RETRIES = 3 MAX_RETRY_AFTER = 60 +DEFAULT_EXPORT_TIMEOUT = 900 # seconds to wait for one scan's export to become ready +DEFAULT_POLL_INTERVAL = 5 # seconds between export status checks _FAILED_EXPORT_STATUSES = {"error", "failed", "cancelled", "canceled"} @@ -192,15 +198,21 @@ def initiate_export(scan_id, headers): return None -def wait_for_export(scan_id, file_id, headers, max_retries=30, wait_time=5): +def wait_for_export(scan_id, file_id, headers, timeout=DEFAULT_EXPORT_TIMEOUT, wait_time=DEFAULT_POLL_INTERVAL): """ Polls the export status until the scan export is ready for download. + Args: + timeout: seconds to keep waiting in total (default 900; large scans can take a while) + wait_time: seconds between status checks + Returns: True if the export is ready. False if Tenable reports a failed export or - max_retries * wait_time seconds pass without it becoming ready. + `timeout` seconds pass without it becoming ready. """ status_url = f"{get_base_url()}/scans/{scan_id}/export/{file_id}/status" + wait_time = max(wait_time, 1) + max_retries = max(1, math.ceil(timeout / wait_time)) for attempt in range(max_retries): try: response = request_with_retry("get", status_url, headers=headers) @@ -216,7 +228,8 @@ def wait_for_export(scan_id, file_id, headers, max_retries=30, wait_time=5): except (requests.exceptions.RequestException, ValueError) as e: logging.error(f"Error checking export status for scan {scan_id}: {e}") time.sleep(wait_time) - logging.error(f"Export did not complete for scan {scan_id}. Skipping.") + logging.error(f"Export did not complete for scan {scan_id} within {timeout} seconds. " + "Skipping. Raise --export-timeout for very large scans.") return False @@ -251,7 +264,14 @@ def download_scan(scan_id, scan_name, file_id, headers, output_dir): response = request_with_retry("get", download_url, headers=headers, stream=True) response.raise_for_status() - total_size = int(response.headers.get("Content-Length", 0)) + # Content-Length counts the bytes on the wire. If the body is compressed, requests hands + # us the decoded bytes, which are more, so the length cannot be used to check them. + encoding = str(response.headers.get("Content-Encoding", "")).strip().lower() + compressed = encoding not in ("", "identity") + try: + total_size = 0 if compressed else int(response.headers.get("Content-Length", 0)) + except (TypeError, ValueError): + total_size = 0 downloaded_size = 0 chunk_size = 1024 * 1024 # 1MB chunks last_update_time = start_time @@ -394,7 +414,15 @@ def parse_args(argv): help="scan id to download (repeat for more), no prompts") parser.add_argument("--output-dir", default="", help="base folder for the Year/Month/Week folders (default: current folder)") - return parser.parse_args(argv) + parser.add_argument("--export-timeout", type=int, default=DEFAULT_EXPORT_TIMEOUT, metavar="SECONDS", + help="how long to wait for each scan's export to become ready " + f"(default: {DEFAULT_EXPORT_TIMEOUT})") + parser.add_argument("--poll-interval", type=int, default=DEFAULT_POLL_INTERVAL, metavar="SECONDS", + help=f"seconds between export status checks (default: {DEFAULT_POLL_INTERVAL})") + args = parser.parse_args(argv) + if args.export_timeout < 1 or args.poll_interval < 1: + parser.error("--export-timeout and --poll-interval must be at least 1 second") + return args def main(argv=None): @@ -454,7 +482,7 @@ def main(argv=None): failures += 1 continue - if not wait_for_export(scan_id, file_id, headers) \ + if not wait_for_export(scan_id, file_id, headers, args.export_timeout, args.poll_interval) \ or not download_scan(scan_id, scan_name, file_id, headers, output_dir): failures += 1 diff --git a/tests/test_tenable.py b/tests/test_tenable.py index ea0cfc0..280ec65 100644 --- a/tests/test_tenable.py +++ b/tests/test_tenable.py @@ -183,9 +183,57 @@ def test_failed_export_status_stops_polling_early(monkeypatch): assert len(get.calls) == 1 -def test_export_that_never_finishes_times_out(monkeypatch): +def test_export_that_never_finishes_times_out_after_the_configured_wait(monkeypatch): get, _ = patch_http(monkeypatch, get=[FakeResponse(json_data={"status": "loading"})] * 3) - assert tsr.wait_for_export(1, 2, {}, max_retries=3, wait_time=0) is False + assert tsr.wait_for_export(1, 2, {}, timeout=3, wait_time=1) is False + assert len(get.calls) == 3 + + +def test_default_wait_is_longer_than_the_old_150_seconds(): + assert tsr.DEFAULT_EXPORT_TIMEOUT >= 600 + polls = tsr.DEFAULT_EXPORT_TIMEOUT / tsr.DEFAULT_POLL_INTERVAL + assert polls > 30 # the old limit was 30 polls of 5 seconds + + +def test_a_slow_export_that_finishes_after_the_old_limit_is_still_downloaded(monkeypatch): + responses = [FakeResponse(json_data={"status": "loading"})] * 40 + [FakeResponse(json_data={"status": "ready"})] + get, _ = patch_http(monkeypatch, get=responses) + assert tsr.wait_for_export(1, 2, {}) is True + assert len(get.calls) == 41 + + +def test_export_timeout_option_reaches_the_wait(monkeypatch, tmp_path): + monkeypatch.setenv("TENABLE_ACCESS_KEY", "AK") + monkeypatch.setenv("TENABLE_SECRET_KEY", "SK") + patch_http(monkeypatch, + get=[FakeResponse(json_data={"scans": [{"id": 1, "name": "A"}]})], + post=[FakeResponse(json_data={"file": 10})]) + seen = {} + monkeypatch.setattr(tsr, "wait_for_export", + lambda sid, fid, h, timeout, wait: seen.update(timeout=timeout, wait=wait) or False) + assert tsr.main(["--all", "--export-timeout", "1800", "--poll-interval", "10", + "--output-dir", str(tmp_path)]) == 1 + assert seen == {"timeout": 1800, "wait": 10} + + +def test_gzip_download_is_not_checked_against_the_compressed_length(monkeypatch, tmp_path): + """Content-Length is the compressed size; the decoded body is longer.""" + body = b"x" * 100 + patch_http(monkeypatch, get=[FakeResponse( + chunks=[body], headers={"Content-Length": "20", "Content-Encoding": "gzip"})]) + out = tsr.download_scan(5, "Scan", 9, {}, str(tmp_path)) + assert out and open(out, "rb").read() == body + + +def test_identity_encoding_is_still_length_checked(monkeypatch, tmp_path): + patch_http(monkeypatch, get=[FakeResponse( + chunks=[b"ab"], headers={"Content-Length": "10", "Content-Encoding": "identity"})]) + assert tsr.download_scan(5, "Scan", 9, {}, str(tmp_path)) is None + + +def test_a_non_numeric_content_length_does_not_crash(monkeypatch, tmp_path): + patch_http(monkeypatch, get=[FakeResponse(chunks=[b"ab"], headers={"Content-Length": "abc"})]) + assert tsr.download_scan(5, "Scan", 9, {}, str(tmp_path)) def test_download_writes_part_then_renames(monkeypatch, tmp_path): From 7f69a6f237e8474f7b0d767e0867f26726f98a24 Mon Sep 17 00:00:00 2001 From: NullSpace-BitCradle <216858096+NullSpace-BitCradle@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:40:27 -0700 Subject: [PATCH 8/9] Document import idempotency, permissions and old-table widths Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi --- README.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 1b54128..720e59d 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ pip install -r requirements.txt `nessus_to_sql.py` requires: - Windows with ODBC Driver 18 for SQL Server installed - Windows Authentication (Trusted Connection) to the target SQL Server -- Permission to insert data, and to create a table and index if you want the script to create the table +- Permission to insert data and to create tables: the import log (always) and the findings table (if you ask the script to create it) ## Usage @@ -54,7 +54,7 @@ python tenable_scan_retrieval.py --all --output-dir D:\scans 2. Select scans: with no options, enter a single number, comma-separated numbers, or "all". `--all` and `--scan-id` skip the prompt. 3. Files are saved as `-.nessus` in `Year/MM-MonthName/Week-XX/` under `--output-dir` (default: the current folder). Year and week are both ISO values, so 2027-01-01 goes in `2026/01-January/Week-53`. -Every request has a timeout (10 s to connect, 60 s to read). A rate-limited request (HTTP 429) is retried up to 3 times. Each download goes to a `.part` file and is renamed only when complete. To use another Tenable cloud, set `TENABLE_URL` (https only), for example `https://fedcloud.tenable.com`. The exit code is `1` if any selected scan failed. +Every request has a timeout (10 s to connect, 60 s to read). A rate-limited request (HTTP 429) is retried up to 3 times. Each download goes to a `.part` file and is renamed only when complete; the size is checked against `Content-Length` unless the response is compressed, where that length does not apply. Each scan's export is polled every 5 seconds for up to 900 seconds. Use `--export-timeout SECONDS` and `--poll-interval SECONDS` to change that for very large scans. To use another Tenable cloud, set `TENABLE_URL` (https only), for example `https://fedcloud.tenable.com`. The exit code is `1` if any selected scan failed. ### Convert to CSV @@ -88,8 +88,11 @@ python nessus_to_sql.py D:\scans --dry-run # print the SQL and row 1. Give a folder or files (or none, to get a folder picker). 2. Give the server, database and table on the command line, or answer the prompts. The table menu lists the existing `dbo` tables and a "Create a new table" choice that asks for a name. -3. An existing table must already have all the script's columns, or the script stops before inserting. To create a table, use `--create-table` with `--table NAME`, or choose it in the menu. A new table gets a unique index on `(host_ip, pluginID, port, protocol, scan_date, file_path)` that ignores duplicate rows, so importing the same file twice does not add its rows twice. A table made some other way has no such index, and importing the same file again adds the rows again. -4. Each file is imported in one transaction, in batches of 500,000 rows. If a batch fails, nothing from that file is kept and the run stops. +3. An existing table must already have all the script's columns, or the script stops before inserting. To create a table, use `--create-table` with `--table NAME`, or choose it in the menu. The findings table has no unique key, so no finding is ever dropped for looking like another one (compliance checks, for instance, share a plugin ID, host and port and differ only in their text). The script skips a row only when all 106 columns equal an earlier row in the same run. +4. Next to the findings table the script keeps `
_import_log` (created on first use, for existing tables too, so the login needs permission to create it). It records each imported file's base name, its SHA-256 and its row count. A file whose name and SHA-256 are already logged is skipped, so running the same folder twice adds nothing. A file with the same name but different content is imported again in full, and the same content under a different name is a separate import (the `file_path` value differs). Delete a row from the log to force a file to be imported again. +5. Each file is imported in one transaction together with its log row, in batches of 500,000 rows. If a batch fails, nothing from that file is kept, it is not logged, and the run stops. The closing message counts rows inserted by this run, files imported and files skipped. + +Tables built by the old version of this script (before this change) have `VARCHAR(150)` columns for `cwe`, `bid`, `mskb` and the other reference columns, and `NVARCHAR(4000)` for `cve`. A finding with many references makes the joined text longer than that, and SQL Server then rejects the whole batch with "String or binary data would be truncated". When you point the script at such a table it prints a warning with the `ALTER TABLE ... ALTER COLUMN ... NVARCHAR(MAX)` statements for the narrow columns. Run those once, or import into a new table. The column check looks at names only, not types. The `file_path` column holds the file's base name (for example `scan1.nessus`), not a full path. The CSV and Excel outputs call the same value File Name. From b68f31a46d1e861e98cbe49c36ad8eedeb39ffba Mon Sep 17 00:00:00 2001 From: NullSpace-BitCradle <216858096+NullSpace-BitCradle@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:03:47 -0700 Subject: [PATCH 9/9] ci: skip Python 3.9 on ubuntu-latest and disable fail-fast Ubuntu 26.04 runners have no Python 3.9 build, so setup-python failed and fail-fast cancelled every other job. 3.9 stays covered on windows-latest. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi --- .github/workflows/tests.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 1a4b44e..cf5e5ad 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -11,9 +11,14 @@ jobs: pytest: runs-on: ${{ matrix.os }} strategy: + fail-fast: false matrix: os: [ubuntu-latest, windows-latest] python-version: ["3.9", "3.13"] + exclude: + # GitHub's Ubuntu 26.04 image has no Python 3.9 build; 3.9 is still tested on Windows. + - os: ubuntu-latest + python-version: "3.9" steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0