This commit is contained in:
Pierre Dubouilh
2021-10-17 20:08:50 +02:00
parent 6741f48285
commit 283653a775
7 changed files with 101 additions and 112 deletions
Generated
+7 -21
View File
@@ -20,6 +20,12 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "anyhow"
version = "1.0.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61604a8f862e1d5c3229fdd78f8b02c68dcf73a4c4b05fd636d12240aaa242c1"
[[package]] [[package]]
name = "atty" name = "atty"
version = "0.2.14" version = "0.2.14"
@@ -47,11 +53,11 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
name = "blockfast" name = "blockfast"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"anyhow",
"clap", "clap",
"lazy_static", "lazy_static",
"linemux", "linemux",
"regex", "regex",
"thiserror",
"tokio", "tokio",
] ]
@@ -399,26 +405,6 @@ dependencies = [
"unicode-width", "unicode-width",
] ]
[[package]]
name = "thiserror"
version = "1.0.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "854babe52e4df1653706b98fcfc05843010039b406875930a70e4d9644e5c417"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa32fd3f627f367fe16f893e2597ae3c05020f8bba2666a4e6ea73d377e5714b"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "tokio" name = "tokio"
version = "1.12.0" version = "1.12.0"
+1 -1
View File
@@ -12,4 +12,4 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
lazy_static = "1.4.0" lazy_static = "1.4.0"
regex = "1.5.4" regex = "1.5.4"
clap = "2.33.3" clap = "2.33.3"
thiserror = "1.0.26" anyhow = "1.0.44"
+4 -4
View File
@@ -1,4 +1,4 @@
use crate::utils::Error; use anyhow::Result;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use std::net::IpAddr; use std::net::IpAddr;
@@ -8,15 +8,15 @@ 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>, Error> { pub fn parse(line: &str) -> Result<Option<IpAddr>> {
// 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();
let ip_str = elts[0]; let ip_str = elts[0];
let ip = ip_str.parse::<IpAddr>().or(Err(Error::CantParse))?; let ip = ip_str.parse::<IpAddr>()?;
let http_code_str = elts[elts.len() - 2] as &str; let http_code_str = elts[elts.len() - 2] as &str;
let http_code = http_code_str.parse::<u32>().or(Err(Error::CantParse))?; let http_code = http_code_str.parse::<u32>()?;
for status in BAD_STATUSES.iter() { for status in BAD_STATUSES.iter() {
if *status == http_code { if *status == http_code {
+36 -47
View File
@@ -1,9 +1,10 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::net::IpAddr; use std::net::IpAddr;
use std::panic::panic_any;
use std::process::Command; use std::process::Command;
use std::sync::Mutex; use std::sync::Mutex;
use anyhow::*;
pub struct Jail { pub struct Jail {
jailtime: u32, jailtime: u32,
allowance: u8, allowance: u8,
@@ -11,10 +12,11 @@ pub struct Jail {
} }
const JAIL_NAME: &str = "blockfast_jail"; const JAIL_NAME: &str = "blockfast_jail";
const GENERAL_PANIC_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() -> Option<()> { fn ipset_init() -> Result<()> {
let init0 = format!("ipset create {} hash:ip timeout 0", JAIL_NAME); let init0 = format!("ipset create {} hash:ip timeout 0", JAIL_NAME);
let init1 = format!( let init1 = format!(
"iptables -I INPUT 1 -m set -j DROP --match-set {} src", "iptables -I INPUT 1 -m set -j DROP --match-set {} src",
@@ -30,41 +32,37 @@ fn ipset_init() -> Option<()> {
let args2: Vec<&str> = init2.split_whitespace().collect(); let args2: Vec<&str> = init2.split_whitespace().collect();
// create // create
let out = Command::new("sudo").args(args0).output().ok()?; let out = Command::new("sudo").args(args0).output()?;
if out.status.code() != Some(0) {
if out.status.code()? != 0 { let already_exists =
let already_exists = std::str::from_utf8(&out.stderr) std::str::from_utf8(&out.stderr)?.contains("set with the same name already exists");
.ok()?
.contains("set with the same name already exists");
if already_exists { if already_exists {
return None; return Ok(());
} else { } else {
eprintln!("{:?}", out); eprintln!("{:?}", out);
panic_any(GENERAL_PANIC_MSG); bail!(ERR_MSG);
} }
} }
// setup input // setup input
let out_input = Command::new("sudo").args(args1).output().ok()?; let out = Command::new("sudo").args(args1).output()?;
if out.status.code() != Some(0) {
if out_input.status.code()? != 0 { eprintln!("{:?}", out);
eprintln!("{:?}", out_input); bail!(ERR_MSG);
panic_any(GENERAL_PANIC_MSG);
} }
// setup fwd // setup fwd
let out_fwd = Command::new("sudo").args(args2).output().ok()?; let out = Command::new("sudo").args(args2).output()?;
if out.status.code() != Some(0) {
if out_fwd.status.code()? != 0 { eprintln!("{:?}", out);
eprintln!("{:?}", out_fwd); bail!(ERR_MSG);
panic_any(GENERAL_PANIC_MSG);
} }
None Ok(())
} }
fn ipset_block(jailtime: u32, ip: IpAddr) -> Option<()> { fn ipset_block(jailtime: u32, ip: IpAddr) -> Result<()> {
let sentence = format!( let sentence = format!(
"ipset add {} {} timeout {}", "ipset add {} {} timeout {}",
JAIL_NAME, JAIL_NAME,
@@ -73,36 +71,29 @@ fn ipset_block(jailtime: u32, ip: IpAddr) -> Option<()> {
); );
let sentence_sl: Vec<&str> = sentence.split_whitespace().collect(); let sentence_sl: Vec<&str> = sentence.split_whitespace().collect();
let out = Command::new("sudo").args(sentence_sl).output().ok()?; let out = Command::new("sudo").args(sentence_sl).output()?;
if out.status.code() != Some(0) {
if out.status.code()? != 0 { eprintln!("{:?}", out);
return None; bail!("error executing ipset ban");
} }
Some(()) Ok(())
} }
impl Jail { impl Jail {
pub fn new(allowance: u8, jailtime: u32) -> Jail { pub fn new(allowance: u8, jailtime: u32) -> Result<Jail> {
if ipset_init().is_some() { ipset_init()?;
panic_any(GENERAL_PANIC_MSG);
};
eprintln!( Ok(Jail {
"+ jail setup, allowing {} offences, jailtime: {}s",
allowance, jailtime
);
Jail {
allowance, allowance,
jailtime, jailtime,
remand: Mutex::new(HashMap::new()), remand: Mutex::new(HashMap::new()),
} })
} }
pub fn probe(&self, ip: IpAddr) -> Option<()> { pub fn probe(&self, ip: IpAddr) -> Result<bool> {
let should_ban = { let should_ban = {
let mut locked_map = self.remand.lock().ok()?; let mut locked_map = self.remand.lock().map_err(|_| anyhow!("cant lock"))?;
// TODO: set time of last offence, and add grace // TODO: set time of last offence, and add grace
let hits = *locked_map.entry(ip).and_modify(|e| *e += 1).or_insert(1); let hits = *locked_map.entry(ip).and_modify(|e| *e += 1).or_insert(1);
@@ -116,12 +107,10 @@ impl Jail {
}; };
if should_ban { if should_ban {
match ipset_block(self.jailtime, ip) { ipset_block(self.jailtime, ip)?;
Some(_) => eprintln!("~ {} going to jail", ip), Ok(true)
None => eprintln!("! ERR {} going to jail", ip), } else {
} Ok(false)
} }
None
} }
} }
+50 -27
View File
@@ -1,3 +1,4 @@
use anyhow::*;
use linemux::MuxedLines; use linemux::MuxedLines;
mod clf; mod clf;
@@ -6,30 +7,61 @@ mod utils;
mod jail; mod jail;
use crate::jail::Jail; use crate::jail::Jail;
use crate::utils::Error;
async fn run() -> Option<()> { fn judge(path_sshd: &str, path_clf: &str, payload: &str, path: &str, jail: &Jail) -> Result<()> {
let do_sshd = !path_sshd.is_empty();
let do_clf = !path_clf.is_empty();
let mut target = "";
let ret_parse = if do_sshd && path.ends_with(path_sshd) {
target = "sshd";
sshd::parse(payload)
} else if do_clf && path.ends_with(path_clf) {
target = "clf ";
clf::parse(payload)
} else {
Err(anyhow!("cant locate file !"))
};
let ip = match ret_parse? {
Some(ip) => ip,
None => return Ok(()),
};
if jail.probe(ip)? {
eprintln!("~ {} - too many infraction, jailtime for: {}", target, ip);
}
Ok(())
}
async fn run() -> Result<()> {
let args = utils::cli().get_matches(); let args = utils::cli().get_matches();
let mut lines = MuxedLines::new().ok()?; let mut lines = MuxedLines::new()?;
// jail // jail
let jailtime: u32 = args.value_of("jailtime")?.parse().ok()?; let jailtime_str = args.value_of("jailtime").unwrap_or("");
let allowance: u8 = args.value_of("allowance")?.parse().ok()?; let jailtime = jailtime_str.parse().context("parsing jailtime")?;
let jail = Jail::new(allowance, jailtime);
let allowance_str = args.value_of("allowance").unwrap_or("");
let allowance = allowance_str.parse().context("parsing allowance")?;
let jail = Jail::new(allowance, jailtime)?;
eprintln!(
"+ jail setup, offences allowed: {}, jailtime {}s",
allowance, jailtime
);
// sshd // sshd
let path_sshd = args.value_of("sshd_logpath").unwrap_or(""); let path_sshd = args.value_of("sshd_logpath").unwrap_or("");
let do_sshd = !path_sshd.is_empty(); if !path_sshd.is_empty() {
if do_sshd { lines.add_file(path_sshd).await?;
lines.add_file(path_sshd).await.ok()?;
eprintln!("+ starting with sshd parsing at {}", path_sshd); eprintln!("+ starting with sshd parsing at {}", path_sshd);
} }
// 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("");
let do_clf = !path_clf.is_empty(); if !path_clf.is_empty() {
if do_clf { lines.add_file(path_clf).await?;
lines.add_file(path_clf).await.ok()?;
eprintln!("+ starting with clf parsing at {}", path_clf); eprintln!("+ starting with clf parsing at {}", path_clf);
} }
@@ -37,28 +69,19 @@ async fn run() -> Option<()> {
let payload = line.line(); let payload = line.line();
let path = line.source().display().to_string(); let path = line.source().display().to_string();
let res = if do_sshd && path.ends_with(path_sshd) { if let Err(err) = judge(path_sshd, path_clf, payload, &path, &jail) {
sshd::parse(payload) eprintln!("! ERR {:?} - file {}", err, path)
} else if do_clf && path.ends_with(path_clf) {
clf::parse(payload)
} else {
Err(Error::UnknownError)
};
if let Ok(Some(ip)) = res {
jail.probe(ip);
} else {
eprintln!("! error processing logline: {}", path);
} }
} }
Some(()) Ok(())
} }
#[tokio::main] #[tokio::main]
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
let _ = run().await; let ret = run().await;
eprintln!("! ERR"); let _ = ret.map_err(|e| eprintln!("! ERROR {:?}", e));
eprintln!("\n");
let _ = utils::cli().print_help(); let _ = utils::cli().print_help();
Ok(()) Ok(())
} }
+3 -3
View File
@@ -1,4 +1,4 @@
use crate::utils::Error; use anyhow::*;
use std::net::IpAddr; use std::net::IpAddr;
use lazy_static::lazy_static; use lazy_static::lazy_static;
@@ -27,7 +27,7 @@ lazy_static! {
]; ];
} }
pub fn parse(line: &str) -> Result<Option<IpAddr>, Error> { pub fn parse(line: &str) -> Result<Option<IpAddr>> {
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)
@@ -46,7 +46,7 @@ pub fn parse(line: &str) -> Result<Option<IpAddr>, Error> {
match ip { match ip {
Some(ip) => Ok(Some(ip)), Some(ip) => Ok(Some(ip)),
None => Err(Error::CantParse), None => Err(anyhow!("cant parse sshd entry")),
} }
} }
-9
View File
@@ -1,14 +1,5 @@
use clap::{App, Arg}; use clap::{App, Arg};
#[derive(Debug, thiserror::Error)]
#[allow(clippy::large_enum_variant)]
pub enum Error {
#[error("cant parse")]
CantParse,
#[error("general error")]
UnknownError,
}
pub fn cli() -> App<'static, 'static> { pub fn cli() -> App<'static, 'static> {
App::new("ban internets scanner fast 🍶") App::new("ban internets scanner fast 🍶")
.version("v0.0.1") .version("v0.0.1")