Detection and Parsing
This document explains how VulnParse-Pin v2.1.1 (Apache-2.0) validates input files, selects parsers safely in O(1) bounded memory, and streams normalized records into the DuckDB workspace (.vpp.db).
NOTE
Looking for a quick operator reference of accepted scanner exports, exact CSV column aliases, XML tag variants, or unsupported format gaps? See Input Scan Schemas.
Input validation (FileInputValidator)
Before parser selection, validate_scanner_input() (src/vulnparse_pin/app/normalization.py) runs FileInputValidator (src/vulnparse_pin/utils/validations.py):
- Allowed extensions:
.xml,.nessus,.csv,.json,.sarif,.jsonl,.ndjson. - Size guardrails:
- Default maximum file size: 500 MiB (
max_size_mb = 500). - Large-report ceiling with
--allow-large(-al): 50 GiB (50 * 1024 * 1024 * 1024bytes).
- Default maximum file size: 500 MiB (
- Streaming format & safety checks:
- XML /
.nessus:FileInputValidator._validate_xml_stream()detects and rejects BOM-less UTF-16LE/BE XML (UTF-16 inputs require a BOM, otherwise UTF-8 must be provided) and validates the XML prolog up to 1 MiB viainspect_xml_prolog(). - JSON /
.sarif: Strips UTF-8 BOM (\xef\xbb\xbf), detects accidental JSONL payloads, runs fullijson.basic_parsefor files<= 2 MiB, and bounded prefixijson+IncompleteJSONErrorsniffing (256 KiB prefix) for larger files. - JSONL /
.ndjson: Validates up to 16 non-empty lines with a per-line cap of 8 MiB (_MAX_JSONL_LINE_BYTES). - CSV: Rejects NUL bytes (
\x00), XML/JSON prefixes, and headers without recognized delimiters (,,;,\t,|).
- XML /
Detection subsystem (SchemaDetector)
Schema detection lives in src/vulnparse_pin/core/schema_detector.py, with registered specs in PARSER_SPECS (src/vulnparse_pin/parsers/__init__.py).
- Single bounded read (64 KiB):
SchemaDetector.select()enforces PFH read checks and reads at most_SNIFF_READ_BYTES = 65_536bytes once per input file, passinghead_bytesto candidatedetect_file()methods. - Format classification (
_classify_head_bytes):- Handles UTF-32 BOM (
\xff\xfe\x00\x00,\x00\x00\xfe\xff), UTF-16 BOM (\xff\xfe,\xfe\xff), and UTF-8 BOM (\xef\xbb\xbf). - Classifies
xml,jsonl,sarif(.sarifsuffix or"runs"+"2.1.0"/sarif/tool.driver),json,csv, orunknown.
- Handles UTF-32 BOM (
- Graduated confidence scoring:
detect_file()returns(confidence, evidence)whereconfidence >= 0.50counts as matched. Legacy booleandetect_file()hooks mapTrue -> 0.9,False -> 0.0. - Deterministic tie-breaking (
_pick_winner): Highestconfidence, then lowestParserSpec.priority, thenparser_name.
Registered parsers (PARSER_SPECS)
| Parser Name | Class / Module | Formats | Scanner | Status |
|---|---|---|---|---|
nessus-xml |
NessusXMLParser (nessusXML_parser.py) |
xml, nessus |
nessus |
stable |
openvas-xml |
OpenVASXMLParser (openvasXML_parser.py) |
xml |
openvas |
stable |
qualys-xml |
QualysXMLParser (qualys_parser.py) |
xml |
qualys |
stable |
nmap-xml |
NmapXMLParser (nmap_parser.py) |
xml |
nmap |
stable |
sarif-2.1.0 |
SarifParser (sarif_parser.py) |
sarif, json |
sarif |
stable |
nuclei-jsonl |
NucleiJSONLParser (nuclei_jsonl_parser.py) |
jsonl, json |
nuclei |
stable |
nessus-csv |
NessusCSVParser (nessus_csv_parser.py) |
csv |
nessus |
stable |
qualys-csv |
QualysCSVParser (qualys_csv_parser.py) |
csv |
qualys |
stable |
openvas-json |
OpenVASParser (openvas_parser.py) |
json |
openvas |
experimental (deprecated=True) |
nessus-json |
NessusParser (nessus_parser.py) |
json, nessus |
nessus |
experimental (deprecated=True) |
NOTE
JSON fallback parsers (openvas-json,nessus-json) are experimental and deprecated;SchemaDetectoremits a warning when selected. Prefer XML, SARIF 2.1.0, Nuclei JSONL, or CSV inputs for production workflows.
Hardened streaming XML parsing (_xml_security.py)
VulnParse-Pin v2.1.1 does not use defusedxml. All XML parsers (nessus-xml, openvas-xml, qualys-xml, nmap-xml, and NmapAdapterPass) use hardened streaming lxml.etree.iterparse and lxml.etree.XMLPullParser helpers in src/vulnparse_pin/parsers/_xml_security.py:
- XML prolog inspection (
inspect_xml_prolog,_PrologGuardedStream):- Bounds prolog bytes before the root element to
MAX_XML_PROLOG_BYTES = 1 MiB. - Detects UTF-8 BOM, UTF-16 BOM, UTF-32 BOM, and BOM-less UTF-16LE / UTF-16BE prologs (
<\x00/\x00<after optional UTF-16 whitespace) and decodes strictly before scanning. - Rejects
<!ENTITY,SYSTEM,PUBLIC, parameter entities (%), internal DTD subsets, NUL bytes, and unterminated DOCTYPE declarations beforelxmlparses the stream.
- Bounds prolog bytes before the root element to
- Hardened
lxmlconfiguration & full-subtree entity checks:safe_iterparse()initializeslxml.etree.iterparse(..., resolve_entities=False, no_network=True, load_dtd=False, dtd_validation=False, huge_tree=False).- Internally iterates all elements even when
tag=filtering is requested, callingassert_no_entity_nodes(elem)across element subtrees so entity nodes outside filtered tags cannot evade fail-closed rejection.
- O(1) streaming memory:
prune_element(elem)clears processed elements and deletes preceding siblings (del parent[0]).
Streaming SARIF 2.1.0, Nuclei JSONL, and CSV parsers
- SARIF 2.1.0 (
SarifParser,sarif_parser.py):- Supports Trivy, Grype, Semgrep, CodeQL, Snyk Container, Clair, Anchore, Syft, and Dockle.
- Uses
_FastSarifStreamReader, which decodes UTF-8 incrementally in 4 MiB chunks (chunk_bytes = 4 * 1024 * 1024) viajson.JSONDecoder.raw_decode, skips irrelevant top-level JSON values in O(1) memory (_skip_json_value), and streamsruns[].results[]viaiter_batches()without materializing giant arrays. Usesijsonfor bounded sniffing/validation. - Enforces an iterative 512-level JSON nesting depth limit (
_MAX_JSON_NESTING_DEPTH = 512, raisingValueErrorconsistently across Python versions and converting anyRecursionErrortoValueError) so pathologically nested SARIF payloads fail closed. - Emits
detection_mode = "sca_container"(for container/SCA tools) or"static_sast"(for SAST tools), along withpackage_purl,location_uri, andline_number.
- Nuclei JSONL (
NucleiJSONLParser,nuclei_jsonl_parser.py):- Streams line-by-line JSON objects (
.jsonl,.ndjson, or JSONL-formatted.json), extractingtemplate-id,info.tags, CVEs/CWEs, anddetection_mode = "active_dast".
- Streams line-by-line JSON objects (
- CSV (
NessusCSVParser,QualysCSVParser):- Raises
csv.field_size_limitto 32 MiB (_MAX_CSV_FIELD_BYTES = min(32 * 1024 * 1024, sys.maxsize)). - Sniffs delimiters across
,,;,\t,|, builds a single-pass header index map, skips malformed rows that violate column contracts, and emits ledger events when rows are dropped.
- Raises
Vendor Export Nuances
- Nessus
.nessusXML (nessus-xml):- Plugin
19506credentialed detection: Inferscredentialed = True(detection_mode = "credentialed_host",signal_reliability = 1.0) when Plugin19506(Nessus Scan Information)<plugin_output>matchesCredentialed checks\s*:\s*yes(case-insensitive)—even when<HostProperties>omitsCredentialed_Scanor appears at the bottom of<ReportHost>, and regardless of whether Plugin19506(severity="0") appears before or after high-severity<ReportItem>elements in the same<ReportHost>(bounded per-host buffering paired with immediateprune_element()preserves O(1) DOM memory). - Nessus 10.7+ CVSS v4.0: Parses
<cvss4_base_score>and<cvss4_vector>(CVSS:4.0/...) with strict precedenceCVSS v4.0 > CVSS v3.x > CVSS v2.0, normalizing vectors by strippingCVSS2#/CVSS3#prefixes and enclosing(...). - Exploit framework tags: Recognizes
<exploit_framework_metasploit>,<exploit_framework_canvas>,<exploit_framework_core>,<exploit_framework_d2_elliot>,<exploited_by_malware>, and<exploited_by_nessus>(true/yes/1) alongside<exploit_available>.
- Plugin
- Nessus CSV (
nessus-csv):- Per-row CVSS precedence (
CVSS v4.0 > CVSS v3.x > CVSS v2.0): Orders candidate score and vector columns by CVSS version priority (CVSS v4.0 Base Score>CVSS v3.0/v3.1 Base Score>CVSS v2.0 Base Score) and resolves per row so empty v4/v3 cells fall back cleanly to populated v2 while populated higher versions take precedence. StripsCVSS2#,CVSS3#, and enclosing(...). - Tenable.sc & host aliases: Recognizes Tenable.sc
Plugin Textas plugin output alongsidePlugin Output, and mapsDNS,DNS Name,NetBIOS, andNetBIOS Namehost/asset columns.
- Per-row CVSS precedence (
- Qualys VMDR XML (
qualys-xml) & Qualys CSV (qualys-csv):- Three Qualys XML schemas: Supports Scan Report XML (
<SCAN>/<SCAN_REPORT>), Asset Data Report XML (<ASSET_DATA_REPORT>→<HOST_LIST><HOST>→<VULN_INFO_LIST><VULN_INFO>with optional<GLOSSARY><VULN_DETAILS_LIST><VULN_DETAILS id="...">lookups), and VM Detection API XML (<HOST_LIST_VM_DETECTION_OUTPUT>→<RESPONSE><HOST_LIST><HOST>→<DETECTION_LIST><DETECTION>), preferringCVSS4>CVSS3.1>CVSS3> v2CVSStags and strippingCVSS2#/CVSS3#/(...). - Qualys CSV report preambles: Scans up to the first 25 non-empty CSV rows in both
detect_fileand_stream_batchesto skip Qualys VMDR report metadata preamble lines until locating the real header row (qid+ host/IP/DNS + title/severity/type/vuln status), applies per-rowCVSS4 Base > CVSS3.1 Base > CVSS3 Base > CVSS Baseprecedence, and recognizes pluralResultsas plugin output.
- Three Qualys XML schemas: Supports Scan Report XML (
- Nmap port-only XML vs.
--nmapexposure context:- Passing an Nmap XML file as a primary positional input (
vpp scan nmap.xml) invokesNmapXMLParser(nmap-xml,detection_mode = "network_probe"), emittingInformationalopen-port findings for port-only scans andHighfindings only when NSE scripts report CVEs or"vulnerable". - Passing an Nmap XML file via
--nmap nmap.xmlalongside primary scanners (vpp scan nessus.xml --nmap nmap.xml) invokesNmapAdapterPass(NmapAdapter@1.0) to enrich.vpp.dbassets(open_ports_json,internet_facing,os), reconcile multi-scanner shadow-IP assets, and surfaceunmatched_shadowhosts without creating informational port findings (port_tiebreak_enabled/scoring_port_bonusapply only to legacyTopN@1.0/Scoring@2.0). See Nmap Context Deep Dive.
- Passing an Nmap XML file as a primary positional input (
Ingestion quality metadata & batch gates
Every parser emits normalized records (NormalizedFindingRecord) via iter_batches() carrying:
detection_mode(credentialed_host,active_dast,sca_container,uncredentialed_banner,static_sast,network_probe)ingestion_confidence,fidelity_tier(high,medium,low),degraded_input,source_format(with""/Nonefor absent optional fields)- During DuckDB ingestion (
src/vulnparse_pin/storage/repositories.py),signal_reliabilityis computed fromdetection_mode. When materializing compatibilityScanResultobjects viaBaseParser._build_scan_result_from_batches(),fidelity_tiermaps tofull/partial/minimal(fidelity_to_scanresult()) and absent description/output fields receiveSENTINEL:No_Description/SENTINEL:No_Plugin_Output.
enforce_batch_ingestion_gates() (src/vulnparse_pin/app/normalization.py) enforces --strict-ingestion, --no-allow-degraded-input, and --min-ingestion-confidence per streamed batch and logs gate rejections to LedgerService.
Extending parsing support
- Subclass
BaseParserinsrc/vulnparse_pin/parsers/. - Implement bounded
detect_file(..., head_bytes=...)returning(confidence, evidence)and streamingiter_batches(batch_size=...)(plusparse()compatibility if needed). - Use
_xml_security.safe_iterparse+prune_elementfor XML inputs; never introducedefusedxml. - Register
ParserSpecinPARSER_SPECS(src/vulnparse_pin/parsers/__init__.py) with explicitstabilityanddeprecatedflags. - Add parser smoke, streaming, and XXE/edge-case tests under
tests/.