TL;DR
This guide shows you how to set up a secure connection between a client and server using authentication (checking who the user is). We’ll use SSH keys for passwordless login, which is much safer than passwords. This protects your data from being intercepted or misused.
Setting Up Secure Client/Server Connection
- Generate an SSH Key Pair on the Client
- Open a terminal or command prompt on the client machine.
- Type:
ssh-keygen -t rsa -b 4096This creates a new RSA key pair with a key size of 4096 bits (a good level of security).
- You’ll be prompted to enter a file in which to save the key. Press Enter to accept the default location (~/.ssh/id_rsa).
- You’ll then be asked for a passphrase. It is highly recommended you set a strong passphrase, but it’s optional. If you don’t want one, just press Enter twice.
- Copy the Public Key to the Server
- There are several ways to do this. The easiest is often
ssh-copy-id.ssh-copy-id user@server_ip_addressReplace user with your username on the server and server_ip_address with the server’s IP address or hostname. You’ll be prompted for your server password one last time.
- If
ssh-copy-idisn’t available, you can manually copy the key:- Display the public key on the client:
cat ~/.ssh/id_rsa.pub - Copy the entire output of this command.
- Connect to your server using SSH with your password:
ssh user@server_ip_address - Edit the
~/.ssh/authorized_keysfile on the server (create it if it doesn’t exist):nano ~/.ssh/authorized_keys - Paste the public key you copied into this file. Each key should be on a new line.
- Save and close the
authorized_keysfile.
- Display the public key on the client:
- There are several ways to do this. The easiest is often
- Test the Connection
- From the client, try connecting to the server again:
ssh user@server_ip_address - If you set a passphrase, you’ll be prompted for it. If not, you should connect without being asked for a password.
- From the client, try connecting to the server again:
- Disable Password Authentication (Optional but Recommended)
- This significantly improves security by preventing brute-force attacks on your server’s passwords.
sudo nano /etc/ssh/sshd_config - Find the line
PasswordAuthentication yesand change it toPasswordAuthentication no. - Also, ensure that
ChallengeResponseAuthentication nois set. - Save and close the file.
- Restart the SSH service:
sudo systemctl restart sshd(or
sudo service ssh restarton older systems).
- This significantly improves security by preventing brute-force attacks on your server’s passwords.
Important Considerations
- Key Security: Protect your private key (~/.ssh/id_rsa) carefully. Anyone with access to this key can log in as you. Don’t share it!
- Passphrase Strength: If you use a passphrase, make it long and complex.
- Firewall Rules: Ensure your firewall allows SSH connections (typically on port 22).