3 Commits
Author SHA1 Message Date
Pierre Dubouilh 62e65929d5 test 2021-10-30 18:42:10 +02:00
Pierre Dubouilh 40d3951c13 document and tweak settings 2021-10-26 17:36:37 +02:00
Pierre Dubouilh 6cf3034c08 use proper enum return type 2021-10-19 11:22:16 +02:00
6 changed files with 109 additions and 87 deletions
-1
View File
@@ -10,4 +10,3 @@ features:
- libmusl static release builds, no libc dependency - libmusl static release builds, no libc dependency
- lighter alternative to fail2ban - lighter alternative to fail2ban
Todo: more granular CLI args to filter HTTP Status codes (e.g. 5 401 leads to a block, but 30 404 before a block) ?
+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"),
}
}) })
} }
+31 -51
View File
@@ -3,65 +3,23 @@ use std::net::IpAddr;
use std::process::Command; use std::process::Command;
use std::sync::Mutex; use std::sync::Mutex;
use std::ffi::CString;
use anyhow::*; use anyhow::*;
use crate::utils::JailStatus;
pub struct Jail { pub struct Jail {
jailtime: u32, jailtime: u32,
allowance: u8, allowance: u8,
ipset_ptr: *const u8, // opaque C ptr to struct ipset
remand: Mutex<HashMap<IpAddr, u8>>, remand: Mutex<HashMap<IpAddr, u8>>,
} }
const JAIL_NAME: &str = "blockfast_jail";
const ERR_MSG: &str = const ERR_MSG: &str =
"error using ipset/iptables, maybe it's not installed, this program isn't running as root ?"; "error using ipset/iptables, maybe it's not installed, this program isn't running as root ?";
fn ipset_init() -> Result<()> {
let init0 = format!("ipset create {} hash:ip timeout 0", JAIL_NAME);
let init1 = format!(
"iptables -I INPUT 1 -m set -j DROP --match-set {} src",
JAIL_NAME
);
let init2 = format!(
"iptables -I FORWARD 1 -m set -j DROP --match-set {} src",
JAIL_NAME
);
let args0: Vec<&str> = init0.split_whitespace().collect();
let args1: Vec<&str> = init1.split_whitespace().collect();
let args2: Vec<&str> = init2.split_whitespace().collect();
// create
let out = Command::new("sudo").args(args0).output()?;
if out.status.code() != Some(0) {
let already_exists =
std::str::from_utf8(&out.stderr)?.contains("set with the same name already exists");
if already_exists {
return Ok(());
} else {
eprintln!("{:?}", out);
bail!(ERR_MSG);
}
}
// setup input
let out = Command::new("sudo").args(args1).output()?;
if out.status.code() != Some(0) {
eprintln!("{:?}", out);
bail!(ERR_MSG);
}
// setup fwd
let out = Command::new("sudo").args(args2).output()?;
if out.status.code() != Some(0) {
eprintln!("{:?}", out);
bail!(ERR_MSG);
}
Ok(())
}
fn ipset_block(jailtime: u32, ip: IpAddr) -> Result<()> { fn ipset_block(jailtime: u32, ip: IpAddr) -> Result<()> {
let sentence = format!( let sentence = format!(
"ipset add {} {} timeout {}", "ipset add {} {} timeout {}",
@@ -80,18 +38,40 @@ fn ipset_block(jailtime: u32, ip: IpAddr) -> Result<()> {
Ok(()) Ok(())
} }
const JAIL_NAME: &str = "blockfast_jail";
const IPSET_SETNAME: u32 = 1;
const IPSET_OPT_FAMILY: u32 = 3;
const IPSET_OPT_IP: u32 = 4;
const IPSET_OPT_TIMEOUT: u32 = 10;
#[link(name = "ipset")]
extern "C" {
fn ipset_init() -> *const u8; //
fn ipset_session_data_set(ipset_struct: *const u8, target: u32, name: CString);
}
impl Jail { impl Jail {
pub fn new(allowance: u8, jailtime: u32) -> Result<Jail> { pub fn new(allowance: u8, jailtime: u32) -> Result<Jail> {
ipset_init()?; let ipset_ptr = unsafe { ipset_init() };
if ipset_ptr.is_null() {
bail!(ERR_MSG);
}
let JAIL_NAME_C = CString::new("blockfast_thisisatest").unwrap();
let a = unsafe { ipset_session_data_set(ipset_ptr, IPSET_SETNAME, JAIL_NAME_C) };
Ok(Jail { Ok(Jail {
allowance, allowance,
jailtime, jailtime,
ipset_ptr,
remand: Mutex::new(HashMap::new()), remand: Mutex::new(HashMap::new()),
}) })
} }
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 +88,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)
} }
} }
} }
+26 -14
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,19 +31,19 @@ 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().context("parsing cli args")?;
// jail // jail
let jailtime_str = args.value_of("jailtime").unwrap_or(""); let jailtime_str = args.value_of("jailtime").unwrap_or("");
@@ -45,7 +52,7 @@ async fn run() -> Result<()> {
let allowance_str = args.value_of("allowance").unwrap_or(""); let allowance_str = args.value_of("allowance").unwrap_or("");
let allowance = allowance_str.parse().context("parsing allowance")?; let allowance = allowance_str.parse().context("parsing allowance")?;
let jail = Jail::new(allowance, jailtime)?; let jail = Jail::new(allowance, jailtime).context("init jail")?;
eprintln!( eprintln!(
"+ jail setup, offences allowed: {}, jailtime {}s", "+ jail setup, offences allowed: {}, jailtime {}s",
allowance, jailtime allowance, jailtime
@@ -61,7 +68,7 @@ async fn run() -> Result<()> {
// common log format // common log format
let path_clf = args.value_of("clf_logpath").unwrap_or(""); let path_clf = args.value_of("clf_logpath").unwrap_or("");
if !path_clf.is_empty() { if !path_clf.is_empty() {
lines.add_file(path_clf).await?; lines.add_file(path_clf).await.context("opening log file")?;
eprintln!("+ starting with clf parsing at {}", path_clf); eprintln!("+ starting with clf parsing at {}", path_clf);
} }
@@ -69,16 +76,21 @@ 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!("~ {} jailtime for: {}", target, ip)
}
};
} }
Ok(()) Ok(())
} }
#[tokio::main] #[tokio::main]
async fn main() -> std::io::Result<()> { async fn main() -> Result<()> {
let ret = run().await; let ret = run().await;
let _ = ret.map_err(|e| eprintln!("! ERROR {:?}", e)); let _ = ret.map_err(|e| eprintln!("! ERROR {:?}", e));
eprintln!("\n"); eprintln!("\n");
+20 -12
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,16 +38,17 @@ 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
.and_then(|c| c.get(2)) .and_then(|c| c.get(2))
.and_then(|m| IpAddr::from_str(m.as_str()).ok()); .and_then(|m| Some(m.as_str()))
.ok_or(anyhow!("sshd cant extract ip"))?;
match ip { match IpAddr::from_str(ip) {
Some(ip) => Ok(Some(ip)), Ok(ip) => Ok(ParsingStatus::BadEntry(ip)),
None => Err(anyhow!("cant parse sshd entry")), Err(_) => Err(anyhow!("cant parse sshd entry")),
} }
} }
@@ -63,8 +65,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 +82,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"),
}
}) })
} }
+18 -2
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 🍶")
@@ -13,14 +29,14 @@ pub fn cli() -> App<'static, 'static> {
Arg::with_name("jailtime") Arg::with_name("jailtime")
.short("j") .short("j")
.help("jail time (seconds)") .help("jail time (seconds)")
.default_value("3600") .default_value("7200")
.takes_value(true), .takes_value(true),
) )
.arg( .arg(
Arg::with_name("allowance") Arg::with_name("allowance")
.short("a") .short("a")
.help("how many offences allowed (max 255") .help("how many offences allowed (max 255")
.default_value("5") .default_value("6")
.takes_value(true), .takes_value(true),
) )
.arg( .arg(