Top Tags

Basic usage of SSH keys import, export, and generate

Basic usage of SSH keys export, and generate

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)

bash
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:

  1. File location (default: ~/.ssh/id_rsa)
  2. Passphrase (optional but recommended for additional security)
bash
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

bash
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)

bash
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:

bash
1# Set correct permissions for private key
2chmod 600 ~/.ssh/id_rsa
3
4# Set correct permissions for public key
5chmod 644 ~/.ssh/id_rsa.pub
6
7# Set correct permissions for authorized_keys
8chmod 600 ~/.ssh/authorized_keys
9
10# Set correct permissions for .ssh directory
11chmod 700 ~/.ssh

Why 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)

bash
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.

bash
1ssh-copy-id -i ~/.ssh/id_ed25519.pub [email protected]

Advantages:

  • Automatically creates .ssh directory if missing
  • Sets correct permissions (700 for directory, 600 for authorized_keys)
  • Prevents duplicate entries
  • Handles edge cases gracefully

Method 3: Copy Specific Key

bash
1ssh-copy-id -i ~/.ssh/id_ed25519_github.pub [email protected]

Method 4: Copy to Non-Standard Port

bash
1ssh-copy-id -i ~/.ssh/id_ed25519.pub -p 2222 [email protected]

Method 5: Manual Multi-Server Deployment

bash
1# Copy to multiple servers
2for server in 192.168.0.13 192.168.0.14 192.168.0.15; do
3 ssh-copy-id -i ~/.ssh/id_ed25519.pub user@$server
4done

Verify Key Installation

bash
1# Test connection without password
2ssh -i ~/.ssh/id_ed25519 [email protected]
3
4# Check authorized_keys on remote server
5ssh [email protected] 'cat ~/.ssh/authorized_keys'

View Your Public Key

bash
1# Display public key content
2cat ~/.ssh/id_rsa.pub
3
4# Copy public key to clipboard (macOS)
5pbcopy < ~/.ssh/id_rsa.pub
6
7# Copy public key to clipboard (Linux with xclip)
8xclip -sel clip < ~/.ssh/id_rsa.pub

Other troubleshooting

SSH Config File for Easy Management

Create ~/.ssh/config to simplify connections:

bash
1# Personal server
2Host homelab
3 HostName 192.168.0.13
4 User admin
5 Port 22
6 IdentityFile ~/.ssh/id_ed25519
7
8# GitHub with specific key
9Host github.com
10 HostName github.com
11 User git
12 IdentityFile ~/.ssh/id_ed25519_github
13
14# Work server with custom settings
15Host work-server
16 HostName server.company.com
17 User developer
18 Port 2222
19 IdentityFile ~/.ssh/id_rsa_work
20 ServerAliveInterval 60
21 ServerAliveCountMax 3

Usage:

bash
1ssh homelab
2# Equivalent to: ssh -i ~/.ssh/id_ed25519 [email protected]

Allow Password authentication

bash
1sudo nano /etc/ssh/sshd_config
2PasswordAuthentication yes
3sudo systemctl restart ssh

or

bash
1PermitRootLogin yes

Security considerations:

  • PasswordAuthentication yes: Enables password login (less secure than keys)
  • PermitRootLogin yes: Allows root login (security risk, use prohibit-password instead)
  • Always restart SSH service after config changes

Recommended secure configuration:

bash
1# Edit SSH config
2sudo nano /etc/ssh/sshd_config
3
4# Recommended settings:
5# PermitRootLogin prohibit-password
6# PasswordAuthentication no
7# PubkeyAuthentication yes
8# ChallengeResponseAuthentication no
9# UsePAM yes
10
11# Restart SSH
12sudo systemctl restart ssh

Disable Password Authentication (Security Hardening)

After setting up key-based authentication:

bash
1# Edit sshd_config
2sudo sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
3sudo sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
4
5# Verify changes
6sudo grep "PasswordAuthentication" /etc/ssh/sshd_config
7
8# Restart SSH service
9sudo systemctl restart ssh
10
11# Verify service status
12sudo systemctl status ssh

Install ssh server

bash
1sudo apt install openssh-server

Complete setup process:

bash
1# Install OpenSSH server
2sudo apt update
3sudo apt install openssh-server -y
4
5# Enable SSH service to start at boot
6sudo systemctl enable ssh
7
8# Start SSH service
9sudo systemctl start ssh
10
11# Check SSH service status
12sudo systemctl status ssh
13
14# Check SSH is listening on port 22
15sudo ss -tulpn | grep :22
16
17# Allow SSH through firewall (UFW)
18sudo ufw allow ssh
19# or specific port
20sudo ufw allow 22/tcp

Change SSH Default Port

For additional security through obscurity:

bash
1# Edit SSH config
2sudo nano /etc/ssh/sshd_config
3
4# Change line:
5# Port 22
6# to:
7# Port 2222
8
9# Restart SSH
10sudo systemctl restart ssh
11
12# Update firewall
13sudo ufw allow 2222/tcp
14sudo ufw delete allow 22/tcp
15
16# Connect with new port
17ssh -p 2222 user@server

Re-generate SSH keys or complete missing keys

bash
1sudo ssh-keygen -A

This 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:

bash
1# Generate specific host key types
2sudo 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 permissions
7sudo chmod 600 /etc/ssh/ssh_host_*_key
8sudo chmod 644 /etc/ssh/ssh_host_*_key.pub
9
10# Restart SSH
11sudo systemctl restart ssh

Advanced Topics

SSH Agent for Key Management

SSH agent stores decrypted private keys in memory:

bash
1# Start SSH agent
2eval "$(ssh-agent -s)"
3
4# Add key to agent
5ssh-add ~/.ssh/id_ed25519
6
7# Add key with specific lifetime (1 hour)
8ssh-add -t 3600 ~/.ssh/id_ed25519
9
10# List loaded keys
11ssh-add -l
12
13# Remove all keys from agent
14ssh-add -D
15
16# Remove specific key
17ssh-add -d ~/.ssh/id_ed25519

SSH Key Forwarding

Allow your local SSH keys to authenticate on remote servers:

bash
1# Connect with agent forwarding
3
4# Or configure in ~/.ssh/config
5Host jumphost
6 HostName jump.example.com
7 ForwardAgent yes

Security warning: Only use agent forwarding on trusted servers.

Convert SSH Key Formats

bash
1# Convert OpenSSH private key to PEM format
2ssh-keygen -p -m PEM -f ~/.ssh/id_rsa
3
4# Convert public key to different formats
5ssh-keygen -e -f ~/.ssh/id_rsa.pub -m RFC4716 > key.rfc4716
6ssh-keygen -e -f ~/.ssh/id_rsa.pub -m PKCS8 > key.pkcs8
7
8# Extract public key from private key
9ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub

View SSH Key Fingerprints

bash
1# View fingerprint of your public key
2ssh-keygen -lf ~/.ssh/id_ed25519.pub
3
4# View fingerprint with different hash algorithms
5ssh-keygen -lf ~/.ssh/id_ed25519.pub -E sha256
6ssh-keygen -lf ~/.ssh/id_ed25519.pub -E md5
7
8# View all server host keys
9for key in /etc/ssh/ssh_host_*_key.pub; do
10 ssh-keygen -lf "$key"
11done

Backup and Restore SSH Keys

bash
1# Backup your SSH directory
2tar -czf ssh-backup-$(date +%Y%m%d).tar.gz ~/.ssh
3
4# Restore from backup
5tar -xzf ssh-backup-20260114.tar.gz -C ~/
6
7# Secure backup to remote location
8rsync -avz --chmod=700 ~/.ssh/ user@backup-server:~/ssh-backup/

Troubleshooting SSH Connection Issues

bash
1# Verbose SSH connection (debug level 1)
3
4# Very verbose (debug level 3)
6
7# Test specific key
8ssh -i ~/.ssh/id_ed25519 -v [email protected]
9
10# Check SSH service logs on server
11sudo journalctl -u ssh -f
12sudo tail -f /var/log/auth.log
13
14# Test SSH configuration
15sudo sshd -t

SSH Key Security Best Practices

  1. Always use passphrases for private keys (except automation scenarios)
  2. Use Ed25519 for new keys (or RSA 4096-bit minimum)
  3. Disable password authentication after setting up keys
  4. Regularly rotate keys (annually or after security incidents)
  5. Use different keys for different purposes (work, personal, servers)
  6. Never share private keys or commit them to version control
  7. Implement fail2ban to prevent brute force attacks
  8. Use SSH certificates for large-scale deployments
  9. Monitor authorized_keys files for unauthorized entries
  10. Backup keys securely with encryption

Install and Configure Fail2Ban

Protect against brute force attacks:

bash
1# Install fail2ban
2sudo apt install fail2ban -y
3
4# Create local configuration
5sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
6
7# Edit configuration
8sudo nano /etc/fail2ban/jail.local
9
10# Basic SSH protection settings:
11# [sshd]
12# enabled = true
13# port = 22
14# filter = sshd
15# logpath = /var/log/auth.log
16# maxretry = 3
17# bantime = 3600
18# findtime = 600
19
20# Start and enable fail2ban
21sudo systemctl enable fail2ban
22sudo systemctl start fail2ban
23
24# Check status
25sudo fail2ban-client status sshd
26
27# Unban an IP
28sudo fail2ban-client set sshd unbanip 192.168.0.100

Quick Reference

Common SSH Commands

bash
1# Connect to server
2ssh user@hostname
3
4# Connect with specific key
5ssh -i ~/.ssh/key user@hostname
6
7# Connect with port forwarding (local port 8080 to remote 80)
8ssh -L 8080:localhost:80 user@hostname
9
10# Connect with dynamic port forwarding (SOCKS proxy)
11ssh -D 9090 user@hostname
12
13# Execute remote command
14ssh user@hostname 'ls -la /var/log'
15
16# Copy file to remote (SCP)
17scp file.txt user@hostname:/path/to/destination
18
19# Copy directory recursively
20scp -r directory/ user@hostname:/path/to/destination
21
22# Sync directories (rsync over SSH)
23rsync -avz -e ssh /local/dir/ user@hostname:/remote/dir/