bubble up parsing errors

This commit is contained in:
Pierre Dubouilh
2021-10-17 18:59:56 +02:00
parent 70cbeae0ed
commit 6741f48285
6 changed files with 121 additions and 30 deletions
+40 -8
View File
@@ -1,7 +1,9 @@
use crate::utils::Error;
use std::net::IpAddr;
use lazy_static::lazy_static;
use regex::Regex;
use std::str::FromStr;
struct Rule {
matcher: String,
@@ -15,7 +17,7 @@ lazy_static! {
extractor: Regex::new(r"(from.)(.*)(.port)").unwrap(),
},
Rule {
matcher: "Invalid user".to_string(),
matcher: "Invalid user ".to_string(),
extractor: Regex::new(r"(from.)(.*)").unwrap(),
},
Rule {
@@ -25,16 +27,27 @@ lazy_static! {
];
}
pub fn parse(line: &str) -> Option<IpAddr> {
let ret = SSHD_BAD.iter().find_map(|rule| {
pub fn parse(line: &str) -> Result<Option<IpAddr>, Error> {
let hits = SSHD_BAD.iter().find_map(|rule| {
if line.contains(&rule.matcher) {
rule.extractor.captures(line)?.get(2)
rule.extractor.captures(line)
} else {
None
}
})?;
});
ret.as_str().parse::<IpAddr>().ok()
if hits.is_none() {
return Ok(None);
}
let ip = hits
.and_then(|c| c.get(2))
.and_then(|m| IpAddr::from_str(m.as_str()).ok());
match ip {
Some(ip) => Ok(Some(ip)),
None => Err(Error::CantParse),
}
}
#[cfg(test)]
@@ -49,7 +62,10 @@ mod tests {
"Sep 26 06:25:32 livecompute sshd[23254]: Invalid user neal from 35.184.211.144"
];
vectors.iter().for_each(|e| assert!(parse(*e).is_some()))
vectors.iter().for_each(|e| {
let ret = parse(*e);
assert!(ret.unwrap().is_some());
})
}
#[test]
@@ -60,6 +76,22 @@ mod tests {
"Sep 26 06:25:32 livecompute sshd[23254]: very good user neal from 35.184.211.144"
];
vectors.iter().for_each(|e| assert!(parse(*e).is_none()))
vectors.iter().for_each(|e| {
let ret = parse(*e);
assert!(ret.unwrap().is_none());
})
}
#[test]
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());
})
}
}