Basic usage of SSH keys import, export, and generate
SSH (Secure Shell) keys provide a more secure authentication method than passwords for accessing remote systems. They use public-key cryptography, where a key pair consists of a private key (kept secret) and a public key (shared with servers).
Understanding SSH Key Types
Modern SSH supports several key types with different security characteristics:
- RSA: Traditional algorithm, recommended minimum 2048-bit (4096-bit preferred)
- Ed25519: Modern elliptic curve algorithm, faster and more secure with shorter keys
- ECDSA: Elliptic Curve Digital Signature Algorithm, 256/384/521-bit options
- DSA: Legacy algorithm, deprecated and should not be used
Create SSH Keys
RSA Key Generation (4096-bit)
1ssh-keygen -t rsa -b 4096 -C "laptop@vlan1"Parameters explained:
-t rsa: Specifies the RSA algorithm-b 4096: Sets key length to 4096 bits (stronger than default 2048)-C "laptop@vlan1": Adds a comment for identification
Interactive prompts:
- File location (default:
~/.ssh/id_rsa) - Passphrase (optional but recommended for additional security)
Modern Ed25519 Key Generation (Recommended)
1ssh-keygen -t ed25519 -C "laptop@vlan1"Ed25519 offers:
- Stronger security with smaller key size (256-bit)
- Better performance
- Resistance to side-channel attacks
- Generated in milliseconds
Generate Key with Custom Filename
1ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_github -C "github-work"Useful for managing multiple identities (work, personal, different services).
Generate Key Without Passphrase (Automation)
1ssh-keygen -t ed25519 -N "" -f ~/.ssh/id_ed25519_automation -C "automated-deployment"Warning: Use only for automated systems in secure environments. The -N "" flag creates a key without passphrase protection.
Key File Permissions
SSH is strict about file permissions for security:
1# Set correct permissions for private key2chmod 600 ~/.ssh/id_rsa3
4# Set correct permissions for public key5chmod 644 ~/.ssh/id_rsa.pub6
7# Set correct permissions for authorized_keys8chmod 600 ~/.ssh/authorized_keys9
10# Set correct permissions for .ssh directory11chmod 700 ~/.sshWhy these permissions matter:
- Private keys must be readable only by owner (600)
- SSH refuses to use keys with overly permissive settings
- Prevents unauthorized access to your authentication credentials
Export public key to remote server
Method 1: Direct Append (Manual)
1cat ~/.ssh/id_rsa.pub | ssh [email protected] 'cat >> .ssh/authorized_keys'This command streams your public key through SSH and appends it to the authorized_keys file.
Method 2: Using ssh-copy-id (Recommended)
1ssh-copy-id -i ~/.ssh/id_ed25519.pub [email protected]Advantages:
- Automatically creates
.sshdirectory if missing - Sets correct permissions (700 for directory, 600 for authorized_keys)
- Prevents duplicate entries
- Handles edge cases gracefully
Method 3: Copy Specific Key
1ssh-copy-id -i ~/.ssh/id_ed25519_github.pub [email protected]Method 4: Copy to Non-Standard Port
1ssh-copy-id -i ~/.ssh/id_ed25519.pub -p 2222 [email protected]Method 5: Manual Multi-Server Deployment
1# Copy to multiple servers2for server in 192.168.0.13 192.168.0.14 192.168.0.15; do3 ssh-copy-id -i ~/.ssh/id_ed25519.pub user@$server4doneVerify Key Installation
1# Test connection without password2ssh -i ~/.ssh/id_ed25519 [email protected]3
4# Check authorized_keys on remote server5ssh [email protected] 'cat ~/.ssh/authorized_keys'View Your Public Key
1# Display public key content2cat ~/.ssh/id_rsa.pub3
4# Copy public key to clipboard (macOS)5pbcopy < ~/.ssh/id_rsa.pub6
7# Copy public key to clipboard (Linux with xclip)8xclip -sel clip < ~/.ssh/id_rsa.pubOther troubleshooting
SSH Config File for Easy Management
Create ~/.ssh/config to simplify connections:
1# Personal server2Host homelab3 HostName 192.168.0.134 User admin5 Port 226 IdentityFile ~/.ssh/id_ed255197 8# GitHub with specific key9Host github.com10 HostName github.com11 User git12 IdentityFile ~/.ssh/id_ed25519_github13 14# Work server with custom settings15Host work-server16 HostName server.company.com17 User developer18 Port 222219 IdentityFile ~/.ssh/id_rsa_work20 ServerAliveInterval 6021 ServerAliveCountMax 3Usage:
1ssh homelab2# Equivalent to: ssh -i ~/.ssh/id_ed25519 [email protected]Allow Password authentication
1sudo nano /etc/ssh/sshd_config2PasswordAuthentication yes3sudo systemctl restart sshor
1PermitRootLogin yesSecurity considerations:
PasswordAuthentication yes: Enables password login (less secure than keys)PermitRootLogin yes: Allows root login (security risk, useprohibit-passwordinstead)- Always restart SSH service after config changes
Recommended secure configuration:
1# Edit SSH config2sudo nano /etc/ssh/sshd_config3
4# Recommended settings:5# PermitRootLogin prohibit-password6# PasswordAuthentication no7# PubkeyAuthentication yes8# ChallengeResponseAuthentication no9# UsePAM yes10
11# Restart SSH12sudo systemctl restart sshDisable Password Authentication (Security Hardening)
After setting up key-based authentication:
1# Edit sshd_config2sudo sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config3sudo sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config4
5# Verify changes6sudo grep "PasswordAuthentication" /etc/ssh/sshd_config7
8# Restart SSH service9sudo systemctl restart ssh10
11# Verify service status12sudo systemctl status sshInstall ssh server
1sudo apt install openssh-serverComplete setup process:
1# Install OpenSSH server2sudo apt update3sudo apt install openssh-server -y4
5# Enable SSH service to start at boot6sudo systemctl enable ssh7
8# Start SSH service9sudo systemctl start ssh10
11# Check SSH service status12sudo systemctl status ssh13
14# Check SSH is listening on port 2215sudo ss -tulpn | grep :2216
17# Allow SSH through firewall (UFW)18sudo ufw allow ssh19# or specific port20sudo ufw allow 22/tcpChange SSH Default Port
For additional security through obscurity:
1# Edit SSH config2sudo nano /etc/ssh/sshd_config3
4# Change line:5# Port 226# to:7# Port 22228
9# Restart SSH10sudo systemctl restart ssh11
12# Update firewall13sudo ufw allow 2222/tcp14sudo ufw delete allow 22/tcp15
16# Connect with new port17ssh -p 2222 user@serverRe-generate SSH keys or complete missing keys
1sudo ssh-keygen -AThis command regenerates all host keys for the SSH server. Used when:
- Server host keys are missing or corrupted
- After system migration or cloning
- Security incident requires key rotation
What it does:
- Generates missing host keys for all supported types (RSA, ECDSA, Ed25519)
- Skips keys that already exist
- Keys are stored in
/etc/ssh/directory
Manual host key generation:
1# Generate specific host key types2sudo ssh-keygen -t rsa -b 4096 -f /etc/ssh/ssh_host_rsa_key -N ""3sudo ssh-keygen -t ed25519 -f /etc/ssh/ssh_host_ed25519_key -N ""4sudo ssh-keygen -t ecdsa -b 521 -f /etc/ssh/ssh_host_ecdsa_key -N ""5
6# Set correct permissions7sudo chmod 600 /etc/ssh/ssh_host_*_key8sudo chmod 644 /etc/ssh/ssh_host_*_key.pub9
10# Restart SSH11sudo systemctl restart sshAdvanced Topics
SSH Agent for Key Management
SSH agent stores decrypted private keys in memory:
1# Start SSH agent2eval "$(ssh-agent -s)"3
4# Add key to agent5ssh-add ~/.ssh/id_ed255196
7# Add key with specific lifetime (1 hour)8ssh-add -t 3600 ~/.ssh/id_ed255199
10# List loaded keys11ssh-add -l12
13# Remove all keys from agent14ssh-add -D15
16# Remove specific key17ssh-add -d ~/.ssh/id_ed25519SSH Key Forwarding
Allow your local SSH keys to authenticate on remote servers:
1# Connect with agent forwarding2ssh -A [email protected]3
4# Or configure in ~/.ssh/config5Host jumphost6 HostName jump.example.com7 ForwardAgent yesSecurity warning: Only use agent forwarding on trusted servers.
Convert SSH Key Formats
1# Convert OpenSSH private key to PEM format2ssh-keygen -p -m PEM -f ~/.ssh/id_rsa3
4# Convert public key to different formats5ssh-keygen -e -f ~/.ssh/id_rsa.pub -m RFC4716 > key.rfc47166ssh-keygen -e -f ~/.ssh/id_rsa.pub -m PKCS8 > key.pkcs87
8# Extract public key from private key9ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pubView SSH Key Fingerprints
1# View fingerprint of your public key2ssh-keygen -lf ~/.ssh/id_ed25519.pub3
4# View fingerprint with different hash algorithms5ssh-keygen -lf ~/.ssh/id_ed25519.pub -E sha2566ssh-keygen -lf ~/.ssh/id_ed25519.pub -E md57
8# View all server host keys9for key in /etc/ssh/ssh_host_*_key.pub; do10 ssh-keygen -lf "$key"11doneBackup and Restore SSH Keys
1# Backup your SSH directory2tar -czf ssh-backup-$(date +%Y%m%d).tar.gz ~/.ssh3
4# Restore from backup5tar -xzf ssh-backup-20260114.tar.gz -C ~/6
7# Secure backup to remote location8rsync -avz --chmod=700 ~/.ssh/ user@backup-server:~/ssh-backup/Troubleshooting SSH Connection Issues
1# Verbose SSH connection (debug level 1)2ssh -v [email protected]3
4# Very verbose (debug level 3)5ssh -vvv [email protected]6
7# Test specific key8ssh -i ~/.ssh/id_ed25519 -v [email protected]9
10# Check SSH service logs on server11sudo journalctl -u ssh -f12sudo tail -f /var/log/auth.log13
14# Test SSH configuration15sudo sshd -tSSH Key Security Best Practices
- Always use passphrases for private keys (except automation scenarios)
- Use Ed25519 for new keys (or RSA 4096-bit minimum)
- Disable password authentication after setting up keys
- Regularly rotate keys (annually or after security incidents)
- Use different keys for different purposes (work, personal, servers)
- Never share private keys or commit them to version control
- Implement fail2ban to prevent brute force attacks
- Use SSH certificates for large-scale deployments
- Monitor authorized_keys files for unauthorized entries
- Backup keys securely with encryption
Install and Configure Fail2Ban
Protect against brute force attacks:
1# Install fail2ban2sudo apt install fail2ban -y3
4# Create local configuration5sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local6
7# Edit configuration8sudo nano /etc/fail2ban/jail.local9
10# Basic SSH protection settings:11# [sshd]12# enabled = true13# port = 2214# filter = sshd15# logpath = /var/log/auth.log16# maxretry = 317# bantime = 360018# findtime = 60019
20# Start and enable fail2ban21sudo systemctl enable fail2ban22sudo systemctl start fail2ban23
24# Check status25sudo fail2ban-client status sshd26
27# Unban an IP28sudo fail2ban-client set sshd unbanip 192.168.0.100Quick Reference
Common SSH Commands
1# Connect to server2ssh user@hostname3
4# Connect with specific key5ssh -i ~/.ssh/key user@hostname6
7# Connect with port forwarding (local port 8080 to remote 80)8ssh -L 8080:localhost:80 user@hostname9
10# Connect with dynamic port forwarding (SOCKS proxy)11ssh -D 9090 user@hostname12
13# Execute remote command14ssh user@hostname 'ls -la /var/log'15
16# Copy file to remote (SCP)17scp file.txt user@hostname:/path/to/destination18
19# Copy directory recursively20scp -r directory/ user@hostname:/path/to/destination21
22# Sync directories (rsync over SSH)23rsync -avz -e ssh /local/dir/ user@hostname:/remote/dir/