Fixed Clippy Warnings (#451)

* fixed clippy warn

* fixed cargo clippy warnging

* fixed clippy warngings in clippy ver 0.1.59

* fixed clippy warnings clippy::unnecessary_to_owned
This commit is contained in:
DustInDark
2022-03-17 08:43:48 +09:00
committed by GitHub
parent 04b881cb66
commit 7c7a86f7c9
11 changed files with 65 additions and 90 deletions

View File

@@ -120,16 +120,15 @@ fn emit_csv<W: std::io::Write>(
displayflag: bool, displayflag: bool,
color_map: Option<HashMap<String, Vec<u8>>>, color_map: Option<HashMap<String, Vec<u8>>>,
) -> io::Result<()> { ) -> io::Result<()> {
let mut wtr; let mut wtr = if displayflag {
if displayflag { csv::WriterBuilder::new()
wtr = csv::WriterBuilder::new()
.double_quote(false) .double_quote(false)
.quote_style(QuoteStyle::Never) .quote_style(QuoteStyle::Never)
.delimiter(b'|') .delimiter(b'|')
.from_writer(writer); .from_writer(writer)
} else { } else {
wtr = csv::WriterBuilder::new().from_writer(writer); csv::WriterBuilder::new().from_writer(writer)
} };
let messages = print::MESSAGES.lock().unwrap(); let messages = print::MESSAGES.lock().unwrap();
// levelの区分が"Critical","High","Medium","Low","Informational","Undefined"の6つであるため // levelの区分が"Critical","High","Medium","Low","Informational","Undefined"の6つであるため
@@ -276,20 +275,18 @@ fn _print_unique_results(
) )
.ok(); .ok();
for (i, level_name) in levels.iter().enumerate() { for (i, level_name) in levels.iter().enumerate() {
let output_str;
let output_raw_str = format!( let output_raw_str = format!(
"{} {} {}: {}", "{} {} {}: {}",
head_word, level_name, tail_word, counts_by_level[i] head_word, level_name, tail_word, counts_by_level[i]
); );
if color_map.is_none() { let output_str = if color_map.is_none() {
output_str = output_raw_str; output_raw_str
} else { } else {
let output_color = let output_color = _get_output_color(color_map.as_ref().unwrap(), level_name);
_get_output_color(color_map.as_ref().unwrap(), &level_name.to_string()); output_raw_str
output_str = output_raw_str
.truecolor(output_color[0], output_color[1], output_color[2]) .truecolor(output_color[0], output_color[1], output_color[2])
.to_string(); .to_string()
} };
writeln!(wtr, "{}", output_str).ok(); writeln!(wtr, "{}", output_str).ok();
} }
wtr.flush().ok(); wtr.flush().ok();
@@ -413,10 +410,9 @@ mod tests {
+ "," + ","
+ testrulepath + testrulepath
+ "," + ","
+ &testfilepath.to_string() + testfilepath
+ "\n"; + "\n";
let mut file: Box<dyn io::Write> = let mut file: Box<dyn io::Write> = Box::new(File::create("./test_emit_csv.csv").unwrap());
Box::new(File::create("./test_emit_csv.csv".to_string()).unwrap());
assert!(emit_csv(&mut file, false, None).is_ok()); assert!(emit_csv(&mut file, false, None).is_ok());
match read_to_string("./test_emit_csv.csv") { match read_to_string("./test_emit_csv.csv") {
Err(_) => panic!("Failed to open file."), Err(_) => panic!("Failed to open file."),
@@ -512,7 +508,7 @@ mod tests {
+ "\n"; + "\n";
let mut file: Box<dyn io::Write> = let mut file: Box<dyn io::Write> =
Box::new(File::create("./test_emit_csv_display.txt".to_string()).unwrap()); Box::new(File::create("./test_emit_csv_display.txt").unwrap());
assert!(emit_csv(&mut file, true, None).is_ok()); assert!(emit_csv(&mut file, true, None).is_ok());
match read_to_string("./test_emit_csv_display.txt") { match read_to_string("./test_emit_csv_display.txt") {
Err(_) => panic!("Failed to open file."), Err(_) => panic!("Failed to open file."),

View File

@@ -203,7 +203,7 @@ impl Detection {
level: rule.yaml["level"].as_str().unwrap_or("-").to_string(), level: rule.yaml["level"].as_str().unwrap_or("-").to_string(),
computername: record_info.record["Event"]["System"]["Computer"] computername: record_info.record["Event"]["System"]["Computer"]
.to_string() .to_string()
.replace("\"", ""), .replace('\"', ""),
eventid: get_serde_number_to_string( eventid: get_serde_number_to_string(
&record_info.record["Event"]["System"]["EventID"], &record_info.record["Event"]["System"]["EventID"],
) )

View File

@@ -100,12 +100,12 @@ impl Message {
.take(target_length) .take(target_length)
.collect::<String>(); .collect::<String>();
let array_str; let array_str =
if let Some(_array_str) = configs::EVENTKEY_ALIAS.get_event_key(&target_str) { if let Some(_array_str) = configs::EVENTKEY_ALIAS.get_event_key(&target_str) {
array_str = _array_str.to_string(); _array_str.to_string()
} else { } else {
array_str = "Event.EventData.".to_owned() + &target_str; "Event.EventData.".to_owned() + &target_str
} };
let split: Vec<&str> = array_str.split('.').collect(); let split: Vec<&str> = array_str.split('.').collect();
let mut is_exist_event_key = false; let mut is_exist_event_key = false;
@@ -202,7 +202,7 @@ impl AlertMessage {
} }
println!( println!(
"Errors were generated. Please check {} for details.", "Errors were generated. Please check {} for details.",
ERROR_LOG_PATH.to_string() *ERROR_LOG_PATH
); );
println!(); println!();
} }
@@ -352,20 +352,14 @@ mod tests {
#[test] #[test]
fn test_error_message() { fn test_error_message() {
let input = "TEST!"; let input = "TEST!";
AlertMessage::alert( AlertMessage::alert(&mut BufWriter::new(std::io::stdout().lock()), input)
&mut BufWriter::new(std::io::stdout().lock()),
&input.to_string(),
)
.expect("[ERROR] TEST!"); .expect("[ERROR] TEST!");
} }
#[test] #[test]
fn test_warn_message() { fn test_warn_message() {
let input = "TESTWarn!"; let input = "TESTWarn!";
AlertMessage::warn( AlertMessage::warn(&mut BufWriter::new(std::io::stdout().lock()), input)
&mut BufWriter::new(std::io::stdout().lock()),
&input.to_string(),
)
.expect("[WARN] TESTWarn!"); .expect("[WARN] TESTWarn!");
} }

View File

@@ -78,7 +78,7 @@ impl AggegationConditionCompiler {
.unwrap() .unwrap()
.as_str() .as_str()
.to_string() .to_string()
.replacen("|", "", 1); .replacen('|', "", 1);
let tokens = self.tokenize(aggregation_str)?; let tokens = self.tokenize(aggregation_str)?;
@@ -232,8 +232,8 @@ impl AggegationConditionCompiler {
if token.starts_with("count(") { if token.starts_with("count(") {
let count_field = token let count_field = token
.replacen("count(", "", 1) .replacen("count(", "", 1)
.replacen(")", "", 1) .replacen(')', "", 1)
.replace(" ", ""); .replace(' ', "");
AggregationConditionToken::Count(count_field) AggregationConditionToken::Count(count_field)
} else if token == " " { } else if token == " " {
AggregationConditionToken::Space AggregationConditionToken::Space

View File

@@ -65,7 +65,7 @@ fn get_alias_value_in_record(
return None; return None;
} }
match utils::get_event_value(alias, record) { match utils::get_event_value(alias, record) {
Some(value) => Some(value.to_string().replace("\"", "")), Some(value) => Some(value.to_string().replace('\"', "")),
None => { None => {
let errmsg = match is_by_alias { let errmsg = match is_by_alias {
true => format!( true => format!(
@@ -121,7 +121,7 @@ pub fn aggregation_condition_select(rule: &RuleNode) -> Vec<AggResult> {
let value_map = &rule.countdata; let value_map = &rule.countdata;
let mut ret = Vec::new(); let mut ret = Vec::new();
for (key, value) in value_map { for (key, value) in value_map {
ret.append(&mut judge_timeframe(rule, value, &key.to_string())); ret.append(&mut judge_timeframe(rule, value, key));
} }
ret ret
} }

View File

@@ -87,8 +87,7 @@ impl SelectionNode for AndSelectionNode {
self.child_nodes self.child_nodes
.iter() .iter()
.map(|child_node| child_node.get_descendants()) .flat_map(|child_node| child_node.get_descendants())
.flatten()
.for_each(|descendant_node| { .for_each(|descendant_node| {
ret.push(descendant_node); ret.push(descendant_node);
}); });
@@ -158,8 +157,7 @@ impl SelectionNode for OrSelectionNode {
self.child_nodes self.child_nodes
.iter() .iter()
.map(|child_node| child_node.get_descendants()) .flat_map(|child_node| child_node.get_descendants())
.flatten()
.for_each(|descendant_node| { .for_each(|descendant_node| {
ret.push(descendant_node); ret.push(descendant_node);
}); });
@@ -315,8 +313,7 @@ impl SelectionNode for LeafSelectionNode {
let filter_rule = FILTER_REGEX.get(self.get_key()); let filter_rule = FILTER_REGEX.get(self.get_key());
if self.get_key() == "EventData" { if self.get_key() == "EventData" {
let values = let values = utils::get_event_value("Event.EventData.Data", &event_record.record);
utils::get_event_value(&"Event.EventData.Data".to_string(), &event_record.record);
if values.is_none() { if values.is_none() {
return self return self
.matcher .matcher

View File

@@ -184,12 +184,11 @@ pub fn get_event_value<'a>(key: &str, event_value: &'a Value) -> Option<&'a Valu
Option::Some(ret) Option::Some(ret)
} else { } else {
let event_key; let event_key = if !key.contains('.') {
if !key.contains('.') { "Event.EventData.".to_string() + key
event_key = "Event.EventData.".to_string() + key;
} else { } else {
event_key = key.to_string(); key.to_string()
} };
for key in event_key.split('.') { for key in event_key.split('.') {
if !ret.is_object() { if !ret.is_object() {
return Option::None; return Option::None;
@@ -207,7 +206,7 @@ pub fn get_thread_num() -> usize {
let threadnum = &conf let threadnum = &conf
.args .args
.value_of("thread-number") .value_of("thread-number")
.unwrap_or_else(|| def_thread_num_str.as_str()); .unwrap_or(def_thread_num_str.as_str());
threadnum.parse::<usize>().unwrap() threadnum.parse::<usize>().unwrap()
} }

View File

@@ -100,16 +100,13 @@ impl App {
if !Path::new("./config").exists() { if !Path::new("./config").exists() {
AlertMessage::alert( AlertMessage::alert(
&mut BufWriter::new(std::io::stderr().lock()), &mut BufWriter::new(std::io::stderr().lock()),
&"Hayabusa could not find the config directory.\nPlease run it from the Hayabusa root directory.\nExample: ./hayabusa-1.0.0-windows-x64.exe".to_string() "Hayabusa could not find the config directory.\nPlease run it from the Hayabusa root directory.\nExample: ./hayabusa-1.0.0-windows-x64.exe"
) )
.ok(); .ok();
return; return;
} }
if configs::CONFIG.read().unwrap().args.args.is_empty() { if configs::CONFIG.read().unwrap().args.args.is_empty() {
println!( println!("{}", configs::CONFIG.read().unwrap().args.usage());
"{}",
configs::CONFIG.read().unwrap().args.usage().to_string()
);
println!(); println!();
return; return;
} }
@@ -153,7 +150,7 @@ impl App {
{ {
AlertMessage::alert( AlertMessage::alert(
&mut BufWriter::new(std::io::stderr().lock()), &mut BufWriter::new(std::io::stderr().lock()),
&"--filepath only accepts .evtx files. Hidden files are ignored.".to_string(), "--filepath only accepts .evtx files. Hidden files are ignored.",
) )
.ok(); .ok();
return; return;
@@ -164,7 +161,7 @@ impl App {
if evtx_files.is_empty() { if evtx_files.is_empty() {
AlertMessage::alert( AlertMessage::alert(
&mut BufWriter::new(std::io::stderr().lock()), &mut BufWriter::new(std::io::stderr().lock()),
&"No .evtx files were found.".to_string(), "No .evtx files were found.",
) )
.ok(); .ok();
return; return;
@@ -195,10 +192,10 @@ impl App {
fn collect_liveanalysis_files(&self) -> Option<Vec<PathBuf>> { fn collect_liveanalysis_files(&self) -> Option<Vec<PathBuf>> {
AlertMessage::alert( AlertMessage::alert(
&mut BufWriter::new(std::io::stderr().lock()), &mut BufWriter::new(std::io::stderr().lock()),
&"-l / --liveanalysis needs to be run as Administrator on Windows.\r\n".to_string(), "-l / --liveanalysis needs to be run as Administrator on Windows.\r\n",
) )
.ok(); .ok();
return None; None
} }
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
@@ -210,7 +207,7 @@ impl App {
if evtx_files.is_empty() { if evtx_files.is_empty() {
AlertMessage::alert( AlertMessage::alert(
&mut BufWriter::new(std::io::stderr().lock()), &mut BufWriter::new(std::io::stderr().lock()),
&"No .evtx files were found.".to_string(), "No .evtx files were found.",
) )
.ok(); .ok();
return None; return None;
@@ -219,7 +216,7 @@ impl App {
} else { } else {
AlertMessage::alert( AlertMessage::alert(
&mut BufWriter::new(std::io::stderr().lock()), &mut BufWriter::new(std::io::stderr().lock()),
&"-l / --liveanalysis needs to be run as Administrator on Windows.\r\n".to_string(), "-l / --liveanalysis needs to be run as Administrator on Windows.\r\n",
) )
.ok(); .ok();
None None
@@ -305,7 +302,7 @@ impl App {
if rule_files.is_empty() { if rule_files.is_empty() {
AlertMessage::alert( AlertMessage::alert(
&mut BufWriter::new(std::io::stderr().lock()), &mut BufWriter::new(std::io::stderr().lock()),
&"No rules were loaded. Please download the latest rules with the --update-rules option.\r\n".to_string(), "No rules were loaded. Please download the latest rules with the --update-rules option.\r\n",
) )
.ok(); .ok();
return; return;
@@ -585,8 +582,8 @@ impl App {
} else if analysis.0.is_normal() { } else if analysis.0.is_normal() {
AlertMessage::alert( AlertMessage::alert(
&mut BufWriter::new(std::io::stderr().lock()), &mut BufWriter::new(std::io::stderr().lock()),
&"update-rules option is git Fast-Forward merge only. please check your rules folder." "update-rules option is git Fast-Forward merge only. please check your rules folder."
.to_string(), ,
).ok(); ).ok();
Err(git2::Error::from_str(&String::default())) Err(git2::Error::from_str(&String::default()))
} else { } else {

View File

@@ -59,7 +59,7 @@ impl EventStatistics {
// もうちょっと感じに書けるといえば書けます。 // もうちょっと感じに書けるといえば書けます。
for record in records.iter() { for record in records.iter() {
let evttime = utils::get_event_value( let evttime = utils::get_event_value(
&"Event.System.TimeCreated_attributes.SystemTime".to_string(), "Event.System.TimeCreated_attributes.SystemTime",
&record.record, &record.record,
) )
.map(|evt_value| evt_value.to_string()); .map(|evt_value| evt_value.to_string());
@@ -82,7 +82,7 @@ impl EventStatistics {
fn stats_eventid(&mut self, records: &[EvtxRecordInfo]) { fn stats_eventid(&mut self, records: &[EvtxRecordInfo]) {
// let mut evtstat_map = HashMap::new(); // let mut evtstat_map = HashMap::new();
for record in records.iter() { for record in records.iter() {
let evtid = utils::get_event_value(&"EventID".to_string(), &record.record); let evtid = utils::get_event_value("EventID", &record.record);
if evtid.is_none() { if evtid.is_none() {
continue; continue;
} }

View File

@@ -94,8 +94,8 @@ impl Timeline {
event_cnt, event_cnt,
(rate * 1000.0).round() / 10.0, (rate * 1000.0).round() / 10.0,
event_id, event_id,
"Unknown".to_string(), "Unknown",
"".to_string() ""
)); ));
} }
} }

View File

@@ -289,7 +289,7 @@ mod tests {
no_use_rule: HashSet::new(), no_use_rule: HashSet::new(),
}; };
let _ = &yaml.read_dir( let _ = &yaml.read_dir(
"test_files/rules/yaml/1.yml".to_string(), "test_files/rules/yaml/1.yml",
&String::default(), &String::default(),
&exclude_ids, &exclude_ids,
); );
@@ -304,11 +304,7 @@ mod tests {
let exclude_ids = RuleExclude { let exclude_ids = RuleExclude {
no_use_rule: HashSet::new(), no_use_rule: HashSet::new(),
}; };
let _ = &yaml.read_dir( let _ = &yaml.read_dir("test_files/rules/yaml/", &String::default(), &exclude_ids);
"test_files/rules/yaml/".to_string(),
&String::default(),
&exclude_ids,
);
assert_ne!(yaml.files.len(), 0); assert_ne!(yaml.files.len(), 0);
} }
@@ -343,8 +339,7 @@ mod tests {
fn test_default_level_read_yaml() { fn test_default_level_read_yaml() {
let mut yaml = yaml::ParseYaml::new(); let mut yaml = yaml::ParseYaml::new();
let path = Path::new("test_files/rules/level_yaml"); let path = Path::new("test_files/rules/level_yaml");
yaml.read_dir(path.to_path_buf(), "", &filter::exclude_ids()) yaml.read_dir(path, "", &filter::exclude_ids()).unwrap();
.unwrap();
assert_eq!(yaml.files.len(), 5); assert_eq!(yaml.files.len(), 5);
} }
@@ -352,7 +347,7 @@ mod tests {
fn test_info_level_read_yaml() { fn test_info_level_read_yaml() {
let mut yaml = yaml::ParseYaml::new(); let mut yaml = yaml::ParseYaml::new();
let path = Path::new("test_files/rules/level_yaml"); let path = Path::new("test_files/rules/level_yaml");
yaml.read_dir(path.to_path_buf(), "informational", &filter::exclude_ids()) yaml.read_dir(path, "informational", &filter::exclude_ids())
.unwrap(); .unwrap();
assert_eq!(yaml.files.len(), 5); assert_eq!(yaml.files.len(), 5);
} }
@@ -360,15 +355,14 @@ mod tests {
fn test_low_level_read_yaml() { fn test_low_level_read_yaml() {
let mut yaml = yaml::ParseYaml::new(); let mut yaml = yaml::ParseYaml::new();
let path = Path::new("test_files/rules/level_yaml"); let path = Path::new("test_files/rules/level_yaml");
yaml.read_dir(path.to_path_buf(), "LOW", &filter::exclude_ids()) yaml.read_dir(path, "LOW", &filter::exclude_ids()).unwrap();
.unwrap();
assert_eq!(yaml.files.len(), 4); assert_eq!(yaml.files.len(), 4);
} }
#[test] #[test]
fn test_medium_level_read_yaml() { fn test_medium_level_read_yaml() {
let mut yaml = yaml::ParseYaml::new(); let mut yaml = yaml::ParseYaml::new();
let path = Path::new("test_files/rules/level_yaml"); let path = Path::new("test_files/rules/level_yaml");
yaml.read_dir(path.to_path_buf(), "MEDIUM", &filter::exclude_ids()) yaml.read_dir(path, "MEDIUM", &filter::exclude_ids())
.unwrap(); .unwrap();
assert_eq!(yaml.files.len(), 3); assert_eq!(yaml.files.len(), 3);
} }
@@ -376,15 +370,14 @@ mod tests {
fn test_high_level_read_yaml() { fn test_high_level_read_yaml() {
let mut yaml = yaml::ParseYaml::new(); let mut yaml = yaml::ParseYaml::new();
let path = Path::new("test_files/rules/level_yaml"); let path = Path::new("test_files/rules/level_yaml");
yaml.read_dir(path.to_path_buf(), "HIGH", &filter::exclude_ids()) yaml.read_dir(path, "HIGH", &filter::exclude_ids()).unwrap();
.unwrap();
assert_eq!(yaml.files.len(), 2); assert_eq!(yaml.files.len(), 2);
} }
#[test] #[test]
fn test_critical_level_read_yaml() { fn test_critical_level_read_yaml() {
let mut yaml = yaml::ParseYaml::new(); let mut yaml = yaml::ParseYaml::new();
let path = Path::new("test_files/rules/level_yaml"); let path = Path::new("test_files/rules/level_yaml");
yaml.read_dir(path.to_path_buf(), "CRITICAL", &filter::exclude_ids()) yaml.read_dir(path, "CRITICAL", &filter::exclude_ids())
.unwrap(); .unwrap();
assert_eq!(yaml.files.len(), 1); assert_eq!(yaml.files.len(), 1);
} }
@@ -394,8 +387,7 @@ mod tests {
let mut yaml = yaml::ParseYaml::new(); let mut yaml = yaml::ParseYaml::new();
let path = Path::new("test_files/rules/yaml"); let path = Path::new("test_files/rules/yaml");
yaml.read_dir(path.to_path_buf(), "", &filter::exclude_ids()) yaml.read_dir(path, "", &filter::exclude_ids()).unwrap();
.unwrap();
assert_eq!(yaml.ignorerule_count, 10); assert_eq!(yaml.ignorerule_count, 10);
} }
#[test] #[test]
@@ -407,7 +399,7 @@ mod tests {
let exclude_ids = RuleExclude { let exclude_ids = RuleExclude {
no_use_rule: HashSet::new(), no_use_rule: HashSet::new(),
}; };
yaml.read_dir(path.to_path_buf(), "", &exclude_ids).unwrap(); yaml.read_dir(path, "", &exclude_ids).unwrap();
assert_eq!(yaml.ignorerule_count, 0); assert_eq!(yaml.ignorerule_count, 0);
} }
#[test] #[test]
@@ -417,7 +409,7 @@ mod tests {
let exclude_ids = RuleExclude { let exclude_ids = RuleExclude {
no_use_rule: HashSet::new(), no_use_rule: HashSet::new(),
}; };
yaml.read_dir(path.to_path_buf(), "", &exclude_ids).unwrap(); yaml.read_dir(path, "", &exclude_ids).unwrap();
assert_eq!(yaml.ignorerule_count, 1); assert_eq!(yaml.ignorerule_count, 1);
} }
} }