Persist firewall rules across VM reboots: re-apply iptables on startup and after SSH reconnect, checking current state to avoid duplicates
This commit is contained in:
1 parent
2d8728edc8
commit
e18395e710
2 files changed
+118
No files matched your search
@@ -380,6 +380,21 @@ def create_app(settings_path=None):
|
||||
except Exception as e:
|
||||
logging.debug(f"Could not initialize SSL cert monitor: {e}")
|
||||
|
||||
# Re-apply firewall rules on startup (restores iptables after VM reboot)
|
||||
try:
|
||||
admin_svc = services.get('admin')
|
||||
k8s_svc = services.get('k8s')
|
||||
if admin_svc and settings.get('firewall'):
|
||||
success, applied, skipped, err = admin_svc.reapply_firewall_rules(settings, k8s_svc)
|
||||
if applied:
|
||||
logging.info(f"Firewall: re-applied rules for ports {applied}")
|
||||
if skipped:
|
||||
logging.info(f"Firewall: skipped {len(skipped)} ports ({', '.join(skipped)})")
|
||||
if err:
|
||||
logging.warning(f"Firewall: reapply error: {err}")
|
||||
except Exception as e:
|
||||
logging.debug(f"Could not reapply firewall rules on startup: {e}")
|
||||
|
||||
# Start connection monitor for auto-reconnection on server restart/VM reboot
|
||||
try:
|
||||
def _connection_monitor():
|
||||
@@ -388,6 +403,7 @@ def create_app(settings_path=None):
|
||||
check_interval = 60 # Check every 60 seconds
|
||||
consecutive_failures = 0
|
||||
max_consecutive_failures = 5
|
||||
last_ssh_ok = True # Track SSH state to detect reconnection
|
||||
|
||||
while True:
|
||||
time.sleep(check_interval)
|
||||
@@ -413,6 +429,20 @@ def create_app(settings_path=None):
|
||||
|
||||
if ssh_ok and db_ok:
|
||||
consecutive_failures = 0
|
||||
# Re-apply firewall rules after SSH reconnection (VM reboot recovery)
|
||||
if not last_ssh_ok:
|
||||
try:
|
||||
admin_svc = services.get('admin')
|
||||
k8s_svc = services.get('k8s')
|
||||
if admin_svc and settings.get('firewall'):
|
||||
success, applied, skipped, err = admin_svc.reapply_firewall_rules(settings, k8s_svc)
|
||||
if applied:
|
||||
logging.info(f"Firewall: re-applied rules after reconnect for ports {applied}")
|
||||
if skipped:
|
||||
logging.info(f"Firewall: skipped {len(skipped)} ports after reconnect")
|
||||
except Exception as e:
|
||||
logging.debug(f"Firewall: reapply after reconnect failed: {e}")
|
||||
last_ssh_ok = True
|
||||
logging.debug("Connection monitor: All services healthy")
|
||||
else:
|
||||
consecutive_failures += 1
|
||||
@@ -425,6 +455,7 @@ def create_app(settings_path=None):
|
||||
logging.info("Connection monitor: SSH connection reset, will reconnect on next request")
|
||||
except Exception:
|
||||
pass
|
||||
last_ssh_ok = False
|
||||
|
||||
# Reset database pool if multiple consecutive failures
|
||||
if not db_ok and db_svc and consecutive_failures >= 3:
|
||||
|
||||
@@ -429,6 +429,93 @@ class AdminService:
|
||||
cur.close()
|
||||
self.db.return_connection(conn)
|
||||
|
||||
def reapply_firewall_rules(self, settings, k8s_service):
|
||||
"""Re-apply iptables firewall rules based on settings after VM reboot.
|
||||
Checks current iptables state first to avoid duplicate rules.
|
||||
Returns (success, applied_ports, skipped_ports, error).
|
||||
"""
|
||||
firewall_cfg = settings.get('firewall', {})
|
||||
if not firewall_cfg:
|
||||
return True, [], [], None
|
||||
|
||||
# Resolve BGD NodePort
|
||||
bgd_port = None
|
||||
try:
|
||||
ns = settings.get('kubernetes', {}).get('namespace', '')
|
||||
if ns and k8s_service:
|
||||
out, _, rc = k8s_service.run(f'get svc -n {ns} -o wide')
|
||||
if rc == 0 and out:
|
||||
for line in out.split('\n'):
|
||||
if '-bgd-svc' in line and 'NodePort' in line:
|
||||
parts = line.split()
|
||||
for p in parts:
|
||||
if ':' in p and p[0].isdigit():
|
||||
port_str = p.split(':')[1].split('/')[0]
|
||||
bgd_port = int(port_str)
|
||||
break
|
||||
except Exception as e:
|
||||
logger.warning(f"Firewall reapply: failed to resolve BGD NodePort: {e}")
|
||||
|
||||
# Build port map: port -> (setting_key, should_block)
|
||||
port_map = {}
|
||||
port_map[18888] = ('block_filebrowser', firewall_cfg.get('block_filebrowser', False))
|
||||
if bgd_port:
|
||||
port_map[bgd_port] = ('block_director', firewall_cfg.get('block_director', False))
|
||||
|
||||
# Check current iptables state
|
||||
active_ports = [str(p) for p in port_map.keys()]
|
||||
all_ports_re = '|'.join(active_ports) if active_ports else 'NONE'
|
||||
try:
|
||||
out, _, _ = self.ssh.run(
|
||||
f'sudo iptables -L INPUT -n 2>/dev/null | grep -E "dpt:({all_ports_re})"; '
|
||||
f'sudo iptables -L FORWARD -n 2>/dev/null | grep -E "dpt:({all_ports_re})"; '
|
||||
f'sudo iptables -t mangle -L PREROUTING -n 2>/dev/null | grep -E "dpt:({all_ports_re})"',
|
||||
timeout=15
|
||||
)
|
||||
except Exception as e:
|
||||
return False, [], [], f"SSH command failed: {e}"
|
||||
|
||||
blocked_ports = set()
|
||||
for line in out.split('\n'):
|
||||
for port_str in active_ports:
|
||||
if f'dpt:{port_str}' in line and 'DROP' in line:
|
||||
blocked_ports.add(int(port_str))
|
||||
|
||||
# Apply rules for ports that should be blocked but aren't
|
||||
applied = []
|
||||
skipped = []
|
||||
for port, (key, should_block) in port_map.items():
|
||||
if not should_block:
|
||||
skipped.append(f"{port} (setting=False)")
|
||||
continue
|
||||
if port in blocked_ports:
|
||||
skipped.append(f"{port} (already blocked)")
|
||||
continue
|
||||
|
||||
cmd = (
|
||||
f'sudo iptables -I INPUT 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && '
|
||||
f'sudo iptables -I INPUT 2 -p tcp --dport {port} -j DROP && '
|
||||
f'sudo iptables -I FORWARD 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && '
|
||||
f'sudo iptables -I FORWARD 2 -p tcp --dport {port} -j DROP && '
|
||||
f'sudo iptables -t mangle -I PREROUTING 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && '
|
||||
f'sudo iptables -t mangle -I PREROUTING 2 -p tcp --dport {port} -j DROP'
|
||||
)
|
||||
try:
|
||||
out, err, rc = self.ssh.run(cmd, timeout=20)
|
||||
if rc != 0 and 'already exists' not in (out + err):
|
||||
logger.warning(f"Firewall reapply: failed to block port {port}: {err}")
|
||||
skipped.append(f"{port} (failed: {err.strip()})")
|
||||
else:
|
||||
applied.append(port)
|
||||
logger.info(f"Firewall reapply: blocked port {port}")
|
||||
except Exception as e:
|
||||
logger.warning(f"Firewall reapply: SSH error for port {port}: {e}")
|
||||
skipped.append(f"{port} (SSH error: {e})")
|
||||
|
||||
if applied:
|
||||
logger.info(f"Firewall reapply: applied rules for ports {applied}")
|
||||
return True, applied, skipped, None
|
||||
|
||||
def edit_faction(self, player_controller_id, faction_id):
|
||||
if player_controller_id is None or faction_id is None:
|
||||
return False, "Missing parameters"
|
||||
|
||||
Reference in new issue
Block a user