exclude-rules.txtとnoisy-rules.txtをコメントに対応 (#362)

* add exclude files comments feature

* trim()

* add error handling and split function

* add id validation

* add comments

* cargo fmt

* fix error statment

* change -full.txt to .txt

* change alert to warn
This commit is contained in:
kazuminn
2022-01-20 23:12:41 +09:00
committed by GitHub
parent 2db8ff9f9a
commit 15ee980711
5 changed files with 68 additions and 56 deletions
+50 -22
View File
@@ -1,6 +1,18 @@
use crate::detections::configs;
use crate::detections::print::AlertMessage;
use crate::detections::print::ERROR_LOG_STACK;
use crate::detections::print::QUIET_ERRORS_FLAG;
use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashSet;
use std::fs;
use std::fs::File;
use std::io::BufWriter;
use std::io::{BufRead, BufReader};
lazy_static! {
static ref IDS_REGEX: Regex =
Regex::new(r"^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$").unwrap();
}
#[derive(Clone, Debug)]
pub struct RuleExclude {
@@ -8,10 +20,8 @@ pub struct RuleExclude {
}
pub fn exclude_ids() -> RuleExclude {
let mut ids;
match fs::read("config/exclude-rules.txt") {
Ok(file) => ids = String::from_utf8(file).unwrap(),
Err(_) => panic!("config/exclude-rules.txt does not exist"),
let mut exclude_ids = RuleExclude {
no_use_rule: HashSet::new(),
};
if !configs::CONFIG
@@ -20,25 +30,43 @@ pub fn exclude_ids() -> RuleExclude {
.args
.is_present("enable-noisy-rules")
{
ids += "\n"; // 改行を入れないとexclude-rulesの一番最後の行とnoisy-rules.txtの一番最初の行が一行にまとめられてしまう。
match fs::read("config/noisy-rules.txt") {
Ok(file) => ids += &String::from_utf8(file).unwrap(),
Err(_) => panic!("config/noisy-rules.txt does not exist"),
};
}
let mut exclude_ids = RuleExclude {
no_use_rule: HashSet::new(),
exclude_ids.insert_ids("config/noisy-rules.txt");
};
for v in ids.split_whitespace() {
let v = v.to_string();
if v.is_empty() {
// 空行は無視する。
continue;
}
exclude_ids.no_use_rule.insert(v);
}
exclude_ids.insert_ids("config/exclude-rules.txt");
return exclude_ids;
}
impl RuleExclude {
fn insert_ids(&mut self, filename: &str) {
let f = File::open(filename);
if f.is_err() {
if configs::CONFIG.read().unwrap().args.is_present("verbose") {
AlertMessage::warn(
&mut BufWriter::new(std::io::stderr().lock()),
&format!("{} does not exist", filename),
)
.ok();
}
if !*QUIET_ERRORS_FLAG {
ERROR_LOG_STACK
.lock()
.unwrap()
.push(format!("{} does not exist", filename));
}
return ();
}
let reader = BufReader::new(f.unwrap());
for v in reader.lines() {
let v = v.unwrap().split("#").collect::<Vec<&str>>()[0]
.trim()
.to_string();
if v.is_empty() || !IDS_REGEX.is_match(&v) {
// 空行は無視する。IDの検証
continue;
}
self.no_use_rule.insert(v);
}
}
}