Skip to content

Commit

Permalink
fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
lukaspustina committed Jul 28, 2018
1 parent a43c9e1 commit d171d3c
Show file tree
Hide file tree
Showing 8 changed files with 172 additions and 124 deletions.
93 changes: 52 additions & 41 deletions src/analyze.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,14 @@ pub struct AnalyzerResult<'a> {
pub pass: usize,
pub fail: usize,
pub error: usize,
pub analysis_results: Vec<Analysis<'a>>
pub analysis_results: Vec<Analysis<'a>>,
}

pub fn default_analysis<'a>(nmap_run: &'a Run, mapping: &'a Mapping, portspecs: &'a PortSpecs) -> AnalyzerResult<'a> {
pub fn default_analysis<'a>(
nmap_run: &'a Run,
mapping: &'a Mapping,
portspecs: &'a PortSpecs,
) -> AnalyzerResult<'a> {
let analyzer = Analyzer::new(&nmap_run, &mapping, &portspecs);
let analysis_results = analyzer.analyze();

Expand All @@ -28,9 +32,15 @@ pub fn default_analysis<'a>(nmap_run: &'a Run, mapping: &'a Mapping, portspecs:
let mut error = 0;
for ar in &analysis_results {
match ar.result {
AnalysisResult::Pass => {pass += 1;},
AnalysisResult::Fail => {fail += 1;},
AnalysisResult::Error{ .. } => {error += 1;},
AnalysisResult::Pass => {
pass += 1;
}
AnalysisResult::Fail => {
fail += 1;
}
AnalysisResult::Error { .. } => {
error += 1;
}
}
}

Expand All @@ -54,7 +64,7 @@ pub struct Analysis<'a> {
pub enum AnalysisResult {
Pass,
Fail,
Error{ reason: String },
Error { reason: String },
}

#[derive(Debug, PartialEq, Serialize)]
Expand All @@ -78,11 +88,7 @@ pub struct Analyzer<'a> {
}

impl<'a> Analyzer<'a> {
pub fn new(
nmap_run: &'a Run,
mapping: &'a Mapping,
portspecs: &'a PortSpecs,
) -> Analyzer<'a> {
pub fn new(nmap_run: &'a Run, mapping: &'a Mapping, portspecs: &'a PortSpecs) -> Analyzer<'a> {
let scanned_host_by_ip = run_to_scanned_hosts_by_ip(&nmap_run);
let portspec_by_ip = portspec_by_ip(&mapping, &portspecs);

Expand All @@ -95,16 +101,16 @@ impl<'a> Analyzer<'a> {
pub fn analyze(&self) -> Vec<Analysis<'a>> {
self.scanned_host_by_ip
.iter()
.map(|(ip, host)| {
match self.portspec_by_ip.get(ip) {
Some(ps) => analyze_host(ip, host, ps),
None => Analysis {
ip,
portspec_name: None,
result: AnalysisResult::Error{reason: "no port spec found for this IP address".to_owned()},
port_results: Vec::new(),
}
}
.map(|(ip, host)| match self.portspec_by_ip.get(ip) {
Some(ps) => analyze_host(ip, host, ps),
None => Analysis {
ip,
portspec_name: None,
result: AnalysisResult::Error {
reason: "no port spec found for this IP address".to_owned(),
},
port_results: Vec::new(),
},
})
.collect()
}
Expand All @@ -124,7 +130,7 @@ fn portspec_by_ip<'a>(
portspec: &'a PortSpecs,
) -> BTreeMap<&'a IpAddr, &'a portspec::PortSpec> {
let pss = portspecs_to_portspec_by_name(portspec);
let mut psbi= BTreeMap::new();
let mut psbi = BTreeMap::new();

for m in &mapping.mappings {
let key: &str = &m.port_spec;
Expand Down Expand Up @@ -257,21 +263,19 @@ mod tests {
#[test]
fn analyzer_no_mapping_for_ip() {
let portspecs = portspec::PortSpecs {
port_specs: vec![
portspec::PortSpec {
name: "Unused Group".to_owned(),
ports: vec![
portspec::Port {
id: 22,
state: portspec::PortState::Closed,
},
portspec::Port {
id: 25,
state: portspec::PortState::Open,
},
],
},
]
port_specs: vec![portspec::PortSpec {
name: "Unused Group".to_owned(),
ports: vec![
portspec::Port {
id: 22,
state: portspec::PortState::Closed,
},
portspec::Port {
id: 25,
state: portspec::PortState::Open,
},
],
}],
};
let nmap = nmap_data();
let mapping = mapping_data();
Expand All @@ -282,9 +286,13 @@ mod tests {

assert_that(&analysis).has_length(2);
let res0 = &analysis[0];
assert_that!(&res0.result).is_equal_to(AnalysisResult::Error{reason: "no port spec found for this IP address".to_owned()});
assert_that!(&res0.result).is_equal_to(AnalysisResult::Error {
reason: "no port spec found for this IP address".to_owned(),
});
let res1 = &analysis[1];
assert_that!(&res1.result).is_equal_to(AnalysisResult::Error{reason: "no port spec found for this IP address".to_owned()});
assert_that!(&res1.result).is_equal_to(AnalysisResult::Error {
reason: "no port spec found for this IP address".to_owned(),
});
}

#[test]
Expand Down Expand Up @@ -847,11 +855,14 @@ mod tests {
Host {
id: "i-0".to_owned(),
hostname: "ec2-192.168.0.3".to_owned(),
ips: vec!["192.168.0.3".parse().unwrap(), "192.168.0.3".parse().unwrap()],
ips: vec![
"192.168.0.3".parse().unwrap(),
"192.168.0.3".parse().unwrap(),
],
name: "Group B server".to_owned(),
port_spec: "Group B".to_owned(),
},
]
],
}
}

Expand Down
19 changes: 10 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub mod nmap;
pub mod output;
pub mod portspec;

pub use analyze::{Analyzer, AnalyzerResult, Analysis, AnalysisResult, default_analysis};
pub use analyze::{default_analysis, Analysis, AnalysisResult, Analyzer, AnalyzerResult};
pub use mapping::Mapping;
pub use nmap::Run;
pub use portspec::PortSpecs;
Expand All @@ -43,16 +43,18 @@ error_chain! {

pub trait FromFile {
fn from_file<P: AsRef<Path>, E>(path: P) -> ::std::result::Result<Self, Error>
where Self: Sized + FromStr<Err = E>, E: error_chain::ChainedError {
where
Self: Sized + FromStr<Err = E>,
E: error_chain::ChainedError,
{
let contents = Self::string_from_file(path).chain_err(|| ErrorKind::InvalidFileFormat)?;

let contents = Self::string_from_file(path)
.chain_err(|| ErrorKind::InvalidFileFormat)?;

Self::from_str(&contents)
.chain_err(|| ErrorKind::InvalidFileFormat)
Self::from_str(&contents).chain_err(|| ErrorKind::InvalidFileFormat)
}

fn string_from_file<P: AsRef<Path>>(path: P) -> ::std::result::Result<String, ::std::io::Error> {
fn string_from_file<P: AsRef<Path>>(
path: P,
) -> ::std::result::Result<String, ::std::io::Error> {
let path: &Path = path.as_ref();

let mut file = File::open(path)?;
Expand All @@ -77,4 +79,3 @@ where
let s = String::deserialize(deserializer)?;
T::from_str(&s).map_err(de::Error::custom)
}

97 changes: 58 additions & 39 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ extern crate nmap_analyze;
extern crate structopt;

use clams::prelude::*;
use nmap_analyze::*;
use nmap_analyze::output::{OutputConfig, OutputDetail, OutputFormat};
use nmap_analyze::*;
use std::path::{Path, PathBuf};
use structopt::StructOpt;

Expand All @@ -25,7 +25,8 @@ error_chain!{
}

#[derive(StructOpt, Debug)]
#[structopt(name = "nmap-analyze",
#[structopt(
name = "nmap-analyze",
about = "analyze nmap xml output and compares port states with specification",
raw(setting = "structopt::clap::AppSettings::ColoredHelp")
)]
Expand All @@ -40,10 +41,19 @@ struct Args {
#[structopt(short = "p", long = "portspec", parse(from_os_str))]
portspec: PathBuf,
/// Select output format
#[structopt(short = "o", long = "output", default_value = "human", raw(possible_values = r#"&["human", "json", "none"]"#))]
#[structopt(
short = "o",
long = "output",
default_value = "human",
raw(possible_values = r#"&["human", "json", "none"]"#)
)]
output_format: OutputFormat,
/// Select output detail level for human output
#[structopt(long = "output-detail", default_value = "fail", raw(possible_values = r#"&["fail", "all"]"#))]
#[structopt(
long = "output-detail",
default_value = "fail",
raw(possible_values = r#"&["fail", "all"]"#)
)]
output_detail: OutputDetail,
/// Do not use colored output
#[structopt(long = "no-color")]
Expand All @@ -67,51 +77,58 @@ fn run() -> Result<i32> {
color: !args.no_color,
};

run_nmap_analyze(&args.nmap, &args.mapping, &args.portspec, &output_config, args.silent)
run_nmap_analyze(
&args.nmap,
&args.mapping,
&args.portspec,
&output_config,
args.silent,
)
}

fn setup(name: &str, args: &Args) {
clams::console::set_color(!args.no_color);

let level: Level = args.verbosity.into();
if !args.silent {
eprintln!("{} version={}, log level={:?}",
eprintln!(
"{} version={}, log level={:?}",
name,
env!("CARGO_PKG_VERSION"),
&level
);
}

let log_config = LogConfig::new(
std::io::stderr(),
false,
Level(log::LevelFilter::Error),
vec![
ModLevel {
std::io::stderr(),
false,
Level(log::LevelFilter::Error),
vec![ModLevel {
module: name.to_owned(),
level,
},
],
None,
}],
None,
);

init_logging(log_config)
.expect("Failed to initialize logging");
init_logging(log_config).expect("Failed to initialize logging");
}

fn run_nmap_analyze<T: AsRef<Path>>(nmap_file: T, mapping_file: T, portspecs_file: T, output_config: &OutputConfig, silent: bool) -> Result<i32> {
fn run_nmap_analyze<T: AsRef<Path>>(
nmap_file: T,
mapping_file: T,
portspecs_file: T,
output_config: &OutputConfig,
silent: bool,
) -> Result<i32> {
info!("Loading port specification file");
let portspecs = PortSpecs::from_file(portspecs_file.as_ref())
.chain_err(|| ErrorKind::InvalidFile)?;
let portspecs =
PortSpecs::from_file(portspecs_file.as_ref()).chain_err(|| ErrorKind::InvalidFile)?;
info!("Loading mappings file");
let mapping = Mapping::from_file(mapping_file.as_ref())
.chain_err(|| ErrorKind::InvalidFile)?;
let mapping = Mapping::from_file(mapping_file.as_ref()).chain_err(|| ErrorKind::InvalidFile)?;
info!("Loading nmap file");
let nmap_run = Run::from_file(nmap_file.as_ref())
.chain_err(|| ErrorKind::InvalidFile)?;
let nmap_run = Run::from_file(nmap_file.as_ref()).chain_err(|| ErrorKind::InvalidFile)?;
info!("Checking nmap sanity");
nmap_run.is_sane()
.chain_err(|| ErrorKind::InvalidFile)?;
nmap_run.is_sane().chain_err(|| ErrorKind::InvalidFile)?;

info!("Analyzing");
let analyzer_result = default_analysis(&nmap_run, &mapping, &portspecs);
Expand All @@ -124,7 +141,8 @@ fn run_nmap_analyze<T: AsRef<Path>>(nmap_file: T, mapping_file: T, portspecs_fil

info!("Summarizing");
if !silent {
println!("Analyzer result summary: {}={}, {}={}, {}={}",
println!(
"Analyzer result summary: {}={}, {}={}, {}={}",
"passed".green(),
analyzer_result.pass,
"failed".red(),
Expand All @@ -135,19 +153,21 @@ fn run_nmap_analyze<T: AsRef<Path>>(nmap_file: T, mapping_file: T, portspecs_fil
}

match analyzer_result {
AnalyzerResult{ fail: 0, error: 0, .. } => {
Ok(0)
},
AnalyzerResult{ fail: x, error: 0, .. } if x > 0 => {
AnalyzerResult {
fail: 0, error: 0, ..
} => Ok(0),
AnalyzerResult {
fail: x, error: 0, ..
}
if x > 0 =>
{
Ok(11)
},
AnalyzerResult{ error: x, .. } if x > 0 => {
Ok(12)
},
AnalyzerResult{ .. } => {
}
AnalyzerResult { error: x, .. } if x > 0 => Ok(12),
AnalyzerResult { .. } => {
error!("This not possible and just to satify the compiler");
Ok(13)
},
}
}
}

Expand All @@ -156,16 +176,15 @@ fn output(output_config: &OutputConfig, analyzer_result: &AnalyzerResult) -> Res
OutputFormat::Human => {
use nmap_analyze::output::HumanOutput;
analyzer_result.output_tty(output_config)
},
}
OutputFormat::Json => {
use nmap_analyze::output::JsonOutput;
let stdout = ::std::io::stdout();
let mut writer = stdout.lock();
analyzer_result.output(output_config, &mut writer)
},
}
OutputFormat::None => Ok(()),
}.map_err(|e| e.into())
}

quick_main!(run);

Loading

0 comments on commit d171d3c

Please sign in to comment.