brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ufw enable with the force flag skips the SSH question, so put it last in a script

Ufw
~/tips/tip-ufw-force-enable-scripts

ufw --force enable

Enables the firewall without the interactive question, for setup scripts.

ufw enable over SSH stops and asks whether you really want to, since it may cut your connection. That question breaks automated setups, so there is a flag to skip it.

In a provisioning script it looks like this:

ufw default deny incoming
ufw default allow outgoing
ufw allow OpenSSH
ufw allow proto tcp from any to any port 80,443
ufw --force enable

--force answers the prompt for you. The order is the whole point: the SSH rule goes in before the firewall comes up, so the connection your script is running over survives.

I’d also add a safety net when doing this by hand on a remote box you can’t reach otherwise. Schedule a disable before you enable:

echo 'ufw disable' | sudo at now + 5 minutes
sudo ufw --force enable

If you can still log in, remove the job with atq and atrm. If you locked yourself out, the firewall switches itself off in five minutes. This needs the at package installed.

Watch for a custom SSH port. ufw allow OpenSSH opens port 22 only, so if sshd listens on another port, allow that number instead. Since --force removes the last warning, a wrong port in a script means a server you can only reach through a console.

Further reading: ufw(8) manual page, at(1) manual page

More Ufw tips sudo ufw app update all sudo ufw show raw sudo ufw allow to 10.0.0.1 proto esp sudo ufw allow to 224.0.0.0/24 from 10.0.0.1 proto vrrp sudo ufw show listening All Ufw tips (32) All topics

Link