/보안/Emergency Recovery After ufw enable Drops SSH (Self-Lockout) + Safe Setup
Securityufwssh 끊김 복구

Emergency Recovery After ufw enable Drops SSH (Self-Lockout) + Safe Setup

Can't SSH in after ufw enable? Immediate recovery if the session is still alive, serial-console and rescue-mode recovery on AWS, GCP, and Oracle when fully locked out, plus copy-paste commands for safely allowing port 22, restricting by IP,

Emergency Recovery After ufw enable Drops SSH (Self-Lockout) + Safe Setup

Locked out after ufw enable? Emergency recovery for a locked server + safe setup

Did you just run sudo ufw enable and now the terminal is frozen and you can't reconnect? Don't panic. You can recover in almost every case. Locked out right now? → Jump to "Emergency recovery by scenario" below. Already recovered and want to prevent a repeat? Skip ahead to "A ufw setup that won't lock you out again".

As VPS and cloud self-hosting have become common, the accident that people just starting to run servers hit most often is firewall self-lockout. You flipped on a firewall with the best of intentions—"let's tighten security a bit"—and immediately locked yourself out. This post has two tracks: (1) how to get back into a server that's locked you out right now, and (2) the correct order for enabling ufw so this never happens again.

Why ufw enable kills your SSH — a mental model

ufw (Uncomplicated Firewall) applies its default policy the moment you turn it on. The defaults are:

Bash
# ufw의 기본 정책 (특별히 바꾸지 않았다면 이 상태)
default deny incoming     # 들어오는 연결은 전부 차단
default allow outgoing    # 나가는 연결은 전부 허용

The key is default deny incoming. The instant you run ufw enable, all inbound traffic without an explicit allow rule is blocked. Port 22 (SSH) is no exception. So if you enable without an SSH allow rule, every new SSH connection attempt being blocked is expected behavior.

So why is the "window that's already open" still alive? — golden window

Here's the important point. You just ran enable, but the current terminal hasn't fully died—it looks frozen but is still alive. That's thanks to the Linux kernel's connection tracking (conntrack). ufw's default rules usually include a rule that keeps already-established (ESTABLISHED) connections, so a session that was already connected just before enable can stay up a little longer.

In other words, that still-alive SSH window is your golden window. Don't try to open a new window (it'll be blocked anyway)—add an allow rule immediately in the window that's already open and you're done, with no extra recovery work.

Emergency recovery by scenario

(A) The session is still alive — the best case

If the existing terminal looks frozen but still accepts commands, allow SSH right away.

Bash
# OpenSSH 프로파일로 허용 (가장 권장)
sudo ufw allow OpenSSH

# 또는 포트로 직접 허용
sudo ufw allow 22/tcp

# 적용 확인
sudo ufw status

If you see Status: active and 22/OpenSSH as ALLOW, you're done. Before you close the current window, always verify that you can reconnect from a new terminal. If you can't, go to (B).

(B) Fully locked out — bypass via the cloud console

If SSH is completely dead, get direct OS access through a path that isn't SSH and turn ufw off. Use the table below for each cloud.

CloudRecovery pathNotes
AWS EC2EC2 Serial Console (console → instance → Connect → serial console)Nitro-based instances; IAM/password setup required in advance
GCPSerial Console or SSH-in-browser (console's "Open SSH in browser window")SSH-in-browser often goes through IAP/metadata, so it can work independently of ufw
Oracle CloudConsole Connection (serial console)Create a console connection from the instance menu, then connect over SSH
Generic VPSProvider panel VNC/Web ConsoleSome providers have no console at all, which makes enable order even more important

Once you're in an OS shell via the console, unlocking is a single command.

Bash
# 방화벽을 통째로 비활성화 (긴급 복구용)
sudo ufw disable

Then reconnect over normal SSH and follow the "Safe setup" sequence below: add allow first, then turn it back on.

When you have to boot into rescue / emergency mode

If even console login fails (for example you only use SSH keys and have no console password), boot into the provider's rescue mode (recovery boot). The original disk then attaches at a separate mount point (e.g. /mnt).

Bash
# rescue 환경에서 원래 루트 디스크가 /mnt 에 마운트됐다고 가정
sudo chroot /mnt /bin/bash
ufw disable
exit
# 이후 정상 부팅으로 재기동

(C) You use a non-standard port but only allowed 22

This is the case where you run SSH on a non-standard port like 2222, then casually added only ufw allow 22/tcp and enabled. The daemon is listening on 2222, but the firewall only opened 22. Get in via the console, check the actual port, and allow that port.

Bash
# SSH 데몬이 실제로 어떤 포트를 듣는지 확인
sudo ss -tlnp | grep ssh
grep -i port /etc/ssh/sshd_config

# 실제 포트(예: 2222) 허용
sudo ufw allow 2222/tcp

A ufw setup that won't lock you out again

Once you've recovered, it's time to turn it on properly. The key is order.

⚠️ Never reverse this order ① Allow the SSH port → ② ufw enable Enable first and you're locked out immediately. Especially if you use a non-standard port like 2222, you must allow that port before enable. This one-line order prevents 99% of self-lockouts.

Bash
# ✅ 올바른 순서
sudo ufw allow OpenSSH        # (비표준 포트면) sudo ufw allow 2222/tcp
sudo ufw enable               # 여기서 "기존 SSH 끊길 수 있다"는 경고가 떠도 allow를 넣었으면 안전

Diagnosing and cleaning up rules

Bash
# 규칙을 번호와 함께 보기 (진단의 기본)
sudo ufw status numbered

# 잘못 넣은 규칙은 번호로 삭제 (위에서 확인한 번호 사용)
sudo ufw delete 3

status numbered is the first command to run when rules are tangled. Numbers can change, so always re-check the number with status immediately before deleting.

Hardening — allow only specific IPs + brute-force mitigation

Instead of opening SSH to the world, you can allow only your own IP or mitigate brute-force attacks.

Bash
# 특정 IP에서만 22번 SSH 허용 (사무실/집 고정 IP일 때 강력 추천)
sudo ufw allow from 203.0.113.5 to any port 22 proto tcp

# brute-force 완화: 30초에 6회 이상 연결 시 자동 차단
sudo ufw limit ssh

💡 A note from the field: At first you'll want to lock it down with allow from <my IP>, but if you're on a dynamic IP or ever connect over mobile tethering, you'll lock yourself out again. I always test that the console recovery path actually works before applying IP restrictions. Don't lock down without a safety net. If you don't have a static IP, limit ssh plus key-based auth is already plenty solid.

5-second checklist before enabling ufw

  1. You know the actual SSH port (ss -tlnp | grep ssh)
  2. You allowed that port before enable
  3. You know the console (serial/VNC) recovery path actually works
  4. After enable, you verify reconnect from a new window before closing the current one
  5. You confirm the port is also open in the cloud security group

References: official docs

The primary sources for the behavior, settings, and errors covered in this post are the following official docs. Check them for version-specific options and exact behavior.

FAQ

Q. I published a Docker container port and it's still exposed even though ufw is supposed to block it. Why? A. Docker bypasses ufw and manipulates iptables NAT chains directly. So if you publish a port like -p 0.0.0.0:8080:80, it punches through even with a ufw deny. The fix is ① bind the port locally only, like 127.0.0.1:8080:80, or ② use a tool like chaifeng/ufw-docker to add DOCKER-USER chain rules in /etc/ufw/after.rules so ufw also controls Docker traffic. If "ufw status looks clean but the port is open," Docker is almost always the culprit.

Q. sudo ufw allow ssh fails with something like "could not find a profile". A. allow ssh / allow OpenSSH depend on a name→port mapping. ssh looks up port 22 in /etc/services; OpenSSH looks up the application profile in /etc/ufw/applications.d. If that mapping is missing or broken, the name won't work. The most reliable approach is to specify the port number directly: sudo ufw allow 22/tcp. For a non-standard port, of course use sudo ufw allow 2222/tcp.

Q. I already have a cloud security group. Do I still need ufw? A. They serve different roles. Security groups / network firewalls sit at the cloud layer "outside" the instance; ufw sits at the host layer "inside" the OS. From a defense-in-depth perspective it's good to have both, but that also means the port must be open on both sides for traffic to flow. When SSH fails, check the security group's inbound rules as well as ufw. If only one side is open and the other is blocked, you won't connect.


Firewall accidents are scary, but once you understand the principle, you can prevent them in five seconds. Remember one sentence: "allow first, enable later." If you just recovered, apply the safe-setup commands above as-is and close this out so it never happens again.

확인 정보
✦ ✦ ✦
편집 검토 · Editorial Review

Nodelog는 모든 콘텐츠의 내용과 출처를 공개 전에 검토합니다. 환경(OS·버전)에 따라 결과가 달라질 수 있는 기술 정보는 공식 문서와 함께 확인하며, 검토 기준과 정정 원칙은 편집 정책에서 안내합니다. 오류를 발견하시면 이메일로 제보해 주세요 — 확인 후 신속히 정정합니다.

편집 책임 · Nodelog 기술 편집팀·발행 · ·업데이트 ·

Comments

Be the first to comment.