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

View File

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

View File

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

View File

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

View File

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

View File

@@ -87,8 +87,7 @@ impl SelectionNode for AndSelectionNode {
self.child_nodes
.iter()
.map(|child_node| child_node.get_descendants())
.flatten()
.flat_map(|child_node| child_node.get_descendants())
.for_each(|descendant_node| {
ret.push(descendant_node);
});
@@ -158,8 +157,7 @@ impl SelectionNode for OrSelectionNode {
self.child_nodes
.iter()
.map(|child_node| child_node.get_descendants())
.flatten()
.flat_map(|child_node| child_node.get_descendants())
.for_each(|descendant_node| {
ret.push(descendant_node);
});
@@ -315,8 +313,7 @@ impl SelectionNode for LeafSelectionNode {
let filter_rule = FILTER_REGEX.get(self.get_key());
if self.get_key() == "EventData" {
let values =
utils::get_event_value(&"Event.EventData.Data".to_string(), &event_record.record);
let values = utils::get_event_value("Event.EventData.Data", &event_record.record);
if values.is_none() {
return self
.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)
} else {
let event_key;
if !key.contains('.') {
event_key = "Event.EventData.".to_string() + key;
let event_key = if !key.contains('.') {
"Event.EventData.".to_string() + key
} else {
event_key = key.to_string();
}
key.to_string()
};
for key in event_key.split('.') {
if !ret.is_object() {
return Option::None;
@@ -207,7 +206,7 @@ pub fn get_thread_num() -> usize {
let threadnum = &conf
.args
.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()
}

View File

@@ -100,16 +100,13 @@ impl App {
if !Path::new("./config").exists() {
AlertMessage::alert(
&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();
return;
}
if configs::CONFIG.read().unwrap().args.args.is_empty() {
println!(
"{}",
configs::CONFIG.read().unwrap().args.usage().to_string()
);
println!("{}", configs::CONFIG.read().unwrap().args.usage());
println!();
return;
}
@@ -153,7 +150,7 @@ impl App {
{
AlertMessage::alert(
&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();
return;
@@ -164,7 +161,7 @@ impl App {
if evtx_files.is_empty() {
AlertMessage::alert(
&mut BufWriter::new(std::io::stderr().lock()),
&"No .evtx files were found.".to_string(),
"No .evtx files were found.",
)
.ok();
return;
@@ -195,10 +192,10 @@ impl App {
fn collect_liveanalysis_files(&self) -> Option<Vec<PathBuf>> {
AlertMessage::alert(
&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();
return None;
None
}
#[cfg(target_os = "windows")]
@@ -210,7 +207,7 @@ impl App {
if evtx_files.is_empty() {
AlertMessage::alert(
&mut BufWriter::new(std::io::stderr().lock()),
&"No .evtx files were found.".to_string(),
"No .evtx files were found.",
)
.ok();
return None;
@@ -219,7 +216,7 @@ impl App {
} else {
AlertMessage::alert(
&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();
None
@@ -305,7 +302,7 @@ impl App {
if rule_files.is_empty() {
AlertMessage::alert(
&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();
return;
@@ -585,8 +582,8 @@ impl App {
} else if analysis.0.is_normal() {
AlertMessage::alert(
&mut BufWriter::new(std::io::stderr().lock()),
&"update-rules option is git Fast-Forward merge only. please check your rules folder."
.to_string(),
"update-rules option is git Fast-Forward merge only. please check your rules folder."
,
).ok();
Err(git2::Error::from_str(&String::default()))
} else {

View File

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

View File

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

View File

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