This commit is contained in:
Pierre Dubouilh
2021-10-10 12:15:39 +02:00
parent d9f5d8139d
commit 70cbeae0ed
10 changed files with 880 additions and 0 deletions
+51
View File
@@ -0,0 +1,51 @@
use std::net::IpAddr;
use lazy_static::lazy_static;
// TODO: allow user-provided list
// TODO: match different error-levels (10 404, but only 5 401, etc...)
lazy_static! {
static ref BAD_STATUSES: [&'static str; 2] = ["401", "429"];
}
pub fn parse(line: &str) -> Option<IpAddr> {
// TODO: Use a proper parser ?
let elts: Vec<&str> = line.split_whitespace().collect();
let ip = elts[0].parse::<IpAddr>().ok();
let http_code = elts[elts.len() - 2] as &str;
BAD_STATUSES.iter().find_map(
|bad_status| {
if http_code == *bad_status {
ip
} else {
None
}
},
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn positive() {
let vectors = [
"8.8.8.8 - p [25/Sep/2021:13:49:56 +0200] \"POST /some/rpc HTTP/2.0\" 401 923",
"8.8.8.8 - p [25/Sep/2021:13:49:56 +0200] \"POST /some/rpc HTTP/2.0\" 429 923",
];
vectors.iter().for_each(|e| assert!(parse(*e).is_some()))
}
#[test]
fn negative() {
let vectors = [
"8.8.8.8 - p [25/Sep/2021:13:49:56 +0200] \"POST /some/rpc HTTP/2.0\" 200 923",
"8.8.8.8 - p [25/Sep/2021:13:49:56 +0200] \"POST /some/rpc HTTP/2.0\" 404 923",
];
vectors.iter().for_each(|e| assert!(parse(*e).is_none()))
}
}
+127
View File
@@ -0,0 +1,127 @@
use std::collections::HashMap;
use std::net::IpAddr;
use std::panic::panic_any;
use std::process::Command;
use std::sync::Mutex;
pub struct Jail {
jailtime: u32,
allowance: u8,
remand: Mutex<HashMap<IpAddr, u8>>,
}
const JAIL_NAME: &str = "blockfast_jail";
const GENERAL_PANIC_MSG: &str =
"error using ipset/iptables, maybe it's not installed, this program isn't running as root ?";
fn ipset_init() -> Option<()> {
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().ok()?;
if out.status.code()? != 0 {
let already_exists = std::str::from_utf8(&out.stderr)
.ok()?
.contains("set with the same name already exists");
if already_exists {
return None;
} else {
eprintln!("{:?}", out);
panic_any(GENERAL_PANIC_MSG);
}
}
// setup input
let out_input = Command::new("sudo").args(args1).output().ok()?;
if out_input.status.code()? != 0 {
eprintln!("{:?}", out_input);
panic_any(GENERAL_PANIC_MSG);
}
// setup fwd
let out_fwd = Command::new("sudo").args(args2).output().ok()?;
if out_fwd.status.code()? != 0 {
eprintln!("{:?}", out_fwd);
panic_any(GENERAL_PANIC_MSG);
}
None
}
fn ipset_block(jailtime: u32, ip: IpAddr) -> Option<()> {
let sentence = format!(
"ipset add {} {} timeout {}",
JAIL_NAME,
ip.to_string(),
jailtime
);
let sentence_sl: Vec<&str> = sentence.split_whitespace().collect();
let out = Command::new("sudo").args(sentence_sl).output().ok()?;
if out.status.code()? != 0 {
return None;
}
Some(())
}
impl Jail {
pub fn new(allowance: u8, jailtime: u32) -> Jail {
if ipset_init().is_some() {
panic_any(GENERAL_PANIC_MSG);
};
eprintln!(
"+ jail setup, allowing {} offences, jailtime: {}s",
allowance, jailtime
);
Jail {
allowance,
jailtime,
remand: Mutex::new(HashMap::new()),
}
}
pub fn probe(&self, ip: IpAddr) -> Option<()> {
let should_ban = {
let mut locked_map = self.remand.lock().ok()?;
// TODO: set time of last offence, and add grace
let hits = *locked_map.entry(ip).and_modify(|e| *e += 1).or_insert(1);
if hits < self.allowance {
false
} else {
locked_map.remove_entry(&ip); // preserve space
true
}
};
if should_ban {
match ipset_block(self.jailtime, ip) {
Some(_) => eprintln!("~ {} going to jail", ip),
None => eprintln!("! ERR {} going to jail", ip),
}
}
None
}
}
+57
View File
@@ -0,0 +1,57 @@
use linemux::MuxedLines;
mod clf;
mod sshd;
mod utils;
mod jail;
use crate::jail::Jail;
async fn run() -> Option<()> {
let args = utils::cli().get_matches();
let mut lines = MuxedLines::new().ok()?;
// jail
let jailtime: u32 = args.value_of("jailtime")?.parse().ok()?;
let allowance: u8 = args.value_of("allowance")?.parse().ok()?;
let jail = Jail::new(allowance, jailtime);
// sshd
let path_sshd = args.value_of("sshd_logpath").unwrap_or("");
let do_sshd = !path_sshd.is_empty();
if do_sshd {
lines.add_file(path_sshd).await.ok()?;
eprintln!("+ starting with sshd parsing at {}", path_sshd);
}
// common log format
let path_clf = args.value_of("clf_logpath").unwrap_or("");
let do_clf = !path_clf.is_empty();
if do_clf {
lines.add_file(path_clf).await.ok()?;
eprintln!("+ starting with clf parsing at {}", path_clf);
}
while let Ok(Some(line)) = lines.next_line().await {
let payload = line.line();
let path = line.source().display().to_string();
if do_sshd && path.ends_with(path_sshd) {
sshd::parse(payload).and_then(|ip| jail.probe(ip));
} else if do_clf && path.ends_with(path_clf) {
clf::parse(payload).and_then(|ip| jail.probe(ip));
} else {
eprintln!("! unknown logline: {}", path);
}
}
Some(())
}
#[tokio::main]
async fn main() -> std::io::Result<()> {
let _ = run().await;
eprintln!("! ERR");
let _ = utils::cli().print_help();
Ok(())
}
+65
View File
@@ -0,0 +1,65 @@
use std::net::IpAddr;
use lazy_static::lazy_static;
use regex::Regex;
struct Rule {
matcher: String,
extractor: Regex,
}
lazy_static! {
static ref SSHD_BAD: [Rule; 3] = [
Rule {
matcher: "Failed password".to_string(),
extractor: Regex::new(r"(from.)(.*)(.port)").unwrap(),
},
Rule {
matcher: "Invalid user".to_string(),
extractor: Regex::new(r"(from.)(.*)").unwrap(),
},
Rule {
matcher: "authentication failure".to_string(),
extractor: Regex::new(r"(rhost=)(.*)").unwrap()
},
];
}
pub fn parse(line: &str) -> Option<IpAddr> {
let ret = SSHD_BAD.iter().find_map(|rule| {
if line.contains(&rule.matcher) {
rule.extractor.captures(line)?.get(2)
} else {
None
}
})?;
ret.as_str().parse::<IpAddr>().ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn positive() {
let vectors = [
"Sep 26 06:25:19 livecompute sshd[23246]: Failed password for root from 179.124.36.195 port 41883 ssh2",
"Sep 26 06:26:14 livecompute sshd[23292]: pam_unix(sshd:auth): authentication failure; logname= u =0 tty=ssh ruser= rhost=5.101.107.190",
"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()))
}
#[test]
fn negative() {
let vectors = [
"Sep 26 06:25:19 livecompute sshd[23246]: successful login 179.124.36.195 port 41883 ssh2",
"Sep 26 06:26:14 livecompute sshd[23292]: pam_unix(sshd:auth): authentication total success; logname= u =0 tty=ssh ruser= rhost=5.101.107.190",
"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()))
}
}
+45
View File
@@ -0,0 +1,45 @@
use clap::{App, Arg};
pub fn cli() -> App<'static, 'static> {
App::new("ban internets scanner fast 🍶")
.version("v0.0.1")
.author("pierre dubouilh <pldubouilh@gmail.com>")
// .arg(Arg::with_name("prune")
// .short("prune")
// .help("prune current logfiles to prefill banlist")
// .default_value("false")
// .takes_value(true))
.arg(
Arg::with_name("jailtime")
.short("j")
.help("jail time (seconds)")
.default_value("3600")
.takes_value(true),
)
.arg(
Arg::with_name("allowance")
.short("a")
.help("how many offences allowed (max 255")
.default_value("5")
.takes_value(true),
)
.arg(
Arg::with_name("sshd_logpath")
.short("sshd_logpath")
.help("path of sshd logfile (disable with empty path)")
.default_value("/var/log/auth.log")
.takes_value(true),
)
.arg(
Arg::with_name("clf_logpath")
.short("clf_logpath")
.help("path of Common-Log-Format (Apache, etc..) logfile")
.default_value("")
.takes_value(true),
)
// .arg(Arg::with_name("clf_bad_http_codes")
// .short("cb")
// .help("bad CLF http codes")
// .default_value("{401, 429}")
// .takes_value(true))
}