diff --git a/docs/content/docs/en/operations/security.mdx b/docs/content/docs/en/operations/security.mdx
index 4c294b582..3cc468913 100644
--- a/docs/content/docs/en/operations/security.mdx
+++ b/docs/content/docs/en/operations/security.mdx
@@ -21,8 +21,10 @@ See [First login](/docs/guide/first-login) for the full checklist.
Set an **IP limit** per client (see [Clients](/docs/config/clients)) to cap the
number of simultaneous source IPs. Enforcement is handled by **Fail2ban**, which
-3x-ui installs and configures for you (enabled by default on script installs, and
-on Docker via `XUI_ENABLE_FAIL2BAN=true`).
+3x-ui installs and configures when you opt in. On a fresh native install,
+answer **Yes** to enable enforcement, or set `XUI_ENABLE_FAIL2BAN=true` for
+unattended and Docker installs. The native installer remembers your choice across
+updates and reinstalls. Source IP tracking continues independently of enforcement.
Manage it from the `x-ui` menu (**22 — IP Limit Management**): install/configure,
change the ban duration (default **30 minutes**), ban/unban an IP, view ban logs,
diff --git a/docs/content/docs/fa/operations/security.mdx b/docs/content/docs/fa/operations/security.mdx
index 06e7b4ba3..e8572dbd6 100644
--- a/docs/content/docs/fa/operations/security.mdx
+++ b/docs/content/docs/fa/operations/security.mdx
@@ -17,7 +17,7 @@ icon: ShieldCheck
## Fail2ban و محدودیتهای IP
-برای هر کلاینت یک **محدودیت IP** تنظیم کنید (به [کلاینتها](/docs/config/clients) مراجعه کنید) تا تعداد IPهای مبدأ همزمان محدود شود. اعمال این محدودیت توسط **Fail2ban** انجام میشود که 3x-ui آن را برای شما نصب و پیکربندی میکند (در نصبهای اسکریپتی بهطور پیشفرض فعال است و در Docker از طریق `XUI_ENABLE_FAIL2BAN=true`).
+برای هر کلاینت یک **محدودیت IP** تنظیم کنید (به [کلاینتها](/docs/config/clients) مراجعه کنید) تا تعداد IPهای مبدأ همزمان محدود شود. اعمال این محدودیت توسط **Fail2ban** انجام میشود که 3x-ui پس از موافقت شما آن را نصب و پیکربندی میکند. در نصب تازه با اسکریپت، برای فعالکردن اعمال محدودیت **Yes** را انتخاب کنید. در نصب خودکار و Docker، `XUI_ENABLE_FAIL2BAN=true` را تنظیم کنید. انتخاب شما در بهروزرسانی و نصب مجدد حفظ میشود. ردیابی IP مبدأ مستقل از اعمال محدودیت ادامه دارد.
آن را از منوی `x-ui` مدیریت کنید (**۲۲ — IP Limit Management**): نصب/پیکربندی، تغییر مدت مسدودسازی (پیشفرض **۳۰ دقیقه**)، مسدودسازی/رفع مسدودی یک IP، مشاهده لاگهای مسدودسازی و بررسی وضعیت. در پشت صحنه:
diff --git a/docs/content/docs/ru/operations/security.mdx b/docs/content/docs/ru/operations/security.mdx
index d9acbe8e6..1bd53c627 100644
--- a/docs/content/docs/ru/operations/security.mdx
+++ b/docs/content/docs/ru/operations/security.mdx
@@ -21,8 +21,10 @@ icon: ShieldCheck
Задайте **ограничение IP** для каждого клиента (см. [Клиенты](/docs/config/clients)), чтобы
ограничить число одновременных исходных IP. Применением правил занимается **Fail2ban**, который
-3x-ui устанавливает и настраивает за вас (включён по умолчанию при установке через скрипт, а
-в Docker — через `XUI_ENABLE_FAIL2BAN=true`).
+3x-ui устанавливает и настраивает по вашему согласию. При новой установке через
+скрипт ответьте **Да**, чтобы включить применение ограничений. Для автоматической
+установки и Docker задайте `XUI_ENABLE_FAIL2BAN=true`. Скрипт сохраняет выбор при
+обновлении и переустановке. Отслеживание исходных IP работает независимо.
Управляйте им из меню `x-ui` (**22 — IP Limit Management**): установка/настройка,
изменение длительности блокировки (по умолчанию **30 минут**), блокировка/разблокировка IP, просмотр журналов блокировок
diff --git a/docs/content/docs/zh/operations/security.mdx b/docs/content/docs/zh/operations/security.mdx
index b62d0fe2a..21856a43f 100644
--- a/docs/content/docs/zh/operations/security.mdx
+++ b/docs/content/docs/zh/operations/security.mdx
@@ -19,8 +19,9 @@ icon: ShieldCheck
## Fail2ban 与 IP 限制
为每个客户端设置一个 **IP 限制**(参见[客户端](/docs/config/clients)),以限制同时使用的源
-IP 数量。限制的执行由 **Fail2ban** 负责,3x-ui 会为你安装并配置好它(脚本安装时默认启用,
-Docker 安装时通过 `XUI_ENABLE_FAIL2BAN=true` 启用)。
+IP 数量。由 **Fail2ban** 执行限制,3x-ui 会在你同意后安装并配置它。首次通过脚本安装时,
+选择 **Yes** 以启用限制。对于无人值守和 Docker 安装,请设置 `XUI_ENABLE_FAIL2BAN=true`。
+脚本会在更新和重新安装时保留你的选择。源 IP 跟踪独立运行。
可从 `x-ui` 菜单(**22 — IP Limit Management**)进行管理:安装/配置、修改封锁时长
(默认 **30 分钟**)、封锁/解封某个 IP、查看封锁日志,以及检查状态。其底层机制如下:
diff --git a/install.sh b/install.sh
index 4d7c50e88..e8008aa4d 100644
--- a/install.sh
+++ b/install.sh
@@ -1228,17 +1228,7 @@ config_after_install() {
fi
if [[ "$db_choice" == "2" ]]; then
local xui_env_file
- case "${release}" in
- ubuntu | debian | armbian)
- xui_env_file="/etc/default/x-ui"
- ;;
- arch | manjaro | parch | alpine)
- xui_env_file="/etc/conf.d/x-ui"
- ;;
- *)
- xui_env_file="/etc/sysconfig/x-ui"
- ;;
- esac
+ xui_env_file=$(xui_env_file_path)
local xui_dsn=""
local pg_mode=""
@@ -1487,35 +1477,33 @@ EOF
${xui_folder}/x-ui migrate
}
-# setup_fail2ban auto-installs and configures fail2ban for the IP Limit feature
-# by invoking the freshly installed x-ui CLI. IP Limit is load-bearing on
-# fail2ban (without it the panel disables the limitIp field and zeroes existing
-# limits), so a fresh install should make it work out of the box, just like the
-# Docker image already does. Non-fatal by design: a fail2ban failure must never
-# abort the panel install.
+xui_env_file_path() {
+ case "$release" in
+ ubuntu | debian | armbian) printf '/etc/default/x-ui\n' ;;
+ arch | manjaro | parch | alpine) printf '/etc/conf.d/x-ui\n' ;;
+ *) printf '/etc/sysconfig/x-ui\n' ;;
+ esac
+}
+
+load_xui_env() {
+ local envfile="${1:-}"
+ [[ -n "$envfile" ]] || envfile=$(xui_env_file_path)
+ if [[ -r "$envfile" ]]; then
+ set -a
+ # shellcheck disable=SC1090
+ source "$envfile"
+ set +a
+ fi
+}
+
+# Delegate only to releases that can honor and persist the administrator's choice.
setup_fail2ban() {
- if [[ -n "${XUI_ENABLE_FAIL2BAN+x}" && "${XUI_ENABLE_FAIL2BAN}" != "true" ]]; then
- echo -e "${yellow}XUI_ENABLE_FAIL2BAN=${XUI_ENABLE_FAIL2BAN}, skipping Fail2ban auto-setup.${plain}"
+ if [[ ! -x /usr/bin/x-ui ]] || ! grep -Fq 'setup_fail2ban_for_lifecycle()' /usr/bin/x-ui; then
+ echo -e "${yellow}This release does not support the persistent IP Limit setup policy. Skipping automatic setup.${plain}"
return 0
fi
-
- if [[ ! -x /usr/bin/x-ui ]]; then
- echo -e "${yellow}x-ui CLI not found; skipping Fail2ban auto-setup.${plain}"
- return 0
- fi
-
- # Scripts older than v3.4.0 have no setup-fail2ban and exit 0 from the
- # usage banner, which would read as success here.
- if ! grep -q '"setup-fail2ban")' /usr/bin/x-ui; then
- echo -e "${yellow}This x-ui.sh predates 'x-ui setup-fail2ban'; skipping Fail2ban auto-setup.${plain}"
- return 0
- fi
-
- echo -e "${green}Setting up Fail2ban for the IP Limit feature...${plain}"
- if /usr/bin/x-ui setup-fail2ban; then
- echo -e "${green}Fail2ban setup complete.${plain}"
- else
- echo -e "${yellow}Fail2ban setup did not finish; IP Limit stays disabled until you run 'x-ui' and open the IP Limit menu. Continuing.${plain}"
+ if ! /usr/bin/x-ui setup-fail2ban "${1:-install}"; then
+ echo -e "${yellow}Fail2ban setup did not finish. Use the IP Limit menu to check its configuration.${plain}"
fi
return 0
}
@@ -1587,25 +1575,7 @@ _xui_service_write_paths_dropin() {
local db_folder log_folder bin_folder main_folder
local path line="" whitespace_paths="" seen_paths="" escaped_path
- if [[ -z "$env_file" ]]; then
- case "${release}" in
- ubuntu | debian | armbian)
- env_file="/etc/default/x-ui"
- ;;
- arch | manjaro | parch | alpine)
- env_file="/etc/conf.d/x-ui"
- ;;
- *)
- env_file="/etc/sysconfig/x-ui"
- ;;
- esac
- fi
- if [[ -r "$env_file" ]]; then
- set -a
- # shellcheck disable=SC1090
- source "$env_file"
- set +a
- fi
+ load_xui_env "$env_file"
# XUI_* wins over the script's own default: the unit hands that same env
# file to the panel through EnvironmentFile=, so these are the folders it
@@ -1784,6 +1754,11 @@ require_repo_files() {
install_x-ui() {
cd ${xui_folder%/x-ui}/
+ local fail2ban_mode=install
+ if [[ -x "${xui_folder}/x-ui" ]]; then
+ fail2ban_mode=update
+ fi
+ load_xui_env
# Download resources
if [ $# == 0 ]; then
@@ -1986,6 +1961,7 @@ install_x-ui() {
chmod +x /usr/bin/x-ui
mkdir -p /var/log/x-ui
config_after_install
+ setup_fail2ban "$fail2ban_mode"
# Etckeeper compatibility
if [ -d "/etc/.git" ]; then
@@ -2023,7 +1999,7 @@ install_x-ui() {
fi
chmod +x /etc/init.d/x-ui
rc-update add x-ui
- rc-service x-ui start
+ rc-service x-ui restart
else
# Install systemd service file
service_installed=false
@@ -2092,17 +2068,13 @@ install_x-ui() {
chmod 644 ${xui_service}/x-ui.service > /dev/null 2>&1
systemctl daemon-reload
systemctl enable x-ui
- systemctl start x-ui
+ systemctl restart x-ui
else
echo -e "${red}Failed to install x-ui.service file${plain}"
exit 1
fi
fi
- # IP Limit relies on fail2ban; install + configure it now so the feature
- # works out of the box (no-op when XUI_ENABLE_FAIL2BAN=false). Never fatal.
- setup_fail2ban
-
echo -e "${green}x-ui ${tag_version}${plain} installation finished, it is running now..."
echo -e ""
echo -e "┌───────────────────────────────────────────────────────┐
diff --git a/internal/database/db.go b/internal/database/db.go
index 969520e78..b6f2d512e 100644
--- a/internal/database/db.go
+++ b/internal/database/db.go
@@ -1851,6 +1851,11 @@ func resetIpLimitsWithoutFail2ban() error {
return nil
}
+ // An explicit enforcement choice can change independently of client limits.
+ if _, configured := os.LookupEnv("XUI_ENABLE_FAIL2BAN"); configured {
+ return db.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error
+ }
+
state, probeErr := fail2banEnforcementState()
if state == fail2banEnforcing {
return db.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error
diff --git a/internal/database/fail2ban_state_test.go b/internal/database/fail2ban_state_test.go
index 509c0ac37..05a3c4e7f 100644
--- a/internal/database/fail2ban_state_test.go
+++ b/internal/database/fail2ban_state_test.go
@@ -54,6 +54,16 @@ func TestFail2banEnforcementStateSeparatesAbsentFromUnrunnable(t *testing.T) {
}
func TestResetIpLimitsKeepsConfiguredLimitsWhenProbeFails(t *testing.T) {
+ testResetIpLimitsKeepsConfiguredLimits(t, 0)
+}
+
+func TestResetIpLimitsKeepsConfiguredLimitsWhenOptedOut(t *testing.T) {
+ t.Setenv("XUI_ENABLE_FAIL2BAN", "false")
+ testResetIpLimitsKeepsConfiguredLimits(t, 1)
+}
+
+func testResetIpLimitsKeepsConfiguredLimits(t *testing.T, wantHistory int64) {
+ t.Helper()
if runtime.GOOS == "windows" {
t.Skip("fail2ban shell fixtures are Unix-only")
}
@@ -103,7 +113,7 @@ func TestResetIpLimitsKeepsConfiguredLimitsWhenProbeFails(t *testing.T) {
if err := db.Model(&model.HistoryOfSeeders{}).Where("seeder_name = ?", "ResetIpLimitNoFail2ban").Count(&count).Error; err != nil {
t.Fatalf("count seeder history: %v", err)
}
- if count != 0 {
- t.Fatalf("seeder history rows = %d, want 0", count)
+ if count != wantHistory {
+ t.Fatalf("seeder history rows = %d, want %d", count, wantHistory)
}
}
diff --git a/scripts_base_path_test.go b/scripts_base_path_test.go
index a5d6df4d2..0fba126c7 100644
--- a/scripts_base_path_test.go
+++ b/scripts_base_path_test.go
@@ -129,6 +129,7 @@ chmod() { :; }
[() { if [[ "${2:-}" == /etc/* ]]; then return 1; fi; builtin [ "$@"; }
_install_xui_service_unit() { printf 'unit\n' >> "$TEST_SETTINGS_DIR/lifecycle"; }
setup_fail2ban() { printf 'fail2ban\n' >> "$TEST_SETTINGS_DIR/lifecycle"; }
+fail2ban_mode=install
`
driver += scriptFunction(t, script, "gen_random_string") + scriptFunction(t, script, function)
if script == "install.sh" {
@@ -142,7 +143,11 @@ setup_fail2ban() { printf 'fail2ban\n' >> "$TEST_SETTINGS_DIR/lifecycle"; }
parent = "install_x-ui"
}
body := scriptFunction(t, script, parent)
- start := strings.Index(body, "\n "+function)
+ startCall := function
+ if script == "update.sh" {
+ startCall = "setup_fail2ban"
+ }
+ start := strings.Index(body, "\n "+startCall)
if start < 0 {
t.Fatalf("%s: missing configuration call in %s", script, parent)
}
@@ -269,10 +274,9 @@ func TestScriptConfigReadFailureKeepsServiceSetup(t *testing.T) {
if err != nil || !strings.Contains(out, "Unable to read webBasePath") {
t.Errorf("service setup should continue after the settings warning: %v\n%s", err, out)
}
- wantLifecycle, wantServices := "fail2ban\n", ""
+ wantLifecycle, wantServices := "fail2ban\nunit\n", "daemon-reload\nenable x-ui\nstart x-ui\n"
if script == "install.sh" {
- wantLifecycle = "unit\nfail2ban\n"
- wantServices = "daemon-reload\nenable x-ui\nstart x-ui\n"
+ wantServices = "daemon-reload\nenable x-ui\nrestart x-ui\n"
}
for name, want := range map[string]string{
"path": "/a/", "username": "admin", "password": "admin", "writes": "",
diff --git a/scripts_fail2ban_test.go b/scripts_fail2ban_test.go
new file mode 100644
index 000000000..d99bde7af
--- /dev/null
+++ b/scripts_fail2ban_test.go
@@ -0,0 +1,211 @@
+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() {
+ if [[ $* == '-v fail2ban-client' ]]; then [[ -f "$TEST_DIR/installed" ]]; else builtin command "$@"; fi
+}
+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",
+ } {
+ 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"
+ return driver
+}
+
+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")
+ }
+ })
+ }
+}
diff --git a/update.sh b/update.sh
index ae1781cbb..7d7e3a1ff 100755
--- a/update.sh
+++ b/update.sh
@@ -253,36 +253,14 @@ config_after_update() {
fi
}
-# setup_fail2ban auto-installs and configures fail2ban for the IP Limit feature
-# by invoking the freshly downloaded x-ui CLI. IP Limit is load-bearing on
-# fail2ban (without it the panel disables the limitIp field and zeroes existing
-# limits), so updating an older install should make it work without a manual
-# trip through the IP Limit menu. Non-fatal: a fail2ban failure must never abort
-# the update. XUI_ENABLE_FAIL2BAN is honored (load_xui_env exports it from the
-# persisted env file, so a deliberate opt-out survives updates).
+# Delegate only to releases that can honor and persist the administrator's choice.
setup_fail2ban() {
- if [[ -n "${XUI_ENABLE_FAIL2BAN+x}" && "${XUI_ENABLE_FAIL2BAN}" != "true" ]]; then
- echo -e "${yellow}XUI_ENABLE_FAIL2BAN=${XUI_ENABLE_FAIL2BAN}, skipping Fail2ban auto-setup.${plain}"
+ if [[ ! -x /usr/bin/x-ui ]] || ! grep -Fq 'setup_fail2ban_for_lifecycle()' /usr/bin/x-ui; then
+ echo -e "${yellow}This release does not support the persistent IP Limit setup policy. Skipping automatic setup.${plain}"
return 0
fi
-
- if [[ ! -x /usr/bin/x-ui ]]; then
- echo -e "${yellow}x-ui CLI not found; skipping Fail2ban auto-setup.${plain}"
- return 0
- fi
-
- # Scripts older than v3.4.0 have no setup-fail2ban and exit 0 from the
- # usage banner, which would read as success here.
- if ! grep -q '"setup-fail2ban")' /usr/bin/x-ui; then
- echo -e "${yellow}This x-ui.sh predates 'x-ui setup-fail2ban'; skipping Fail2ban auto-setup.${plain}"
- return 0
- fi
-
- echo -e "${green}Setting up Fail2ban for the IP Limit feature...${plain}"
- if /usr/bin/x-ui setup-fail2ban; then
- echo -e "${green}Fail2ban setup complete.${plain}"
- else
- echo -e "${yellow}Fail2ban setup did not finish; IP Limit stays disabled until you run 'x-ui' and open the IP Limit menu. Continuing.${plain}"
+ if ! /usr/bin/x-ui setup-fail2ban update; then
+ echo -e "${yellow}Fail2ban setup did not finish. Use the IP Limit menu to check its configuration.${plain}"
fi
return 0
}
@@ -706,6 +684,7 @@ update_x-ui() {
# config_after_update's CLI calls never run them on the same database at once (#6728).
echo -e "${green}Migrating database...${plain}"
"${xui_folder}/x-ui" migrate
+ setup_fail2ban
if [[ $release == "alpine" ]]; then
echo -e "${green}Installing startup unit x-ui.rc...${plain}"
@@ -784,11 +763,6 @@ update_x-ui() {
config_after_update
- # IP Limit relies on fail2ban; install + configure it now so the feature
- # works out of the box on update too (no-op when XUI_ENABLE_FAIL2BAN=false).
- # Never fatal.
- setup_fail2ban
-
echo -e "${green}x-ui ${tag_version}${plain} updating finished, it is running now..."
echo -e ""
echo -e "┌───────────────────────────────────────────────────────┐
diff --git a/x-ui.rc b/x-ui.rc
index 55f6246be..b1ae7626f 100644
--- a/x-ui.rc
+++ b/x-ui.rc
@@ -9,10 +9,13 @@ depend() {
need net
}
start_pre(){
+ if [ "${XUI_ENABLE_FAIL2BAN+x}" ]; then
+ export XUI_ENABLE_FAIL2BAN
+ fi
cd /usr/local/x-ui
}
reload() {
ebegin "Reloading ${RC_SVCNAME}"
kill -USR1 $(cat $pidfile)
eend $?
-}
\ No newline at end of file
+}
diff --git a/x-ui.sh b/x-ui.sh
index 5f44a144d..d47d53a9b 100644
--- a/x-ui.sh
+++ b/x-ui.sh
@@ -2277,7 +2277,8 @@ iplimit_main() {
show_menu
;;
1)
- confirm "Proceed with installation of Fail2ban & IP Limit?" "y"
+ echo "IP Limit bans apply host-wide and can interrupt other clients behind a shared relay."
+ confirm "Enable IP Limit and restart the running panel to apply the choice?" "n"
if [[ $? == 0 ]]; then
install_iplimit
else
@@ -2285,14 +2286,15 @@ iplimit_main() {
fi
;;
2)
+ local preference
+ if ! preference=$(read_fail2ban_preference) || [[ "$preference" == "false" ]] || ! iplimit_jail_configured; then
+ LOGE "Enable IP Limit before changing its ban duration."
+ iplimit_main
+ return
+ fi
read -rp "Please enter new Ban Duration in Minutes [default 30]: " NUM
if [[ $NUM =~ ^[0-9]+$ ]]; then
- create_iplimit_jails ${NUM}
- if [[ $release == "alpine" ]]; then
- rc-service fail2ban restart
- else
- systemctl restart fail2ban
- fi
+ create_iplimit_jails "$NUM" && fail2ban-client reload 3x-ipl
else
echo -e "${red}${NUM} is not a number! Please, try again.${plain}"
fi
@@ -2363,15 +2365,80 @@ iplimit_main() {
esac
}
-setup_fail2ban_iplimit() {
- # Honor the same toggle the panel uses (isFail2BanEnabled): enabled when the
- # var is unset or exactly "true"; any other explicit value means the operator
- # opted out, so do nothing rather than install a fail2ban the panel ignores.
- if [[ -n "${XUI_ENABLE_FAIL2BAN+x}" && "${XUI_ENABLE_FAIL2BAN}" != "true" ]]; then
- echo -e "${yellow}XUI_ENABLE_FAIL2BAN=${XUI_ENABLE_FAIL2BAN}, skipping Fail2ban setup.${plain}\n"
+read_fail2ban_preference() {
+ (
+ local envfile
+ envfile=$(xui_env_file_path)
+ if [[ -e "$envfile" ]]; then
+ # shellcheck disable=SC1090
+ source "$envfile" || return 1
+ fi
+ if [[ ${XUI_ENABLE_FAIL2BAN+x} ]]; then
+ if [[ "$XUI_ENABLE_FAIL2BAN" == "true" ]]; then
+ printf 'true\n'
+ else
+ printf 'false\n'
+ fi
+ fi
+ )
+}
+
+persist_fail2ban_preference() {
+ local choice="$1" envfile temp
+ envfile=$(xui_env_file_path)
+ if [[ -L "$envfile" ]]; then
+ envfile=$(readlink -f -- "$envfile") || return 1
+ fi
+ mkdir -p -- "${envfile%/*}" || return 1
+ temp=$(mktemp "${envfile}.XXXXXX") || return 1
+ if [[ -e "$envfile" ]] && ! {
+ cp -p -- "$envfile" "$temp" &&
+ awk '!/^[[:space:]]*(export[[:space:]]+)?XUI_ENABLE_FAIL2BAN=/' "$envfile" > "$temp"
+ }; then
+ rm -f -- "$temp"
+ return 1
+ fi
+ if ! printf 'XUI_ENABLE_FAIL2BAN=%s\n' "$choice" >> "$temp" || ! mv -f -- "$temp" "$envfile"; then
+ rm -f -- "$temp"
+ return 1
+ fi
+}
+
+iplimit_jail_configured() {
+ [[ -f /etc/fail2ban/jail.d/3x-ipl.conf ]] ||
+ grep -Eq '^[[:space:]]*\[3x-ipl\]' /etc/fail2ban/jail.conf /etc/fail2ban/jail.local 2>/dev/null ||
+ fail2ban-client status 3x-ipl > /dev/null 2>&1
+}
+
+setup_fail2ban_for_lifecycle() {
+ local mode="$1" choice
+ choice=$(read_fail2ban_preference) || return 1
+ if [[ -z "$choice" ]] && iplimit_jail_configured; then
+ # Preserve legacy jails, including later overrides to their enabled state.
return 0
fi
+ if [[ -z "$choice" ]]; then
+ choice=false
+ if [[ "$mode" == "install" && "${NONINTERACTIVE:-1}" == "0" ]]; then
+ echo "IP Limit bans apply host-wide and can interrupt other clients behind a shared relay."
+ if confirm "Install Fail2ban and enable IP Limit?" "n"; then
+ choice=true
+ fi
+ fi
+ fi
+ persist_fail2ban_preference "$choice" || return 1
+ if [[ "$choice" == "false" ]]; then
+ echo "IP Limit enforcement is opted out."
+ return 0
+ fi
+ if command -v fail2ban-client > /dev/null 2>&1 && iplimit_jail_configured; then
+ fail2ban-client status 3x-ipl > /dev/null 2>&1 || start_iplimit_jail
+ return
+ fi
+ XUI_ENABLE_FAIL2BAN=true setup_fail2ban_iplimit
+}
+setup_fail2ban_iplimit() {
if ! command -v fail2ban-client &> /dev/null; then
echo -e "${green}Fail2ban is not installed. Installing now...!${plain}\n"
@@ -2390,6 +2457,9 @@ setup_fail2ban_iplimit() {
apt-get install python3-pip -y
python3 -m pip install pyasynchat --break-system-packages
fi
+ if [[ "$os_version" -ge 2200 ]]; then
+ apt-get install -y python3-systemd
+ fi
apt-get install fail2ban nftables -y
;;
debian)
@@ -2453,107 +2523,142 @@ setup_fail2ban_iplimit() {
echo -e "${green}Configuring IP Limit...${plain}\n"
# make sure there's no conflict for jail files
- iplimit_remove_conflicts
+ iplimit_remove_conflicts || return 1
# Check if log file exists
if ! test -f "${iplimit_banned_log_path}"; then
- touch ${iplimit_banned_log_path}
+ touch "$iplimit_banned_log_path" || return 1
fi
# Check if service log file exists so fail2ban won't return error
if ! test -f "${iplimit_log_path}"; then
- touch ${iplimit_log_path}
+ touch "$iplimit_log_path" || return 1
fi
# Create the iplimit jail files
# we didn't pass the bantime here to use the default value
- create_iplimit_jails
+ create_iplimit_jails || return 1
- # Launching fail2ban
- if [[ $release == "alpine" ]]; then
- if [[ $(rc-service fail2ban status | grep -F 'status: started' -c) == 0 ]]; then
- rc-service fail2ban start
- else
- rc-service fail2ban restart
- fi
- rc-update add fail2ban
- else
- if ! systemctl is-active --quiet fail2ban; then
- systemctl start fail2ban
- else
- systemctl restart fail2ban
- fi
- systemctl enable fail2ban
- fi
+ start_iplimit_jail || return 1
echo -e "${green}IP Limit installed and configured successfully!${plain}\n"
return 0
}
-# install_iplimit is the interactive (menu) entry point: it runs the shared
-# setup and then returns to the menu. The non-interactive installer path uses
-# setup_fail2ban_iplimit directly via `x-ui setup-fail2ban`.
+configure_default_sshd_backend() {
+ local config_dir="$1" auth_log="$2" jail_file
+ local override="$config_dir/jail.d/3x-ipl-backend.conf"
+ [[ ( "$release" == "debian" && ${os_version:-0} -ge 12 ) || ( "$release" == "ubuntu" && ${os_version:-0} -ge 2200 ) ]] || return 0
+ [[ ! -e "$auth_log" && ! -e "$override" && ! -L "$override" && ! -e "$config_dir/paths-overrides.local" ]] || return 0
+
+ # Repair the distro's stock SSH jail for journal-only hosts.
+ awk '
+ /^[[:space:]]*\[/ { section = $0 }
+ section ~ /\[DEFAULT\]/ && /^[[:space:]]*backend[[:space:]]*=[[:space:]]*auto[[:space:]]*$/ { stock_backend = 1 }
+ section ~ /\[sshd\]/ && /^[[:space:]]*backend[[:space:]]*=[[:space:]]*%[(]sshd_backend[)]s[[:space:]]*$/ { stock_ssh = 1 }
+ section ~ /\[sshd\]/ && /^[[:space:]]*logpath[[:space:]]*=[[:space:]]*%[(]sshd_log[)]s[[:space:]]*$/ { stock_log = 1 }
+ END { exit !(stock_backend && stock_ssh && stock_log) }
+ ' "$config_dir/jail.conf" 2>/dev/null || return 0
+
+ for jail_file in "$config_dir/jail.local" "$config_dir/jail.d/"*.conf "$config_dir/jail.d/"*.local; do
+ [[ -f "$jail_file" ]] || continue
+ if awk '
+ /^[[:space:]]*\[/ { section = $0 }
+ section ~ /\[(DEFAULT|sshd)\]/ && /^[[:space:]]*(backend|logpath)[[:space:]]*=/ { custom = 1 }
+ END { exit !custom }
+ ' "$jail_file"; then
+ return 0
+ fi
+ done
+
+ if ! /usr/bin/python3 -c 'from systemd import journal' > /dev/null 2>&1; then
+ apt-get install -y python3-systemd || return 1
+ fi
+ printf '[sshd]\nbackend = systemd\n' > "$override"
+}
+
+start_iplimit_jail() {
+ if fail2ban-client ping > /dev/null 2>&1; then
+ fail2ban-client reload --if-exists 3x-ipl || return 1
+ else
+ configure_default_sshd_backend /etc/fail2ban /var/log/auth.log || return 1
+ if [[ $release == "alpine" ]]; then
+ rc-service fail2ban start && rc-update add fail2ban || return 1
+ else
+ systemctl start fail2ban && systemctl enable fail2ban || return 1
+ fi
+ fi
+ fail2ban-client status 3x-ipl > /dev/null 2>&1
+}
+
+apply_iplimit_preference() {
+ local choice="$1"
+ persist_fail2ban_preference "$choice" || {
+ LOGE "Could not save the IP Limit preference."
+ return 1
+ }
+ export XUI_ENABLE_FAIL2BAN="$choice"
+}
+
install_iplimit() {
- setup_fail2ban_iplimit
+ if apply_iplimit_preference true && setup_fail2ban_iplimit; then
+ if check_status; then restart 0; fi
+ else
+ LOGE "IP Limit setup did not finish."
+ fi
before_show_menu
}
+iplimit_can_uninstall() {
+ local status dump jails
+ status=$(LC_ALL=C fail2ban-client status 2>/dev/null) || return 1
+ jails=$(sed -nE 's/^.*Jail list:[[:space:]]*//p' <<< "$status")
+ [[ "$jails" == "3x-ipl" ]] || return 1
+ dump=$(LC_ALL=C fail2ban-client -d 2>/dev/null) || return 1
+ jails=$(grep -E "^\[['\"]add['\"]," <<< "$dump")
+ # Require a known dump containing only the managed jail before removing the package.
+ [[ "$jails" == "['add', '3x-ipl', "* && "$jails" != *$'\n'* ]]
+}
+
+remove_iplimit_jail() {
+ if fail2ban-client status 3x-ipl > /dev/null 2>&1; then
+ fail2ban-client stop 3x-ipl || return 1
+ fi
+ iplimit_remove_conflicts || return 1
+ rm -f -- /etc/fail2ban/filter.d/3x-ipl.conf /etc/fail2ban/action.d/3x-ipl.conf /etc/fail2ban/jail.d/3x-ipl.conf
+}
+
remove_iplimit() {
echo -e "${green}\t1.${plain} Only remove IP Limit configurations"
echo -e "${green}\t2.${plain} Uninstall Fail2ban and IP Limit"
echo -e "${green}\t0.${plain} Back to Main Menu"
- read -rp "Choose an option: " num
+ local num uninstall_package=false
+ read -rp "Choose an option (a running panel will restart to apply the change): " num
case "$num" in
- 1)
- rm -f /etc/fail2ban/filter.d/3x-ipl.conf
- rm -f /etc/fail2ban/action.d/3x-ipl.conf
- rm -f /etc/fail2ban/jail.d/3x-ipl.conf
- if [[ $release == "alpine" ]]; then
- rc-service fail2ban restart
- else
- systemctl restart fail2ban
+ 1 | 2)
+ if [[ "$num" == "2" ]] && iplimit_can_uninstall; then
+ uninstall_package=true
fi
- echo -e "${green}IP Limit removed successfully!${plain}\n"
- before_show_menu
- ;;
- 2)
- rm -rf /etc/fail2ban
- if [[ $release == "alpine" ]]; then
- rc-service fail2ban stop
- else
- systemctl stop fail2ban
+ if ! apply_iplimit_preference false || ! remove_iplimit_jail; then
+ LOGE "IP Limit removal did not finish."
+ return 1
fi
- case "${release}" in
- ubuntu | debian | armbian)
- apt-get remove -y fail2ban
- apt-get purge -y fail2ban -y
- apt-get autoremove -y
- ;;
- fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
- dnf remove fail2ban -y
- dnf autoremove -y
- ;;
- centos)
- if [[ "${VERSION_ID}" =~ ^7 ]]; then
- yum remove fail2ban -y
- yum autoremove -y
- else
- dnf remove fail2ban -y
- dnf autoremove -y
- fi
- ;;
- arch | manjaro | parch)
- pacman -Rns --noconfirm fail2ban
- ;;
- alpine)
- apk del fail2ban
- ;;
- *)
- echo -e "${red}Unsupported operating system. Please uninstall Fail2ban manually.${plain}\n"
- exit 1
- ;;
- esac
- echo -e "${green}Fail2ban and IP Limit removed successfully!${plain}\n"
+ if [[ "$uninstall_package" == "true" ]]; then
+ case "${release}" in
+ ubuntu | debian | armbian) apt-get remove -y fail2ban ;;
+ fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol) dnf remove -y fail2ban ;;
+ centos)
+ if [[ "${VERSION_ID}" =~ ^7 ]]; then yum remove -y fail2ban; else dnf remove -y fail2ban; fi
+ ;;
+ arch | manjaro | parch) pacman -R --noconfirm fail2ban ;;
+ alpine) apk del fail2ban ;;
+ *) false ;;
+ esac || LOGE "Could not uninstall Fail2ban."
+ elif [[ "$num" == "2" ]]; then
+ echo "Keeping Fail2ban because other jails are present or its configuration could not be verified."
+ fi
+ if check_status; then restart 0; fi
+ echo -e "${green}IP Limit removed. Future updates will respect this choice.${plain}\n"
before_show_menu
;;
0)
@@ -2608,20 +2713,7 @@ create_iplimit_jails() {
# Use default bantime if not passed => 30 minutes
local bantime="${1:-30}"
- # Uncomment 'allowipv6 = auto' in fail2ban.conf
- sed -i 's/#allowipv6 = auto/allowipv6 = auto/g' /etc/fail2ban/fail2ban.conf
-
- # Debian 12+ / Ubuntu 22.04+ log sshd to the journal only; a jail.d override
- # survives package upgrades. Only the stock 'backend = auto' is overridden.
- if [[ ( "${release}" == "debian" && ${os_version} -ge 12 ) || ( "${release}" == "ubuntu" && ${os_version} -ge 2200 ) ]] &&
- sed -n '0,/action =/p' /etc/fail2ban/jail.conf | grep -q '^backend = auto'; then
- cat << EOF > /etc/fail2ban/jail.d/3x-ipl-backend.conf
-[DEFAULT]
-backend = systemd
-EOF
- fi
-
- cat << EOF > /etc/fail2ban/jail.d/3x-ipl.conf
+ cat << EOF > /etc/fail2ban/jail.d/3x-ipl.conf || return 1
[3x-ipl]
enabled=true
backend=auto
@@ -2633,7 +2725,7 @@ findtime=32
bantime=${bantime}m
EOF
- cat << EOF > /etc/fail2ban/filter.d/3x-ipl.conf
+ cat << EOF > /etc/fail2ban/filter.d/3x-ipl.conf || return 1
[Definition]
datepattern = ^%%Y/%%m/%%d %%H:%%M:%%S
failregex = \[LIMIT_IP\]\s*Email\s*=\s*.+\s*\|\|\s*Disconnecting OLD IP\s*=\s*\s*\|\|\s*Timestamp\s*=\s*\d+
@@ -2652,7 +2744,7 @@ EOF
local exempt_ports="${ssh_ports}"
[[ -n "${panel_port}" ]] && exempt_ports="${exempt_ports},${panel_port}"
- cat << EOF > /etc/fail2ban/action.d/3x-ipl.conf
+ cat << EOF > /etc/fail2ban/action.d/3x-ipl.conf || return 1
[INCLUDES]
before = iptables-allports.conf
@@ -2690,11 +2782,20 @@ iplimit_remove_conflicts() {
/etc/fail2ban/jail.local
)
+ local file temp
for file in "${jail_files[@]}"; do
- # Check for [3x-ipl] config in jail file then remove it
- if test -f "${file}" && grep -qw '3x-ipl' ${file}; then
- sed -i "/\[3x-ipl\]/,/^$/d" ${file}
- echo -e "${yellow}Removing conflicts of [3x-ipl] in jail (${file})!${plain}\n"
+ [[ -f "$file" ]] && grep -Eq '^[[:space:]]*\[3x-ipl\]' "$file" || continue
+ if [[ -L "$file" ]]; then
+ file=$(readlink -f -- "$file") || return 1
+ fi
+ temp=$(mktemp "${file}.XXXXXX") || return 1
+ if ! {
+ cp -p -- "$file" "$temp" &&
+ awk '/^[[:space:]]*\[/ { managed = ($0 ~ /^[[:space:]]*\[3x-ipl\]/) } !managed' "$file" > "$temp" &&
+ mv -f -- "$temp" "$file"
+ }; then
+ rm -f -- "$temp"
+ return 1
fi
done
}
@@ -3761,7 +3862,7 @@ if [[ $# -gt 0 ]]; then
check_install 0 && show_banlog 0
;;
"setup-fail2ban")
- setup_fail2ban_iplimit
+ setup_fail2ban_for_lifecycle "${2:-update}"
;;
"update")
check_install 0 && update 0