Files
coulobre/src/coulobre/firewall_bans.py
T

164 lines
4.6 KiB
Python

import ipaddress
import json
import os
import pwd
from datetime import UTC, datetime
from pathlib import Path
from uuid import uuid4
from .node_files import (
check_root_file,
replace_configuration,
require_root_directory,
write_new_file,
)
RUNTIME = Path("/run/coulobre-fail2ban")
CONFIG = RUNTIME / "config"
SOCKET = RUNTIME / "fail2ban.sock"
JAILS = ("coulobre-sshd", "coulobre-postfix", "coulobre-dovecot")
BAN_TABLE = "coulobre_bans"
def render_jails(policy):
sources = " ".join(map(str, policy.admin_sources))
defaults = (
"[DEFAULT]\n"
"backend = systemd\n"
"bantime = 600\n"
"findtime = 600\n"
"maxretry = 5\n"
"usedns = no\n"
f"ignoreip = 127.0.0.0/8 ::1 {sources}\n"
)
jails = [(JAILS[0], "sshd", str(policy.ssh_port))]
if "mail" in policy.services:
jails.extend(
(
(JAILS[1], "postfix[mode=auth]", "465,587"),
(JAILS[2], "dovecot", "143,993"),
)
)
return defaults + "".join(
f"\n[{name}]\nenabled = true\nfilter = {filter_name}\n"
f"action = nftables[type=multiport, table={BAN_TABLE}, "
f'name={name}, port="{destinations}", protocol=tcp, blocktype=drop]\n'
for name, filter_name, destinations in jails
)
def prepare_bans(policy, state_directory):
config = CONFIG
require_root_directory(config, create_mode=0o700)
for name in ("filter.d", "action.d"):
link = config / name
target = Path("/etc/fail2ban") / name
require_root_directory(target)
if not os.path.lexists(link):
link.symlink_to(target, target_is_directory=True)
elif not link.is_symlink() or link.readlink() != target:
raise ValueError(f"Unexpected Fail2ban configuration at {link}.")
server_config = (
"[Definition]\n"
"logtarget = STDOUT\n"
"loglevel = INFO\n"
f"socket = {SOCKET}\n"
f"pidfile = {RUNTIME / 'fail2ban.pid'}\n"
f"dbfile = {state_directory / 'fail2ban.sqlite3'}\n"
)
for name, content in (
("fail2ban.conf", server_config),
("jail.conf", render_jails(policy)),
):
path = config / name
if os.path.lexists(path):
check_root_file(path, mode=0o600)
replace_configuration(path, content, mode=0o600)
else:
write_new_file(path, content, mode=0o600)
def client(run, *arguments):
return run(
"/usr/bin/fail2ban-client",
"-c",
str(CONFIG),
"-s",
str(SOCKET),
*arguments,
)
def ban_status(run):
if not SOCKET.is_socket():
return {"running": False, "jails": {}}
summary = client(run, "status")
names = next(
(
line.split("Jail list:", 1)[1]
for line in summary.splitlines()
if "Jail list:" in line
),
"",
)
enabled = {name.strip() for name in names.split(",")}
return {
"running": True,
"jails": {
name: client(run, "get", name, "banip").split()
for name in JAILS
if name in enabled
},
}
def operator_name():
try:
uid = int(Path("/proc/self/loginuid").read_text())
except (OSError, ValueError):
uid = 4294967295
if uid == 4294967295:
uid = int(os.environ.get("SUDO_UID", "0"))
try:
return pwd.getpwuid(uid).pw_name
except KeyError:
return str(uid)
def record_unblock(path, event, result):
if os.path.lexists(path):
check_root_file(path, mode=0o600)
fd = os.open(
path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o600
)
with os.fdopen(fd, "a", encoding="utf-8") as log:
event = event | {
"time": datetime.now(UTC).isoformat(),
"result": result,
}
log.write(json.dumps(event) + "\n")
log.flush()
os.fsync(log.fileno())
def unblock(run, path, jail, address, reason):
if "%" in address or not reason.strip() or len(reason) > 250:
raise ValueError(
"Enter an IP address and a reason of up to 250 characters."
)
address = str(ipaddress.ip_address(address))
event = {
"id": str(uuid4()),
"operator": operator_name(),
"jail": jail,
"address": address,
"reason": reason,
}
record_unblock(path, event, "requested")
try:
count = client(run, "set", jail, "unbanip", address).strip()
except (OSError, ValueError):
record_unblock(path, event, "failed")
raise
record_unblock(path, event | {"removed": count == "1"}, "completed")