cleanup & optimisation

This commit is contained in:
Pierre Dubouilh
2022-08-21 20:15:36 +02:00
parent 89e6d2bff1
commit 5b9e81af5f
8 changed files with 285 additions and 303 deletions
+12 -20
View File
@@ -1,8 +1,7 @@
use anyhow::*;
use lazy_static::lazy_static;
use regex::Regex;
use std::net::IpAddr;
use std::str::FromStr;
use std::{net::IpAddr, str::FromStr};
use crate::utils::ParsingStatus;
@@ -15,27 +14,24 @@ lazy_static! {
static ref SSHD_BAD: [Rule; 3] = [
Rule {
matcher: "Failed password".to_string(),
extractor: Regex::new(r"(from.)(.*)(.port)").unwrap(),
extractor: Regex::new(r"(from.)(\S+)").unwrap(),
},
Rule {
matcher: "Invalid user ".to_string(),
extractor: Regex::new(r"(from.)(.*)").unwrap(),
extractor: Regex::new(r"(from.)(\S+)").unwrap(),
},
Rule {
matcher: "authentication failure".to_string(),
extractor: Regex::new(r"(rhost=)(.*)").unwrap()
extractor: Regex::new(r"(rhost=)(\S+)").unwrap()
},
];
}
pub fn parse(line: &str) -> Result<ParsingStatus> {
let hits = SSHD_BAD.iter().find_map(|rule| {
if line.contains(&rule.matcher) {
rule.extractor.captures(line)
} else {
None
}
});
let hits = SSHD_BAD
.iter()
.find(|rule| line.contains(&rule.matcher))
.and_then(|r| r.extractor.captures(line));
if hits.is_none() {
return Ok(ParsingStatus::OkEntry);
@@ -43,12 +39,10 @@ pub fn parse(line: &str) -> Result<ParsingStatus> {
let ip = hits
.and_then(|c| c.get(2))
.and_then(|m| IpAddr::from_str(m.as_str()).ok());
.and_then(|m| IpAddr::from_str(m.as_str()).ok())
.ok_or_else(|| anyhow!("cant parse sshd line"))?;
match ip {
Some(ip) => Ok(ParsingStatus::BadEntry(ip)),
None => Err(anyhow!("cant parse sshd entry")),
}
Ok(ParsingStatus::BadEntry(ip))
}
#[cfg(test)]
@@ -93,12 +87,10 @@ mod tests {
fn malformed() {
let vectors = [
"Sep 26 06:25:19 livecompute sshd[23246]: Failed password for root from 179.124.36.195.232 port 41883 ssh2",
"Sep 26 06:26:14 livecompute sshd[23292]: pam_unix(sshd:auth): authentication failure; logname= u =0 tty=ssh ruser= rhost=",
];
vectors.iter().for_each(|e| {
let ret = parse(*e);
assert!(ret.is_err());
parse(*e).expect_err("");
})
}
}