Posted on
Artificial Intelligence

AI-Assisted Firewall Management

Author
  • User
    linuxbash
    Posts by this author
    Posts by this author

AI-Assisted Firewall Management on Linux: From Noisy Logs to Safe, Actionable Rules

If you’ve ever woken up to a pager storm because your VM started dropping SSH or your web app got hammered by a port scan, you know firewall management can be both urgent and tedious. Logs are noisy, policies are nuanced, and “one wrong rule” can lock you out. What if AI could help you summarize the chaos, draft safe rules from plain English, and highlight anomalies—while you stay in control?

This post shows how to pair Linux firewalls (ufw, firewalld, nftables) with lightweight Bash and a local LLM to speed up analysis and policy creation—without handing the keys to a black box.


Why AI-assisted firewalling is worth your time

  • Complexity isn’t going away. Modern stacks mix services, ports, zones, and ephemeral IPs. It’s easy to miss a port or over-open a range.

  • Logs are abundant but hard to digest. AI can summarize patterns across thousands of lines and propose next steps faster than manual grep-wrangling.

  • You stay in the loop. With guardrails like dry runs, syntax checks, and rollback plans, you can safely accept or reject AI suggestions.


Prerequisites and setup (pick one frontend, but you can install multiple)

Only enable one firewall frontend (ufw or firewalld) at a time. nftables is the modern backend most distros use under the hood.

  • Install packages (Debian/Ubuntu with apt):

    • sudo apt update
    • sudo apt install -y ufw firewalld nftables jq fail2ban
  • Install packages (Fedora/RHEL/CentOS with dnf):

    • sudo dnf install -y ufw firewalld nftables jq fail2ban
  • Install packages (openSUSE with zypper):

    • sudo zypper refresh
    • sudo zypper install -y ufw firewalld nftables jq fail2ban
  • Enable your chosen firewall:

    • ufw:
    • sudo ufw logging on
    • sudo ufw default deny incoming
    • sudo ufw allow OpenSSH
    • sudo ufw enable
    • firewalld:
    • sudo systemctl enable --now firewalld
    • sudo firewall-cmd --set-log-denied=all (logs denied packets)
    • sudo firewall-cmd --add-service=ssh --permanent
    • sudo firewall-cmd --reload
    • nftables (if using directly):
    • sudo systemctl enable --now nftables
    • sudo nft list ruleset
  • Optional: local LLM for private, offline assistance (Ollama):

    • curl -fsSL https://ollama.com/install.sh | sh
    • ollama pull llama3
    • Define a helper so you can swap models/APIs later:
    • export LLM_CMD='ollama run llama3'

Note: If you already use a hosted LLM, set LLM_CMD to a wrapper that reads stdin and writes a plain-text response to stdout.


Actionable steps to put AI to work (safely)

1) Turn firewall events into machine-readable data

You can’t summarize what you can’t parse. The goal: extract blocked sources, destination ports, and counts as simple tables the AI (and you) can reason about.

  • UFW log location (Debian/Ubuntu): /var/log/ufw.log. Enable logging if needed:

    • sudo ufw logging on
  • Quick top talkers (UFW):

    • sudo awk '/UFW BLOCK/ {src="";dpt="-"; for (i=1;i<=NF;i++){ if ($i ~ /^SRC=/) src=substr($i,5); if ($i ~ /^DPT=/) dpt=substr($i,5) } if(src!="") print src":"dpt }' /var/log/ufw.log | sort | uniq -c | sort -nr | head
  • Firewalld denied packets (enable denied logging first):

    • sudo firewall-cmd --set-log-denied=all
    • Kernel journal view (last hour):
    • sudo journalctl -k --since "1 hour ago" | awk '/DENIED|REJECT/ {src="";dpt="-"; for (i=1;i<=NF;i++){ if ($i ~ /^SRC=/) src=substr($i,5); if ($i ~ /^DPT=/) dpt=substr($i,5) } if(src!="") print src":"dpt }' | sort | uniq -c | sort -nr | head
  • JSON from journal (useful for richer prompts later):

    • sudo journalctl -k -o json --since "1 hour ago" | jq -r 'select(.MESSAGE|test("UFW BLOCK|DENIED|REJECT")) | .MESSAGE' | head

Outcome: a compact list of sources and ports that trigger blocks, ready for a human or AI to summarize into “what’s happening and what should we do?”

2) Summarize noisy logs with AI to surface what matters

Let the model build an executive summary and a to-do list from your last hour of blocked events.

  • Gather data and prompt the model:
    • BLOCKS=$(sudo awk '/UFW BLOCK/ {src="";dpt="-"; for (i=1;i<=NF;i++){ if ($i ~ /^SRC=/) src=substr($i,5); if ($i ~ /^DPT=/) dpt=substr($i,5) } if(src!="") print src":"dpt }' /var/log/ufw.log | sort | uniq -c | sort -nr | head -n 50)
    • printf '%s\n\n%s\n%s\n' "Summarize firewall blocks:" "$BLOCKS" "Group by intent, identify obvious malicious patterns, and list 3 safe remediation options with pros/cons." | ${LLM_CMD}

What you’ll get: a short, readable summary (e.g., “95% SSH brute-force from 203.0.113.0/24, 22/tcp; sporadic 1433 scans; suggest rate-limiting SSH and temporary CIDR block”). You keep the decision-making, but faster.

3) Draft rules from plain English—then validate before applying

Always validate and review generated rules. Favor nftables checks and firewalld config checks.

  • Example: ask for nftables commands only, then syntax-check:

    • PROMPT="Output only valid nftables commands (no explanations). Goal: allow tcp 443 from 203.0.113.0/24 to 10.0.0.10, drop other inbound except established/related. Use inet table, input chain."
    • RULES=$(printf '%s' "$PROMPT" | ${LLM_CMD} | sed 's/\r$//')
    • printf '%s\n' "$RULES" | sudo nft -c -f - (checks syntax without applying)
    • If clean, apply:
    • printf '%s\n' "$RULES" | sudo nft -f -
    • Save and persist:
    • sudo sh -c 'nft list ruleset > /etc/nftables.conf'
    • sudo systemctl enable --now nftables
  • Firewalld policy from intent (review each command before running):

    • Example intents and corresponding commands:
    • “Open HTTPS permanently” → sudo firewall-cmd --add-service=https --permanent && sudo firewall-cmd --reload
    • “Allow SSH only from 203.0.113.0/24” →
      • sudo firewall-cmd --permanent --new-zone=trusted-ssh
      • sudo firewall-cmd --permanent --zone=trusted-ssh --add-source=203.0.113.0/24
      • sudo firewall-cmd --permanent --zone=trusted-ssh --add-service=ssh
      • sudo firewall-cmd --reload
    • Sanity-check firewalld config:
    • sudo firewall-cmd --check-config
  • UFW policy from intent (manual review recommended):

    • “Allow 80/443, rate-limit SSH, default deny inbound”:
    • sudo ufw default deny incoming
    • sudo ufw allow 80/tcp
    • sudo ufw allow 443/tcp
    • sudo ufw limit 22/tcp

Tip: Keep a “staging” VM to test generated commands before production. For remote hosts, schedule a rollback in case you lock yourself out:

  • echo "sleep 120; ufw delete limit 22/tcp; ufw allow 22/tcp" | at now

4) Detect anomalies and auto-suggest countermeasures

Spot spikes and unusual sources, then get proposed mitigations.

  • Build a quick baseline and compare:
    • BASE=$(sudo awk '/UFW BLOCK/{for(i=1;i<=NF;i++){if($i ~ /^SRC=/) s=substr($i,5)} if(s!="") print s}' /var/log/ufw.log | sort | uniq -c | sort -nr | head -n 100)
    • CURR=$(sudo awk '/UFW BLOCK/{for(i=1;i<=NF;i++){if($i ~ /^SRC=/) s=substr($i,5)} if(s!="") print s}' /var/log/ufw.log | tail -n 1000 | sort | uniq -c | sort -nr | head -n 100)
    • printf '%s\n%s\n\n%s\n%s\n' "BASELINE:" "$BASE" "CURRENT:" "$CURR" | ${LLM_CMD}

Ask the model: “Identify significant deviations and suggest minimally invasive mitigations (rate-limits, temporary /24 blocks, honeypot redirects). Output suggested commands for my chosen tool.”

  • For brute-force SSH: consider fail2ban (AI can propose filters, but you apply and verify):
    • Debian/Ubuntu: sudo apt install -y fail2ban
    • Fedora/RHEL: sudo dnf install -y fail2ban
    • openSUSE: sudo zypper install -y fail2ban
    • Enable:
    • sudo systemctl enable --now fail2ban

Real-world style scenario (putting it together)

Goal: Harden a public VM hosting a web app.

  • Baseline firewall (choose one):

    • ufw:
    • sudo ufw default deny incoming
    • sudo ufw allow 80/tcp
    • sudo ufw allow 443/tcp
    • sudo ufw limit 22/tcp
    • sudo ufw enable
    • firewalld:
    • sudo systemctl enable --now firewalld
    • sudo firewall-cmd --set-log-denied=all
    • sudo firewall-cmd --add-service=http --permanent
    • sudo firewall-cmd --add-service=https --permanent
    • sudo firewall-cmd --add-rich-rule='rule family="ipv4" service name="ssh" limit value="15/m" accept' --permanent
    • sudo firewall-cmd --reload
  • Summarize recent noise and get proposals:

    • BLOCKS=$(sudo awk '/UFW BLOCK/{...}' /var/log/ufw.log | sort | uniq -c | sort -nr | head -n 50) (use the full awk from above)
    • printf '%s\n\n%s\n' "Summarize and propose specific ufw/firewalld/nftables commands (no explanations):" "$BLOCKS" | ${LLM_CMD}
  • Validate and apply cautiously:

    • nftables: printf '%s' "$RULES" | sudo nft -c -f - then sudo nft -f -
    • firewalld: sudo firewall-cmd --check-config then run proposed commands and sudo firewall-cmd --reload
  • Close the loop:

    • sudo ufw status verbose or sudo firewall-cmd --list-all or sudo nft list ruleset

Safety checklist (don’t skip)

  • Don’t enable both ufw and firewalld simultaneously.

  • Always syntax-check before applying (e.g., nft -c -f -, firewall-cmd --check-config).

  • Keep a console session open and a timed rollback ready for remote changes.

  • Log before and after states (e.g., nft list ruleset snapshots).

  • Treat AI output as a draft, not gospel—review every command.


Conclusion and next steps

AI won’t replace your judgment, but it can radically speed up the grunt work: parsing logs, summarizing intent, and drafting rule candidates. Start small—summarize your last hour of blocks, accept one safe recommendation, and validate it end to end. From there, wire the pattern into a weekly report or change workflow.

Try it today: 1) Install your tools (ufw/firewalld/nftables, jq, optional fail2ban + a local LLM). 2) Run the “top talkers” and summary steps. 3) Ask the model to draft minimal rules, then validate and apply safely.

Have a neat prompt, script, or workflow? Share it back with your team—or upstream to your favorite repo—so the next 3 a.m. incident becomes a 10-minute fix.