mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-11-29 14:04:46 +03:00
2db45393cf
The 3x-ipl Fail2ban action bans with iptables and ip6tables, but the setup installed only fail2ban and nftables. Debian 12/13 and Ubuntu 22.04/24.04 do not pull iptables in with fail2ban, so on a host without it every ban logged "iptables: not found", showed up in the jail's banned list and applied no rule, while the setup reported success. A configured 3x-ipl jail now always has its ban tools. Writing the action installs them when they are missing, and so does an update over a jail an earlier release set up, whether the choice is stored or not. A jail that is already running is restarted after the install so bans it recorded without a rule get one. When the tools cannot be installed the setup fails with the reason instead of writing a jail that enforces nothing. The lifecycle fixture now models the tools as present, so its cases no longer depend on the host running the tests.
308 lines
14 KiB
Go
308 lines
14 KiB
Go
package main
|
|
|
|
import (
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestNativeFail2banLifecycle(t *testing.T) {
|
|
if runtime.GOOS == "windows" {
|
|
t.Skip("requires a POSIX shell")
|
|
}
|
|
bash, err := exec.LookPath("bash")
|
|
if err != nil {
|
|
t.Skip("requires bash")
|
|
}
|
|
for _, tc := range []struct {
|
|
name, initial, command, wantChoice string
|
|
setup, installed, jail, ssh bool
|
|
}{
|
|
{name: "Enter declines", command: "export NONINTERACTIVE=0; printf '\\n' | setup_install", wantChoice: "false"},
|
|
{name: "Yes enables", command: "export NONINTERACTIVE=0; printf 'y\\n' | setup_install", wantChoice: "true", setup: true, installed: true, jail: true},
|
|
{name: "unattended unset", command: "setup_install", wantChoice: "false"},
|
|
{name: "unattended false", command: "XUI_ENABLE_FAIL2BAN=false setup_install", wantChoice: "false"},
|
|
{name: "unattended true", command: "XUI_ENABLE_FAIL2BAN=true setup_install", wantChoice: "true", setup: true, installed: true, jail: true},
|
|
{name: "retry configured jail without replacing its ban duration", initial: "legacy", command: "rm \"$TEST_DIR/managed-running\"; XUI_ENABLE_FAIL2BAN=true setup_update; test -e \"$TEST_DIR/managed-running\"", wantChoice: "true", installed: true, jail: true},
|
|
{name: "legacy active keeps configuration", initial: "legacy", command: "setup_update", installed: true, jail: true},
|
|
{name: "update without managed jail", initial: "ssh", command: "setup_update", wantChoice: "false", installed: true, ssh: true},
|
|
{name: "remove and reinstall", initial: "legacy ssh", command: "printf '1\\n' | remove_iplimit; XUI_ENABLE_FAIL2BAN=true setup_update; setup_install", wantChoice: "false", installed: true, ssh: true},
|
|
{name: "remove package and update", initial: "legacy", command: "printf '2\\n' | remove_iplimit; setup_update", wantChoice: "false"},
|
|
{name: "package removal protects ssh", initial: "legacy ssh", command: "printf '2\\n' | remove_iplimit; setup_update", wantChoice: "false", installed: true, ssh: true},
|
|
{name: "explicit menu re-enable", initial: "legacy", command: "printf '1\\n' | remove_iplimit; install_iplimit; setup_update", wantChoice: "true", setup: true, installed: true, jail: true},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
driver := setupFail2banScriptFixture(t, dir)
|
|
for _, line := range strings.Fields(tc.initial) {
|
|
switch line {
|
|
case "legacy":
|
|
writeFail2banFixture(t, dir, "fail2ban/jail.d/3x-ipl.conf", "[3x-ipl]\nenabled = true\nbantime = 47m\n")
|
|
writeFail2banFixture(t, dir, "installed", "")
|
|
writeFail2banFixture(t, dir, "managed-running", "")
|
|
case "ssh":
|
|
writeFail2banFixture(t, dir, "fail2ban/jail.d/sshd.local", "[sshd]\nenabled = true\n")
|
|
writeFail2banFixture(t, dir, "installed", "")
|
|
writeFail2banFixture(t, dir, "ssh-running", "")
|
|
}
|
|
}
|
|
writeFail2banFixture(t, dir, "env", "XUI_DB_TYPE=postgres\nOTHER_KEY='value with spaces'\n")
|
|
cmd := exec.CommandContext(t.Context(), bash, "-c", driver+"\n"+tc.command)
|
|
for _, e := range os.Environ() {
|
|
if !strings.HasPrefix(e, "XUI_") && !strings.HasPrefix(e, "NONINTERACTIVE=") && !strings.HasPrefix(e, "TEST_DIR=") {
|
|
cmd.Env = append(cmd.Env, e)
|
|
}
|
|
}
|
|
cmd.Env = append(cmd.Env, "TEST_DIR="+dir)
|
|
out, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("shell flow: %v\n%s", err, out)
|
|
}
|
|
wantEnv := "XUI_DB_TYPE=postgres\nOTHER_KEY='value with spaces'\n"
|
|
if tc.wantChoice != "" {
|
|
wantEnv += "XUI_ENABLE_FAIL2BAN=" + tc.wantChoice + "\n"
|
|
}
|
|
if env := readScriptState(t, dir, "env"); env != wantEnv {
|
|
t.Errorf("preference file = %q, want stored %s and untouched options", env, tc.wantChoice)
|
|
}
|
|
for path, present := range map[string]bool{"setup": tc.setup, "installed": tc.installed, "fail2ban/jail.d/3x-ipl.conf": tc.jail, "ssh-running": tc.ssh} {
|
|
_, err := os.Stat(filepath.Join(dir, path))
|
|
if (err == nil) != present {
|
|
t.Errorf("%s present = %t, want %t (stat %v)", path, err == nil, present, err)
|
|
}
|
|
}
|
|
if tc.ssh && readScriptState(t, dir, "fail2ban/jail.d/sshd.local") != "[sshd]\nenabled = true\n" {
|
|
t.Errorf("independent SSH jail configuration changed")
|
|
}
|
|
if tc.jail && !tc.setup && !strings.Contains(readScriptState(t, dir, "fail2ban/jail.d/3x-ipl.conf"), "bantime = 47m") {
|
|
t.Error("update rewrote the existing jail's ban duration")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func writeFail2banFixture(t *testing.T, dir, path, contents string) {
|
|
t.Helper()
|
|
target := filepath.Join(dir, filepath.FromSlash(path))
|
|
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(target, []byte(contents), 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func setupFail2banScriptFixture(t *testing.T, dir string) string {
|
|
t.Helper()
|
|
driver := `red= green= yellow= plain= release=debian
|
|
xui_env_file_path() { printf '%s\n' "$TEST_DIR/env"; }
|
|
LOGE() { printf '%s\n' "$*"; }
|
|
before_show_menu() { :; }
|
|
check_status() { return 1; }
|
|
systemctl() {
|
|
if [[ $1 == stop ]]; then rm -f "$TEST_DIR/ssh-running" "$TEST_DIR/managed-running"; fi
|
|
}
|
|
apt-get() { rm -f "$TEST_DIR/installed"; }
|
|
command() {
|
|
case "$*" in
|
|
'-v fail2ban-client') [[ -f "$TEST_DIR/installed" ]] ;;
|
|
'-v iptables' | '-v ip6tables') [[ -f "$TEST_DIR/$2" ]] ;;
|
|
*) builtin command "$@" ;;
|
|
esac
|
|
}
|
|
fail2ban-client() {
|
|
case "$*" in
|
|
'status 3x-ipl') [[ -f "$TEST_DIR/managed-running" ]] ;;
|
|
'stop 3x-ipl') rm -f "$TEST_DIR/managed-running" ;;
|
|
status)
|
|
local jails=
|
|
[[ ! -f "$TEST_DIR/managed-running" ]] || jails=3x-ipl
|
|
[[ ! -f "$TEST_DIR/ssh-running" ]] || jails="${jails:+$jails, }sshd"
|
|
printf 'Status\n- Jail list:\t%s\n' "$jails" ;;
|
|
-d)
|
|
[[ ! -f "$TEST_DIR/fail2ban/jail.d/3x-ipl.conf" ]] || echo "['add', '3x-ipl', 'auto']"
|
|
[[ ! -f "$TEST_DIR/fail2ban/jail.d/sshd.local" ]] || echo "['add', 'sshd', 'auto']" ;;
|
|
*) return 1 ;;
|
|
esac
|
|
}
|
|
start_iplimit_jail() { touch "$TEST_DIR/managed-running"; }
|
|
setup_fail2ban_iplimit() {
|
|
mkdir -p "$TEST_DIR/fail2ban/jail.d"
|
|
printf '[3x-ipl]\nenabled=true\nbantime=30m\n' > "$TEST_DIR/fail2ban/jail.d/3x-ipl.conf"
|
|
touch "$TEST_DIR/setup" "$TEST_DIR/installed" "$TEST_DIR/managed-running"
|
|
}
|
|
`
|
|
source, err := os.ReadFile("x-ui.sh")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, name := range []string{
|
|
"confirm", "read_fail2ban_preference", "persist_fail2ban_preference",
|
|
"iplimit_jail_configured", "setup_fail2ban_for_lifecycle", "apply_iplimit_preference",
|
|
"iplimit_remove_conflicts", "iplimit_can_uninstall", "remove_iplimit_jail",
|
|
"install_iplimit", "remove_iplimit", "iplimit_ban_tools_present", "ensure_iplimit_ban_tools",
|
|
} {
|
|
if strings.Contains(string(source), "\n"+name+"() {\n") {
|
|
driver += strings.ReplaceAll(scriptFunction(t, "x-ui.sh", name), "/etc/fail2ban", filepath.Join(dir, "fail2ban"))
|
|
}
|
|
}
|
|
cli := "#!/bin/bash\n" + driver + "\ncase \"$1\" in\n\"setup-fail2ban\")\n"
|
|
if strings.Contains(driver, "\nsetup_fail2ban_for_lifecycle() {\n") {
|
|
cli += "setup_fail2ban_for_lifecycle \"${2:-update}\";;\n"
|
|
} else {
|
|
cli += "setup_fail2ban_iplimit;;\n"
|
|
}
|
|
writeFail2banFixture(t, dir, "x-ui", cli+"esac\n")
|
|
for script, name := range map[string]string{"install.sh": "setup_install", "update.sh": "setup_update"} {
|
|
wrapper := scriptFunction(t, script, "setup_fail2ban")
|
|
wrapper = strings.Replace(wrapper, "setup_fail2ban() {", name+"() {", 1)
|
|
wrapper = strings.ReplaceAll(wrapper, "/usr/bin/x-ui", filepath.Join(dir, "x-ui"))
|
|
driver += wrapper
|
|
}
|
|
driver += "\nexport NONINTERACTIVE=1\n"
|
|
writeFail2banFixture(t, dir, "iptables", "")
|
|
writeFail2banFixture(t, dir, "ip6tables", "")
|
|
return driver
|
|
}
|
|
|
|
func TestIPLimitBanToolsAreEnsured(t *testing.T) {
|
|
if runtime.GOOS == "windows" {
|
|
t.Skip("requires a POSIX shell")
|
|
}
|
|
bash, err := exec.LookPath("bash")
|
|
if err != nil {
|
|
t.Skip("requires bash")
|
|
}
|
|
const legacyJail = "[3x-ipl]\nenabled = true\nbantime = 47m\n"
|
|
const install = "update\ninstall -y iptables\n"
|
|
for _, tc := range []struct {
|
|
name, command, env, wantPackages, wantRestarts string
|
|
present, unavailable, jail, wantFailure bool
|
|
}{
|
|
{name: "writing the action installs the missing tools", command: "create_iplimit_jails", wantPackages: install},
|
|
{name: "present tools need no package and no restart", command: "create_iplimit_jails", present: true, jail: true},
|
|
{name: "an update repairs a running legacy jail", command: "setup_fail2ban_for_lifecycle update", jail: true, wantPackages: install, wantRestarts: "restart 3x-ipl\n"},
|
|
{name: "an update repairs a stored opt-in", command: "setup_fail2ban_for_lifecycle update", env: "XUI_ENABLE_FAIL2BAN=true\n", jail: true, wantPackages: install, wantRestarts: "restart 3x-ipl\n"},
|
|
{name: "tools that cannot be installed fail the setup", command: "create_iplimit_jails", unavailable: true, wantPackages: install, wantFailure: true},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
driver := setupFail2banScriptFixture(t, dir) + `
|
|
iplimit_log_path="$TEST_DIR/3xipl.log" iplimit_banned_log_path="$TEST_DIR/3xipl-banned.log" xui_folder="$TEST_DIR/app"
|
|
apt-get() {
|
|
printf '%s\n' "$*" >> "$TEST_DIR/packages"
|
|
if [[ $* == *iptables* && ! -f "$TEST_DIR/unavailable" ]]; then touch "$TEST_DIR/iptables" "$TEST_DIR/ip6tables"; fi
|
|
}
|
|
fail2ban-client() {
|
|
case "$*" in
|
|
'status 3x-ipl') [[ -f "$TEST_DIR/managed-running" ]] ;;
|
|
'restart 3x-ipl') printf '%s\n' "$*" >> "$TEST_DIR/restarts" ;;
|
|
*) return 1 ;;
|
|
esac
|
|
}
|
|
` + strings.ReplaceAll(scriptFunction(t, "x-ui.sh", "create_iplimit_jails"), "/etc/fail2ban", filepath.Join(dir, "fail2ban"))
|
|
for _, sub := range []string{"jail.d", "filter.d", "action.d"} {
|
|
if err := os.MkdirAll(filepath.Join(dir, "fail2ban", sub), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if !tc.present {
|
|
for _, tool := range []string{"iptables", "ip6tables"} {
|
|
if err := os.Remove(filepath.Join(dir, tool)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
}
|
|
if tc.unavailable {
|
|
writeFail2banFixture(t, dir, "unavailable", "")
|
|
}
|
|
if tc.jail {
|
|
writeFail2banFixture(t, dir, "fail2ban/jail.d/3x-ipl.conf", legacyJail)
|
|
writeFail2banFixture(t, dir, "installed", "")
|
|
writeFail2banFixture(t, dir, "managed-running", "")
|
|
}
|
|
writeFail2banFixture(t, dir, "env", tc.env)
|
|
writeFail2banFixture(t, dir, "packages", "")
|
|
writeFail2banFixture(t, dir, "restarts", "")
|
|
cmd := exec.CommandContext(t.Context(), bash, "-c", driver+"\n"+tc.command)
|
|
for _, e := range os.Environ() {
|
|
if !strings.HasPrefix(e, "XUI_") && !strings.HasPrefix(e, "TEST_DIR=") {
|
|
cmd.Env = append(cmd.Env, e)
|
|
}
|
|
}
|
|
cmd.Env = append(cmd.Env, "TEST_DIR="+dir)
|
|
out, err := cmd.CombinedOutput()
|
|
if (err != nil) != tc.wantFailure {
|
|
t.Fatalf("shell flow error = %v, want failure %t\n%s", err, tc.wantFailure, out)
|
|
}
|
|
for _, tool := range []string{"iptables", "ip6tables"} {
|
|
_, statErr := os.Stat(filepath.Join(dir, tool))
|
|
if (statErr == nil) == tc.wantFailure {
|
|
t.Errorf("%s present = %t after the flow, want %t", tool, statErr == nil, !tc.wantFailure)
|
|
}
|
|
}
|
|
if got := readScriptState(t, dir, "packages"); got != tc.wantPackages {
|
|
t.Errorf("package manager calls = %q, want %q", got, tc.wantPackages)
|
|
}
|
|
if got := readScriptState(t, dir, "restarts"); got != tc.wantRestarts {
|
|
t.Errorf("jail restarts = %q, want %q", got, tc.wantRestarts)
|
|
}
|
|
_, actionErr := os.Stat(filepath.Join(dir, "fail2ban", "action.d", "3x-ipl.conf"))
|
|
if tc.wantFailure && (actionErr == nil || !strings.Contains(string(out), "iptables and ip6tables")) {
|
|
t.Errorf("setup without ban tools wrote the action (stat %v) or hid the reason: %s", actionErr, out)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestNativeFail2banStockSSHBackend(t *testing.T) {
|
|
if runtime.GOOS == "windows" {
|
|
t.Skip("requires a POSIX shell")
|
|
}
|
|
bash, err := exec.LookPath("bash")
|
|
if err != nil {
|
|
t.Skip("requires bash")
|
|
}
|
|
const stock = "[DEFAULT]\nbackend = auto\n\n[sshd]\nlogpath = %(sshd_log)s\nbackend = %(sshd_backend)s\n"
|
|
const ownJail = "[monitor]\nbackend = polling\nlogpath = /var/log/monitor.log\n"
|
|
const override = "fail2ban/jail.d/3x-ipl-backend.conf"
|
|
for _, tc := range []struct {
|
|
name, release, version, customFile, customContents, want string
|
|
}{
|
|
{name: "Debian 12 journal only", release: "debian", version: "12", want: "[sshd]\nbackend = systemd\n"},
|
|
{name: "Ubuntu 22.04 journal only", release: "ubuntu", version: "2204", want: "[sshd]\nbackend = systemd\n"},
|
|
{name: "file logs available", release: "debian", version: "12", customFile: "auth.log"},
|
|
{name: "operator SSH configuration", release: "ubuntu", version: "2404", customFile: "fail2ban/jail.d/sshd.local", customContents: "[sshd]\nbackend = polling\n"},
|
|
{name: "operator default backend", release: "debian", version: "12", customFile: "fail2ban/jail.local", customContents: "[DEFAULT]\nbackend = polling\n"},
|
|
{name: "legacy persisted override", release: "debian", version: "12", customFile: override, customContents: "[DEFAULT]\nbackend = systemd\n", want: "[DEFAULT]\nbackend = systemd\n"},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
writeFail2banFixture(t, dir, "fail2ban/jail.conf", stock)
|
|
writeFail2banFixture(t, dir, "fail2ban/jail.d/monitor.local", ownJail)
|
|
if tc.customFile != "" {
|
|
writeFail2banFixture(t, dir, tc.customFile, tc.customContents)
|
|
}
|
|
script := scriptFunction(t, "x-ui.sh", "configure_default_sshd_backend")
|
|
script += "\napt-get() { :; }\nrelease=\"$1\" os_version=\"$2\"\nconfigure_default_sshd_backend \"$3/fail2ban\" \"$3/auth.log\""
|
|
out, err := exec.CommandContext(t.Context(), bash, "-c", script, "test", tc.release, tc.version, dir).CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("configure default backend: %v, %s", err, out)
|
|
}
|
|
got, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(override)))
|
|
if tc.want == "" && !os.IsNotExist(err) {
|
|
t.Fatalf("unexpected override, err=%v: %s", err, got)
|
|
}
|
|
if tc.want != "" && (err != nil || string(got) != tc.want) {
|
|
t.Fatalf("override = %q, want %q, err=%v", got, tc.want, err)
|
|
}
|
|
if readScriptState(t, dir, "fail2ban/jail.conf") != stock || readScriptState(t, dir, "fail2ban/jail.d/monitor.local") != ownJail {
|
|
t.Fatal("stock config or independent jail was rewritten")
|
|
}
|
|
})
|
|
}
|
|
}
|