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
// Copyright 2020 David Young
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
#![warn(missing_docs)]

//! This is a library for parsing Nessus XML files and providing iterators
//! over the useful features. Currently, the whole XML file is read into
//! appropriate data structures and iterators are provided over the hosts
//! and ports.
//!
//!  ```rust,no_run
//! # use nessus_xml_parser::NessusScan;
//! let xml = r#"
//! <?xml version="1.0" ?>
//! <NessusClientData_v2>
//! ...
//! </NessusClientData_v2>
//! "#;
//! let nessus = NessusScan::parse(&xml).unwrap();
//! ```

pub use policy::*;
pub use report::*;
use roxmltree::Document;

mod policy;
mod report;

/// Error types returned by this crate.
#[derive(thiserror::Error, Debug)]
pub enum Error {
    /// General XML parsing errors
    #[error("error parsing file as XML document")]
    XmlError(#[from] roxmltree::Error),
    /// Specific Nessus parsing errors
    #[error("error parsing Nessus XML output: {0}")]
    InvalidNessusOutput(String),
}

/// Provide From<&str> to allow static strings
impl From<&str> for Error {
    fn from(s: &str) -> Self {
        Self::InvalidNessusOutput(s.to_string())
    }
}

/// Provide From<&String> to allow format!()
impl From<&String> for Error {
    fn from(s: &String) -> Self {
        Self::InvalidNessusOutput(s.to_string())
    }
}

/// This struct holds the two sections of a Nessus XML file. Every XML
/// file must have a single Policy section, and zero or one Report
/// sections.
///
/// * The Policy section contains information about the scan settings,
/// plugins used, etc.
///
/// * The Report section contains the results from having run a Nessus
/// scan with the provided Policy
///
/// This crate provides iterators over the discovered hosts and ports.
#[derive(Debug)]
pub struct NessusScan {
    /// The Policy section contains information about the scan settings,
    /// plugins used, etc.
    policy: Policy,
    /// The Report section contains the results from having run a Nessus
    /// scan with the provided Policy
    report: Option<Report>,
}

impl NessusScan {
    /// Returns the Policy section from a report
    pub fn policy(&self) -> &Policy {
        &self.policy
    }

    /// Returns the Report section from a report
    pub fn report(&self) -> &Option<Report> {
        &self.report
    }

    /// Attempt to parse an XML object as a Nessus report
    ///
    /// ```rust,no_run
    /// # use nessus_xml_parser::NessusScan;
    /// let xml = r#"
    /// <?xml version="1.0" ?>
    /// <NessusClientData_v2>
    /// ...
    /// </NessusClientData_v2>
    /// "#;
    /// let nessus = NessusScan::parse(&xml).unwrap();
    /// ```
    pub fn parse(nessus_xml_str: &str) -> Result<Self, Error> {
        // Parse the input as XML
        let doc = Document::parse(&nessus_xml_str)?;
        let root_element = doc.root_element();
        if root_element.tag_name().name() != "NessusClientData_v2" {
            return Err(Error::from("expected `NessusClientData_v2` root tag"));
        }

        let mut policy: Option<Policy> = None;
        let mut report: Option<Report> = None;

        for child in root_element.children() {
            match child.tag_name().name() {
                "Policy" => {
                    if policy.is_some() {
                        // there may only be one Policy section
                        return Err(Error::from("Too many Policy sections"));
                    } else {
                        policy = Some(Policy::from(child)?);
                    }
                }
                "Report" => {
                    if report.is_some() {
                        // there may only be one Report section
                        return Err(Error::from("Too many Report sections"));
                    } else {
                        report = Some(Report::parse(&child)?);
                    }
                }
                _ => {}
            }
        }

        let policy =
            policy.ok_or_else(|| Error::from("expected Policy section"))?;

        Ok(NessusScan { policy, report })
    }

    /// Returns an interator over the hosts in the scan
    ///
    /// ```rust,no_run
    /// # use nessus_xml_parser::NessusScan;
    /// let xml = r#"
    /// <?xml version="1.0" ?>
    /// <NessusClientData_v2>
    /// ...
    /// </NessusClientData_v2>
    /// "#;
    /// let nessus = NessusScan::parse(&xml).unwrap();
    /// for host in nessus.hosts() {
    ///     println!("Hostname: {}", host);    
    /// }
    /// ```
    pub fn hosts(&self) -> std::slice::Iter<ReportHost> {
        if let Some(rep) = &self.report {
            return rep.hosts.iter();
        }
        [].iter()
    }

    /// Returns an interator over the ports in the scan.
    ///
    /// ```rust,no_run
    /// # use nessus_xml_parser::NessusScan;
    /// let xml = r#"
    /// <?xml version="1.0" ?>
    /// <NessusClientData_v2>
    /// ...
    /// </NessusClientData_v2>
    /// "#;
    /// let nessus = NessusScan::parse(&xml).unwrap();
    /// for (host, port) in nessus.ports() {
    ///     println!("Hostname: {}, port: {}", host, port.id);    
    /// }
    /// ```
    pub fn ports(&self) -> std::vec::IntoIter<(&ReportHost, Port)> {
        let mut results = Vec::new();
        for host in self.hosts() {
            for item in &host.items {
                if item.port != 0 {
                    results.push((host, item.port()));
                }
            }
        }

        results.sort();
        results.dedup();

        results.into_iter()
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn load_xml_format_without_report() {
        let xml = r#"<?xml version="1.0" ?>
<NessusClientData_v2>
    <Policy>
        <policyName>MyExamplePolicy</policyName>
        <policyComments>Thisisanexamplepolicy</policyComments>
        <Preferences>
            <ServerPreferences>
                <preference>
                    <name>max_hosts</name>
                    <value>30</value>
                </preference>
                <preference>
                    <name>plugin_set</name>
                    <value>123634;108478;84316;36080;126581;61117;46758;42271;65403;56011;</value>
                </preference>
            </ServerPreferences>
            <PluginsPreferences>
                <item>
                    <pluginName>WebApplicationTestsSettings</pluginName>
                    <pluginId>39471</pluginId>
                    <fullName>WebApplicationTestsSettings[checkbox]:Enablewebapplic-ationstests</fullName>
                    <preferenceName>Enablewebapplicationstests</preferenceName>
                    <preferenceType>checkbox</preferenceType>
                    <preferenceValues>no</preferenceValues>
                    <selectedValue>no</selectedValue>
                </item>
            </PluginsPreferences>
        </Preferences>
        <FamilySelection>
            <FamilyItem>
                <FamilyName>WebServers</FamilyName>
                <Status>disabled</Status>
            </FamilyItem>
        </FamilySelection>
        <IndividualPluginSelection>
            <PluginItem>
                <PluginId>34220</PluginId>
                <PluginName>netstatportscanner(WMI)</PluginName>
                <Family>Portscanners</Family>
                <Status>enabled</Status>
            </PluginItem>
        </IndividualPluginSelection>
    </Policy>
</NessusClientData_v2>
        "#;

        let nessus = NessusScan::parse(&xml).unwrap();

        assert_eq!(nessus.policy().policy_name, "MyExamplePolicy");

        // This report has no report section, so the hosts iterator
        // must therefore be empty (and immediately return None)
        let mut hosts = nessus.hosts();
        assert!(hosts.next().is_none());
    }

    #[test]
    fn load_xml_format_with_report() {
        let xml = r#"<?xml version="1.0" ?>
<NessusClientData_v2>
    <Policy>
        <policyName>MyExamplePolicy</policyName>
        <policyComments>Thisisanexamplepolicy</policyComments>
        <Preferences>
            <ServerPreferences>
                <preference>
                    <name>max_hosts</name>
                    <value>30</value>
                </preference>
                <preference>
                    <name>plugin_set</name>
                    <value>123634;108478;84316;36080;126581;61117;46758;42271;65403;56011;</value>
                </preference>
            </ServerPreferences>
            <PluginsPreferences>
                <item>
                    <pluginName>WebApplicationTestsSettings</pluginName>
                    <pluginId>39471</pluginId>
                    <fullName>WebApplicationTestsSettings[checkbox]:Enablewebapplic-ationstests</fullName>
                    <preferenceName>Enablewebapplicationstests</preferenceName>
                    <preferenceType>checkbox</preferenceType>
                    <preferenceValues>no</preferenceValues>
                    <selectedValue>no</selectedValue>
                </item>
            </PluginsPreferences>
        </Preferences>
        <FamilySelection>
            <FamilyItem>
                <FamilyName>WebServers</FamilyName>
                <Status>disabled</Status>
            </FamilyItem>
        </FamilySelection>
        <IndividualPluginSelection>
            <PluginItem>
                <PluginId>34220</PluginId>
                <PluginName>netstatportscanner(WMI)</PluginName>
                <Family>Portscanners</Family>
                <Status>enabled</Status>
            </PluginItem>
        </IndividualPluginSelection>
    </Policy>
<Report name="Router-Uncredentialed">
    <ReportHost name="10.129.121.252">
        <HostProperties>
            <tag name="cpe-3">cpe:/a:mysql:mysql:5.5.9 -&gt; MySQL 5.5.9</tag>
            <tag name="cpe-2">cpe:/a:mysql:mysql:5.5.9 -&gt; MySQL 5.5.9</tag>
            <tag name="netbios-name">ECLIPSE</tag>
            <tag name="cpe-1">cpe:/o:microsoft:windows_xp</tag>
            <tag name="cpe-0">cpe:/o:microsoft:windows_2000</tag>
            <tag name="HOST_END_TIMESTAMP">1593441583</tag>
            <tag name="HOST_END">Mon Jun 29 14:39:43 2020</tag>
            <tag name="host-ip">10.129.121.252</tag>
            <tag name="HOST_START_TIMESTAMP">1593441445</tag>
            <tag name="HOST_START">Mon Jun 29 14:37:25 2020</tag>
        </HostProperties>
        <ReportItem
            port="445"
            svc_name="cifs"
            protocol="tcp"
            severity="0"
            pluginID="11011"
            pluginName="Microsoft Windows SMB Service Detection"
            pluginFamily="Windows"
            >
            <asset_inventory>True</asset_inventory>
            <description>
                The remote service understands the CIFS (Common Internet File
                System) or Server Message Block (SMB) protocol, used to provide
                shared access to files, printers, etc between nodes on a network.
            </description>
            <fname>cifs445.nasl</fname>
            <os_identification>True</os_identification>
            <plugin_modification_date>2020/01/22</plugin_modification_date>
            <plugin_name>Microsoft Windows SMB Service Detection</plugin_name>
            <plugin_publication_date>2002/06/05</plugin_publication_date>
            <plugin_type>remote</plugin_type>
            <risk_factor>None</risk_factor>
            <script_version>1.41</script_version>
            <solution>n/a</solution>
            <synopsis>
                A file / print sharing service is listening on the remote host.
            </synopsis>
            <plugin_output>
                A CIFS server is running on this port.
            </plugin_output>
        </ReportItem>
    </ReportHost>
    <ReportHost name="192.168.0.10">
    <HostProperties>
        <tag name="HOST_END">Wed Mar 09 22:55:00 2011</tag>
        <tag name="operating-system">MicrosoftWindowsXPProfessional(English)</tag>
        <tag name="mac-address">00:1e:8c:83:ad:5f</tag>
        <tag name="netbios-name">ZESTY</tag>
        <tag name="HOST_START">Wed Mar 09 22:48:10 2011</tag>
    </HostProperties>
    <ReportItem port="445" svc_name="cifs" protocol="tcp" severity="0" pluginID="10394" pluginName="Microsoft Windows SMB Log In Possible" pluginFamily="Windows">
        <asset_inventory>True</asset_inventory>
        <description>The remote host is running a Microsoft Windows operating system or Samba, a CIFS/SMB server for Unix. It was possible to log into it using one of the following accounts :

- NULL session
- Guest account
- Supplied credentials</description>
        <fname>smb_login.nasl</fname>
        <plugin_modification_date>2020/03/09</plugin_modification_date>
        <plugin_name>Microsoft Windows SMB Log In Possible</plugin_name>
        <plugin_publication_date>2000/05/09</plugin_publication_date>
        <plugin_type>remote</plugin_type>
        <risk_factor>None</risk_factor>
        <script_version>1.160</script_version>
        <see_also>http://www.nessus.org/u?5c2589f6
https://support.microsoft.com/en-us/help/246261</see_also>
        <solution>n/a</solution>
        <synopsis>It was possible to log into the remote host.</synopsis>
        <plugin_output>- NULL sessions are enabled on the remote host.
</plugin_output>
    </ReportItem>
    <ReportItem port="139" svc_name="smb" protocol="tcp" severity="0" pluginID="11011" pluginName="Microsoft Windows SMB Service Detection" pluginFamily="Windows">
        <asset_inventory>True</asset_inventory>
        <description>The remote service understands the CIFS (Common Internet File System) or Server Message Block (SMB) protocol, used to provide shared access to files, printers, etc between nodes on a network.</description>
        <fname>cifs445.nasl</fname>
        <os_identification>True</os_identification>
        <plugin_modification_date>2020/01/22</plugin_modification_date>
        <plugin_name>Microsoft Windows SMB Service Detection</plugin_name>
        <plugin_publication_date>2002/06/05</plugin_publication_date>
        <plugin_type>remote</plugin_type>
        <risk_factor>None</risk_factor>
        <script_version>1.41</script_version>
        <solution>n/a</solution>
        <synopsis>A file / print sharing service is listening on the remote host.</synopsis>
        <plugin_output>
An SMB server is running on this port.
</plugin_output>
    </ReportItem>
</ReportHost>
</Report>
</NessusClientData_v2>
        "#;

        let nessus = NessusScan::parse(&xml).unwrap();

        assert_eq!(nessus.policy().policy_name, "MyExamplePolicy");

        let mut hosts = nessus.hosts();

        assert_eq!(hosts.next().unwrap().name, "10.129.121.252");
        assert_eq!(hosts.next().unwrap().name, "192.168.0.10");
        assert!(hosts.next().is_none());
    }
}