Thursday, August 27, 2009

SSH in a more secure way

SSH is a wonderful tool, I cann't praise it enough. But as all powerful tools it requires special attention to its use. In this post I want to put good recommendations into action. The guidelines are:

1. No "root" direct access;
2. Only ONE user should have remote access to the system AND "su" rights;
3. All users with full featured shells, except for the one with "su" rights, should NOT have remote access granted (you can always become any user with the access user);
4. All other users that MUST have remote access MUST have restricted shells, like "rbash".

A. The SSH server configuration at: /etc/ssh/sshd_config

(below are the excerpt from the file whose change are recommended)

# This is the default, but it is important to keep it explicit
Port 22
# If you have several interfaces it may be good to force the access to be from a specific network interface/address or mask, this is your server IP address or IP masked range.
# using will NOT grant access to someone addressing your server outside the 192.168.X.X range.
# Enforce the use of ONLY the version 2
Protocol 2
# Turns root remote access off
PermitRootLogin no
# Will log authentication failures when half the amount is tried: it does NOT block access JUST logs failures
MaxAuthTries 4
# If your clients are not behind a proxy it is wise to restrict the amount of open sessions that a single host can make to your machine
MaxSessions 4
# This can be a security issue. Suit yourself (I need it for CruiseControl)
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
# I really like PAM
UsePAM yes
# This can be really annoying if you have several users trying to connect simultaneously, but it helps to prevent brute-force attacks to your server, keep it low.
MaxStartups 2

B. The PAM setup at: /etc/pam.d/sshd

(add the following line)

auth required item=user sense=allow file=/etc/sshd/sshd.allow onerr=fail

This line tells PAM to look for the file /etc/sshd/sshd.allow for the users that are ALLOWED to access your server through SSH. This file should contain only the users that REALLY need direct remote access.

cat > /etc/ssh/sshd.allow << __END__
chown root:root /etc/ssh/sshd.allow
chmod 400 /etc/ssh/sshd.allow

C. The IPTABLES part at: /etc/sysconfig/iptables

(Add or modify the following line):

-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT

D. Restart the servers:

service sshd restart
service iptables restart

Have fun!!!


No comments: