FIREWALL·SSH ufw · nft · openssh

ubuntu LTS · ufw · nftables · openssh

Firewall & SSH,
the door and the key.

Close every port you do not need, then let yourself in without a password. One page of ufw, nftables, iptables, firewalld, keys, sshd hardening, and tunnels — plus the four mistakes that lock you out of your own box. Click any line to copy it.

65 commands 9 sections 4 traps press / to filter
drag · rotate fig.01 — shield, packets turned away

Command index

click to copy · filtered live
01

UFW

·
  • $ sudo ufw status verbose Rules in order, plus default policy and logging level. Read this first.
  • $ sudo ufw default deny incoming Anything not explicitly allowed is dropped. The sane starting point.
  • $ sudo ufw default allow outgoing Outbound stays open, so apt, DNS and updates keep working.
  • $ sudo ufw allow 22/tcp Open SSH first. Enabling with no SSH rule ends your session.
  • $ sudo ufw allow from 10.0.0.0/24 to any port 5432 Postgres reachable from the LAN only — not from the internet.
  • $ sudo ufw limit 22/tcp Allow SSH but throttle repeat connections: a cheap brute-force brake.
  • $ sudo ufw app list Named profiles like Nginx Full and OpenSSH that expand to ports.
  • $ sudo ufw delete allow 80/tcp Delete by the exact rule text status prints.
  • $ sudo ufw enable Turn it on and persist across reboots; --dry-run previews.
02

nftables

·
  • $ sudo nft list ruleset The whole live ruleset — tables, chains, rules. Read this before editing.
  • $ sudo nft add table inet filter inet covers IPv4 and IPv6 in one table. No separate ip6 rules.
  • $ sudo nft add chain inet filter input '{ type filter hook input priority 0; policy drop; }' Base chain on the input hook, default policy drop. Quote the spec.
  • $ sudo nft add rule inet filter input ct state established,related accept Let replies to your own connections back in. Without this line, nothing works.
  • $ sudo nft add rule inet filter input tcp dport 22 accept Allow SSH. Rules are evaluated top to bottom; order is the logic.
  • $ sudo nft add rule inet filter input iifname lo accept Loopback. Local services talk to each other over it and expect it open.
  • $ sudo nft add rule inet filter input tcp dport { 80, 443 } accept Set syntax: one rule, two ports, instead of repeating the line.
  • $ sudo nft -f /etc/nftables.conf Load a ruleset from file. That file — not your typed rules — is what boots.
  • $ sudo nft delete table inet filter Wipe every chain and rule in the table. No confirmation prompt.
03

iptables

·
  • $ sudo iptables -L -n -v --line-numbers Rules with packet counters and line numbers. Read before you change anything.
  • $ sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT Append to the end of INPUT. -I inserts at the top instead.
  • $ sudo iptables -I INPUT 1 -s 10.0.0.0/24 --dport 5432 -j ACCEPT Insert as rule 1, reachable from the LAN only — not the internet.
  • $ sudo iptables -P INPUT DROP Default policy. Set it last, after the rules that keep you connected.
  • $ sudo iptables -D INPUT -p tcp --dport 80 -j ACCEPT Delete by repeating the rule exactly, or by number: -D INPUT 3.
  • $ sudo iptables-save > /etc/iptables/rules.v4 Persist. iptables forgets every rule at reboot unless this file is loaded.
  • $ sudo iptables -F Flush all rules in the table. The policy still applies — and may still drop you.
04

firewalld

·
  • $ sudo firewall-cmd --state Running or not. The default on RHEL, Fedora, Alma, Rocky; Ubuntu uses ufw.
  • $ sudo firewall-cmd --get-active-zones Which zone each interface is in. Every zone is a different trust level.
  • $ sudo firewall-cmd --add-service=ssh --permanent Open SSH in the default zone and write it to disk.
  • $ sudo firewall-cmd --add-port=8080/tcp --permanent For a port no service definition covers. Services are the tidier habit.
  • $ sudo firewall-cmd --reload Apply permanent changes. Without it you only edited the runtime copy.
  • $ sudo firewall-cmd --list-all Default zone in full: services, ports, rich rules, masquerade, forwards.
  • $ sudo firewall-cmd --remove-service=http --permanent Close it again, then --reload — or nothing changed.
05

Ports & Listeners

·
  • $ ss -tulpn Every listening TCP/UDP socket with the process that owns it. Start here.
  • $ sudo ss -tulpn 'sport = :22' Is 22 on 0.0.0.0 or only 127.0.0.1? The address decides who can reach it.
  • $ sudo lsof -i :8080 The process behind one port, when ss is not installed.
  • $ sudo fuser -k 8080/tcp Kill whatever holds the port. Blunt — and it clears a stuck dev server.
  • $ nc -zv host 443 Is the port reachable from here? Three-second answer, no browser.
  • $ curl -sS -o /dev/null -w '%{http_code}' localhost:8080 Status code only. Proves the app answers locally, before you blame the firewall.
  • $ sudo ufw status numbered Rules with indexes, so ufw delete 3 is unambiguous.
06

SSH Keys

·
  • $ ssh-keygen -t ed25519 -C "you@laptop" Ed25519: short, fast, and the current default. Use RSA 4096 only for old servers.
  • $ ssh-copy-id -i ~/.ssh/id_ed25519.pub deploy@host Installs the public key in authorized_keys with correct modes for you.
  • $ ssh -i ~/.ssh/id_ed25519 deploy@host Pick the key explicitly; add -v when it is refused and you need the reason.
  • $ ssh-add ~/.ssh/id_ed25519 Load into the agent, so the passphrase is asked once per session.
  • $ ssh-keygen -lf ~/.ssh/id_ed25519.pub Fingerprint and bit length — compare it against what the server reports.
  • $ ssh-keygen -R host Drop a changed host key from known_hosts after a rebuild.
  • $ ssh-keygen -p -f ~/.ssh/id_ed25519 Change or add a passphrase without regenerating the key.
  • $ chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys sshd silently ignores keys with looser modes. This is the usual culprit.
07

sshd Hardening

·
  • $ sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak Back it up first. You will want it from the provider console.
  • $ sudo sshd -t Validate the config before reloading. A typo here locks everyone out.
  • $ sudo sshd -T | grep -Ei 'password|permitroot|pubkey' The effective values after includes and defaults — not what the file says.
  • $ sudo sed -i 's/^#*PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config Keys only. Prove a key login in a second session before closing this one.
  • $ sudo sed -i 's/^#*PermitRootLogin.*/PermitRootLogin prohibit-password/' /etc/ssh/sshd_config Root by key only — or no, and use sudo from a normal account.
  • $ sudo grep -Ei '^(AllowUsers|AllowGroups)' /etc/ssh/sshd_config Whitelist who may log in at all. No output means everyone may.
  • $ sudo systemctl reload ssh Reload keeps existing sessions alive; restart drops them.
  • $ sudo fail2ban-client status sshd Bans after repeated failures, with the current ban list.
  • $ sudo journalctl -u ssh -n 50 --no-pager Who tried, from where, and why the last login was refused.
08

Tunnels & Transfer

·
  • $ ssh -L 5432:localhost:5432 deploy@host Local forward: your localhost:5432 becomes the server's. Keeps a database off the internet.
  • $ ssh -R 8080:localhost:3000 deploy@host Remote forward: the server's port 8080 reaches the dev server on your laptop.
  • $ ssh -D 1080 deploy@host SOCKS proxy on 1080. Point the browser at it for a full tunnel.
  • $ ssh -N -f -L 8080:localhost:80 deploy@host -N runs no command, -f forks into the background.
  • $ ssh -J bastion deploy@10.0.0.5 Jump host in one step, no ProxyCommand line to remember.
  • $ scp -P 2222 file.tar deploy@host:/srv/ Capital -P is the port. Lowercase -p preserves timestamps.
  • $ rsync -avz --delete dist/ deploy@host:/srv/app/ Incremental and resumable. The trailing slash means "contents", not the folder.
  • $ sftp deploy@host Interactive get/put when rsync flags are not worth the thought.
  • $ autossh -M 0 -N -L 8080:localhost:80 deploy@host Reconnects the tunnel when the link drops. Plain ssh does not.
09

ssh config

·
# ~/.ssh/config
Host prod
  HostName 203.0.113.10
  User deploy
  IdentityFile ~/.ssh/id_ed25519
  IdentitiesOnly yes
  ServerAliveInterval 30

Host db
  HostName 10.0.0.5
  User deploy
  ProxyJump prod
  LocalForward 5432 localhost:5432

Host *
  AddKeysToAgent yes
  HashKnownHosts yes
  • $ ssh prod All of the above in two words: host, user, key, keepalive.
  • $ ssh -G prod The config as ssh resolves it, defaults included. Use it to debug overrides.
  • $ chmod 600 ~/.ssh/config ssh ignores a config anyone else can read — silently.

Traps

the four that lock you out
T1

ufw enable, before port 22

Default-deny plus no SSH rule equals a closed door and no key. Run sudo ufw allow 22/tcp first, and check with ufw show added — then enable. Console access is the only way back.

T2

iptables without a save

Every rule lives in memory. Reboot and the box comes up wide open — or, if the policy was saved without the allow rules, not at all. Persist with iptables-save, or move to nftables and load a file.

T3

PasswordAuthentication no, untested

Turning off passwords before confirming a key login ends your session and your access. Open a second terminal, log in with the key, keep it open, and only then reload sshd.

T4

chmod -R 777 ~/.ssh

sshd refuses keys when ~/.ssh or authorized_keys is group- or world-writable, and logs nothing useful about it. Correct modes are 700 on the directory, 600 on the files.

✓