git init
This commit is contained in:
157
agent/src/fail2ban.rs
Normal file
157
agent/src/fail2ban.rs
Normal file
@@ -0,0 +1,157 @@
|
||||
use crate::command;
|
||||
use anyhow::{bail, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{net::IpAddr, time::Duration};
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct Status {
|
||||
pub installed: bool,
|
||||
pub running: bool,
|
||||
pub version: Option<String>,
|
||||
pub jails: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Serialize, PartialEq)]
|
||||
pub struct JailStatus {
|
||||
pub jail: String,
|
||||
pub currently_failed: u64,
|
||||
pub total_failed: u64,
|
||||
pub currently_banned: u64,
|
||||
pub total_banned: u64,
|
||||
pub banned_ips: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct BanRequest {
|
||||
pub jail: String,
|
||||
pub ip: String,
|
||||
}
|
||||
|
||||
pub async fn status(timeout: Duration) -> Status {
|
||||
let version = match command::run("fail2ban-client", &["--version"], timeout).await {
|
||||
Ok(output) => Some(output.stdout.trim().to_owned()),
|
||||
Err(_) => {
|
||||
return Status {
|
||||
installed: false,
|
||||
running: false,
|
||||
version: None,
|
||||
jails: vec![],
|
||||
}
|
||||
}
|
||||
};
|
||||
match command::run("fail2ban-client", &["status"], timeout).await {
|
||||
Ok(output) => Status {
|
||||
installed: true,
|
||||
running: true,
|
||||
version,
|
||||
jails: parse_jail_list(&output.stdout),
|
||||
},
|
||||
Err(_) => Status {
|
||||
installed: true,
|
||||
running: false,
|
||||
version,
|
||||
jails: vec![],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn jail(name: &str, timeout: Duration) -> Result<JailStatus> {
|
||||
validate_jail(name)?;
|
||||
let output = command::run("fail2ban-client", &["status", name], timeout).await?;
|
||||
Ok(parse_jail_status(name, &output.stdout))
|
||||
}
|
||||
|
||||
pub async fn ban(request: &BanRequest, unban: bool, timeout: Duration) -> Result<()> {
|
||||
validate_jail(&request.jail)?;
|
||||
let ip: IpAddr = request
|
||||
.ip
|
||||
.parse()
|
||||
.map_err(|_| anyhow::anyhow!("invalid IP address"))?;
|
||||
let operation = if unban { "unbanip" } else { "banip" };
|
||||
command::run(
|
||||
"fail2ban-client",
|
||||
&[
|
||||
"set",
|
||||
request.jail.as_str(),
|
||||
operation,
|
||||
ip.to_string().as_str(),
|
||||
],
|
||||
timeout,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_jail(name: &str) -> Result<()> {
|
||||
if name.is_empty()
|
||||
|| name.len() > 64
|
||||
|| !name
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_' | b'.'))
|
||||
{
|
||||
bail!("invalid jail name")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_jail_list(text: &str) -> Vec<String> {
|
||||
text.lines()
|
||||
.find_map(|line| line.split_once("Jail list:"))
|
||||
.map(|(_, list)| {
|
||||
list.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|v| !v.is_empty())
|
||||
.map(str::to_owned)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn parse_jail_status(name: &str, text: &str) -> JailStatus {
|
||||
let mut result = JailStatus {
|
||||
jail: name.to_owned(),
|
||||
..JailStatus::default()
|
||||
};
|
||||
for line in text.lines() {
|
||||
let normalized = line.trim().trim_start_matches(['|', '`', '-', '_']).trim();
|
||||
let Some((key, value)) = normalized.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
let value = value.trim();
|
||||
match key.trim() {
|
||||
"Currently failed" => result.currently_failed = value.parse().unwrap_or_default(),
|
||||
"Total failed" => result.total_failed = value.parse().unwrap_or_default(),
|
||||
"Currently banned" => result.currently_banned = value.parse().unwrap_or_default(),
|
||||
"Total banned" => result.total_banned = value.parse().unwrap_or_default(),
|
||||
"Banned IP list" => {
|
||||
result.banned_ips = value.split_whitespace().map(str::to_owned).collect()
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_statuses() {
|
||||
assert_eq!(
|
||||
parse_jail_list("Number of jail: 2\nJail list: sshd, nginx-http-auth\n"),
|
||||
vec!["sshd", "nginx-http-auth"]
|
||||
);
|
||||
let jail = parse_jail_status("sshd", "Currently failed: 2\nTotal failed: 14\nCurrently banned: 1\nTotal banned: 3\nBanned IP list: 192.0.2.1\n");
|
||||
assert_eq!(jail.currently_banned, 1);
|
||||
assert_eq!(jail.banned_ips, vec!["192.0.2.1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_command_like_jail() {
|
||||
assert!(validate_jail("sshd").is_ok());
|
||||
assert!(validate_jail("sshd;shutdown").is_err());
|
||||
assert!(validate_jail("../../root").is_err());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user