Problem Statement
Explain SSH key-based authentication and security best practices for SSH configuration. How do you set up and secure SSH access?
Explanation
Generate SSH key pair with ssh-keygen -t rsa -b 4096 -C 'comment' creating private key (~/.ssh/id_rsa) and public key (~/.ssh/id_rsa.pub). Never share private key. Use ed25519 keys for better security with smaller key size: ssh-keygen -t ed25519. Protect private key with passphrase for additional security layer.
Copy public key to remote server with ssh-copy-id user@host or manually append public key to ~/.ssh/authorized_keys on remote server with correct permissions (700 for .ssh directory, 600 for authorized_keys file). Test key authentication: ssh user@host should login without password. If prompted for password, check permissions and sshd_config settings.
Secure SSH configuration in /etc/ssh/sshd_config: disable root login (PermitRootLogin no), disable password authentication (PasswordAuthentication no) after setting up keys, change default port (Port 2222) for security through obscurity, allow specific users (AllowUsers user1 user2), use Protocol 2 only, set LoginGraceTime 30 to prevent connection hanging attacks, limit authentication attempts (MaxAuthTries 3).
Advanced security: use fail2ban to block brute force attempts by banning IPs with multiple failed logins, configure two-factor authentication with Google Authenticator PAM module, use SSH certificates instead of keys for large deployments, implement jump hosts/bastion servers for accessing internal networks, restrict SSH access by IP with firewall rules or TCPWrappers (/etc/hosts.allow, /etc/hosts.deny).
Monitoring and auditing: monitor /var/log/auth.log for failed login attempts and suspicious activity, set up alerts for successful root logins or logins from unexpected IPs, regularly audit authorized_keys files for unauthorized entries, rotate SSH keys periodically, and review SSH configuration with tools like ssh-audit. Apply updates promptly to patch security vulnerabilities. Understanding SSH security is critical for protecting server access.
Practice Sets
This question appears in the following practice sets: