nessus-parser 0.3.0

A parser for `.nessus` (v2) XML reports
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! Types for Nessus `<ReportItem>` findings and their normalized fields.

use std::{borrow::Cow, collections::HashMap, str::FromStr};

use jiff::civil::Date;
use roxmltree::Node;

use crate::{StringStorageExt, error::FormatError};

/// Network transport protocol attached to a report item.
#[derive(Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
pub enum Protocol {
    /// TCP.
    Tcp,
    /// UDP.
    Udp,
    /// ICMP.
    Icmp,
}

impl Protocol {
    /// Returns the lowercase protocol name used in Nessus XML.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Tcp => "tcp",
            Self::Udp => "udp",
            Self::Icmp => "icmp",
        }
    }
}

impl FromStr for Protocol {
    type Err = FormatError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "tcp" => Ok(Self::Tcp),
            "udp" => Ok(Self::Udp),
            "icmp" => Ok(Self::Icmp),
            other => Err(FormatError::UnexpectedProtocol(other.into())),
        }
    }
}

/// Execution context/type of a Nessus plugin finding.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum PluginType {
    /// Summary-level plugin output.
    Summary,
    /// Remote network check.
    Remote,
    /// Combined local+remote behavior.
    Combined,
    /// Local check on the scanned host.
    Local,
}

impl FromStr for PluginType {
    type Err = FormatError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "summary" => Ok(Self::Summary),
            "remote" => Ok(Self::Remote),
            "combined" => Ok(Self::Combined),
            "local" => Ok(Self::Local),
            other => Err(FormatError::UnexpectedPluginType(other.into())),
        }
    }
}

/// Normalized severity/risk level.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub enum Level {
    /// Informational / no severity.
    None = 0,
    /// Low severity.
    Low = 1,
    /// Medium severity.
    Medium = 2,
    /// High severity.
    High = 3,
    /// Critical severity.
    Critical = 4,
}

impl Level {
    fn from_int(int: &str) -> Result<Self, FormatError> {
        match int {
            "0" => Ok(Self::None),
            "1" => Ok(Self::Low),
            "2" => Ok(Self::Medium),
            "3" => Ok(Self::High),
            "4" => Ok(Self::Critical),
            other => Err(FormatError::UnexpectedLevel(other.into())),
        }
    }

    fn from_text(s: &str) -> Result<Self, FormatError> {
        match s {
            "None" => Ok(Self::None),
            "Low" => Ok(Self::Low),
            "Medium" => Ok(Self::Medium),
            "High" => Ok(Self::High),
            "Critical" => Ok(Self::Critical),
            other => Err(FormatError::UnexpectedLevel(other.into())),
        }
    }
}

/// Represents a `<ReportItem>` element, which is a single finding or piece of
/// information reported by a Nessus plugin for a specific host and port.
#[derive(Debug)]
pub struct Item<'input> {
    /// The unique identifier of the Nessus plugin that generated this item.
    pub plugin_id: u32,
    /// The name of the plugin.
    pub plugin_name: Cow<'input, str>,
    /// The port number associated with this finding.
    pub port: u16,
    /// The protocol associated with the port (TCP, UDP, ICMP).
    pub protocol: Protocol,
    /// The service name discovered on the port (e.g., "www", "general").
    pub svc_name: &'input str,
    /// The severity level of the finding.
    pub severity: Level,
    /// The family that the plugin belongs to (e.g., "Windows", "CGI abuses").
    pub plugin_family: &'input str,
    /// The raw output from the plugin, which often contains detailed evidence.
    pub plugin_output: Option<Cow<'input, str>>,

    /// The suggested solution or remediation for the finding.
    pub solution: Cow<'input, str>,
    /// The version of the plugin script.
    // $Revision: 1.234 $ | 1.234
    pub script_version: &'input str,
    /// The risk factor associated with the finding (e.g., "High", "None").
    pub risk_factor: Level,
    /// The type of the plugin (e.g., remote, local).
    pub plugin_type: PluginType,
    /// The date when the plugin was first published.
    pub plugin_publication_date: jiff::civil::Date,
    /// The date when the plugin was last modified.
    pub plugin_modification_date: jiff::civil::Date,
    /// The filename of the plugin script (e.g., "example.nasl").
    pub fname: &'input str,
    /// A detailed description of the vulnerability or finding.
    pub description: Cow<'input, str>,
    /// A boolean indicating if a known exploit for the vulnerability exists.
    pub exploit_available: bool,
    /// A boolean indicating if the vulnerability was exploited by Nessus during the scan.
    pub exploited_by_nessus: bool,
    /// A description of how easy it is to exploit the vulnerability.
    // "Exploits are available" | "No known exploits are available" | "No exploit is required"
    pub exploitability_ease: Option<&'input str>,

    /// The agent type the plugin is applicable to ("all", "unix", "windows").
    pub agent: Option<&'input str>,

    /// The `CVSSv2` vector string.
    pub cvss_vector: Option<&'input str>,
    /// The `CVSSv2` temporal vector string.
    pub cvss_temporal_vector: Option<&'input str>,
    /// The `CVSSv3` vector string.
    pub cvss3_vector: Option<&'input str>,
    /// The `CVSSv3` temporal vector string.
    pub cvss3_temporal_vector: Option<&'input str>,
    /// The `CVSSv4` vector string.
    pub cvss4_vector: Option<&'input str>,
    /// The `CVSSv4` threat vector string.
    pub cvss4_threat_vector: Option<&'input str>,

    /// A map to hold any other elements from the `ReportItem` not explicitly
    /// parsed into other fields. The key is the XML tag name.
    pub others: HashMap<&'input str, Vec<Cow<'input, str>>>,
}

impl<'input> Item<'input> {
    #[expect(clippy::too_many_lines, clippy::similar_names)]
    pub(crate) fn from_xml_node(node: Node<'_, 'input>) -> Result<Self, FormatError> {
        let mut plugin_id = None;
        let mut plugin_name = None;
        let mut port = None;
        let mut protocol = None;
        let mut svc_name = None;
        let mut severity = None;
        let mut plugin_family = None;

        for attribute in node.attributes() {
            match attribute.name() {
                "pluginID" => {
                    if plugin_id.is_some() {
                        return Err(FormatError::RepeatedTag("pluginID"));
                    }
                    plugin_id = Some(attribute.value_storage().parse()?);
                }
                "pluginName" => {
                    if plugin_name.is_some() {
                        return Err(FormatError::RepeatedTag("pluginName"));
                    }
                    plugin_name = Some(attribute.value_storage().to_cow());
                }
                "port" => {
                    if port.is_some() {
                        return Err(FormatError::RepeatedTag("port"));
                    }
                    port = Some(attribute.value().parse()?);
                }
                "protocol" => {
                    if protocol.is_some() {
                        return Err(FormatError::RepeatedTag("protocol"));
                    }
                    protocol = Some(attribute.value_storage().parse()?);
                }
                "svc_name" => {
                    if svc_name.is_some() {
                        return Err(FormatError::RepeatedTag("svc_name"));
                    }
                    svc_name = Some(attribute.value_storage().to_str()?);
                }
                "severity" => {
                    if severity.is_some() {
                        return Err(FormatError::RepeatedTag("severity"));
                    }
                    severity = Some(Level::from_int(attribute.value())?);
                }
                "pluginFamily" => {
                    if plugin_family.is_some() {
                        return Err(FormatError::RepeatedTag("pluginFamily"));
                    }
                    plugin_family = Some(attribute.value_storage().to_str()?);
                }

                // Intentional: we fail fast on unknown attributes to keep the parser strict.
                other => return Err(FormatError::UnexpectedXmlAttribute(other.into())),
            }
        }

        let mut plugin_output = None;

        let mut solution = None;
        let mut script_version = None;
        let mut risk_factor = None;
        let mut plugin_type = None;
        let mut plugin_publication_date = None;
        let mut plugin_modification_date = None;
        let mut fname = None;
        let mut description = None;

        let mut agent = None;
        let mut cvss_vector = None;
        let mut cvss3_vector = None;
        let mut cvss_temporal_vector = None;
        let mut cvss3_temporal_vector = None;
        let mut cvss4_vector = None;
        let mut cvss4_threat_vector = None;
        let mut exploitability_ease = None;
        let mut exploit_available = None;
        let mut exploited_by_nessus = None;

        let mut others: HashMap<_, Vec<_>> = HashMap::new();

        for child in node.children() {
            if child.is_text() {
                if let Some(text) = child.text()
                    && !text.trim().is_empty()
                {
                    return Err(FormatError::UnexpectedText(text.into()));
                }
                continue;
            }

            let name = child.tag_name().name();
            if let Some(value) = child.text_storage() {
                match name {
                    "plugin_output" => {
                        if plugin_output.is_some() {
                            return Err(FormatError::RepeatedTag("plugin_output"));
                        }
                        plugin_output = Some(value.to_cow());
                    }
                    "solution" => {
                        if solution.is_some() {
                            return Err(FormatError::RepeatedTag("solution"));
                        }
                        solution = Some(value.to_cow());
                    }
                    "description" => {
                        if description.is_some() {
                            return Err(FormatError::RepeatedTag("description"));
                        }
                        description = Some(value.to_cow());
                    }

                    "script_version" => {
                        if script_version.is_some() {
                            return Err(FormatError::RepeatedTag("script_version"));
                        }
                        script_version = Some(value.to_str()?);
                    }
                    "risk_factor" => {
                        if risk_factor.is_some() {
                            return Err(FormatError::RepeatedTag("risk_factor"));
                        }
                        risk_factor = Some(Level::from_text(value.as_str())?);
                    }
                    "plugin_type" => {
                        if plugin_type.is_some() {
                            return Err(FormatError::RepeatedTag("plugin_type"));
                        }
                        plugin_type = Some(value.parse()?);
                    }
                    "plugin_publication_date" => {
                        if plugin_publication_date.is_some() {
                            return Err(FormatError::RepeatedTag("plugin_publication_date"));
                        }
                        plugin_publication_date = Some(Date::strptime("%Y/%m/%d", value.as_str())?);
                    }
                    "plugin_modification_date" => {
                        if plugin_modification_date.is_some() {
                            return Err(FormatError::RepeatedTag("plugin_modification_date"));
                        }
                        plugin_modification_date =
                            Some(Date::strptime("%Y/%m/%d", value.as_str())?);
                    }
                    "fname" => {
                        if fname.is_some() {
                            return Err(FormatError::RepeatedTag("fname"));
                        }
                        fname = Some(value.to_str()?);
                    }

                    "agent" => {
                        if agent.is_some() {
                            return Err(FormatError::RepeatedTag("agent"));
                        }
                        agent = Some(value.to_str()?);
                    }
                    "cvss_vector" => {
                        if cvss_vector.is_some() {
                            return Err(FormatError::RepeatedTag("cvss_vector"));
                        }
                        cvss_vector = Some(value.to_str()?);
                    }
                    "cvss3_vector" => {
                        if cvss3_vector.is_some() {
                            return Err(FormatError::RepeatedTag("cvss3_vector"));
                        }
                        cvss3_vector = Some(value.to_str()?);
                    }
                    "cvss_temporal_vector" => {
                        if cvss_temporal_vector.is_some() {
                            return Err(FormatError::RepeatedTag("cvss_temporal_vector"));
                        }
                        cvss_temporal_vector = Some(value.to_str()?);
                    }
                    "cvss3_temporal_vector" => {
                        if cvss3_temporal_vector.is_some() {
                            return Err(FormatError::RepeatedTag("cvss3_temporal_vector"));
                        }
                        cvss3_temporal_vector = Some(value.to_str()?);
                    }
                    "cvss4_vector" => {
                        if cvss4_vector.is_some() {
                            return Err(FormatError::RepeatedTag("cvss4_vector"));
                        }
                        cvss4_vector = Some(value.to_str()?);
                    }
                    "cvss4_threat_vector" => {
                        if cvss4_threat_vector.is_some() {
                            return Err(FormatError::RepeatedTag("cvss4_threat_vector"));
                        }
                        cvss4_threat_vector = Some(value.to_str()?);
                    }
                    "exploitability_ease" => {
                        if exploitability_ease.is_some() {
                            return Err(FormatError::RepeatedTag("exploitability_ease"));
                        }
                        exploitability_ease = Some(value.to_str()?);
                    }
                    "exploit_available" => {
                        if exploit_available.is_some() {
                            return Err(FormatError::RepeatedTag("exploit_available"));
                        }
                        // Intentional: any non-"true" value (including invalid strings) is treated as false.
                        exploit_available = Some(value.as_str() == "true");
                    }
                    "exploited_by_nessus" => {
                        if exploited_by_nessus.is_some() {
                            return Err(FormatError::RepeatedTag("exploited_by_nessus"));
                        }
                        // Intentional: any non-"true" value (including invalid strings) is treated as false.
                        exploited_by_nessus = Some(value.as_str() == "true");
                    }

                    _ => others.entry(name).or_default().push(value.to_cow()),
                }
            } else {
                return Err(FormatError::UnexpectedNode(name.into()));
            }
        }

        Ok(Self {
            plugin_id: plugin_id.ok_or(FormatError::MissingAttribute("pluginID"))?,
            plugin_name: plugin_name.ok_or(FormatError::MissingAttribute("pluginName"))?,
            port: port.ok_or(FormatError::MissingAttribute("port"))?,
            protocol: protocol.ok_or(FormatError::MissingAttribute("protocol"))?,
            svc_name: svc_name.ok_or(FormatError::MissingAttribute("svc_name"))?,
            severity: severity.ok_or(FormatError::MissingAttribute("severity"))?,
            plugin_family: plugin_family.ok_or(FormatError::MissingAttribute("pluginFamily"))?,
            solution: solution.ok_or(FormatError::MissingTag("solution"))?,
            script_version: script_version.ok_or(FormatError::MissingTag("script_version"))?,
            risk_factor: risk_factor.ok_or(FormatError::MissingTag("risk_factor"))?,
            plugin_type: plugin_type.ok_or(FormatError::MissingTag("plugin_type"))?,
            plugin_publication_date: plugin_publication_date
                .ok_or(FormatError::MissingTag("plugin_publication_date"))?,
            plugin_modification_date: plugin_modification_date
                .ok_or(FormatError::MissingTag("plugin_modification_date"))?,
            fname: fname.ok_or(FormatError::MissingTag("fname"))?,
            description: description.ok_or(FormatError::MissingTag("description"))?,
            plugin_output,
            agent,
            cvss_vector,
            cvss3_vector,
            cvss_temporal_vector,
            cvss3_temporal_vector,
            cvss4_vector,
            cvss4_threat_vector,
            exploitability_ease,
            exploit_available: exploit_available == Some(true),
            exploited_by_nessus: exploited_by_nessus == Some(true),
            others,
        })
    }
}

#[cfg(test)]
mod tests {
    use roxmltree::Document;

    use crate::error::FormatError;

    use super::{Item, Level, PluginType, Protocol};

    fn parse_item(xml: &str) -> Result<Item<'_>, FormatError> {
        let doc = Document::parse(xml).expect("test XML should parse");
        let node = doc.root_element();
        Item::from_xml_node(node)
    }

    fn minimal_item_xml(extra_attributes: &str, extra_children: &str) -> String {
        format!(
            r#"<ReportItem pluginID="1" pluginName="x" port="80" protocol="tcp" svc_name="www" severity="2" pluginFamily="General" {extra_attributes}>
  <solution>fix</solution>
  <script_version>1.0</script_version>
  <risk_factor>Medium</risk_factor>
  <plugin_type>remote</plugin_type>
  <plugin_publication_date>2024/01/01</plugin_publication_date>
  <plugin_modification_date>2024/01/02</plugin_modification_date>
  <fname>x.nasl</fname>
  <description>desc</description>
  {extra_children}
</ReportItem>"#
        )
    }

    #[test]
    fn protocol_and_plugin_type_parsing_cover_invalid_values() {
        assert!(matches!("tcp".parse(), Ok(Protocol::Tcp)));
        assert!(matches!(
            "not-proto".parse::<Protocol>(),
            Err(FormatError::UnexpectedProtocol(_))
        ));
        assert!(matches!("local".parse(), Ok(PluginType::Local)));
        assert!(matches!(
            "bad".parse::<PluginType>(),
            Err(FormatError::UnexpectedPluginType(_))
        ));
    }

    #[test]
    fn item_rejects_unknown_attribute() {
        let xml = minimal_item_xml(r#"bad="x""#, "");
        let err = parse_item(&xml).expect_err("must fail");
        assert!(matches!(err, FormatError::UnexpectedXmlAttribute(_)));
    }

    #[test]
    fn item_rejects_non_empty_text_node() {
        let xml = minimal_item_xml("", "hello");
        let err = parse_item(&xml).expect_err("must fail");
        assert!(matches!(err, FormatError::UnexpectedText(_)));
    }

    #[test]
    fn item_rejects_missing_required_fields() {
        let xml = r#"<ReportItem pluginID="1" pluginName="x" port="80" protocol="tcp" svc_name="www" severity="2" pluginFamily="General"></ReportItem>"#;
        let err = parse_item(xml).expect_err("must fail");
        assert!(matches!(err, FormatError::MissingTag("solution")));
    }

    #[test]
    fn item_rejects_repeated_child_tag() {
        let xml = minimal_item_xml("", "<solution>again</solution>");
        let err = parse_item(&xml).expect_err("must fail");
        assert!(matches!(err, FormatError::RepeatedTag("solution")));
    }

    #[test]
    fn item_coerces_exploit_booleans() {
        let xml = minimal_item_xml(
            "",
            r"
  <exploit_available>true</exploit_available>
  <exploited_by_nessus>not-true</exploited_by_nessus>
",
        );
        let item = parse_item(&xml).expect("must parse");
        assert!(item.exploit_available);
        assert!(!item.exploited_by_nessus);
    }

    #[test]
    fn level_invalid_values_fail() {
        let xml = minimal_item_xml("", "").replace(
            "<risk_factor>Medium</risk_factor>",
            "<risk_factor>NotALevel</risk_factor>",
        );
        let err = parse_item(&xml).expect_err("must fail");
        assert!(matches!(err, FormatError::UnexpectedLevel(_)));

        assert!(matches!(
            Level::from_int("9"),
            Err(FormatError::UnexpectedLevel(_))
        ));
        assert!(matches!(
            Level::from_text("NotALevel"),
            Err(FormatError::UnexpectedLevel(_))
        ));
    }
}