20 Mar 2011

Securing Linux: few tips for good configuration of SSHD

Most people install sshd daemon using command apt-get install open-sshd, and then forgets about making it more secure. In this article I will point out few sshd options which you should have in your sshd config when going to production.

SSHD config options

Use only protocol version 2 (more secure)
Protocol 2
Ban root login
PermitRootLogin no or allow to login as root only using ssh-keys PermitRootLogin without-password
Disable User logins with Null passwords
PermitEmptyPasswords no
Changing sshd port (on which daemon listens for connections) and limit network interfaces binding
Port 6667 and ListenAddress
Generate a new key after some fixed time
KeyRegenerationInterval 1h - This option defines how long the server waits before automatically regenerating its key. This is a security measure to prevent decrypting captured sessions.
Check user permissions before login (files/directories)
StrictModes yes
Limit maximum concurrent connections to sshd (in case you are DDOSED)
MaxStartups
If you have slower connection - try to use compression
Compression yes you can specify compression level Compressionlevel 8 (1 in being the fastest and 9 being the slowest but most compressed)
Check if connection to user is still alive
KeepAlive yes - This will tell the session to make sure your connection stays connected and to also listen for outages when your network go down, it will automatically kill your session for you.
Disable reverse DNS loockups
UseDNS no
Maximum Authentication Tries
MaxAuthTries 3
Allow access to sshd only to specified users or groups
AllowUsers sinx or AllowGroups group_name
Deny access to sshd for users or groups
DenyUsers johny or DenyGroups group_name
Lock SFTP connections in users directory (version 4.8+)
Change settings dynamically (for example different settings for different client IP or different user)
Subsystem sftp internal-sftp
Example (all should be in ONE LINE!)
Match Group users
      ChrootDirectory /home
      AllowTCPForwarding no
      X11Forwarding no
      ForceCommand internal-sftp
This would chroot all members of the users group to the /home directory and start sftp-server. Here is detailed information about creating chrooted sshd.
  Match address 192.0.2.0/24,3ffe:ffff::/32,!10.*
          PasswordAuthentication yes
  
Connect timeout - if you have slow internet connection
ConnectTimeout 30
ServerAliveInterval - if you have slow internet connection
ServerAliveInterval 30
Privilage separation
UsePrivilegeSeparation yes - Specifies whether sshd separates privileges by creating an unprivileged child process to prevent privilege escalation by containing any corruption within the unprivileged processes.
Disable host based authentication
HostbasedAuthentication no and IgnoreRhosts yes
Disable empty passwords
PermitEmptyPasswords no
Print informations about user last login
PrintLastLog yes
Print MOTD for user
PrintMotd yes

If you want to test config before restarting SSH invoke: sshd -t. Here is more detailed info about securing ssh Top 20 OpenSSH Server Best Security Practices. If you are really paranoid you can use one-time-passwords using OTPW.

Manage hosts.{allow,deny} files (TCP wrappers)

  • /etc/hosts.allow - white list, trusted computers
  • /etc/hosts.deny - black list, list of blocked computers

Syntax of hosts.{allow,deny} files

sshd: 10.0.0.10

Disable connection permission after N failed logins

This can be done usign few methods:
  • sshguard software
  • DenyHosts checks /var/log/auth.log file every 30s and gets client IP address of every of failed login attempt suspicious IP addresses are written to /etc/hosts.deny. Check out config variables: DENY_THRESHOLD_INVALID (invalid login), DENY_THRESHOLD_VALID (invalid password), PURGE_DENY (delete IPs of attackers older than some time). Think about SYNC_* to keep list of attackers up-to-date, list of 50 most active IP of failed logins will be send to the cloud. If you want to clear IP list run sudo denyhosts --purge.
  • fail2ban - uses iptables to block some hosts exactly like sshguard. It can secure SSH, FTP, IMAP/POP3/SMTP servers. It is not as advanced like denyhosts. There is also a bug: when in log file will be "messages repeated x times", fail2ban will count only first occurrence. Options to check: bantime (how long ban will be active).
  • ipt_recent - iptables module, which counts number of connections from every ip. Removing hosts from ipt_recent is fairly simple echo clear > proc/net/ipt_recent/DEFAULT - for clear all IPs or echo '-110.11.12.4' > proc/net/ipt_recent/DEFAULT
  • PAM module: pam_tally.so - not recommended ; buggy

For more information about log analysis check out this site.

Bonus

There are plenty of interesting options in sshd daemon, many of them are described in Linux Journal: Use ssh_config To Simplify Your Life article or on article in this site. One of nice option is to alias servers, change default login when writing ssh host. It can be done changing ~/.ssh/config file (remember about permissions chmod 600 ~/.ssh/config). Now, you can write desired settings to this file
Host dev-server
  HostName dev.mydomain.com
  User backup
#  IdentityFile ~/.ssh/backup_dsa
And later write only ssh dev-server and you are connected as user backup!.

Bonus #2

Comparing local and remote files
ssh user@host "cat /tmp/remotefile" | diff - /tmp/localfile
diff <(ssh user@host cat remote-filename) local-filename
Outputting your microphone to a remote computer's speaker
dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp
Securely transfer a directory with tar/ssh (without scp)!
This is very simillar to using NetCat [PL] but with encryption over the wire.
ssh user@host "tar cvzf - /path" | tar xvzf - /path
Send local file to remote system without scp
cat tempfile |ssh user@host 'sh -c "cat - >>~/tempfile"'
ssh user@host 'cat - > file' < file

How to store your password in memory for some time

It is bad to have your passphrase-protected key permanently stored in ssh-agent, because anyone with access to your machine can use the key without the pass phrase. A better solution is to use ssh-agent with the -t option to establish a lifetime (after which you will need to re-enter the passphrase). Typical setup is to keep ssh-agent running with a 2-hour lifespan, and connect to that automatically when user is logged in. Basically lines below should prevent re-entering passphrase more often than every two hours.

Generate key
ssh-keygen -t dsa -f ~/.ssh/id_dsa -C "you@example.com"
cat ~/.ssh/id_dsa.pub | ssh you@other-host 'cat - >> ~/.ssh/authorized_keys'
Set-up ssh agent
echo "source ~/.ssh-agent" >> ~/.bash_profile
. ~/.bash_profile # reload bash profile
Connect to server
ssh-agent -t 7200 > ~/.ssh-agent # run this only once after login
source ~/.ssh-agent
[... log in ...]
[.. disconnect ..]
ssh-add
If you are interested in secure connection to remote server throught ssh without password you should read: OpenSSH key management.

Connect to computer behind firewall

When having computer behind a firewall whose configuration you don’t have access to? It’s pretty easy to connect to it. Remember to have option GatewayPorts yes in your /etc/ssh/sshd_config. Here you can find more info about ssh tunnels.

  1. from the computer you wish to access:
    ssh -R 2002:localhost:22 mypublicserver.com
  2. from any computer than can access mypublicserver.com:
    ssh mypublicserver.com -p 2002
  3. you may want to consider "autossh" (restarts ssh connections if they ever exit/disconnect)

Additional resources [en]

Additional resources [pl]

No comments:

Post a Comment