- Posted on
- • Artificial Intelligence
AI-Based Firewall Rule Generation
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
AI-Based Firewall Rule Generation on Linux: From Plain English to Secure Rules
Tired of alt-tabbing between man pages while trying not to lock yourself out of SSH? Imagine describing the policy you want in plain English—“Allow SSH from the office, drop everything else”—and getting back a vetted set of nftables/iptables/firewalld/ufw commands you can review, test, and apply. That’s the promise of AI-based firewall rule generation: faster iteration, fewer typos, and a safer path from intent to enforcement.
This article covers why the approach is useful, how to set up a minimal AI-assisted workflow on Linux, and 3–5 actionable steps—including concrete examples—to help you try it safely.
Why AI for firewall rules is worth your time
Policy is written by humans, enforced by machines. LLMs are good at translating natural language to structured commands. With careful prompting and output constraints, they can draft rulesets that match your intent.
Reduced toil and fewer footguns. Much of firewall work is repetitive: default-deny, allow SSH, add rate limits, and block known bad IPs. AI can draft these consistently so you can spend time on architecture and verification.
Deterministic verification. Firewalls aren’t magic. You can and should validate proposed commands with dry-runs, syntax checks, and test packets before applying—making AI a low-risk assistant rather than an autonomous agent.
Prerequisites and installation
You’ll need a firewall backend (nftables, iptables, firewalld, or ufw), plus basic CLI tools. Install packages appropriate to your distro. You can install multiple backends, but only enable/use one at a time.
- Debian/Ubuntu (apt):
sudo apt update
sudo apt install -y nftables iptables ufw firewalld jq curl git
- Fedora/RHEL/CentOS Stream (dnf):
sudo dnf install -y nftables iptables ufw firewalld jq curl git
On some RHEL/CentOS variants, ufw may be in EPEL:
sudo dnf install -y epel-release
sudo dnf install -y ufw
- openSUSE/SLE (zypper):
sudo zypper refresh
sudo zypper install -y nftables iptables ufw firewalld jq curl git
Optional (for log-driven examples later):
- Suricata IDS
- apt:
sudo apt install -y suricata - dnf:
sudo dnf install -y suricata - zypper:
sudo zypper install -y suricata
- apt:
To run a local AI model (no cloud required), install Ollama:
curl -fsSL https://ollama.com/install.sh | sh
Then run a model (pick one that fits your system; examples: llama3, mistral, qwen2):
ollama pull llama3
Note:
- Enable only the firewall manager you plan to use (e.g., ufw OR firewalld, not both). For nftables as a base layer, ensure your chosen manager isn’t fighting it.
Step 1 — Decide your backend and guardrails
Before involving AI, decide:
Which backend you’ll use:
- nftables (modern default on many distros)
- iptables (legacy, still common)
- firewalld (daemon/zone abstraction; uses nftables underneath on modern systems)
- ufw (simple interface, Debian/Ubuntu friendly)
Your safety baseline:
- Keep console access or out-of-band management available.
- Pre-allow SSH from your current IP/subnet before testing any default-drop policies.
- Practice with a VM or lab host.
If you choose nftables as your base backend, enable it:
sudo systemctl enable --now nftables
For firewalld:
sudo systemctl enable --now firewalld
For ufw (be careful—this applies rules immediately):
sudo ufw enable
Step 2 — Structure AI outputs so you can validate them
Free-form prose from AI is not what you want feeding a firewall. Force structured JSON with explicit commands, revert steps, and a short rationale. Here’s a small Bash helper that:
Prompts a local LLM via Ollama
Requests JSON-only output
Writes candidate commands to a timestamped script
Gives you hints on how to validate safely
Save this as ai-fw and make it executable.
#!/usr/bin/env bash
set -euo pipefail
# Usage: ai-fw [nftables|iptables|firewalld|ufw] "Describe the policy in plain English"
MODEL="${MODEL:-llama3}"
BACKEND="${1:-nftables}"
shift || true
POLICY="${*:-}"
if [[ -z "${POLICY}" ]]; then
echo "Usage: ai-fw [nftables|iptables|firewalld|ufw] \"Describe the policy in plain English\""
exit 1
fi
read -r -d '' SYS <<'EOS' || true
You are a firewall assistant. Output only compact JSON with this schema:
{
"backend":"nftables|iptables|firewalld|ufw",
"commands":["..."],
"revert":["..."],
"rationale":"..."
}
Constraints:
- Never modify unrelated tables/chains.
- Prefer idempotent commands.
- For nftables: assume table inet filter and chains input/output/forward exist; if not, include the necessary 'add table' and 'add chain' with policies.
- For iptables: use iptables (not iptables-nft) one-liners.
- For firewalld: use firewall-cmd with --permanent and rich-rules where needed.
- For ufw: use explicit 'allow'/'deny' with 'from', 'to', 'proto', 'port'.
- Include safe revert commands that undo the change.
- Do not include commentary.
EOS
PROMPT=$(jq -Rn --arg backend "$BACKEND" --arg policy "$POLICY" '{
role:"user",
content: "Target backend: \($backend)\nPolicy: \($policy)"
} | .content')
# Query local LLM via Ollama and extract the first JSON object
RAW=$(printf "%s\n\n%s\n" "$SYS" "$PROMPT" | ollama run "$MODEL" 2>/dev/null || true)
JSON=$(printf "%s" "$RAW" | sed -n '/{/,/}/p')
if [[ -z "$JSON" ]]; then
echo "No JSON received from model. Raw output:"
printf "%s\n" "$RAW"
exit 2
fi
echo "$JSON" | jq .
echo
FILE="ai-fw-$(date +%Y%m%d-%H%M%S)-$BACKEND.sh"
echo "#!/usr/bin/env bash" > "$FILE"
echo "set -euo pipefail" >> "$FILE"
echo "$JSON" | jq -r '.commands[]' >> "$FILE"
chmod +x "$FILE"
echo "Candidate commands saved to $FILE"
case "$BACKEND" in
nftables)
echo "Syntax check (no apply): sudo nft -c -f <(tail -n +3 $FILE)"
;;
firewalld)
echo "Apply with sudo bash $FILE, then reload: sudo firewall-cmd --reload"
;;
ufw)
echo "Review carefully. On some systems you can test with: sudo ufw --dry-run allow/deny ..."
;;
iptables)
echo "Review carefully. Consider applying in a console session or with a rollback plan."
;;
esac
echo
echo "To revert, run these (generated) commands after review:"
echo "$JSON" | jq -r '.revert[]'
Make it executable:
chmod +x ai-fw
Step 3 — Generate, validate, and apply candidate rules
Example 1: Baseline inbound policy (nftables)
- Goal: Default drop inbound; allow established/related; allow ICMP; allow SSH only from 192.168.1.0/24.
Generate:
./ai-fw nftables "Default drop inbound; allow established/related and icmp; allow ssh from 192.168.1.0/24; drop everything else."
Validate (syntax-only):
sudo nft -c -f <(tail -n +3 $(ls -t ai-fw-nftables*.sh | head -1))
Apply after inspection:
sudo bash $(ls -t ai-fw-nftables*.sh | head -1)
Persist nftables rules by writing your final policy to /etc/nftables.conf:
sudo sh -c 'nft list ruleset > /etc/nftables.conf'
sudo systemctl enable --now nftables
Example 2: Rate-limit SSH with firewalld rich rules
- Goal: Allow SSH but limit new connections to 15/minute.
Generate:
./ai-fw firewalld "On public zone, allow ssh but rate limit to 15 per minute."
Apply and reload:
sudo bash $(ls -t ai-fw-firewalld*.sh | head -1)
sudo firewall-cmd --reload
Example 3: Temporary block a noisy IP with ufw
- Goal: Deny all from 203.0.113.45 for 1 hour (we’ll add and later remove).
Generate:
./ai-fw ufw "Temporarily block all traffic from 203.0.113.45. Also include revert commands."
Review, then:
sudo bash $(ls -t ai-fw-ufw*.sh | head -1)
# ... set yourself a reminder to run the revert commands later
Step 4 — Close the loop with logs (optional)
Turn detections into proposed rules. For instance, tail SSH auth failures and prompt the AI for a short-lived block. Keep a human in the loop.
Auth log to candidate block (illustrative):
journalctl -u ssh -f | \
awk '/Failed password for invalid user|Failed password for/ {print $(NF-2)}' | \
uniq | while read ip; do
./ai-fw nftables "For IP $ip, propose a temporary inbound block with a clean revert. Use inet filter input chain."
done
Better yet, use Suricata alerts as the trigger:
- Install Suricata (see packages above), enable and start it, then parse /var/log/suricata/fast.log to propose targeted blocks or rate limits. Always review before applying.
Step 5 — Practical safety tips
Always pre-allow your current SSH source before enabling default-drop policies.
Validate first:
- nftables:
nft -c -f file(syntax check only) - firewalld: apply with
--permanent, then--reloadand verify with--list-all - ufw: inspect
ufw status numberedbefore/after - iptables: consider applying in a console session and keep revert commands ready
- nftables:
Order matters. Default drop should typically be the last matched policy after explicit allows. For nftables, prefer clear chains and explicit priorities.
Version control your policy. Store the generated script and a human-reviewed ruleset in Git.
Don’t run multiple managers at once. Pick one of nftables directly, firewalld, or ufw for enforcement.
Real-world example prompts you can try
“On nftables, allow outbound DNS/HTTP/HTTPS, allow inbound SSH from 10.0.0.0/24, and drop everything else. Include revert.”
“For firewalld public zone, open 80/tcp and 443/tcp, drop ping, and log dropped inbound to the kernel log. Include revert.”
“With iptables, rate-limit SSH to 10 connections per minute and drop bursts. Include revert.”
Run with the helper, review the JSON, validate, and only then apply.
Conclusion and next steps
AI-based firewall rule generation won’t replace your judgment—but it can dramatically reduce the friction from “security intent” to “auditable, consistent commands.” Start in a lab VM, pick your backend, and use the helper script to generate candidate rules you validate and commit. Then:
Wrap this into a simple internal CLI for your team.
Add CI checks that run
nft -cor firewalld dry-verification on proposed changes.Integrate with logs to propose rules, but keep a manual approval step.
If you found this useful, try the examples on a non-production host today. Refine the prompt to match your environment, and share your lessons learned with your team.