use proper enum return type

This commit is contained in:
Pierre Dubouilh
2021-10-17 20:49:37 +02:00
parent 283653a775
commit 4d2aee5178
5 changed files with 73 additions and 29 deletions
+14 -7
View File
@@ -1,3 +1,4 @@
use crate::utils::ParsingStatus;
use anyhow::Result; use anyhow::Result;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use std::net::IpAddr; use std::net::IpAddr;
@@ -8,7 +9,7 @@ lazy_static! {
static ref BAD_STATUSES: [u32; 2] = [401, 429]; static ref BAD_STATUSES: [u32; 2] = [401, 429];
} }
pub fn parse(line: &str) -> Result<Option<IpAddr>> { pub fn parse(line: &str) -> Result<ParsingStatus> {
// TODO: Use a proper parser ? // TODO: Use a proper parser ?
let elts: Vec<&str> = line.split_whitespace().collect(); let elts: Vec<&str> = line.split_whitespace().collect();
@@ -20,11 +21,11 @@ pub fn parse(line: &str) -> Result<Option<IpAddr>> {
for status in BAD_STATUSES.iter() { for status in BAD_STATUSES.iter() {
if *status == http_code { if *status == http_code {
return Ok(Some(ip)); return Ok(ParsingStatus::BadEntry(ip));
} }
} }
Ok(None) Ok(ParsingStatus::OkEntry)
} }
#[cfg(test)] #[cfg(test)]
@@ -39,8 +40,11 @@ mod tests {
]; ];
vectors.iter().for_each(|e| { vectors.iter().for_each(|e| {
let ret = parse(*e); let ret = parse(*e).unwrap();
assert!(ret.unwrap().is_some()); match ret {
ParsingStatus::BadEntry(_) => {}
_ => panic!("bad parsing"),
}
}) })
} }
@@ -52,8 +56,11 @@ mod tests {
]; ];
vectors.iter().for_each(|e| { vectors.iter().for_each(|e| {
let ret = parse(*e); let ret = parse(*e).unwrap();
assert!(ret.unwrap().is_none()); match ret {
ParsingStatus::OkEntry => {}
_ => panic!("bad parsing"),
}
}) })
} }
+5 -3
View File
@@ -5,6 +5,8 @@ use std::sync::Mutex;
use anyhow::*; use anyhow::*;
use crate::utils::JailStatus;
pub struct Jail { pub struct Jail {
jailtime: u32, jailtime: u32,
allowance: u8, allowance: u8,
@@ -91,7 +93,7 @@ impl Jail {
}) })
} }
pub fn probe(&self, ip: IpAddr) -> Result<bool> { pub fn probe(&self, ip: IpAddr) -> Result<JailStatus> {
let should_ban = { let should_ban = {
let mut locked_map = self.remand.lock().map_err(|_| anyhow!("cant lock"))?; let mut locked_map = self.remand.lock().map_err(|_| anyhow!("cant lock"))?;
@@ -108,9 +110,9 @@ impl Jail {
if should_ban { if should_ban {
ipset_block(self.jailtime, ip)?; ipset_block(self.jailtime, ip)?;
Ok(true) Ok(JailStatus::Jailed(ip))
} else { } else {
Ok(false) Ok(JailStatus::Remand)
} }
} }
} }
+22 -10
View File
@@ -7,8 +7,15 @@ mod utils;
mod jail; mod jail;
use crate::jail::Jail; use crate::jail::Jail;
use crate::utils::*;
fn judge(path_sshd: &str, path_clf: &str, payload: &str, path: &str, jail: &Jail) -> Result<()> { fn judge(
path_sshd: &str,
path_clf: &str,
payload: &str,
path: &str,
jail: &Jail,
) -> Result<Judgment> {
let do_sshd = !path_sshd.is_empty(); let do_sshd = !path_sshd.is_empty();
let do_clf = !path_clf.is_empty(); let do_clf = !path_clf.is_empty();
let mut target = ""; let mut target = "";
@@ -24,16 +31,16 @@ fn judge(path_sshd: &str, path_clf: &str, payload: &str, path: &str, jail: &Jail
}; };
let ip = match ret_parse? { let ip = match ret_parse? {
Some(ip) => ip, ParsingStatus::OkEntry => return Ok(Judgment::Good),
None => return Ok(()), ParsingStatus::BadEntry(ip) => ip,
}; };
if jail.probe(ip)? { match jail.probe(ip)? {
eprintln!("~ {} - too many infraction, jailtime for: {}", target, ip); JailStatus::Remand => Ok(Judgment::Remand),
JailStatus::Jailed(ip) => Ok(Judgment::Bad(target, ip)),
} }
Ok(())
} }
async fn run() -> Result<()> { async fn run() -> Result<()> {
let args = utils::cli().get_matches(); let args = utils::cli().get_matches();
let mut lines = MuxedLines::new()?; let mut lines = MuxedLines::new()?;
@@ -69,9 +76,14 @@ async fn run() -> Result<()> {
let payload = line.line(); let payload = line.line();
let path = line.source().display().to_string(); let path = line.source().display().to_string();
if let Err(err) = judge(path_sshd, path_clf, payload, &path, &jail) { match judge(path_sshd, path_clf, payload, &path, &jail) {
eprintln!("! ERR {:?} - file {}", err, path) Err(err) => eprintln!("! ERR {:?} - file {}", err, path),
} Ok(Judgment::Good) => {}
Ok(Judgment::Remand) => {}
Ok(Judgment::Bad(target, ip)) => {
eprintln!("~ too many infraction, {} jailtime for: {}", target, ip)
}
};
} }
Ok(()) Ok(())
+16 -9
View File
@@ -1,10 +1,11 @@
use anyhow::*; use anyhow::*;
use std::net::IpAddr;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use regex::Regex; use regex::Regex;
use std::net::IpAddr;
use std::str::FromStr; use std::str::FromStr;
use crate::utils::ParsingStatus;
struct Rule { struct Rule {
matcher: String, matcher: String,
extractor: Regex, extractor: Regex,
@@ -27,7 +28,7 @@ lazy_static! {
]; ];
} }
pub fn parse(line: &str) -> Result<Option<IpAddr>> { pub fn parse(line: &str) -> Result<ParsingStatus> {
let hits = SSHD_BAD.iter().find_map(|rule| { let hits = SSHD_BAD.iter().find_map(|rule| {
if line.contains(&rule.matcher) { if line.contains(&rule.matcher) {
rule.extractor.captures(line) rule.extractor.captures(line)
@@ -37,7 +38,7 @@ pub fn parse(line: &str) -> Result<Option<IpAddr>> {
}); });
if hits.is_none() { if hits.is_none() {
return Ok(None); return Ok(ParsingStatus::OkEntry);
} }
let ip = hits let ip = hits
@@ -45,7 +46,7 @@ pub fn parse(line: &str) -> Result<Option<IpAddr>> {
.and_then(|m| IpAddr::from_str(m.as_str()).ok()); .and_then(|m| IpAddr::from_str(m.as_str()).ok());
match ip { match ip {
Some(ip) => Ok(Some(ip)), Some(ip) => Ok(ParsingStatus::BadEntry(ip)),
None => Err(anyhow!("cant parse sshd entry")), None => Err(anyhow!("cant parse sshd entry")),
} }
} }
@@ -63,8 +64,11 @@ mod tests {
]; ];
vectors.iter().for_each(|e| { vectors.iter().for_each(|e| {
let ret = parse(*e); let ret = parse(*e).unwrap();
assert!(ret.unwrap().is_some()); match ret {
ParsingStatus::BadEntry(_) => {}
_ => panic!("bad parsing"),
}
}) })
} }
@@ -77,8 +81,11 @@ mod tests {
]; ];
vectors.iter().for_each(|e| { vectors.iter().for_each(|e| {
let ret = parse(*e); let ret = parse(*e).unwrap();
assert!(ret.unwrap().is_none()); match ret {
ParsingStatus::OkEntry => {}
_ => panic!("bad parsing"),
}
}) })
} }
+16
View File
@@ -1,4 +1,20 @@
use clap::{App, Arg}; use clap::{App, Arg};
use std::net::IpAddr;
pub enum ParsingStatus {
OkEntry,
BadEntry(IpAddr),
}
pub enum Judgment {
Good,
Remand,
Bad(&'static str, IpAddr),
}
pub enum JailStatus {
Remand,
Jailed(IpAddr),
}
pub fn cli() -> App<'static, 'static> { pub fn cli() -> App<'static, 'static> {
App::new("ban internets scanner fast 🍶") App::new("ban internets scanner fast 🍶")