diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..d12fa0f --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,484 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aho-corasick" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" +dependencies = [ + "memchr", +] + +[[package]] +name = "ansi_term" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" +dependencies = [ + "winapi", +] + +[[package]] +name = "atty" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" +dependencies = [ + "hermit-abi", + "libc", + "winapi", +] + +[[package]] +name = "autocfg" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "blockfast" +version = "0.1.0" +dependencies = [ + "clap", + "lazy_static", + "linemux", + "regex", + "tokio", +] + +[[package]] +name = "bytes" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "clap" +version = "2.33.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37e58ac78573c40708d45522f0d80fa2f01cc4f9b4e2bf749807255454312002" +dependencies = [ + "ansi_term", + "atty", + "bitflags", + "strsim", + "textwrap", + "unicode-width", + "vec_map", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06ed27e177f16d65f0f0c22a213e17c696ace5dd64b14258b52f9417ccb52db4" +dependencies = [ + "cfg-if", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d82cfc11ce7f2c3faef78d8a684447b40d503d9681acebed6cb728d45940c4db" +dependencies = [ + "cfg-if", + "lazy_static", +] + +[[package]] +name = "filetime" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "975ccf83d8d9d0d84682850a38c8169027be83368805971cc4f238c2b245bc98" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "winapi", +] + +[[package]] +name = "fsevent-sys" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c0e564d24da983c053beff1bb7178e237501206840a3e6bf4e267b9e8ae734a" +dependencies = [ + "libc", +] + +[[package]] +name = "futures-core" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88d1c26957f23603395cd326b0ffe64124b818f4449552f960d815cfba83a53d" + +[[package]] +name = "futures-task" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d3d00f4eddb73e498a54394f228cd55853bdf059259e8e7bc6e69d408892e99" + +[[package]] +name = "futures-util" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36568465210a3a6ee45e1f165136d68671471a501e632e9a98d96872222b5481" +dependencies = [ + "autocfg", + "futures-core", + "futures-task", + "pin-project-lite 0.2.7", + "pin-utils", + "slab", +] + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "inotify" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d88ed757e516714cd8736e65b84ed901f72458512111871f20c1d377abdfbf5e" +dependencies = [ + "bitflags", + "inotify-sys", + "libc", +] + +[[package]] +name = "inotify-sys" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb" +dependencies = [ + "libc", +] + +[[package]] +name = "kqueue" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "058a107a784f8be94c7d35c1300f4facced2e93d2fbe5b1452b44e905ddca4a9" +dependencies = [ + "kqueue-sys", + "libc", +] + +[[package]] +name = "kqueue-sys" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8367585489f01bc55dd27404dcf56b95e6da061a256a666ab23be9ba96a2e587" +dependencies = [ + "bitflags", + "libc", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "libc" +version = "0.2.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd8f7255a17a627354f321ef0055d63b898c6fb27eff628af4d1b66b7331edf6" + +[[package]] +name = "linemux" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faffd44046d5dcc8b31e76840fa2a9e975b3b6e6ad2db576cf71dca8c27945b9" +dependencies = [ + "futures-util", + "notify", + "pin-project-lite 0.1.12", + "tokio", +] + +[[package]] +name = "log" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "memchr" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" + +[[package]] +name = "mio" +version = "0.7.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c2bdb6314ec10835cd3293dd268473a835c02b7b352e788be788b3c6ca6bb16" +dependencies = [ + "libc", + "log", + "miow", + "ntapi", + "winapi", +] + +[[package]] +name = "miow" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9f1c5b025cda876f66ef43a113f91ebc9f4ccef34843000e0adf6ebbab84e21" +dependencies = [ + "winapi", +] + +[[package]] +name = "notify" +version = "5.0.0-pre.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "245d358380e2352c2d020e8ee62baac09b3420f1f6c012a31326cfced4ad487d" +dependencies = [ + "bitflags", + "crossbeam-channel", + "filetime", + "fsevent-sys", + "inotify", + "kqueue", + "libc", + "mio", + "walkdir", + "winapi", +] + +[[package]] +name = "ntapi" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6bb902e437b6d86e03cce10a7e2af662292c5dfef23b65899ea3ac9354ad44" +dependencies = [ + "winapi", +] + +[[package]] +name = "num_cpus" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05499f3756671c15885fee9034446956fff3f243d6077b91e5767df161f766b3" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "pin-project-lite" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "257b64915a082f7811703966789728173279bdebb956b143dbcd23f6f970a777" + +[[package]] +name = "pin-project-lite" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d31d11c69a6b52a174b42bdc0c30e5e11670f90788b2c471c31c1d17d449443" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "proc-macro2" +version = "1.0.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9f5105d4fdaab20335ca9565e106a5d9b82b6219b5ba735731124ac6711d23d" +dependencies = [ + "unicode-xid", +] + +[[package]] +name = "quote" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d0b9745dc2debf507c8422de05d7226cc1f0644216dfdfead988f9b1ab32a7" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "redox_syscall" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8383f39639269cde97d255a32bdb68c047337295414940c68bdd30c2e13203ff" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d07a8629359eb56f1e2fb1652bb04212c072a87ba68546a04065d525673ac461" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.6.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "slab" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c307a32c1c5c437f38c7fd45d753050587732ba8628319fbdf12a7e289ccc590" + +[[package]] +name = "strsim" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" + +[[package]] +name = "syn" +version = "1.0.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4eac2e6c19f5c3abc0c229bea31ff0b9b091c7b14990e8924b92902a303a0c0" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "textwrap" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "tokio" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2c2416fdedca8443ae44b4527de1ea633af61d8f7169ffa6e72c5b53d24efcc" +dependencies = [ + "autocfg", + "bytes", + "memchr", + "num_cpus", + "pin-project-lite 0.2.7", + "tokio-macros", +] + +[[package]] +name = "tokio-macros" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "154794c8f499c2619acd19e839294703e9e32e7630ef5f46ea80d4ef0fbee5eb" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "unicode-width" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" + +[[package]] +name = "unicode-xid" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" + +[[package]] +name = "vec_map" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" + +[[package]] +name = "walkdir" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "808cf2735cd4b6866113f648b791c6adc5714537bc222d9347bb203386ffda56" +dependencies = [ + "same-file", + "winapi", + "winapi-util", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..f9b24a7 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "blockfast" +version = "0.1.0" +authors = ["Pierre Dubouilh "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +linemux = "0.2" +tokio = { version = "1", features = ["rt-multi-thread", "macros"] } +lazy_static = "1.4.0" +regex = "1.5.4" +clap = "2.33.3" \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..077aef0 --- /dev/null +++ b/Makefile @@ -0,0 +1,23 @@ +build: + cargo build + cargo clippy + cargo fmt + +run: + cargo run -- -s=/tmp/sshdtest -c=/tmp/clftest + +watch: + ls src/*.rs | entr -rc -- make run + +test: + cargo test + +watch-test: + ls src/*.rs | entr -rc -- make test + +release: + cargo build --target x86_64-unknown-linux-musl --release + +ci: test + cargo fmt --all -- --check + cargo clippy -- -D warnings \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..762f924 --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +# blockfast + +block ssh and http scanners fast + +features: + - generic SSH log parser + - generic Common Log Format parser (apache logs, caddy logs, etc...) + - sane defaults + - fast ip ban with `ipset` + - libmusl static release builds, no libc dependency + - 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) ? diff --git a/src/clf.rs b/src/clf.rs new file mode 100644 index 0000000..1060e56 --- /dev/null +++ b/src/clf.rs @@ -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 { + // TODO: Use a proper parser ? + let elts: Vec<&str> = line.split_whitespace().collect(); + let ip = elts[0].parse::().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())) + } +} diff --git a/src/jail.rs b/src/jail.rs new file mode 100644 index 0000000..ef45127 --- /dev/null +++ b/src/jail.rs @@ -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>, +} + +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 + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..e1dc806 --- /dev/null +++ b/src/main.rs @@ -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(()) +} diff --git a/src/sshd.rs b/src/sshd.rs new file mode 100644 index 0000000..28b3b9f --- /dev/null +++ b/src/sshd.rs @@ -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 { + 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::().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())) + } +} diff --git a/src/utils.rs b/src/utils.rs new file mode 100644 index 0000000..596ab87 --- /dev/null +++ b/src/utils.rs @@ -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 ") + // .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)) +}