"Connection refused" on SSH right after adding your key: fail2ban did it
You add your SSH key, get "Permission denied", retry a few times, and then the server answers "Connection refused". Here is why fail2ban and ufw lock you out, and how to get back in safely.

You add your public key to the server, try to log in, and get Permission denied (publickey). You change something small, try again, and again. Then the error changes to ssh: connect to host ... port 22: Connection refused. That SSH connection refused message rarely means the server is down. Most of the time, your own security setup has banned you.
I have done this to myself on a fresh VPS, and I have seen it in other people's setups too. Once you understand the sequence, it takes five minutes to fix and you will not repeat it.
What happened: from "Permission denied" to SSH connection refused
The pattern is almost always the same:
- You set up the key, but something is slightly wrong. The wrong user, the wrong key file, bad permissions on
~/.ssh/authorized_keys, or root login already disabled. - SSH answers
Permission denied (publickey). The server is reachable and the SSH daemon is working. It just rejected your credentials. - You retry several times in a minute or two. Each attempt is logged as a failure in
/var/log/auth.log. - fail2ban reads that log, counts the failures from your IP, and adds a firewall rule that rejects your IP. Now the TCP connection itself is refused, so you never reach SSH at all.
The difference between the two errors matters. "Permission denied" means you reached SSH and authentication failed. "Connection refused" means something stopped you before SSH. If you were connecting fine a minute earlier, the obvious suspect is a ban, not a crashed service.
Depending on how the ban action is set up, you might see a timeout instead of "refused". The cause is the same.
Why fail2ban and ufw both treat you as an attacker
Two separate tools can produce this lockout, and on many servers both are active.
fail2ban watches log files for failure patterns. Its sshd jail matches failed logins and connections that close during authentication. When an IP reaches maxretry failures within findtime, it is banned for bantime. The defaults ship in /etc/fail2ban/jail.conf, and many setups override them in jail.local, so check your own values. fail2ban cannot tell your laptop apart from a bot in another country. A failure is a failure.
A detail that catches people: your SSH agent may offer several keys one after another. Each rejected key moves you closer to the server's MaxAuthTries limit, and the disconnect that follows is logged as a failure. One command can therefore count for more than you expect.
ufw rate limiting is the second source. If you set up the firewall with ufw limit ssh or ufw limit 22/tcp, ufw rejects an IP that opens too many connections in a short window, roughly six within 30 seconds. This does not need a failed login. Quick retries, a deploy script that opens a new connection for every command, or scp running in a loop can all trigger it. The good news is that this block clears by itself after a short wait.
I covered setting up both tools in Securing a new VPS: SSH keys, firewall and fail2ban without locking yourself out. This article is the recovery side of that setup.
Get back in and unban your IP with fail2ban-client
First, find a way into the server that does not come from the banned IP. You have a few options:
- Your host's web console. On my Hostinger VPS, hPanel has a browser terminal that works even when SSH from my laptop is blocked.
- A different network, such as a mobile hotspot, which gives you a different public IP.
- Waiting for the ban to expire, if
bantimeis short.
Next, find the public IP you were connecting from. Run this on your laptop:
curl -s https://ifconfig.me
Then check fail2ban on the server:
sudo fail2ban-client status
sudo fail2ban-client status sshd
The second command lists the currently banned IPs for the sshd jail. If yours is in the list, unban it:
sudo fail2ban-client set sshd unbanip 203.0.113.10
To see why you were banned, look at the logs:
sudo tail -n 50 /var/log/fail2ban.log
sudo grep sshd /var/log/auth.log | tail -n 30
If fail2ban does not list your IP, check ufw instead:
sudo ufw status numbered
A rule showing LIMIT on port 22 means rate limiting is active. Wait about 30 seconds and try again. Keep the limit if you want it, but space out your connections. That is what multiplexing below is for.
If you work from a fixed IP, you can tell fail2ban to ignore it. Create or edit /etc/fail2ban/jail.local:
[DEFAULT]
ignoreip = 127.0.0.1/8 ::1 203.0.113.10
[sshd]
enabled = true
Then reload with sudo systemctl reload fail2ban. Be careful here. Home and office IPs often change, and whitelisting a shared network means anyone else on it is whitelisted too.
Fix the real cause on your machine first
Unbanning without fixing the cause just resets the counter. Find out why the key was rejected:
ssh -v your-user@203.0.113.10
Read the output for the lines that say which keys were offered and which was rejected. The usual causes:
- Wrong user. The key is in
/home/your-user/.ssh/authorized_keys, but you are connecting as root. - Too many keys in the agent. The right key is offered after several wrong ones.
- Permissions.
~/.sshshould be700andauthorized_keysshould be600, both owned by the user.
Fix the permissions on the server like this:
chmod 700 /home/your-user/.ssh
chmod 600 /home/your-user/.ssh/authorized_keys
chown -R your-user:your-user /home/your-user/.ssh
Then make your client offer only the right key, using the config in the next section.
Stop logging in ten times: SSH connection multiplexing
Most lockouts I have seen came from many short connections, not from one bad password. Every ssh, scp, rsync or deploy step opens a new connection and authenticates again. Connection multiplexing lets these reuse one authenticated connection.
Add this to ~/.ssh/config on your laptop:
Host myvps
HostName 203.0.113.10
User your-user
IdentityFile ~/.ssh/id_ed25519
IdentitiesOnly yes
ControlMaster auto
ControlPath ~/.ssh/cm-%r@%h:%p
ControlPersist 10m
Now ssh myvps authenticates once. Any scp or rsync to myvps in the next ten minutes rides on the same connection, with no new login and nothing new for fail2ban or ufw to count. IdentitiesOnly yes stops the agent from offering every key you own.
Two useful commands:
ssh -O check myvps # is a master connection running?
ssh -O exit myvps # close it
One note: multiplexing works on macOS, Linux and WSL. The native Windows OpenSSH client has limited support for it, so use WSL there if you rely on it. If you run deploys like the one in Deploy a Node.js app on a VPS with PM2 and Nginx, this one change removes most accidental rate-limit hits.
Lock it down properly: PermitRootLogin and AllowUsers
The fix is not to weaken fail2ban. It is to make the allowed path clear and everything else fail. On Ubuntu 22.04, create a drop-in file such as /etc/ssh/sshd_config.d/10-hardening.conf:
PermitRootLogin no
PasswordAuthentication no
AllowUsers your-user
PermitRootLogin no blocks direct root logins. AllowUsers means only that account can log in at all. The file starts with 10- on purpose. sshd uses the first value it reads for each setting, and files in this folder load in alphabetical order. A file like 50-cloud-init.conf that sets PasswordAuthentication yes would otherwise win.
Test the config before reloading, and keep your current session open:
sudo sshd -t
sudo systemctl reload ssh
Then open a new terminal and confirm you can still log in. Only close the old session once the new one works.
Remember what this means in practice. After this change, typing ssh root@... out of habit produces exactly the failures that get you banned. Put the right user in ~/.ssh/config and the habit stops mattering.
FAQ
How do I unban my IP in fail2ban?
Get in through a console or another network. Then run sudo fail2ban-client status sshd to confirm the ban, and sudo fail2ban-client set sshd unbanip YOUR_IP to remove it.
Why does SSH say connection refused when the server is running?
A firewall rule is rejecting your IP before it reaches SSH. Usually that rule comes from a fail2ban ban or ufw rate limiting. Test from another network to confirm.
How long does a fail2ban lockout last?
As long as bantime in your jail configuration. Check /etc/fail2ban/jail.local and jail.conf, because the value differs between setups.
Should I just disable fail2ban?
No. Fix the client config, use multiplexing, and whitelist a stable IP if you have one. An SSH port exposed to the internet gets probed all the time.
Stuck on a server problem like this one? Talk to the editor at ahmed-adil.com.



