Secure Remote Server Access use SSH Key Authentication
Chen Hao posted on 16 Jan 2025To replace password-based SSH authentication with SSH key authentication, follow these steps:
Understanding SSH Key Authentication
SSH key authentication is a secure method for accessing remote servers without using passwords. Here’s what you need to know:
- Key Pair: SSH uses a public-private key pair for authentication.
- Security: It’s more secure than password-based authentication.
- Convenience: Once set up, it allows for password-less logins.
Setting Up SSH Keys in Your Local Machine
Follow these steps to set up SSH key authentication:
- Generate the key pair on your local machine:
ssh-keygen -t ed25519 -C "your_email@example.com"
- Copy the public key to the server:
ssh-copy-id username@remote_host
- Ensure proper permissions:
chmod 600 ~/.ssh/id_ed25519 chmod 644 ~/.ssh/id_ed25519.pub
Ed25519 vs RSA: Choosing Your Key Type
When generating SSH keys, you’ll encounter different algorithms. Here’s a comparison of Ed25519 and RSA:
Feature | Ed25519 | RSA |
---|---|---|
Security | Higher for equivalent key sizes | Good, but requires larger keys |
Key Size | Smaller (256 bits) | Larger (2048 or 4096 bits) |
Performance | Faster | Slower |
Compatibility | Newer systems | Widely supported |
Ed25519 is recommended for new deployments due to its superior security and performance.
Configuring SSH on the Server
- Create the .ssh directory if it doesn’t exist:
mkdir -p ~/.ssh && chmod 700 ~/.ssh
- Create or edit the authorized_keys file:
nano ~/.ssh/authorized_keys
Paste the public key you copied from your local machine into this file.
- Set the correct permissions:
chmod 600 ~/.ssh/authorized_keys
- Modify the SSH configuration to enable key-based authentication:
sudo nano /etc/ssh/sshd_config
Ensure these lines are set:
PubkeyAuthentication yes PasswordAuthentication no
- Restart the SSH service:
sudo systemctl restart sshd
Conect to Server using SSH Key Authentication
Test the connection:
ssh -i /path/to/your/private_key username@remote_host
Troubleshooting Common SSH Issues
If you encounter issues, try these solutions:
- Permission denied (publickey): Check key permissions and authorized_keys file.
- Too open permissions: Use
chmod 600
for private keys andchmod 644
for public keys. - Invalid format: Ensure you’re using the private key, not the public key (.pub file).