Friday, September 07, 2007

Secure your ssh with PKI

It shocks me how many otherwise intelligent people leave port 22 wide open on their machines. In case you didn't know, this is the default port for ssh -- an widely used method of making connections to a machine from remote locations.

ssh is a wonderful system. The default install on virtually every unix like system out there (including Linux, the various BSDs, and Mac OS X) is inherently insecure, and subject to brute force attacks. We see these on our servers virtually every day. A brute force attack is shockingly simple to implement -- the attacker simply runs a script that tries many, many username/password combinations until they get in. Once they have an account, it's only a hop, skip and jump to root access.

Then bad things happen.

There are a number of ways to make it tougher for attackers, of course. First, configure your firewall to only allow incoming ssh requests from known, safe IP addresses. Additionally, you should implement PKI security on your ssh system. This is, fortunately, very simple to do.
The process is simple:
  1. Generate your public/private key pair
  2. Install the keys on the machines you are going to use to access the server
  3. Modify your ssh server's config file to require known keys
  4. Restart your server
We are going to generate RSA keys for our client. The public key will live on the remote server, and both keys will live on the client machine. For simplicity, we will generate our keys on the server, and then transfer them to our client machine. Log onto the server as the account you want to generate keys for, and then execute these commands:

server$ cd ~
server$ mkdir .ssh
server$ chmod 700 .ssh
server$ ssh-keygen -q -f ~/.ssh/id_rsa -t rsa
Enter passphrase (empty for no passphrase):
Enter same passphrpase again:

Entering a passphrase is optional.... but do it anyway.
Now lock down the file permissions...

chmod go-w ~/.ssh

Now copy the contents of .ssh directory to your client machine. Use a USB key or some other secure method, just to be safe.
Now we need to modify the /etc/ssh/sshd_config file for our ssh server. Mine looks like this:

Protocol 2

HostKey /etc/ssh/ssh_host_rsa_key

SyslogFacility AUTHPRIV

AuthorizedKeysFile .ssh/

HostbasedAuthentication no

PasswordAuthentication no

ChallengeResponseAuthentication no

UsePAM yes

X11Forwarding yes

Subsystem sftp /usr/libexec/openssh/sftp-server

AllowUsers tcs

This is a bare minimum. Note the items in red:
  • your public key must exist in /home/yourhomedirectory/.ssh/
  • ChallengeResponseAuthentication disables simple username/passwords to log on
  • AllowUsers is another safety check -- only users who exist here will be able to log in regardless as to what keys they have.
Now, restart your sshd server, and give it a try.