Configure SSH Server to auth with private keys

Auth with ssh-keys provides more security. In config below we enable key auth and disable password auth.

Configuration

To enable SSH auth via private keys, and disable password auth, just create simple sshd_config file.

Note: if you make some misconfiguration you can not connect to your server via SSH so please check all configs.

Note: by default SSH server try to find public keys into /home/$user/.ssh/authorized_keys file. You need to set-up valid permissions to this file.

cat << EOF > /etc/ssh/sshd_config  
X11Forwarding yes    # Enable X11 Forwarding  
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES  
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE  
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT  
AcceptEnv XMODIFIERS  
ChallengeResponseAuthentication no  
GSSAPIAuthentication no  
HostbasedAuthentication no  
RhostsRSAAuthentication no  
PubkeyAuthentication yes  
PasswordAuthentication no  
RSAAuthentication yes  
IgnoreRhosts yes  
PermitEmptyPasswords no  
PermitRootLogin no  
LogLevel INFO  
Port 22  
PrintLastLog yes  
PrintMotd yes  
Protocol 2  
StrictModes yes  
Subsystem sftp /usr/libexec/openssh/sftp-server  
SyslogFacility AUTHPRIV  
TCPKeepAlive yes  
UsePAM no  
EOF  

Now you need logon with your user and create authorized_keys file.

su user  
mkdir .ssh && touch .ssh/authorized_keys  
chmod 0700 .ssh  
chmod 0600 .ssh/authorized_keys  

Generate and add your ssh-key

Also you need to generate private and public keys for yours user. Do not forget to copy public key to server!

ssh-keygen -b 2048 -C "comment" -f .ssh/myserver  
cat .ssh/myserver.pub | ssh user@example.com "cat >> ~/.ssh/authorized_keys"  

Restart SSH Service

Remember that you can lose access to your server via ssh so I'am strongly recommend to re-check all configs twice!

service sshd restart  

Troubleshooting

If you cant connect to your server via ssh and got error message sshd[27427]: Authentication refused: bad ownership or modes for file /home/$user/.ssh/authorized_keys then you need to re-check permissions to .ssh and .ssh/authorized_keys. Right permissions is 0700 for .ssh and 0600 for .ssh/authorized_keys.

Additional

Some time you will want to connect to some host without ssh keys you can use the fallowing line to make it possible:

ssh -o PreferredAuthentications=keyboard-interactive,password -o PubkeyAuthentication=no host.example.org -l %user%