Top 20 OpenSSH Server Best Security Practices

by on July 24, 2009 · 143 comments· LAST UPDATED December 5, 2009

in , ,

Don't tell anyone that I'm free

OpenSSH is the implementation of the SSH protocol. OpenSSH is recommended for remote login, making backups, remote file transfer via scp or sftp, and much more. SSH is perfect to keep confidentiality and integrity for data exchanged between two networks and systems. However, the main advantage is server authentication, through the use of public key cryptography. From time to time there are rumors about OpenSSH zero day exploit. Here are a few things you need to tweak in order to improve OpenSSH server security.

Default Config Files and SSH Port

  • /etc/ssh/sshd_config - OpenSSH server configuration file.
  • /etc/ssh/ssh_config - OpenSSH client configuration file.
  • ~/.ssh/ - Users ssh configuration directory.
  • ~/.ssh/authorized_keys or ~/.ssh/authorized_keys - Lists the public keys (RSA or DSA) that can be used to log into the user’s account
  • /etc/nologin - If this file exists, sshd refuses to let anyone except root log in.
  • /etc/hosts.allow and /etc/hosts.deny : Access controls lists that should be enforced by tcp-wrappers are defined here.
  • SSH default port : TCP 22
SSH Session in Action

SSH Session in Action

#1: Disable OpenSSH Server

Workstations and laptop can work without OpenSSH server. If you need not to provide the remote login and file transfer capabilities of SSH, disable and remove the SSHD server. CentOS / RHEL / Fedora Linux user can disable and remove openssh-server with yum command:
# chkconfig sshd off
# yum erase openssh-server

Debian / Ubuntu Linux user can disable and remove the same with apt-get command:
# apt-get remove openssh-server
You may need to update your iptables script to remove ssh exception rule. Under CentOS / RHEL / Fedora edit the files /etc/sysconfig/iptables and /etc/sysconfig/ip6tables. Once done restart iptables service:
# service iptables restart
# service ip6tables restart

#2: Only Use SSH Protocol 2

SSH protocol version 1 (SSH-1) has man-in-the-middle attacks problems and security vulnerabilities. SSH-1 is obsolete and should be avoided at all cost. Open sshd_config file and make sure the following line exists:

Protocol 2

#3: Limit Users' SSH Access

By default all systems user can login via SSH using their password or public key. Sometime you create UNIX / Linux user account for ftp or email purpose. However, those user can login to system using ssh. They will have full access to system tools including compilers and scripting languages such as Perl, Python which can open network ports and do many other fancy things. One of my client has really outdated php script and an attacker was able to create a new account on the system via a php script. However, attacker failed to get into box via ssh because it wasn't in AllowUsers.

Only allow root, vivek and jerry user to use the system via SSH, add the following to sshd_config:

AllowUsers root vivek jerry

Alternatively, you can allow all users to login via SSH but deny only a few users, with the following line:

DenyUsers saroj anjali foo

You can also configure Linux PAM allows or deny login via the sshd server. You can allow list of group name to access or deny access to the ssh.

#4: Configure Idle Log Out Timeout Interval

User can login to server via ssh and you can set an idel timeout interval to avoid unattended ssh session. Open sshd_config and make sure following values are configured:

ClientAliveInterval 300
ClientAliveCountMax 0

You are setting an idle timeout interval in seconds (300 secs = 5 minutes). After this interval has passed, the idle user will be automatically kicked out (read as logged out). See how to automatically log BASH / TCSH / SSH users out after a period of inactivity for more details.

#5: Disable .rhosts Files

Don't read the user's ~/.rhosts and ~/.shosts files. Update sshd_config with the following settings:

IgnoreRhosts yes

SSH can emulate the behavior of the obsolete rsh command, just disable insecure access via RSH.

#6: Disable Host-Based Authentication

To disable host-based authentication, update sshd_config with the following option:

HostbasedAuthentication no

#7: Disable root Login via SSH

There is no need to login as root via ssh over a network. Normal users can use su or sudo (recommended) to gain root level access. This also make sure you get full auditing information about who ran privileged commands on the system via sudo. To disable root login via SSH, update sshd_config with the following line:

PermitRootLogin no

However, bob made excellent point:

Saying "don't login as root" is h******t. It stems from the days when people sniffed the first packets of sessions so logging in as yourself and su-ing decreased the chance an attacker would see the root pw, and decreast the chance you got spoofed as to your telnet host target, You'd get your password spoofed but not root's pw. Gimme a break. this is 2005 - We have ssh, used properly it's secure. used improperly none of this 1989 will make a damn bit of difference. -Bob

#8: Enable a Warning Banner

Set a warning banner by updating sshd_config with the following line:

Banner /etc/issue

Sample /etc/issue file:

----------------------------------------------------------------------------------------------
You are accessing a XYZ Government (XYZG) Information System (IS) that is provided for authorized use only.
By using this IS (which includes any device attached to this IS), you consent to the following conditions:
+ The XYZG routinely intercepts and monitors communications on this IS for purposes including, but not limited to,
penetration testing, COMSEC monitoring, network operations and defense, personnel misconduct (PM),
law enforcement (LE), and counterintelligence (CI) investigations.
+ At any time, the XYZG may inspect and seize data stored on this IS.
+ Communications using, or data stored on, this IS are not private, are subject to routine monitoring,
interception, and search, and may be disclosed or used for any XYZG authorized purpose.
+ This IS includes security measures (e.g., authentication and access controls) to protect XYZG interests--not
for your personal benefit or privacy.
+ Notwithstanding the above, using this IS does not constitute consent to PM, LE or CI investigative searching
or monitoring of the content of privileged communications, or work product, related to personal representation
or services by attorneys, psychotherapists, or clergy, and their assistants. Such communications and work
product are private and confidential. See User Agreement for details.
----------------------------------------------------------------------------------------------

Above is standard sample, consult your legal team for exact user agreement and legal notice details.

#8: Firewall SSH Port # 22

You need to firewall ssh port # 22 by updating iptables or pf firewall configurations. Usually, OpenSSH server must only accept connections from your LAN or other remote WAN sites only.

Netfilter (Iptables) Configuration

Update /etc/sysconfig/iptables (Redhat and friends specific file) to accept connection only from 192.168.1.0/24 and 202.54.1.5/29, enter:

-A RH-Firewall-1-INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 22 -j ACCEPT
-A RH-Firewall-1-INPUT -s 202.54.1.5/29 -m state --state NEW -p tcp --dport 22 -j ACCEPT

If you've dual stacked sshd with IPv6, edit /etc/sysconfig/ip6tables (Redhat and friends specific file), enter:

 -A RH-Firewall-1-INPUT -s ipv6network::/ipv6mask -m tcp -p tcp --dport 22 -j ACCEPT

Replace ipv6network::/ipv6mask with actual IPv6 ranges.

*BSD PF Firewall Configuration

If you are using PF firewall update /etc/pf.conf as follows:

pass in on $ext_if inet proto tcp from {192.168.1.0/24, 202.54.1.5/29} to $ssh_server_ip port ssh flags S/SA synproxy state

#9: Change SSH Port and Limit IP Binding

By default SSH listen to all available interfaces and IP address on the system. Limit ssh port binding and change ssh port (by default brute forcing scripts only try to connects to port # 22). To bind to 192.168.1.5 and 202.54.1.5 IPs and to port 300, add or correct the following line:

Port 300
ListenAddress 192.168.1.5
ListenAddress 202.54.1.5

A better approach to use proactive approaches scripts such as fail2ban or denyhosts (see below).

#10: Use Strong SSH Passwords and Passphrase

It cannot be stressed enough how important it is to use strong user passwords and passphrase for your keys. Brute force attack works because you use dictionary based passwords. You can force users to avoid passwords against a dictionary attack and use john the ripper tool to find out existing weak passwords. Here is a sample random password generator (put in your ~/.bashrc):

genpasswd() {
	local l=$1
       	[ "$l" == "" ] && l=20
      	tr -dc A-Za-z0-9_ < /dev/urandom | head -c ${l} | xargs
}

Run it:
genpasswd 16
Output:

uw8CnDVMwC6vOKgW

#11: Use Public Key Based Authentication

Use public/private key pair with password protection for the private key. See how to use RSA and DSA key based authentication. Never ever use passphrase free key (passphrase key less) login.

#12: Use Keychain Based Authentication

keychain is a special bash script designed to make key-based authentication incredibly convenient and flexible. It offers various security benefits over passphrase-free keys. See how to setup and use keychain software.

#13: Chroot SSHD (Lock Down Users To Their Home Directories)

By default users are allowed to browse the server directories such as /etc/, /bin and so on. You can protect ssh, using os based chroot or use special tools such as rssh. With the release of OpenSSH 4.8p1 or 4.9p1, you no longer have to rely on third-party hacks such as rssh or complicated chroot(1) setups to lock users to their home directories. See this blog post about new ChrootDirectory directive to lock down users to their home directories.

#14: Use TCP Wrappers

TCP Wrapper is a host-based Networking ACL system, used to filter network access to Internet. OpenSSH does supports TCP wrappers. Just update your /etc/hosts.allow file as follows to allow SSH only from 192.168.1.2 172.16.23.12 :

sshd : 192.168.1.2 172.16.23.12 

See this FAQ about setting and using TCP wrappers under Linux / Mac OS X and UNIX like operating systems.

#15: Disable Empty Passwords

You need to explicitly disallow remote login from accounts with empty passwords, update sshd_config with the following line:

PermitEmptyPasswords no

#16: Thwart SSH Crackers (Brute Force Attack)

Brute force is a method of defeating a cryptographic scheme by trying a large number of possibilities using a single or distributed computer network. To prevents brute force attacks against SSH, use the following softwares:

  • DenyHosts is a Python based security tool for SSH servers. It is intended to prevent brute force attacks on SSH servers by monitoring invalid login attempts in the authentication log and blocking the originating IP addresses.
  • Explains how to setup DenyHosts under RHEL / Fedora and CentOS Linux.
  • Fail2ban is a similar program that prevents brute force attacks against SSH.
  • security/sshguard-pf protect hosts from brute force attacks against ssh and other services using pf.
  • security/sshguard-ipfw protect hosts from brute force attacks against ssh and other services using ipfw.
  • security/sshguard-ipfilter protect hosts from brute force attacks against ssh and other services using ipfilter.
  • security/sshblock block abusive SSH login attempts.
  • security/sshit checks for SSH/FTP bruteforce and blocks given IPs.
  • BlockHosts Automatic blocking of abusive IP hosts.
  • Blacklist Get rid of those bruteforce attempts.
  • Brute Force Detection A modular shell script for parsing application logs and checking for authentication failures. It does this using a rules system where application specific options are stored including regular expressions for each unique auth format.
  • IPQ BDB filter May be considered as a fail2ban lite.

#17: Rate-limit Incoming Port # 22 Connections

Both netfilter and pf provides rate-limit option to perform simple throttling on incoming connections on port # 22.

Iptables Example

The following example will drop incoming connections which make more than 5 connection attempts upon port 22 within 60 seconds:

#!/bin/bash
inet_if=eth1
ssh_port=22
$IPT -I INPUT -p tcp --dport ${ssh_port} -i ${inet_if} -m state --state NEW -m recent  --set
$IPT -I INPUT -p tcp --dport ${ssh_port} -i ${inet_if} -m state --state NEW -m recent  --update --seconds 60 --hitcount 5 -j DROP
 

Call above script from your iptables scripts. Another config option:

$IPT -A INPUT  -i ${inet_if} -p tcp --dport ${ssh_port} -m state --state NEW -m limit --limit 3/min --limit-burst 3 -j ACCEPT
$IPT -A INPUT  -i ${inet_if} -p tcp --dport ${ssh_port} -m state --state ESTABLISHED -j ACCEPT
$IPT -A OUTPUT -o ${inet_if} -p tcp --sport ${ssh_port} -m state --state ESTABLISHED -j ACCEPT
# another one line example
# $IPT -A INPUT -i ${inet_if} -m state --state NEW,ESTABLISHED,RELATED -p tcp --dport 22 -m limit --limit 5/minute --limit-burst 5-j ACCEPT

See iptables man page for more details.

*BSD PF Example

The following will limits the maximum number of connections per source to 20 and rate limit the number of connections to 15 in a 5 second span. If anyone breaks our rules add them to our abusive_ips table and block them for making any further connections. Finally, flush keyword kills all states created by the matching rule which originate from the host which exceeds these limits.

sshd_server_ip="202.54.1.5"
table <abusive_ips> persist
block in quick from <abusive_ips>
pass in on $ext_if proto tcp to $sshd_server_ip port ssh flags S/SA keep state (max-src-conn 20, max-src-conn-rate 15/5, overload <abusive_ips> flush)

#18: Use Port Knocking

Port knocking is a method of externally opening ports on a firewall by generating a connection attempt on a set of prespecified closed ports. Once a correct sequence of connection attempts is received, the firewall rules are dynamically modified to allow the host which sent the connection attempts to connect over specific port(s). A sample port Knocking example for ssh using iptables:

$IPT -N stage1
$IPT -A stage1 -m recent --remove --name knock
$IPT -A stage1 -p tcp --dport 3456 -m recent --set --name knock2
 
$IPT -N stage2
$IPT -A stage2 -m recent --remove --name knock2
$IPT -A stage2 -p tcp --dport 2345 -m recent --set --name heaven
 
$IPT -N door
$IPT -A door -m recent --rcheck --seconds 5 --name knock2 -j stage2
$IPT -A door -m recent --rcheck --seconds 5 --name knock -j stage1
$IPT -A door -p tcp --dport 1234 -m recent --set --name knock
 
$IPT -A INPUT -m --state ESTABLISHED,RELATED -j ACCEPT
$IPT -A INPUT -p tcp --dport 22 -m recent --rcheck --seconds 5 --name heaven -j ACCEPT
$IPT -A INPUT -p tcp --syn -j doo
  • fwknop is an implementation that combines port knocking and passive OS fingerprinting.
  • Multiple-port knocking Netfilter/IPtables only implementation.

#19: Use Log Analyzer

Read your logs using logwatch or logcheck. These tools make your log reading life easier. It will go through your logs for a given period of time and make a report in the areas that you wish with the detail that you wish. Make sure LogLevel is set to INFO or DEBUG in sshd_config:

LogLevel INFO

#20: Patch OpenSSH and Operating Systems

It is recommended that you use tools such as yum, apt-get, freebsd-update and others to keep systems up to date with the latest security patches.

Other Options

To hide openssh version, you need to update source code and compile openssh again. Make sure following options are enabled in sshd_config:

#  Turn on privilege separation
UsePrivilegeSeparation yes
# Prevent the use of insecure home directory and key file permissions
StrictModes yes
# Turn on  reverse name checking
VerifyReverseMapping yes
# Do you need port forwarding?
AllowTcpForwarding no
X11Forwarding no
#  Specifies whether password authentication is allowed.  The default is yes.
PasswordAuthentication no

Verify your sshd_config file before restarting / reloading changes:
# /usr/sbin/sshd -t

Tighter SSH security with two-factor or three-factor (or more) authentication.

References:

  1. The official OpenSSH project.
  2. Forum thread: Failed SSH login attempts and how to avoid brute ssh attacks
  3. man pages sshd_config, ssh_config, tcpd, yum, and apt-get.

If you have a technique or handy software not mentioned here, please share in the comments below to help your fellow readers keep their openssh based server secure.

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 143 comments… read them below or add one }

1 Ahmed July 25, 2009 at 1:12 am

A honeypot for the SSH Service.
http://kojoney.sourceforge.net/
BTW, I haven’t used it before

Reply

2 Rezaul Karim July 25, 2009 at 10:34 am

A very nice tutorial.

Reply

3 Chris July 25, 2009 at 1:18 pm

I think you have a typo here. Did you want to say

~/.ssh/authorized_keys or ~/.ssh/authorized_keys2

instead of

~/.ssh/authorized_keys or ~/.ssh/authorized_keys

? (notice the trailing number)

Anyway very nice tutorial! Thanks!

Reply

4 Adil October 3, 2011 at 8:27 am

yup chris it is

~/.ssh/authorized_key or ~/.ssh/authorized_key2

here is the place where you past the new key.

Reply

5 Ashwani July 25, 2009 at 1:43 pm

I think this tutorial concludes various how-tos around web this…is simply most comprehensive,easy to understand article on ssh.

Thanks vivek yaar …keep rocking :-)

Reply

6 pradeep July 25, 2009 at 3:59 pm

nice one…

Reply

7 Charanjit Singh July 25, 2009 at 5:19 pm

Hmmm again as I always say AWSOME Dude Thanks.. Really helpfull…

RGD
Charanjit Cheema
RHCT

Reply

8 derDrache July 25, 2009 at 5:50 pm

There is still some (small) merit to disallowing root login. Virtually every unix-type system has a “root” account, so allowing root to log in means one less thing that an attacker has to guess (at the least). Of course, if you’re only allowing public key authentication this is sort of moot, and otherwise, depending on your set-up, it might be more inconvenience than it is worth, but it is still something to take into account.

Reply

9 MetroMagz December 1, 2011 at 2:37 pm

You could disable it and run as the another account which that account has same permit as root account, that’s what i do on my server.

This tutorial very useful as the sysadmin.

Reply

10 George July 26, 2009 at 2:10 am

Another potential problem with disallowing root login is in case you use central authentication (e.g. LDAP) in your infrastructure and your LDAP server(s) are unavailable, then you would really appreciate being able to login using the local root account.

Reply

11 anomie July 26, 2009 at 3:56 pm

I generally ignore advice from people who can’t make communicate without cursing like a sailor. You might consider editing out some of bob’s more colorful language — it’s very juvenile and cheapens the point he is trying to make.

In any case, bob is making a straw man argument and ignoring an obvious benefit. Disabling root login means crackers first have to figure out (enabled) ssh user logins to launch a successful brute force attack. It buys the sysadmin more time, and it’s another layer in the security onion.

Reply

12 Enzo August 3, 2011 at 6:08 am

If someone is using a brute force attack, they will find a valid account anyway. If you cannot protect the root account, then you cannot protect any account and you might as well turn off ssh because you are clueless and incompetent.

Reply

13 Philippe Petrinko August 3, 2011 at 7:41 am

@Enzo

> “you might as well turn off ssh because you are clueless and incompetent.”

No need to be rude to enlight your point.
Insults are inappropriate in a technical debate, and counter-productive.

A brute force attack is much more difficult if you don’t now any login.

Why ? Try it yourself: when you try a login + password, system rejects you but never says what was wrong : login or login+password

Mathematically, you’ll have to multiply number of average attempt for root login by number of possible login name, which makes a real difference, and give system more opportunity to reject your IP and stop your attack.

Reply

14 Cody August 3, 2011 at 1:09 pm

Well said, Philippe.

Frankly, someone being rude in such a way is only going to make that person look less intelligible and that person will also be taken less seriously. It comes down to constructive criticism versus being arrogant and holding little argument, in the end.

And the funny thing is, regarding his remark of you might as well turn off ssh. Well then why not go further and say: turn off the computer? Ah right – because any computer is not 100% secure, even a computer that is off. Yes, you should secure it as much as possible but to claim turning off ssh is going to make it magically more secure is ridiculous. In that case, you may as well turn off other services that are far less secure. Indeed – there’s many attack vectors out there, and as you (Philippe) point out not having a valid login is pretty much not nice for an attacker if you can’t login with root remotely. Indeed, by the time you may find a valid login, you may have been blocked by a firewall or some other system. Exactly why the old apache phf bug was so useful: it wasn’t so you could crack root password, it was so you could get a valid login so you can get one step closer and you could even have possibility of trying a local exploit – more of those than remote, more than likely. If you by chance had a root password found, fine, but that wasn’t the only use of it (clearly).

Thing is – the original person, anomie, was correct.

Reply

15 anomie July 26, 2009 at 3:58 pm

Should have read: “… from people who can’t communicate…”

Reply

16 nixCraft July 26, 2009 at 4:27 pm

@Chris, Older versions of openssh has differentiated files for authorized keys by version.

@anomie, Thanks, I’ve edited out bob’s colourful language.

@Ashwani / Charanjit / pradeep, Happy to know you like this post.

Reply

17 nbensa July 26, 2009 at 5:50 pm

@Geoge: if you add a local user to passwd, then you don’t need root.

ssh nbensa@ldap
nbensa@ldap:~$ su -
root@ldap:

Reply

18 mossholderm July 26, 2009 at 6:23 pm

Bob’s comments in the article, regarding the futileness of disabling root logins may be appropriate for home systems, but for a corporate environment, it is vital. Unless you for your users to log in with their own user account prior to using su/super to become root, you lose all accountability. How are you supposed to know which dimwit broke things?!? :)

Reply

19 markhahn August 5, 2011 at 6:54 pm

ssh, of course, knows whose key was used to login as root – there’s no lack of accountability there. you don’t get an audit trail of what the person did, but you don’t with “sudo su -” either. it really boils down to whether you use root so infrequently that sudo is viable – remember that every time you type your password, you stand a chance of exposing it.

Reply

20 CiderMark August 9, 2011 at 7:33 am

@markhahn

ssh only knows the key if you are using one and all that proves is that the person had access to the key. Using a key for root is fine but you would still need to set a password for root (in case the network is down and you have to access the server from the console). With remote root login enabled, I would only need access to someone else’s PC and the password for root. There is nothing that could be used, forensically, on the server to identify me. At least if I had to log on to my own, personal, account and then su to root the IP address AND the originators login are recorded.

Having said that, though, if you haven’t got centralised logging once you’ve got access to root you just delete the auditing files and do whatever it was you weren’t supposed to be doing!!!

Reply

21 graz January 22, 2012 at 10:11 am

I’m still a bit unsure about how using sudo to su – is a good idea.

logon to server with regular account and bad password 12345678
sudo su-
12345678 and you have a root shell..

Surely to step up to the root user from a regular account you should be issuing a separate password. I see the thought behind protecting the root password by never having to type it and no one having to know it, but with sudo su – someone can gain root without the root pw anyway, so whats the point of protecting it if its not needed anyway.

Just my 2 cents anyway..

Reply

22 robsku April 9, 2013 at 11:25 am

I agree that with allowing sudo access with regular account password to all commands as root (which is the default in ubuntu user account created on install for example), but disabling root login through ssh and requiring use of sudo or su to root doesn’t have to equal that.

Although since I switched to Linux I ran my system with sshd root-login enabled and without extra protection like denyhosts or fail2ban without succesful break-ins for years (logs show constant attempts of brute force attacks, but it’s not a powerful method) before beefing up my security I finally decided to take additional measures.

I installed denyhosts, which has dropped log entries of failed attempts humongously. I also set it to allow no root logins, although configuring denyhosts to ban any attempting IP immediately for failed root login attempt, because I knew anyone doing that would not be me so it should be blocked anyway.
I also have sudo enabled, but unlike in ubuntus default configuration I have not allowed everything with my regular account password. Sudo is highly configurable and I’ve configured some (carefully thought out) command that it lets me run as root without asking password at all, then set of commands I can use with my (faster to type) regular account password – and finally the rest is set up to show a different prompt and require root password. This means if I actually want to switch to root shell instead of just running individual commands via sudo I can just as easily run ‘su -’ as ‘sudo su -’.

Of course for home server this might be a bit overkill and makes gaining root access more work for me, but considering that:
a) it only takes ‘su -’ and entering second password – not really that much extra work for something you don’t do that often remotely anyway.
b) I avoid using ‘su -’ too often and prefer running command via root – it is widely recommended as working in root shell is more prone to accidents than using sudo. Even if you never even accidentally (and never is a big word) leave a terminal open with root shell while leaving the computer (whether to pick up coffee from kitchen or on public library machine is just different in how dangerous it is, the problem is still the same) there is always a chance that you accidentally type something meant for other terminal, like the notorious rm -rf examples, in the root shell. Using sudo you always know what you’re doing as you won’t accidentally type sudo in front of command you don’t intend to run as root :) Also, with sudo you get the benefit of not having to type in root password for every command and the benefit of time-out, which you don’t have in root shell (also the time-out length is configurable).

So all in one, sudo is a good tool but the way it’s configured in ubuntu it’s pretty useless, even dangerous, and disabling root login on sshd is a good idea as well. You might also consider disabling logging in as root locally – that is from login prompt/screen, not via su.

Just my 2 cents.

Reply

23 mossholderm July 26, 2009 at 6:26 pm

@George – If you are using central authentication, you should also consider using something like pam-ccreds and/or libnss-db to keep cached copies of critical accounts. That way you can still get in, even if contact with the central auth server is broken.

Reply

24 Mouring July 27, 2009 at 2:55 am

#4: Configure Idle Log Out Timeout Interval

User can login to server via ssh and you can set an idel timeout interval to avoid unattended ssh session. Open sshd_config and make sure following values are configured:

ClientAliveInterval 300
ClientAliveCountMax 0

Can we please stop the misbelief that ClientAlive* and ServerAlive* have ANYTHING TO DO WITH Idle timeout? It is used to detect is the remote side still exists. It has absolutely nothing to do with a session being idle.

- Ben

Reply

25 Lawrence D'Oliveiro July 27, 2009 at 11:12 am

Strange. You say to disable host-based authentication. Yet you say to use TCP wrappers, which applies host-based permissions!

Reply

26 Cody February 3, 2011 at 2:23 pm

Lawrence – it’s not strange. Although I see what you’re thinking, you’re missing one thing.

Host based _authentication_ – keyword is authentication.

Please note output in ‘man sshd_config’ :

Specifies whether rhosts or /etc/hosts.equiv authentication together with successful public key client host authentication is allowed (host-based authen‐
tication). This option is similar to RhostsRSAAuthentication and applies to protocol version 2 only. The default is “no”.

This is completely different. Rhosts was a nasty thing – it was basically this: trust relationship. This is exactly what ip spoofing’s main use is (more specifically, ip spoofing is part of trust relationship exploitation).

if a host was in the .rhosts – they potentially don’t need any credentials or they don’t need a password if they’re a certain user and other possibilities. And you (if I recall anyway – been a long time!) don’t have to specify a specific host even – you could have all as long as user name is the same. Well then what if a user actually creates a user by that name on their own system ? Yeah, access. HostbasedAuthentication is very similar – perhaps slightly more secure – to rsh.

On the other hand, tcp wrappers does not _authenticate_! It allows you to deny or allow _connections_ – completely different from authentication. Further, some programs have the possibility to use it that auto place IP’s in it after some event (say fail2ban as one example).

So no, it’s not strange at all.

Two other responses – one to someone who wrote a message here and another to Vivek.

To the person who mentioned spoofing:
You can say the spoofing is a worry. Except … well, not exactly. Keep in mind spoofing is a blind attack (= you won’t get the response if it’s not your ip = you can’t establish a connection). Also, you should block ip’s claiming to be from yourself anyway (your server won’t send a packet to yourself in this way unless something is wrong). Further, most programs that do similar things (fail2ban, ossec etc) have a whitelist.

And I agree – Vivek, you really should remove that part about Bob making an “excellent point”. It’s actually an incredibly lousy point as others have pointed out. And as someone mentioned it for 2010 (when they wrote the response) but they didn’t know about 2005. I’ll say I do. It was a lousy point then and it is a lousy point now even beyond 2010. Besides, really, how hard is it to login in with a normal user and type “su -” or “sudo su -” … ? If you absolutely have to have it, then at least have a pass-phrase (key pass phrase) and make it a strong one while you’re at it.

And yes, this is an old post but I think some things I wrote would be beneficial to others who arrive later (assuming they are unaware or don’t realize the things).

Reply

27 Rob Lingle July 27, 2009 at 4:48 pm

Check out the MaxStartups directive for preventing brute force cracks. Easier than adjusting your firewall rules an potentially locking yourself out.

If you use Moonshine for deployment, there’s a plugin that makes all of this easy and provides secure defaults.

Reply

28 Mauro July 27, 2009 at 8:02 pm

Another point of disallowing root logins is that if bob logs in and messes up the system, you can (theoretically) trace that. If root logs in and messes up something, who is root?

Reply

29 Chris July 27, 2009 at 8:47 pm

There are times where root logins are appropriate, such as a larger scale of environment. If you are an admin with 100+ systems that need to be patched (thus requiring root privs), then you would have to:

1) scp files to each system using an unprivileged account
2) ssh into each system using an unprivileged account
3) sudo to install the patch

That doesn’t exactly scale well in terms of efficiency.

If you employ Kerberos authentication *with ticket passing* (allowed users are listed in ~root/.k5login) while using SSH, then allowing a direct root login is not a problem as each access is directly attributable to someone’s Kerberos ticket.

Combine Kerberos & SSH and suddenly those three steps listed above become two steps inside a for-loop. Enter your password *once* to establish your Kerberos ticket, and come back in a bit to smile glibly at your efficiency!

Reply

30 richard July 27, 2009 at 10:10 pm

You can use the file /etc/ssh/sshrc and/or the folder ~/.ssh/rc for execute a personal script at the connection (see man sshd)

Reply

31 Per H July 27, 2009 at 10:14 pm

Regarding root logon…
When I was browsing my security log for some weeks ago I discovered that there had been several attempts to login as root on my home server. (And it was more than one attempt that had been going on for days, so some zombie machines in China were just executing it’s evil script).
So… evil zombie machines are trying to login as root on other machines every day, why not just turn off the ssh-login for root.

I know that the probability for finding the right password is extremely low, but if nothing stops these zombie-machines/botnets/whatever from trying they sooner or later (ok, probably almost never) will find the right password.

But as we all rarely need to login as root, it’s for the sake of security better to take the extra time so login and su:ing whatever we need to do.

Reply

32 Chris May 7, 2011 at 12:57 pm

I also agree and was thinking the same thing. There are lots of scans going on out there trying root. Some honeypot logs suggest long term attacks against root, coming from China. Sure odds are really low that a strong password would ever be broken but they are there.

Now lets suppose a 0 day does come out some day, what account do you supposed they would try?

Reply

33 Ed July 28, 2009 at 4:06 pm

Chris: script it. If you’re feeling daring, you could even put the script into the ‘shell’ for the ‘non-privileged user’, such that whenever someone with an authorized ssh key connects to that account with scp, it accepts the scp, and then automatically kicks off a ‘sudo install ‘. This would, of course, require automating the install prompts also.

Vivek Gite: If that’s bob’s language *fixed*, I’d hate to see the original.

If you’ve Firewalled the SSH server (#8), then using TCP Wrappers (#14) is pointless, as TCP wrappers are pretty much an expensive firewall (as it forks for every new connection attempt.) TCP wrappers used to add some capability that didn’t come built-in to the OS. But since Linux has iptables built in, TCP wrappers isn’t necessary. (As I recall, TCP wrappers was still useful back in the days of the original Linux firewall. But sometime between then and now, I believe all of its features have been incorporated. Certainly everything that was mentioned here has been.) As such, putting the block in TCP wrappers would just add yet another place for me to configure the same stuff.

Reply

34 sasdaman July 28, 2009 at 10:47 pm

Thanks great post! Have been looking for a decent article on OpenSSH for a while now! Stumbled upon this by chance!

Reply

35 Kapil July 29, 2009 at 8:23 am

Nice Tutorial

Reply

36 swapnil July 29, 2009 at 6:24 pm

great.Really helpful.tahnks

Reply

37 nbensa July 29, 2009 at 6:55 pm

i don’t want more replies. how do i unsubscribe from this blog?

Reply

38 nixCraft July 29, 2009 at 7:57 pm

@nbensa,

Removed. FYI, there is link at the bottom to manage your thread subscription i.e. “Manage subscriptions” link.

Reply

39 Leszek July 29, 2009 at 8:40 pm

Great suggestions as usual Vivek! Thanks!

Reply

40 Andrés Aquino July 30, 2009 at 6:08 pm

thanks man, very useful…

Reply

41 lyonn August 4, 2009 at 8:32 pm

Very effective your post, really i dont know about security of the ssh server, but now i can implements in my system.

greetings!

Reply

42 jabellon August 5, 2009 at 10:54 am

Hi,

What is the difference between Protocol 2 and Protocol 2,1 ?
and which is better to use and why?

Thanks a lot

Reply

43 Dot2Kode August 14, 2009 at 10:59 pm

Very nice tutorial….Having all the info. you put together in one place…I was looking through my bookmarks on SSH and I think I had 20+ different url’s for this info and not as well explained…Thanks for taking the time and putting this together in one easy to follow tutorial…Keep up the good work!

Reply

44 BlueNile August 19, 2009 at 10:13 am

jabellon,

If you specify both ssh protocols, the order is significant. Only the first in the order is considered.

SSH Protocol 2 provides additional mechanisms for confidentiality (the traffic is encrypted using 3DES, Blowfish, CAST128 or Arcfour) and integrity (hmac-md5, hmac-sha1). Note that protocol 1 lacks a strong mechanism for ensuring the integrity of the connection.

Some of the major advantages of Portocol 2 over Protocol 1 are listed below.

- Separate transport, authentication, and connection protocols
- Strong cryptographic integrity check
- Any number of session channels per connection
- Supports Publick key authentication which includes DSA, RSA and OpenPGP ( RSA has been recently added)
- User authentication exchange is more flexible, and allows requiring multiple forms of authentication for access.

Reply

45 anonym2 August 26, 2009 at 9:11 pm

Use programs like denyhosts or fail2ban. Ideal for brute force attacks.

Reply

46 Lennie August 31, 2009 at 1:23 am

Use scponly as shell, with *forwarding disabled, for customers and such which need to copy files only. It’s better then using ftp or something stupid like that,

Reply

47 ungeekdeplus September 1, 2009 at 7:57 am

Nice tuto.

But if you install DenyHosts and these kind of tools be careful about IP spoofing.
What happend if someone spoof your workstation ip address and does brut force your server ? You can’t login !!

Reply

48 Ricardo September 14, 2009 at 5:32 pm

Very good, i don’t have problem!!! Surely, my openSSH is more secure

Reply

49 Marlon September 17, 2009 at 1:46 pm

Hi,

Did you faced with situation that users scape from their resctricted shell directory using putty to send a remote “bash” command ?

Reply

50 Nina September 30, 2009 at 7:44 am

Thank you, good tutorial. I’m learning Linux it is very helpful tutorial. Thank you again!!!

Reply

51 Theodis Butler September 30, 2009 at 5:18 pm

Forget the point “Bob” made with item 7 disabling root login. It is not horseshit…you’re giving automated brute force programs a username to try with a dictionary. 50% of the login authentication will automatically be cracked if user root is a valid account then all that is left is to guess the password.

Reply

52 Henrik October 2, 2009 at 1:07 pm

About #9:
A better approach to use proactive approaches scripts such as fail2ban or
denyhosts (see below).

and some later comments.

“fail2ban” and “denyhost” are NOT proactive. They _react_ to stuff that they see in the logs AFTER they happened.

And they don’t avoid attacks as such, but only slow them down. They don’t help very much against a botnet (the login attempts will come from lots of dfferent IPs) and depending on your ban action might develop into an unintended denial of service attack by themselves. (So be careful what your ban action does and which resources it uses.)

Changing the default ssh port IS proactive as it avoids every unaimed ssh attack, be it brute force password guessing, denial of service, or attacks that use vulnerabilities in ssh that are exposed before authentication is finished. (Yes, there were such vulnerabilities in the history of ssh (not sure if openssh was vulnerable) ).

Reply

53 Sean October 3, 2009 at 4:59 pm

As others have said, I don’t allow root login. I do use denyhosts but if brute force attackers only need the password half the battle is won. For this reason I use strong usernames too

Reply

54 Greg Bowyer October 10, 2009 at 10:25 am

One of the things I did some time ago on one of my ssh servers was to install incrond (a daemon that listens to inotify and then runs a script)
http://inotify.aiken.cz/?section=incron&page=faq&lang=en

I then made it run a script that consitsted of “et call home” and shutdown the machine if certain special filess were touched (/bin/ls passwd /etc/shadow etc etc)

I am sure that similer tricks can be pulled of for the other OS’s.

Reply

55 Wirasto S. Karim October 13, 2009 at 1:52 pm

Good tutorial. Thank’s.

Reply

56 Michael Lam October 15, 2009 at 5:09 am

Firstly, good tutorial. I had never thought my server can be attacked until logwatch rang some bells. I have installed denyhost, with an option to send me a mail whenever an ip was blocked. This woke me up (literally via Blackberry) when I received at least one brute force attack a day. I agree with Henrik about a possible DOS opportunity with denyhost and furthermore, the longer the list, the longer it takes to log in. I have received attacks from parts of the world I did not think existed on the Internet. I will give yours & Henrik’s suggestion of moving the SSH port a try. It is a good suggestion. Thanks again.

And, Yeah. I agree with anome. Bob needs a mouth wash (your edit was not good enough).

Reply

57 Philippe October 16, 2009 at 12:44 pm

I am sorry, I really don’t understand the meaning of:
“One of my client has really outdated php script”
Would you please rephrase it another way?

Reply

58 John W October 24, 2009 at 6:45 am

I permit root logins for one reason: I also use SFTP. And I can’t tell my FTP client to subsequently login as another user. And maybe my geek credentials are lacking on this board, but I’d much rather view or edit (find/replace) any root owned log or text file longer than a few dozen lines in a GUI text editor like TextMate (or BBEdit) than wade through it using a bunch of arcane commands in vim or emacs to do what I want.

Reply

59 Foamhead October 31, 2009 at 5:34 am

I have been out of the Linux Admin world for a few years, and just got back into it…I just got my (first) new server on line; only ssh is open for outside communications, everything else is blocked. I just checked my logs, less than 24 hours later. I have already had an 8 hour ssh brute force attack from Korea – a new login attempt every 2 seconds. I heartily thank you for this wonderful tutorial – it has helped me remember everything I forgot in the last couple of years – and helped me harden my server!

Reply

60 Bhaskar Chowdhury November 4, 2009 at 2:02 pm

Thanks vivek. Quite a handful of procedures.

Reply

61 Jim Gray November 9, 2009 at 3:30 pm

@John W – I agree with you regarding the SFTP logins and root permissions. I like using the graphical interface rather than terminal for editing. Can someone suggest a terminal editor that is better than vi or pico? I like WinSCP. The only problem is the work around for disallowing root. Is there any way to allow root only locally within a LAN, so that the server sits behind a router and can still remain headless?

great article and discussion.

Reply

62 roger January 31, 2011 at 10:41 pm

I like midnight commanders editor… mc is a pretty awesome tool all around. You can navigate like you would in nautilus and if you have mouse support for ncurses you can click on the file you want to edit click file and edit and its just like a gui text editor… All this without X, totally brilliant. Since I got into server administration its become one of my top tools for everything.

Reply

63 Sujit Nandi November 20, 2009 at 4:03 pm

thanks guys.this is really good disc.

Reply

64 Stefano November 22, 2009 at 4:09 pm

Just thanks! :)

Reply

65 Knut-Perry G Brumoen December 14, 2009 at 1:41 am

@Jim Gray
Have you tried MC?
If you’ve been around since the “old days” you most likely will think Norton Commander when you run it.. ;)
Midnight Commander looks very much like the old Norton Commander, or even the other graphical file manager for DOS, don’t remember the name now. That one also had a blue background just like NC and MC.
Most distros has MC in their repositories..
If not you will find the sources at midnight-commander.org

Reply

66 joe December 27, 2009 at 5:31 pm

Bob is NOT making an “excellent” point.

Not using root is just good, darned practice.

- individual authentication & accountability
Log in as ‘joey’, then sudo … provides audit trail & allows us to know WHO is using root privilege,

- root account is a KNOWN target, make them work for it
But they don’t know what YOUR account name may be. Slow down the brute force attacks. Force the bad guys to break 1 account, and then have to break another (root) to gain privilege.

Reply

67 snap December 31, 2009 at 11:05 pm

Uh, no PermitRootLogin without-password?
PasswordAuthentication no?

Use public-key auth, disable passwords, and also solve the brute-force problem for free.

Reply

68 TechiePark February 3, 2010 at 11:36 am

Hello,
I wanted to know how to enable last login in sshd_config?

Thanks

Reply

69 2hot6ft2 February 5, 2010 at 4:16 pm

Nice writeup Vivek,

I found a couple things to tweak my SSH server in it that I hadn’t considered. 6 months and your writeup is still useful and getting responses.

There are a couple things that could be added

To #1
“Debian / Ubuntu Linux user can disable and remove the same with apt-get command:
# apt-get remove openssh-server”

That will remove the server. If you just want to stop the server then you would use:
sudo /etc/init.d/ssh stop
Just replace “stop” with “start” or “restart” depending on want you want to do.

Thought of something to add to #11 and that is that best said in this quote:

“SSH can use either “RSA” (Rivest-Shamir-Adleman) or “DSA” (“Digital Signature Algorithm”) keys. Both of these were considered state-of-the-art algorithms when SSH was invented, but DSA has come to be seen as less secure in recent years. RSA is the only recommended choice for new keys, so this guide uses “RSA key” and “SSH key” interchangeably.”

From here: https://help.ubuntu.com/community/SSH/OpenSSH/Keys

On the same page there is this:

Key Encryption Level
Note: The default is a 2048 bit key. You can increase this to 4096 bits with the -b flag (Increasing the bits makes it harder to crack the key by brute force methods).

ssh-keygen -t rsa -b 4096

Keep up the good work.

Reply

70 Val February 9, 2010 at 3:42 pm

I usually handle this by using iptables rather than taking other actions.
1) Disable root login
2) Deny access to the whole world by using iptables, but first allow your IP to connect otherwise you´ll be denying access yourself then append this rule.

iptables -A INPUT -p tcp -m tcp –dport 22 -j DROP

Remember, too much security doesn’t mee too much good ^^

The tutorial is quiet good.

Reply

71 KRRAJU March 2, 2010 at 4:25 pm

Wow awesome and Excelnt articles for Unix [Linux] .

Thanks a lot to share with us.

-Raju

Reply

72 Live March 21, 2010 at 3:36 am

Is it true that key-based, password-less login is sufficient for an average home user? Because what I know, it already cuts brute force attacks. In real life, this simply means, your house is safe unless someone stole your front door house key, right?

Thanks.

Reply

73 TheGrendle April 27, 2010 at 5:48 pm

In response to Bob’s comment on SSH root access:

I’m not sure about 2005, but here in 2010, we worry about accountability. In the real world, there is usually more than one administrator who has his/her hand in system maintenance. If they are allowed/able to log in as root directly, we have little way of tracing back who made what change. Forcing all users to log in under their own account and su to root maintains an audit trail. Remember, not all threats are external ones.

Reply

74 someone May 10, 2010 at 5:55 pm

@#8disable root login

if you could login as root, attackers would only need to bruteforce your root’s password and they are in.
if you disable root, they will need to get a user+pass that actually can su and THEN they can start getting the root’s pass.

imho disabling root ssh login is a simple directive but pretty useful which pretty much destroys the possibility of bture force logins.

another idea is: put ssh on a non 22 port.
nice candidates are (3)1337, 2222, … most portscan bots run just 0-1024.
its another simple hurdle for attackers to get over.

Reply

75 Philippe Petrinko May 11, 2010 at 4:27 pm

Yes, I would rather disable root login (ssh and others).

But then, how would you use a remote GUI SFTP Client with root access ?
(such as NAUTILUS under Linux, or as WinSCP under MsWin)

I can’t picture a solution. Can someone?

To Vivek: Would you consider the following restriction: using an intermediary PC (kept secret as much as possible) on local network close to the server you want to access.
This PC would be the only one from which you could access the server via SSH.
You & Distant PC Internet local net secret PC public server

AAMOF, I do not know what could keep a local PC much “secret”, but you may know and teach us.

Reply

76 nixCraft May 11, 2010 at 8:37 pm

My laptop has full access within lan behind firewall and host tcpd only access connection from local subnet. Also, take a look at /etc/security/ directory. You can restrict root login from certain ips, time of the day and much more.

Reply

77 Nathan Fisher May 14, 2010 at 12:55 pm

I whole heartedly disagree with Bob’s argument. It isn’t about sniffing the root password, but rather auditing. If you have multiple admin’s on a system I think it far better to force them to use unique login id’s per user than a single shared root account. When combined with centralized logging there is at least an audit trail, even if its only partial.

Reply

78 Anonymous June 22, 2010 at 8:49 am

1′ OR ’1′=’1

Reply

79 nyuszika7h August 2, 2011 at 6:38 pm

Nice try, but that didn’t work. :)

Reply

80 Aruljane June 28, 2010 at 6:37 am

Simple way to stop the bruteforce attack using iptables

iptables -A INPUT -i eth0 -p tcp –dport 22 -m state –state NEW -m recent –set –name SSH
iptables -A INPUT -i eth0 -p tcp –dport 22 -m state –state NEW -m recent –update –seconds 60 –hitcount 3 –rttl –name SSH -j DROP

service iptables save

Reply

81 Dave June 30, 2010 at 11:22 pm

Port knocking is security by obscurity. Something you don’t want. Seriously, pressing ctrl-C 4 times. If I by accident press it 5 times, the whole sequence has to be started again.. Just picture this scenario: the company router is down and 80 coworkers are standing behind you shouting and yelling why the internet is broken.. I love to see you keeping it cool and focus on when you get the SSH passphrase prompt when every second it’s get more and more crowded behind you. Oh and their comes the chief. You better hurry now..

Why not use IPSEC with X.509 certifications. Login using a VPN client. That would give you a local LAN IP. Just open you SSH server for the VPN IP range and you don’t have to access SSH anymore directly from the internet.

Just use ‘iptables -A INPUT –in-interface ${WAN_IP} -p tcp –dport 22 -j TARPIT’ to make life hard for script kiddies. I really love the iptables tarpit. It’s also great to prevent port scans. Just use the ‘recent’ module and the attacker is sucked into a void if too many ports are scanned.

Reply

82 robsku April 9, 2013 at 5:44 pm

Your workplace scenario is fear by absurd imaginary situations.

If your workplace actually is like that I suggest quitting from mental institution and finding a new job, because if the root password dialog is already so catastrophical scenario, the actual fixing of issue is something you have no chance with.

Reply

83 Sal September 25, 2010 at 8:22 pm

First of all, this is a great article. It’s very comprehensive, and includes most all options you can use to harden SSHd.

Just to let everyone know (even though it’s already been mentioned in the comments), number 4 is completely incorrect. That, as said before, only applies to keepalive packets. A keepalive packet is simply a way to keep the connection open, which is almost exactly the opposite of what you’re trying to do. If you want to force a login timeout, you can set a bash environment variable in /etc/profile, /etc/bashrc, /etc/bash.bashrc, or the user(s)’ ~/.bashrc . Just add the following line:

export TMOUT=300

Done. Now any account with this environment variable set automatically logs out in five minutes. If you want to disable it, since it’s pretty annoying, all you have to do once you’ve logged in is this:

$ unset TMOUT (The $ is your command prompt)

All of the other points mentioned in this article are great ideas for securing your SSHd. The best ones (in no particular order) are changing the ssh port, using the AllowUsers directive, choosing good passwords, using public key authentication/disabling password authentication if you’ve assigned keys to all users who must login, and chrooting the user to their home directory. Be careful with the chroot, however, as this hinders the user’s ability to do pretty much anything. It’s best for users that can only SCP/SFTP, as they aren’t even likely to notice being confined to the chroot, anyway.

The BEST way to prevent brute force attacks is changing the SSH port. If you use any non-standard port, you’ve thwarted over 90% of all script-kiddie attacks, as they typically only scan port 22. There is a chance they could scan to determine other ports (particularly the most common alternate ports, like 2222), in which case you would simply combine the alternate port with BFD or fail2ban or similar. Combine all or most of the above and you have yourself a very secure setup.

Reply

84 Philippe Petrinko September 26, 2010 at 8:04 am

Hi Vivek,

There is a typo up above, in:
“~/.ssh/authorized_keys or ~/.ssh/authorized_keys – Lists the public keys”

A “2″ is missing : “or ~/.ssh/authorized_keys2″

But otherwise, it seems that one should prevent using that deprecated (since 2001) file name.

Would you make it clear to anyone by a warning that you write so well?

Please note that some other web pages need to be updated accordingly.

Reference:
http://sial.org/howto/openssh/#s6
http://marc.info/?l=openssh-unix-dev&m=100508718416162&w=2

Thanks again for your long term past work on maintaining such a huge and interesting web site !

Reply

85 Hasan Zubair November 6, 2010 at 3:51 pm

very Nice article

Reply

86 Sreejith Sathyan November 25, 2010 at 10:24 am

Very nice Tutorial…..

Reply

87 zcworld February 16, 2011 at 2:13 am

I like my secure shell, its like chroot users to there home folder via winscp or some other SCP client and blocks SSH login, is an nice tool, as well
http://sourceforge.net/projects/mysecureshell/

Reply

88 Bhanu February 16, 2011 at 4:15 am

Thank you.

Reply

89 IlayarajaDharmaraj March 15, 2011 at 12:03 pm

Very nice & usefull tutorial. Thanks

Reply

90 Zoltan SEBESTYEN March 30, 2011 at 7:50 pm

Thanks really nice sum up of SSH + iptables features.
Especially liked port knocking + IP binding limit.

Reply

91 ubundom May 27, 2011 at 1:10 pm

If I log off from a client machine and then log on again, it seems that I have to re-enter my passphrase in order to access a remote machine with Public Key based Authentication (practice #11). Is this the expected behaviour from ssh-agent/ PuTTY Pageant (practice #12)?

Thanks for the hidden bonus extra 5% of these simple to follow rules: you have posted 21 not 20:

#8: Enable a Warning Banner
and
#8: Firewall SSH Port # 22

Reply

92 BoBo May 27, 2011 at 11:08 pm

Yes.

But, if you are login and logout in same session, you can skip the passphrase with ssh-agent or keychain. Unix desktop operating system has inbuilt support for keychain to remember your passphrase.

Reply

93 Cody May 27, 2011 at 11:14 pm

Passphrase or password? Different thing. If you’re using keys and the key has a passphrase, then yes you’ll need to enter it. Password is another story.

And I see someone else responded. Now I know why I was thinking there might be cache: keychain. I tend to avoid that kind of thing and I’m dead tired.

And as for him using keychain, no idea if that’d work since he’s I assume on Windows (putty?). So in general, yes you do unless you have a way to cache it like BoBo suggested.

Reply

94 BoBo May 28, 2011 at 12:09 am

> no idea if that’d work since he’s I assume on Windows (putty?).
On Windows XP I use Pageant which is an SSH authentication agent for PuTTY, PSCP and Plink. As long as Pageant[1] is running in the taskbar, you can log in to your SSH server without providing the passphrase. Another option Cygwin on Microsoft Windows[2].

[1] http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
[2] http://www.cygwin.com/

Reply

95 Johannes July 8, 2011 at 10:08 am

One other great thing reagarding portknocking is single packet authentication SPA you can protect all applications that is stateful connection oriented. Set the firewall in default drop stance and only authenitcation and open the port to the service you need if someone if throwing port scans at the box they will never see the open port. I strongly recommend to checkout cipherdyne.org/fwknop

Reply

96 Roland July 21, 2011 at 10:57 am

Great posting, nice discussion.

@root-login: in addition to the security issues for remote intruders, consider some additional advantages of sudo.

Time out: Consider the admin who logs in as root in the morning and logs out when going home at the end of the day. The risks of an open root terminal while he is away from his desk. Using sudo, the root terminal won’t be active very long when he leaves his desk.

Easy: Then, using sudo, the admin needs to remember one fewer strong password, namely only his personal user password.

No sharing: Also, there is no need to share a root password. If that might leak out and there are several or many admins, all need to be informed and to memorize a new strong password.

Who would ever want a root password now?

Reply

97 Cody July 21, 2011 at 1:46 pm

Re time-out:

The administrator should not really stay logged in while away from desk, anyway. I’ve also not seen timeout with sudo except with needing to supply a password (meaning sudo su – then leaving the shell via exit/logout then sudo again). It might be a configurable option, not sure as I don’t actually need or use it here (only admin) and I don’t allow remote login.

Re easy: I don’t know about you, but the amount of “strong” passwords out there are amazingly not strong. Further, I know plenty write down their passwords, share them etc. Look up the list of bad passwords out there (compiled by people doing research on the subject). Heck, look at the dictionary lists out there. I’d much rather have two strong passwords.

Re no sharing: ok, fair but do consider the double edged sword of: enforce strong passwords = more likely people write them down. Don’t enforce = you have weaker passwords.

Lastly, another issue I have with sudo. Imagine this scenario (yes this is an old exploit but its been done, and it actually could be done with a different exploit in time or even currently):

User X abuses phf bug in apache. User actually gets /etc/password unshadowed (example, remember). User X runs a dictionary attack, finds password. User X logs in. User X wonders if the user has sudo access. Lo and behold t hey do. Well now what? One less password is one less step.

So yes, it may have some advantages but it also has disadvantages.

Put another way: security is not 100% even with a locked up, turned off computer. Locked and no key? Never heard of a locksmith ? Etc. Remember physical access = root access anyway. That’s not to say you shouldn’t secure as much as possible, but nothing is fool proof, sudo included. Also, sadly in this world disadvantages often come with advantages and vice versa (i.e., good comes with bad).

Reply

98 Roland July 21, 2011 at 3:37 pm

#timeout: works like this: at t1 you do “sudo edit /etc/somefile” and you will be prompted for your user password. at t2 you do “sudo edit /etc/someotherfile”. With small edits and delta-t is small, you will not be prompted again for a password. But if you leave your desk for a while, and a colleague or janitor will try a sudo command, (s)he will be prompted for the password.

# strong passwords: An admin knowing the (shared) root password needs also to memorize a personal password for doing things that do not require root access. With sudo, the admin has one password less to worry about, which leaves more energy and motivation for a single, stronger, password.

#sudo su: this is circumventing the use of sudo. Still you need to use one password less than with not using sudo. Also, sudo su has its uses. Sometimes I create a user account that is locked, e.g., no password exist to login. But with sudo su you can still login.

Yes, complete security will never be achieved, but I believe sudo is a step in that direction.

Reply

99 Cody July 21, 2011 at 3:57 pm

timeout: yes, that works – I even mentioned that one (perhaps I was vague; I would believe that!). but still, should not be left logged in anyway (be it screen locked or something else) when not there. So, point is: yes, you CAN do sudo cmd but even then you should not stay logged in and if you do use su (it can be useful at times when doing a lot of editing of configuration files or some such) then it won’t time out. Again, likely some what preference and something else i mention later.

strong passwords: agreed, I don’t think the root password should be shared – hence the fair enough remark. Still though, one less password can be a flaw. It isn’t necessarily a flaw, but it can be. See next point (i already mentioned this one though but will again).

sudo su: true, however, as you point out it is useful at times (I used this one a lot in the past and still do at times). But still, my point of getting a user password (keeping in mind some don’t have nearly as strong passwords as they should) and then having sudo access could be a problem IF that password is stolen. The problem isn’t even really the set up in a lot of the cases, but that the user is who chooses the password and the password is one of the weakest links in the chain of security. Because lets face it: if you can make it, you can break it.

I’ll give you that sudo has some benefits, e.g, not having to have a root password set or even not having it known to more than one, but there’s still some issues with it. That’s all I was getting at. I think what it boils down to is actually it depends on the environment, the amount of users, etc. Or even limiting root to one user (be it by groups, or changing user requirements, whatever the case may be. I mean a programmer doesn’t need root, necessarily). Obviously with multiple administrators you do have an issue right from the get go. Best solution may not be a solution at all in some cases: again, environment and requirements is a part of it.

As for my remark about security being complete. Yes, agreed you shouldn’t dismiss it. That would be a terrible mistake (as has been proven time and again especially lately). It actually bothers me in many ways – security is the responsibility of everyone working together (there goes the passwords being weak or written down issue again).

Anyway, I’ll finish by saying: yes, it has its uses. But at same time, just like chroot has potential issues, so to does sudo. Then again, what doesn’t ? My main points were simply you should always log off and keep your passwords safe – else you run into trouble. And of course, nowadays a real issue is more web related. The amount of non filtered queries to databases, etc., is a real hazard to a lot of people!

Reply

100 robsku April 9, 2013 at 6:30 pm

I have configured sudo to allow only very limited carefully selected set of commands with my own password (and a couple, mostly with parameters also limited to selected ones, even without password and then most configured to require root password.

I don’t use sudo because it enables use without needing to remember two passwords nor to run su (su runs fine itself), but from many replies it seems that today people know sudo more from the default root account policy of ubuntu than from ever studying sudo’s features and configuration options :(

Reply

101 Pkboyz August 2, 2011 at 6:49 pm

using failed2ban is also a great way to protect your ssh server.

Reply

102 Vietnam advisor September 6, 2011 at 11:23 am

Thanks for your info ” OpenSSH is the implementation of the SSH protocol. OpenSSH is recommended for remote login, making backups, remote file transfer via scp or sftp, and much more. SSH is perfect to keep confidentiality and integrity for data exchanged between two networks and systems”.
Anyone can suggest a smart expert to set it up for my company.

Reply

103 Jose Baars October 3, 2011 at 4:58 pm

If you demand or even allow the use of su or sudo, then you must disable any form of interactive access of user root, even at console level, or else you have a possible accountability leak.

Basically everybody implicitly agrees that the fundamental security model of Unix/Linux is flawed in at least these ways:
- It doesn’t scale well ( more than 1 admin *have* to use one account: root)
- It doesn’t offer sufficient granularity ( you either have all with root, or almost nothing)
- It is virtually impossible to guarantee accountability in all cases.

I would be interested to see developments to solve that problem in more fundamental way than to patch it up with nice or, more often, ugly and cumbersome add-ons.

Reply

104 robsku April 9, 2013 at 6:50 pm

Multiple admin accounts:
Add new group: admins
Add admin user-accounts to group ‘admins’
Execute ‘find’ at root directory to search files owned by user/group “root:root” and to execute “chown :admins” and “chmod g=rw”, or if file has execute permission for root set “chmod g=rwx” for each file. If there are files belonging to user “root” but some other group then I’m sure any unix admin worth his title know how to configure filesystem to use ACL rules and how to add additional group permissions to files with “setfacl” command – if not, “man setfacl” will help – if it doesn’t, perhaps one should consider quitting as administrator.

Or to put it simply: Add a group for admin accounts and give filepermissions to users on that group same access rights “root” has. Simple. There is no flaw in security model on this – if there was, it was before ACL permissions were common on *nix-like systems, and it was about complexity of setting up groups and access permissions so that different groups could access same files. It was messy, and often admins took the easier route in more hairy cases, but that’s mostly in the past – and when I say “mostly”, I mean that it’s an issue of outdated unix/linux systems (and in case of linux it’s simply solved by upgrading – outdated unices that aren’t updated any more are really the only problem.

Reply

105 vinit November 26, 2011 at 12:36 pm

hi i used the command SCP to transfer files but uploading speed is not goin above 32KBps. WHY?
is there any limit of speed in SCP
second thing is there any way to transfer filesat high speed but secure way between two Linux machine.
please reply me at my ID vinit.j@echidnainc.com thanks

Reply

106 arrogant admin November 27, 2011 at 10:41 am

# Turn on reverse name checking
VerifyReverseMapping yes

Don’t do this. It will cause you a painful delay when logging in, should your DNS servers get inaccessible (i.e. uplink down) or misconfigured.
Exacty the moment you need to fix it ASAP.

And, probably, a lot of “POSSIBLE BREAK-IN ATTEMPT” useless chatter in your syslog should your ssh clients’ reverse zone be misconfigured somehow (a lot of ISPs are misconfigured that way, so nobody cares). Don’t know if recent versions of sshd do that, though. Seen that on older systems.

Reply

107 Siddharth December 12, 2011 at 7:13 pm

hey, Vivek,
thank you for this excellent post.
I have a query
Is it possible to block multiple ssh logins from a single client pc?
i mean, a single client must be allowed to run only one ssh sessionat any given time.
If it helps, my server is debian and client is ubuntu

Reply

108 Henry Paul December 30, 2011 at 6:00 am

There is another solution to root auditing and login. We use root login with without-password option so key login is allowed remotely, password is denied. Then we configured EASH shell for session logging on our jump server and restrict ssh logins via jump server. Basically the entire ssh session is logged to a remote server for future auditing, and we still have a more convenient access to the system for running automated scripts, etc.

Reply

109 MUNIKRISHNAN.M January 9, 2012 at 6:12 am

this details are very help full Linux learner and working system admins

thank you

Reply

110 Andrew Bruce January 19, 2012 at 12:59 am

One technique I like to use is to have local, low-priv accounts used for SSH access on a nice’n’empty box. This in conjunction with TCP forwarding allows me to let users in (no passwords, of course, just PK authentication) and then chroot the users to lock them in their current dir. That minimizes zero-day risk cuz the SSH users have no privs on the domain, network, or anything else–they are simply placeholders to allow TCP port forwarding to be setup. Users setting up tunnels to “real” servers get prompted with our strong two-factor authentication so we have the best of both worlds.

VPN would be fine but it is very slow compared to SSH. No, this is *not* due to protocol (I’ve timed VPN and SSH and there is no detectable difference in throughput). It is instead due to the edge firewalls that trap / track all VPN traffic and the shitty VPN clients the organization wants us to use.

To sum up: keep your SSH server clean of all other software, use local low-priv user accounts, use only PK for authentication, maybe tie in IP filtering to prevent hackers from even knowing about your listening port. Port knocking is too complicated for me to explain to users, or I’d be using that instead (tres kewl approach).

Reply

111 precious March 27, 2012 at 4:31 pm

Hello I want to know if the SSH can work with Window i have bitvise Tunnelier I want to know how i can work with it can if you can help me with host usename and pasword. hope to hear from you very soon

Reply

112 Andrey March 29, 2012 at 4:26 am

Thank You!

Reply

113 AnomyII April 15, 2012 at 5:33 pm

Wow, default Googly searches should have a date filter, since everything is on the indelible web, that it resurrected such an old post as first hit? OK fine I’ll play…

While anomie might be offended by a few f**ks and god****ns where *HE’S* from, I live in NYC and F**K! is no more a curse word than OW! or CUT IT OUT! — people do not even bother stopping their 4 year olds from saying it. It’s lost all vulgarity here, and is completely acceptable in the business world too, well unless you’re doing I.T. work for a church organization. Maybe.

The point is, you say you don’t listen because you feel cussing is childish, I’d like to point out that good information is good information no matter how it’s delivered. Censoring someone else’s speech because it offends you? So when did you join the Republican party?

PS: Your reference is a bit dated, mate. Sailor? Who the hell sails anymore besides the Chinese? I’m guessing you’ve never been in a dockside bar anyway, since that world must offend your sensibilities! (I’m kidding) You want to hear a stream of profanity to make that proverbial sailor blush, engage an NYPD officer in conversation. :)

- – - – - – - –

I would also like to point out that #10, random password example, that your script only uses A-Z, a-z, 0-9… while “uw8CnDVMwC6vOKgW” is pretty complex for a brute force attempt on a connection-limited server, that could be brute forced in our “everyone has <50Mbit connections" world very quickly, where the addition of even a single ! or ? would send the brute force routine's runtime an order of magnitude higher.

It's a moot point anyway, NO ONE is going to memorize a random password. It's a Bad Idea(TM). If they bothered memorizing a random string, chances are that after they did so, they would n e v e r change it, and what's worse in this scenario? If you're this paranoid about security, you're a canidate for a one-time-password setup and a SecurID key fob.

Reply

114 Skaperen April 16, 2012 at 7:41 pm

I don’t agree with “There is no need to login as root via ssh over a network” but neither do I agree with Bob’s reasoning, either. The argument I heard was it allowed each admin to have their own root login, and avoided everyone having to get a new shared root password when one of them leaked or quit. But SSH keys, which are more secure, avoided that. So I disallow PASSWORD access to root and require keys only.

Logging directly in as root has advantages, like making sure rsync-over-ssh can back up the system when it originates from the backup servers.

Reply

115 undermined April 26, 2012 at 4:29 pm

In my opinion it comes down to knowing what you are trying to protect. If your system needs any level of protection, then you need full auditability. Remote logins directly to the root user (or any other privileged user) prevent adequate accountability. Yes, one can argue that PK authentication is stronger than PW authentication but I’ve never known a user to change the PK, whereas all of my users are required to change their passwords regularily. We all know that security is a process and that having layers is an important aspect of defending a system from the onslaught of attacks out there (and the new ones coming out hourly). It is much harder for a server to verify that the PK used to authenticate is pass-phrase protected; this is where the last argument breaks down for me. As someone who is responsible for the security of a server, I can’t control what tools or configurations the client-side has/uses. I agree that allowing admins to login and ‘sudo su -’ using their own passwords is a convenience and an attempt at balancing the use of the root password. We do many things in my environment, which is fairly large (over 6,500 midrange systems): 1. We have a local, non-privileged account to allow remote SSH logins when LDAP/Kerberos are unavailable. 2. We limit the use of the ‘su’ binary to members of a specific group (root:trusted, 4550). 3. The account listed in #1 is a member of the appropriate group so that it can execute the ‘su’ binary. 4. All admins have to change their passwords at least every 30 days. 5. All non-admins have to change their passwords at least every 90 days. 6. All password changes are verified through crack to ensure strong password are selected. 7. We use TCPWrappers to limit the connectivity to the servers from specific “SSH gateway” servers for regular users. We allow admins to connect directly because we have a dedicated subnet on the LAN where the admins workstations are, inside a locked room with physical access controls. 8. We run auditd on the SSH gateway servers to log all commands. We run auditd on the servers to log all root commands that have an assigned terminal (only some systems, especially regulated systems, require logging all commands, including those without an assigned terminal, such as cron jobs, etc). 9. Physical access to the raised-floor is limited. 10. Access to the serial console is done through an iLO connection with authentication to the Active Directory system so root logins on the console are still attributable to an individual (and one from a different authentication subsystem). 11. All logs are centralized to log proxy servers and then forwarded to an appliance that ensures 2 years of off-site, non-modifiable logs.

When we patch our systems (roughly 1 admin to 350-400 systems), we use tools for doing this efficiently. We do not expect an admin to login to each server manually and run a command, either as the root user directly or by use of sudo su -. This just wouldn’t work in a large environment. The use of tools for this specific purpose, and one that is done monthly at that, was well justified. It just doesn’t make sense to use the patching need to justify the lessening of the security posture, especially in a large environment, where the purchase of a tool is more efficient, doesn’t require the lessening of security, and has a faster ROI, especially in a large environment.

If you don’t know what you are trying to secure, and you can’t account for every action on the host, then you ultimately don’t have adequate security, imho. There are definately some challenges that arise in larger environments that home operations don’t usually encounter but you are also far more likely to need a stronger security posture in said larger environment than in the home operation.

Two-factor authentication is your friend, as is education and enforcement, where possible, such as with pam_crack to ensure strong passwords.

Just my $0.02…

Reply

116 Lucas Dohring April 28, 2012 at 9:15 pm

An alternative for generating passwords is:

alias genpasswd='dd if=/dev/urandom count=1 bs=$1 2> /dev/null | ascii85 -n'

Use as `genpasswd 16` for a 16 character password.
note: you need ascii85 installed.

Reply

117 Peter O May 9, 2012 at 9:17 am

I need to comment on Bob’s excellent point, I disagree.

Most corporate install have more than one admin. It’s impossible to tell who actually logged in if they just log on as root. It’s better to log in with your real username and then sudo. This makes it all traceable in syslog.

Reply

118 C H June 1, 2012 at 12:00 am

I have an opinion about root login. I’m rather fond of creating multiple root accounts: aroot, broot, croot, droot, etc. That way, you can have your accountability and your quick access too.

Reply

119 Mr Smith June 10, 2012 at 8:47 am

Just wanted to add another thanks and nice how to on securing ssh access. Gives people plenty to chew on and research for further reading on the topic. Also … not that really matters, also posted to say, jebuz people get over the use of profanity eh. Can only speak for me, but it’s extremely annoying to see 18 crying der widdle eyes out over a tad of adult language having been used. Sheesh … you’re not going to die from it or etc.

BE STRONG LADIES/LADS !!! Shield your delicate eyes from the horrid nasty words !!! D:

lmao … end pet peeve rant. :)

Reply

120 A June 17, 2012 at 1:12 am

Thanks for the guide. I’m looking to disable error feedback when it doesn’t find an appropriate auth method. For example:

No supported authentication methods available (server sent: publickey)
or
(server sent: publickey, gssapi-keyex,gsappi-with-mic)

I want to prevent disclosure of the available auth methods? I assume I have to recompile, but before I go there, is it possible?

Thanks,
Ayman

Reply

121 Haakon Løtveit July 8, 2012 at 3:28 pm

Would it be a good idea to use a different port than port 22?

Might not always be feasible, but it seems like a good idea at least.

Reply

122 PFudd October 2, 2012 at 5:51 am

Some people say root login is bad because it’s an easy target for hackers to try and brute-force, and if all of your admins are ssh-ing to the ‘root’ account, then there’s no way to tell which one broke the system after the fact. Also, disallowing root login forces hackers to break into two accounts, not just one.

There’s a problem with disallowing root logins: if you have to log in as a non-root user, and then are required to use ‘sudo’ with the same password, then your non-root password is just as valuable as the root password, and non-root passwords are not guarded nearly as well as root passwords. Doesn’t your email client store (obfuscated but not encrypted) your password in its configuration files somewhere?

Even if you have use ‘su’ with a different root password than your account password, if someone has your account password they can log into your shell account and install a keystroke logging wrapper around ‘su’, probably based on ‘expect’ or ‘autoexpect’.

My preferred solution is to have separate uid-0 root accounts for all admins, with unique passwords for each, to maintain accountability. Then I require admins to ssh directly into their root accounts, no su’ing or sudo’ing allowed. This prevents someone with your non-root shell account password from putting a trivial wrapper (in your personal startup files) around ‘su’ or ‘sudo’, since you’ve already authenticated to the system before any user-accessible code is reached. I also use ssh-keys for authentication, with strong passwords as backup in case ssh-keys are lost or destroyed. I also have a tcpwrapper around ssh which restricts access to my corner of North America, which cuts down the junk tremendously.

Cheers!

Reply

123 Cody October 2, 2012 at 11:29 pm

To be honest if they already have access to a local user that is not their own, then you have an issue at that point already. It doesn’t really matter the cause. For all you know they could have already used a local exploit and then they wouldn’t need to worry about the other stuff. In fact, I would imagine that if their goal is to get root, they already are (and you SHOULD assume that: to NOT assume that is dangerous).

But assuming that is not the case, there’s other things to consider.
First: keep your ssh keys safe (ssh should help with that even because of it forcing certain permissions if i recall?).
No passwords to log in. You could add a passphrase to the key, too and then either use ssh-add (or not). If you do use ssh-add you could always (for example) force a ssh-add -D (or better: use the -t option when using ssh-add; could do that automatically for all users, even). And if you do keep your keys safe (obviously unique per uid), you still have another layer of protection on the remote end: your (hopefully) safe password required per sudo (or whatever) (but see below still on that part).

All that aside, you also could of course only allow certain commands with sudo, including specific options/args to the command. And depending on how many people need ssh access (or even how many different blocks of ips will be connecting) you can use ip{,6}tables to only allow certain ips (or indeed alternatively tcpwrappers). You could also use something like fail2ban (or any other number of programs in addition to the others).

If you’re going to go through the thought of ‘it’s dangerous to log in as root’ then you may as well follow through (having a different user with perms as root may have a use but the fact remains that if one of those is compromised – or you forget to remove them after they leave the company – then your ENTIRE machine is compromised). Having more than one user with a id of 0 isn’t really that different than just allowing root (only difference is WHO did it and although that is something to consider it does not mitigate the end result). If someone makes a copy of your house keys (or you give them a copy) that does not mean your house is any more safe (if they get in your house they can take/damage/do whatever things you could do too). In fact, in some ways I would say it is less safe (more copies = more possibilities. That’s exactly how Apache’s server got compromised last year or whenever it was in recent times).

And besides, you really should only have full access when you need it. I can see how you might want to su (via sudo or otherwise) for several operations but once done you should logout. You should always log out when done and that is the same no matter how you authenticated.

Reply

124 AdvancedBeginner October 15, 2012 at 4:14 pm

I would not recommend showing a banner with explanation of “XYZ system you are accessing” as it gives more clues/confirmation to those wanting to breach into your network… if they are here, quite possibly they are here for reason…

Reply

125 Erik October 18, 2012 at 11:29 pm

A couple of things about this:

On the controversial root login topic:

In a modern managed environment, it’s almost a requirement that key-based root SSH logins be enabled. There are simply far too many tools which rely on using that functionality. That said, there’s no real good reason to allow “normal” password root logins, so use the above ‘PermitRootLogin without-password’ and ‘PasswordAuthentication no’ – though, note that ALL users will be required to have SSH keys set up. Bastion hosts are a good idea here: create one with no root logins allowed via SSH, and all users have to password login. You can then set up key-based logins from that host to all the appropriate infrastructure. Admin Users can then log into other machines as themselves before ‘su’ or ‘sudo’ to root, AND you have left open root key’d SSHs for the automation. In addition, ‘sudo’ is NOT a complete replacement for ‘su’ – there are a number of cases I can quote you where running sudo will NOT work, while running after a ‘su – ‘ WILL. EVen when sudo options claim to DoTheRightThing. Sometimes, root just is better.

DON’T play the “change SSHD port to something besides 22″ game. It’s merely security through obscurity (which is practically worthless), and leads to a whole lot of extra configuration EVERYWHERE, which in turn leads to many more opportunities for mistakes. Leave it running on the default port. It’s a default, for a reason.

For the same reasons, I’d avoid port knocking. It’s a huge hassle, and doesn’t add much security, and only adds complexity everywhere. Simplicity of configuration adds far more security than a complicated scheme.

To the above poster on the authorized_keys filename: virtually all SSH (including modern OpenSSH) implementations never bothered to make the switch to requiring authorized_keys2 for Protocol2 keys. Nowdays, virtually all implementations use ONLY the authorized_keys file (and won’t look at authorized_keys2) and file all keys there, so the article should be kept as-is.

Finally, to recommending a 4096 keylength: that’s excessive. 2048 is *very* sufficient for anytime in the future we care about, and there’s a non-trivial penalty to pay for that added keylength, particularly if you run a system that has very frequent SSH logins. A 4096-bit key is NOT twice as long as a 2048-bit key, it’s 2048-times as long, and can easily quadruple or more the time to do authentication. Modern factoring techniques can’t even approach a 2048-bit key, and unless there’s a algorithmic breakthrough, any hardware in our professional lifetime won’t either. Use 4096 bits only to satisfy some pedantic legality.

Reply

126 Cody October 20, 2012 at 7:31 pm

True. Though I would say that security through obscurity isn’t practically worthless but instead it is more harmful and therefore completely worthless. The same applies to a badly configured firewall, even.

Security through obscurity (and companies relying on it – especially companies that have products of their own with a security flaw) is a reason why people will make public flaws and even exploits for those flaws/holes. Some say releasing exploits is harmful and unethical and whatever else but I would rather ask them this:

Would you prefer the company be FORCED to fix it or would rather prefer that it’s not made public and instead wait until someone with bad intentions finds it and abuses it ? Obscure does not mean it can’t be found. And what if it is a product YOU or your COMPANY uses ?

Fact is companies do ignore these things and so it is good that people release the exploits. Microsoft has indeed ignored many things and that’s the least of it: they have even made claims that some backdoors (and probably other types of exploits/etc) were less serious than they seem. To that I say: 1) Do they care that little about their customers ? If a building inspector found a hole or crack in a ceiling in a building and ignored it and signed it off as OK, wouldn’t you be unhappy ? Should be: it’s a safety risk. A risk is a risk no matter how minor someone thinks it is. 2) Are they too lazy or incapable of fixing the problem and that is why they dismiss it as not an issue ?

But of course they’re not the only ones in that. As for the Microsoft case I am thinking of the BackOrifice family of backdoors.

Reply

127 anon October 23, 2012 at 4:32 pm
PasswordAuthentication no

Please note that this is not enough to use key-only authentication. Depending on the server configuration (e.g., FreeBSD’s out-of-the-box one), you’ll also need to use —

UsePAM no
ChallengeResponseAuthentication no

This is a requirement for any of our servers running sshd, external-facing or not.

Reply

128 Nathan October 23, 2012 at 7:51 pm

Disabling root is not simply about making the system more secure it creates a layer of accountability; if every admin has their own account and no one has the root password you can track activity to a specific user/account. Serve those accounts from a central directory service (e.g. LDAP) or use a configuration management tool (e.g. Chef or Puppet) and it becomes a very simple (and reliable) task to (dis|en)able a users access across your infrastructure. Running non-standard ports, while security through obscurity, does *marginally* increase the cost of finding a service that can be exploited by a zero day exploit. VPN’s and restricted IP’s would be preferable but, may not always be an option.

Reply

129 Cody October 23, 2012 at 11:40 pm

On root: true that it makes it more secure and adds to accountability. Maybe I am not following you right on every admin having their own account (so forgive me if this is not what you mean) but: it would depend on what activity you’re referring to. Some you could track more easily but not everything is logged, either (and history can be cleared among other things). Maybe you mean sudo though and in that case it often is an option but not always.

On the note of finding a a service: that depends on how you look at it, I would say. It does mean it takes more work for those who are very inexperienced and are using a tool that only checks a service by port. But of course there’s many other options out there. Naturally, if you combine changing the port with rate limiting connections per IP (in general) then it will take longer but it still can be done (as in, nmap and many other tools has plenty of potential to slow things down among other options). I think the issue is not “it should not be done because it is security through obscurity” so much as that some will take it as “if I do this that’s all I need to do”. Fine if you do everything else too, but it isn’t a security mechanism by itself and people unfortunately do not put that together. Combine that with the below and it is even worse : Years ago the r* services and telnet were common. Of course, to do remote log on or remote tasks via those (or even allow!) is insane but at one point that was the norm and the point there is the internet protocols weren’t designed with security in mind (so: to think changing a port is all you should do is of course a flaw. Not saying that everyone thinks it is all you need to do, but I am pretty sure some do think like that. That’s why as I mentioned in another post exploits being released to the public is actually good).

You’re right that restricted IPs is not always an option. But when it is, of course it should be done. It indeed would depend on many circumstances. That’s unfortunate. But changing ports isn’t going to make that go away for anyone who knows how the service works (especially if they have the source to the exploit).

Reply

130 Chase Venters October 23, 2012 at 8:04 pm

The bash function for generating passwords is good, but another good option is the pwgen command available on most Linux distributions through your native repositories.

Reply

131 Winston Weinert October 31, 2012 at 4:41 pm

Another good option is to comment out the “auth” lines for “pam_unix.so” and “pam_opieaccess.so” on FreeBSD. This forces users to either key-based authentication or One Time Passwords. Note that using OTP doesn’t ensure your connection from the client machine is insecure, it’s just a good compromise if you don’t have access to a trusted machine with keys. Don’t do anything you wouldn’t do over telnet when using OTP on an insecure box.

Reply

132 Kevin December 19, 2012 at 12:50 am

Ofcourse what measures you would put in place and to what level they could be called paranoid depends on the purpose of the machine and what you actually do to counteract attacks.
My homeserver is connected to the internet on some ports, among which SSH.
I have root disabled, Canonical does this by default (yay) and you need to actually undertake action to be able to use root, if root would be active i’d disable this even though the point of this from a security standpoint could be argued. On top of this i’ve got Fail2Ban running to, among other things, keep an eye on SSH and autoban anything that fails to login more then x-amount of time. Combine that with a custom login name and password of decent length and ofcourse keeping everything reasonbly up to date and having all other sane security configurations in place (like the firewall that allows only ports that are actually going to be used) I am confident all is fine for about 99% of the situations.
You could do all sorts of fancy things with methods of authentication but to me thats just not worth the hassle.

Reply

133 Boyd Kelly January 19, 2013 at 4:43 pm

I don’t really agree that Bob’s point about ‘PermitRootLogin no’ is ‘Excellent’. The root account is a known account with elevated privileges. If is is available to log in to remotely, it is also available for a brute force attack. There are other ways of preventing this, but the most simple requiring no resources, it simply to not allow root login remotely, but allow a user with a weird name and very secure password.

Reply

134 krnkris February 6, 2013 at 3:58 pm

‘PermitRootLogin’
If this option is set to “no”, root is not allowed to log in.

Based on:
http://www.openbsd.org/cgi-bin/man.cgi?query=sshd_config&sektion=5

Reply

135 Madhusudan March 25, 2013 at 12:07 pm

Hi Guys,
Need a help. Is there any ways you can log/track the operations [Like move,delete] done by a user in a RHEL server using by a WinSCP ??
Currently I am able to see only login/logout logs in /var/log/sshd.log …
Is there any ways I can see more logs what exact operations done by a user ??
Current sshd_config setting for Logging is “LogLevel INFO”.

Thanks inadvance
Rao

Reply

136 rups June 17, 2013 at 1:03 pm

Hi its a very nice tutorial.

I was looking for the possible obstacles in implementation of SSH in the network? It would be great if somebody can provide answer.

Thanks

Reply

137 Anonymous June 18, 2013 at 8:50 pm

I too disagree with Bob, not only deny ssh as root, but the entire root account should be disabled and use sudo instead, this provides an audit trail that being root does not.

For those that do not use sudo, still disable ssh as root will make it so if in the obscenely rare case you are attacked, said attacker now needs 2 passwords, normal user and root to gain root access.

Limiting the su command to the wheel group is also a great idea.

I alos suggest Bob get a spell checker.

thanks

Reply

138 Cody June 18, 2013 at 11:56 pm

How exactly do you suppose you’re going to disable root ? Do you mean disable it except on certain consoles (through /etc/securetty or /etc/login.defs) ? Or do you mean one cannot use ‘sudo su -’ to change to root (which to me is not the same as disabling root; root is still enabled but you’re restricting who can become root). And if you mean by shell then that is easily defeated (again unless of course you are talking about sudo only where you can limit commands and arguments given). If root didn’t have a shell (say /sbin/nologin) then I would think that would have some real problems in certain cases too (been a while since I’ve looked at initscripts but there might be a problem for emergency logging in). Even if there is not a problem with emergency shell then you have to remember that if there’s physical access there is the possibility of editing the init part in the boot loader. Ah well, just some random thoughts.

Based on how you worded the post I assume you mean don’t allow ‘su -’ either by sudo or otherwise. But still root is not itself disabled.

And you’re correct that two different passwords is better than one (though there’s also been debates over the years on this issue relating to strength of passwords). But since we’re talking ssh the better way is:

a key with a passphrase attached to it and disallow password logins in ssh, period.

wheel is indeed another option although su is not the only command with the execute suid bit (not that it’s the same thing but that doesn’t mean suid cannot be abused to escalate privileges).

And I know I should resist the temptation since no one is perfect and this is not a typing class (or even anything that needs to be professionally proofread – this post is just as unprofessional as any other) but I have very little willpower with this type of thing: the same sentence you suggest Bob uses a spell checker has a typo: alos versus also. As for Bob’s claim that it was only because of unencrypted sessions I have the following to say:

1) It was not only unencrypted sessions. Another consideration was you have an added layer of defence.
2) telnet has had for many years encryption (option -x). Whether most servers or clients enable it is frankly irrelevant because it was not the only issue any way.

As for keychain I don’t understand why the need these days. Why not just use ssh-add ? You can specify a time out, you can clear any sessions and is it really that bad to run it when you log in and just not specify a time out ? People who work on more than one machine surely are used to multiple passwords for multiple types of accounts (and services). And let’s not forget that it’s less of a hassle than, say, password ages (restricting recently used passwords even). That’s not even considering libpwquality (which is far more restrictive than the default password testing). Each to their own of course and maybe there’s other things I don’t remember from keychain (long time ago) that make it more appealing. (This is more a curiosity than anything. I don’t honestly care otherwise – everyone should use what works for themselves.)

Reply

139 Gaston Wagner March 19, 2014 at 9:32 pm

md5 pass:
echo “A great password” | md5sum

generate random password:
tr -cd [:alnum:][:punct:] < /dev/urandom | head -c 20 ; echo

Reply

140 Bobba June 25, 2014 at 8:27 am

Bob is an Idiot.
The reason to disallow remote-root logins is so you could track which of your sysadmins logged in and used su/do to become root.
I, for one, prefer that someone who wants to pwn my servers will have to figure out TWO passwords, and not just one.
It was never about “first packets”. That attack was for telnet, not SSH. SSH was always properly encrypted.

Reply

141 Cody June 25, 2014 at 4:51 pm

He is an idiot. But I think that he was getting at now that there IS encryption there is no need to disable it. Problems of that logic are many and that is not even considering that yes, two passwords are better than one. And even more than that: ssh key with passphrase on top of normal user passwords and root passwords. But even his wording of spoof and passwords makes one wonder what he was on … spoofed passwords ? What you see is that he’s using spoof and sniff interchangeably and that is hilarious itself. And I do not believe for a nanosecond that he made a typo more than once (and he wrote sniff then spoof more than one time both in the idea of sniffing) but I do believe he is talking from the mouth of exactly what he is claiming the idea of ‘disable root logins’ is. In other words, he’s talking/writing as horseshit.

On the other hand, encryption doesn’t always mean 100% guarantee that there is no interception. Indeed, I seem to remember (and a quick search suggests this) there being a MiTM attack with SSH1.

As for the suggestions on this page, I cannot recall if I ever remarked about them. But I’ll point out some things anyway: changing port doesn’t really do much except for script kiddies. If you are running sshd and they want to find out they will (They = more skilled than script kiddies). But see later where I discuss that even this is not really all that useful. I’d argue that similar is for port knocking although there’s definitely more to it (but if you can filter by IP then there’s usually no need to do that). As I seem to remember, port knocking has other uses though, including getting around filters (I might be remembering something wrong or even mixing this up with other techniques… one that just came to mind being tunnels which could definitely be an option there.. but I seem to remember port knocking having uses otherwise as well).
As for su versus sudo (which after checking, I think this was a different thread on this site… but well, it applies to logging in, so..) I think there’s one key difference that some seem to miss, with whether or not is a good option. Indeed it has its uses. But depending on setup and who needs access to what logins, then not using sudo means they need more than one password. Of course there is also requiring them being in the wheel group in addition to that. sudo definitely has uses (for instance: one command and the defined options/etc. allowed and nothing else is forbidden) but it isn’t the only option and some times it is not the best option; it all depends on the environment.

While ssh chroot might be OK just keep in mind that it has inherent security risks (chroot in general, that is).

Ignoring .rhosts file is obviously a good thing because let’s not forget that it allowed logging in with any IP with no password, aside from other issues.

I seriously doubt a warning will matter to an attacker. Such legal statements are silly as it has (in most countries) long been illegal to log in to another computer with a password that you yourself are not authorised to use. So what difference does it make to add a warning? It won’t make them thing, “Well I thought this was a good idea but maybe I better not…” The fact they already connected is likely noticed and if they were meaning to attack they obviously do not care about any silly statements about legalities (they already were planning on ignoring the law).

On PAM, do be careful how you set that up as that can be a problem. Apache actually has documented this mistake (after they were compromised.. they have typically given detailed analysis of breaches).

And lastly, back to the subject of changing ports. I’m sorry to inform but unless this was a skilled attacker (I doubt it) then brute force tools do more than just use the standard port. I know this because there was a mistake on a server after an updated firewall (I seem to remember it was due to my IP block changing and the other administrator forgot to deny everyone else on forwarding, see next part) that made me see on an internal host brute force login attempts (as root and other users). The problem then is that if ssh itself was already bound to 22 on the main server, then if forwarding a port to ssh on the internal server (think: vm) then it cannot use port 22, can it? No, so it uses another port and forwards it to the internal server at the proper port. In other words the internal port 22 is only reachable by the _other_ external port (that is not 22). So once again, changing port has no value in normal circumstances. In the normal circumstances it actually makes things worse if you rely on that because you have a false sense of security (even if that is “one less thing to worry about” – sorry to inform you but that is NOT something you should not worry about).

Reply

142 Forrest July 15, 2014 at 5:32 pm

I have the need to implement Idle Log Out Timeout policies on some systems. But, I would like to have exceptions on a couple of accounts. From what I can tell, the SSH configuration doesn’t provide for this.

Can someone confirm/elaborate?

Reply

143 Cody July 16, 2014 at 12:00 pm

Well I think I should make clear why #4 works at all. It is more like a hack.
From the sshd_config(5):

“If this threshold is reached while client alive messages are being sent, sshd will disconnect the client, terminating the session. It is important to note that the use of client alive messages is very different from TCPKeepAlive (below). The client alive messages are sent through the encrypted channel and therefore will not be spoofable. The TCP keepalive option enabled by TCPKeepAlive is spoofable. The client alive mechanism is valuable when the client or server depend on knowing when a connection has become inactive.”

Okay, what does that mean? TCP Keepalives allow idle connections (no packets seen) to maintain a connection under the conditions as such:
1) Server sends keepalive probe.
2) If client responds, keep connection and stop. Else, continue.
3) Send another probe at a (programmable) interval. Do this up to X times (also programmable, as is keepalive in general). If no response from the client is seen, the connection is considered ‘dead’ and it timesout.

Above it states TCP keepalive being spoofable. I don’t know for sure but I suspect what it is getting at is you don’t have to actually USE the connection in order for keepalive responses to be sent (so you can remain idle yet your connection is maintained).

Meanwhile, the other option is saying: if connection is idle, as in no command input (maybe output – not sure.. didn’t check), then send a probe. But since the max is 0, it doesn’t give the client a chance.
It is interesting to note, however, that based on a test just now: not sending a command while max > 0 it still seems fine (this is connecting/logging in AFTER setting the max and reloading/restarting configuration). However, at 0 (and same thing: logging in AFTER) it disconnects. That seems more like tcp keepalives but given that it is not yet 5 (actually looked back and now it is 5, about to hit submit) and I’ve been awake since a bit before 2, well… I could be reading something wrong (or doing something wrong). As for TCP keepalives, I know that part is correct because I use those options in a service I am the programmer for.

That being noted: I don’t immediately see an option for this, aside from (and not confirmed) placing it in to their own ssh file (and in which case they could update). So unless I’m missing something (which IS entirely possible) then no, you’ll need to resort to other methods. The only thought is if you can use this in one of the client matches in the sshd config file itself. Hmm, looking at the man page again, the Match blocks do not allow the above options, so you’ll need to resort to something else. This is for sshd 5.3p1-94.

HTH.

Reply

Leave a Comment

Tagged as: , , , , , , , , , ,

Previous post:

Next post: