Sub topic 5
Reading SSH failures: timeouts, refused connections, permission errors
This chapter assumes you can run basic Linux commands and the AWS CLI, and that you know what a security group, a route table, and a key pair are. The earlier chapters in this tutorial covered those pieces. Here you will work backward from an error message to the layer that caused it.
Why the symptom tells you where to look
An SSH connection passes through several layers in a fixed order. A failure at one layer produces a different message than a failure at the next. Reading the message correctly saves you from changing settings that were never the problem.
- Your machine resolves the address and sends a TCP packet to port 22.
- The packet crosses the internet gateway, the route table, the network ACL, and the security group.
- The
sshddaemon on the instance accepts the TCP connection. - SSH exchanges host keys, and your client checks the server identity.
sshdchecks your key against the login user's authorized keys.- A shell starts.
Timeouts: the packet never arrives
A timeout means no answer came back at all. The client prints Connection timed out or Operation timed out, or it just waits. Nothing reached sshd, so changing keys or users will not help. Check these items in order.
- Instance state. The instance must be
running. A stopped instance does not answer. - Public address. From the internet you need a public IPv4 address or an Elastic IP. A public IP changes when you stop and start an instance, so an address you saved earlier may now belong to someone else. Confirm the current one:
aws ec2 describe-instances \
--instance-ids i-0123456789abcdef0 \
--query "Reservations[].Instances[].[State.Name,PublicIpAddress]" \
--output text- Route table. The subnet's route table needs a route for
0.0.0.0/0that targets an internet gateway. A subnet without it is private, whatever the instance's address says. - Security group. The group needs an inbound rule for TCP port 22 that includes your current source address. Home and office addresses change, so a rule that worked last week may now be wrong.
- Network ACL. NACLs are stateless. The subnet's ACL must allow inbound port 22 and also outbound traffic to ephemeral ports (1024-65535), because replies use those ports.
- Your own network. Some corporate and public networks block outbound port 22. Test from another network, such as a phone hotspot, before you blame AWS.
To check what address you are connecting from and what the group allows, run these two commands:
curl -s https://checkip.amazonaws.com
aws ec2 describe-security-groups \
--group-ids sg-0123456789abcdef0 \
--query "SecurityGroups[].IpPermissions"If your address is not covered, add it as a single-host rule:
aws ec2 authorize-security-group-ingress \
--group-id sg-0123456789abcdef0 \
--protocol tcp \
--port 22 \
--cidr 203.0.113.25/32You can also test the port without SSH. The nc command (netcat) tries a TCP connection and reports the result:
nc -vz -w 5 203.0.113.25 22A timeout here confirms a network-layer block. A success message means the network path is fine and the problem is higher up.
Connection refused: the packet arrived and was rejected
ssh: connect to host 203.0.113.25 port 22: Connection refused is a different failure from a timeout. It means a response came back from the instance, and the response said nothing is listening on that port. So the network path works. A refusal usually has one of these causes.
- The instance is still booting. Right after launch,
sshdmay not have started. Wait a minute and retry. Check that both status checks pass:
aws ec2 describe-instance-status \
--instance-ids i-0123456789abcdef0 \
--query "InstanceStatuses[].[InstanceStatus.Status,SystemStatus.Status]" \
--output textsshdis stopped or failed to start. A broken/etc/ssh/sshd_config, a full disk, or a bad user-data script can stop it. Read the boot log without logging in:
aws ec2 get-console-output \
--instance-id i-0123456789abcdef0 \
--latest \
--output textsshdlistens on another port. Some hardened images move SSH to a different port. If so, pass it with-pand make sure the security group allows that port.- A firewall on the instance rejects the port. A host firewall such as
iptablesorfirewalldcan send a reject instead of dropping the packet.
If SSH is broken and you cannot get in to fix it, Session Manager (covered later in this tutorial) is the usual way back in, provided the instance was prepared for it beforehand.
Permission errors: you reached sshd and it said no
When you see Permission denied (publickey), the network, the instance, and sshd are all working. Authentication is what failed. Run the client in verbose mode to see which keys were offered and what the server answered:
ssh -v -i ~/.ssh/my-key.pem [email protected]Look for lines such as Offering public key and Authentications that can continue. Then check the common causes.
| Cause | What you will see | Fix |
|---|---|---|
| Wrong login user | `Permission denied (publickey)` with a valid key | Use the user for the AMI, such as `ec2-user` on Amazon Linux or `ubuntu` on Ubuntu |
| Wrong key pair | The key offered is accepted by no user | Find the key pair name in the instance details and use that private key |
| Key file not passed | `-v` shows only default keys offered | Add `-i path/to/key.pem` or an `IdentityFile` entry |
| Too many keys offered | `Too many authentication failures` | Add `-o IdentitiesOnly=yes` so only the named key is tried |
| Authorized keys damaged on the instance | Correct user and key still fail | Repair `~/.ssh/authorized_keys` and its modes through another access path |
The key pair is fixed when an instance launches. Creating a new key pair in the console later does not change the keys already installed on a running instance.
Key file permissions
If the private key can be read by other users, the client refuses to use it and prints WARNING: UNPROTECTED PRIVATE KEY FILE! followed by Permissions 0644 for 'my-key.pem' are too open. This is a local problem, and it is fixed on your own machine:
chmod 400 ~/.ssh/my-key.pem
ssh -i ~/.ssh/my-key.pem [email protected]If you have saved the settings in ~/.ssh/config, the host entry supplies the user, address, and key together, so a mismatch among them is one fewer thing to get wrong:
Host web1
HostName 203.0.113.25
User ec2-user
IdentityFile ~/.ssh/my-key.pem
IdentitiesOnly yesHost key warnings
If you see WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!, the client remembers a different host key for that address than the one the server now presents. On AWS this is usually harmless. You may have stopped and started an instance, so its public IP now points to a new machine, or you replaced an instance and reused an Elastic IP. The client records host keys in ~/.ssh/known_hosts.
If you know the instance was replaced, remove the stale entry and reconnect:
ssh-keygen -R 203.0.113.25
ssh -i ~/.ssh/my-key.pem [email protected]A repeatable procedure
Work from the outside in, and change one thing at a time.
- Read the exact message and classify it as timeout, refused, permission denied, or local warning.
- For a timeout, confirm the instance state, the current public IP, the route, the security group, the NACL, and your own source address.
- For a refusal, check status checks and the console output, then the port.
- For a permission error, run
ssh -v, then check the user, the key, and the key file mode. - Retest with
nc -vzfor network questions and withssh -vfor authentication questions.
Summary of symptoms
| Symptom | Layer | First check |
|---|---|---|
| Hangs, then times out | Network | Security group source address and route to the internet gateway |
| `Connection refused` | Instance | Status checks, console output, SSH port |
| `Permission denied (publickey)` | Identity | Login user and key pair |
| `UNPROTECTED PRIVATE KEY FILE` | Local file | `chmod 400` on the key |
| `REMOTE HOST IDENTIFICATION HAS CHANGED` | Local trust record | Whether the instance or IP changed |
Exercise
You run ssh -i key.pem [email protected] and the command hangs for about two minutes before printing "Connection timed out". nc -vz -w 5 203.0.113.25 22 also times out. List two causes you would check first, and explain why changing the key or login user will not help.
Show answer
Check the security group for an inbound TCP 22 rule that covers your current public address, and check that the subnet route table has a 0.0.0.0/0 route to an internet gateway. You could also check the instance's current public IP, the network ACL, and whether your own network blocks outbound port 22. Keys and users are used only after the TCP connection is established and the SSH handshake begins. The timeout shows that no packet got through, so authentication is never reached.
Exercise
A teammate gets Permission denied (publickey) on an Ubuntu instance with the correct key file, using ssh -i key.pem [email protected]. What do you tell them, and what command output would confirm it?
Show answer
Tell them to log in as ubuntu, which is the default user for Ubuntu AMIs, not ec2-user. Running ssh -v shows that the key was offered and rejected for the user ec2-user. Connecting with [email protected] should succeed with the same key. Because the error is a permission error and not a timeout or a refusal, the network and sshd are known to be working.