Top 20 OpenSSH Server Best Security Practices

OpenSSH Security Tips

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. This page shows how to secure your OpenSSH server running on a Linux or Unix-like system to improve sshd security.

OpenSSH defaults

  • TCP port – 22
  • OpenSSH server config file – sshd_config (located in /etc/ssh/)
  • OpenSSH client config file – ssh_config (located in /etc/ssh/)

1. Use SSH public key based login

OpenSSH server supports various authentication. It is recommended that you use public key based authentication. First, create the key pair using following ssh-keygen command on your local desktop/laptop:

DSA and RSA 1024 bit or lower ssh keys are considered weak. Avoid them. RSA keys are chosen over ECDSA keys when backward compatibility is a concern with ssh clients. All ssh keys are either ED25519 or RSA. Do not use any other type.

$ ssh-keygen -t key_type -b bits -C "comment"
$ ssh-keygen -t ed25519 -C "Login to production cluster at xyz corp"
$ ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa_aws_$(date +%Y-%m-%d) -C "AWS key for abc corp clients"

Next, install the public key using ssh-copy-id command:
$ ssh-copy-id -i /path/to/public-key-file user@host
$ ssh-copy-id user@remote-server-ip-or-dns-name
$ ssh-copy-id vivek@rhel7-aws-server

When promoted supply user password. Verify that ssh key based login working for you:
$ ssh vivek@rhel7-aws-server
OpenSSH server security best practices
For more info on ssh public key auth see:

2. Disable root user login

Before we disable root user login, make sure regular user can log in as root. For example, allow vivek user to login as root using the sudo command.

How to add vivek user to sudo group on a Debian/Ubuntu

Allow members of group sudo to execute any command. Add user vivek to sudo group:
$ sudo adduser vivek sudo
Verify group membership with id command $ id vivek

How to add vivek user to sudo group on a CentOS/RHEL server

Allows people in group wheel to run all commands on a CentOS/RHEL and Fedora Linux server. Use the usermod command to add the user named vivek to the wheel group:
$ sudo usermod -aG wheel vivek
$ id vivek

Test sudo access and disable root login for ssh

Test it and make sure user vivek can log in as root or run the command as root:
$ sudo -i
$ sudo /etc/init.d/sshd status
$ sudo systemctl status httpd

Once confirmed disable root login by adding the following line to sshd_config:
PermitRootLogin no
ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no

See “How to disable ssh password login on Linux to increase security” for more info.

3. Disable password based login

All password-based logins must be disabled. Only public key based logins are allowed. Add the following in your sshd_config file:
AuthenticationMethods publickey
PubkeyAuthentication yes

Older version of SSHD on CentOS 6.x/RHEL 6.x user should use the following setting:
PubkeyAuthentication yes

4. Limit Users’ ssh access

By default, all systems user can login via SSH using their password or public key. Sometimes you create UNIX / Linux user account for FTP or email purpose. However, those users can log in to the 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. Only allow root, vivek and jerry user to use the system via SSH, add the following to sshd_config:
AllowUsers vivek jerry
Alternatively, you can allow all users to login via SSH but deny only a few users, with the following line in sshd_config:
DenyUsers root 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.

5. Disable Empty Passwords

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

6. Use strong passwords and passphrase for ssh users/keys

It cannot be stressed enough how important it is to use strong user passwords and passphrase for your keys. Brute force attack works because user goes to 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


7. Firewall SSH TCP port # 22

You need to firewall ssh TCP port # 22 by updating iptables/ufw/firewall-cmd 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 and, enter:

-A RH-Firewall-1-INPUT -s -m state --state NEW -p tcp --dport 22 -j ACCEPT
-A RH-Firewall-1-INPUT -s -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.

UFW for Debian/Ubuntu Linux

UFW is an acronym for uncomplicated firewall. It is used for managing a Linux firewall and aims to provide an easy to use interface for the user. Use the following command to accept port 22 from only:
$ sudo ufw allow from to any port 22
Read “Linux: 25 Iptables Netfilter Firewall Examples For New SysAdmins” for more info.

*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 {,} to $ssh_server_ip port ssh flags S/SA synproxy state

8. Change SSH Port and limit IP binding

By default, SSH listens to all available interfaces and IP address on the system. Limit ssh port binding and change ssh port (many brutes forcing scripts only try to connect to TCP port # 22). To bind to and IPs and port 300, add or correct the following line in sshd_config:

Port 300

A better approach to use proactive approaches scripts such as fail2ban or denyhosts when you want to accept connection from dynamic WAN IP address.

9. Use TCP wrappers (optional)

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

sshd : 

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

10. Thwart SSH crackers/brute force attacks

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

  • 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.
  • sshguard protect hosts from brute force attacks against ssh and other services using pf.
  • security/sshblock block abusive SSH login attempts.
  • IPQ BDB filter May be considered as a fail2ban lite.

11. Rate-limit incoming traffic at TCP port # 22 (optional)

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:

$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.

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)

12. Use port knocking (optional)

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 to the 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 -p tcp --dport 22 -m recent --rcheck --seconds 5 --name heaven -j ACCEPT
$IPT -A INPUT -p tcp --syn -j door

For more info see:

13. Configure idle log out timeout interval

A user can log in to the server via ssh, and you can set an idle 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.

14. Enable a warning banner for ssh users

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 a standard sample, consult your legal team for specific user agreement and legal notice details.

15. Disable .rhosts files (verification)

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.

16. Disable host-based authentication (verification)

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

17. 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:

18. Chroot OpenSSH (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.

19. Disable OpenSSH server on client computer

Workstations and laptop can work without OpenSSH server. If you do not provide the remote login and file transfer capabilities of SSH, disable and remove the SSHD server. CentOS / RHEL users can disable and remove openssh-server with the yum command:
$ sudo yum erase openssh-server
Debian / Ubuntu Linux user can disable and remove the same with the apt command/apt-get command:
$ sudo 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

20. Bonus tips from Mozilla

If you are using OpenSSH version 6.7+ or newer try following settings:

#################[ WARNING ]########################
# Do not use any setting blindly. Read sshd_config #
# man page. You must understand cryptography to    #
# tweak following settings. Otherwise use defaults #
# Supported HostKey algorithms by order of preference.
HostKey /etc/ssh/ssh_host_ed25519_key
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
# Specifies the available KEX (Key Exchange) algorithms.
# Specifies the ciphers allowed
#Specifies the available MAC (message authentication code) algorithms
# LogLevel VERBOSE logs user's key fingerprint on login. Needed to have a clear audit track of which key was using to log in.
# Log sftp level file access (read/write/etc.) that would not be easily logged otherwise.
Subsystem sftp  /usr/lib/ssh/sftp-server -f AUTHPRIV -l INFO

You can grab list of cipher and alog supported by your OpenSSH server using the following commands:
$ ssh -Q cipher
$ ssh -Q cipher-auth
$ ssh -Q mac
$ ssh -Q kex
$ ssh -Q key

OpenSSH Security Tutorial Query Ciphers and algorithms choice

How do I test sshd_config file and restart/reload my SSH server?

To check the validity of the configuration file and sanity of the keys for any errors before restarting sshd, run:
$ sudo sshd -t
Extended test mode:
$ sudo sshd -T
Finally restart sshd on a Linux or Unix like systems as per your distro version:
$ sudo systemctl start ssh ## Debian/Ubunt Linux##
$ sudo systemctl restart sshd.service ## CentOS/RHEL/Fedora Linux##
$ doas /etc/rc.d/sshd restart ## OpenBSD##
$ sudo service sshd restart ## FreeBSD##

Other susggesions

  1. Tighter SSH security with 2FA – Multi-Factor authentication can be enabled with OATH Toolkit or DuoSecurity.
  2. 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 also:

  • The official OpenSSH project.
  • Man pages: sshd(8),ssh(1),ssh-add(1),ssh-agent(1)

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.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 175 comments so far... add one
CategoryList of Unix and Linux commands
Disk space analyzersdf ncdu pydf
File Managementcat tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
175 comments… add one
  • Ahmed Jul 25, 2009 @ 1:12

    A honeypot for the SSH Service.
    BTW, I haven’t used it before

  • Rezaul Karim Jul 25, 2009 @ 10:34

    A very nice tutorial.

  • Chris Jul 25, 2009 @ 13:18

    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!

    • Adil Oct 3, 2011 @ 8:27

      yup chris it is

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

      here is the place where you past the new key.

  • Ashwani Jul 25, 2009 @ 13:43

    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 🙂

  • pradeep Jul 25, 2009 @ 15:59

    nice one…

  • Charanjit Singh Jul 25, 2009 @ 17:19

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

    Charanjit Cheema

  • derDrache Jul 25, 2009 @ 17:50

    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.

    • MetroMagz Dec 1, 2011 @ 14:37

      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.

  • George Jul 26, 2009 @ 2:10

    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.

    • PePa Jul 20, 2014 @ 1:52

      There is an enormous security benefit to disable root login on ssh and only allow 1 particular user name, preferably with a hard to guess and long name:
      AllowUsers very_long_horse_user_dog_name

      If you use LDAP, you make sure you also have a local account with the same name and the necessary sudo rights.

      • Cody Aug 20, 2014 @ 13:01

        Not allowing root is wise. And only allowing one user is fine too, depending on set up (but it kind of breaks multi-user environment, does it not ? It won’t work in many cases …) But the really long name is absurd and unhelpful. Better spend the time on using keys (WITH passphrases), passwords (not simple, short, stupid passwords, no writing it down, unique password, and other password safety practices should be followed) and proper ingress and egress filtering (among other things). Also combine that with (depending on what you need) restricting what commands (with exact parameters and parameter arguments) can be run as a user (if requiring root access, that is …). You could go further too. Besides that, the long name in a way is pointless: if you require ssh keys (which is good if at all possible) and even if not, if they (example) compromise the account that will (or can) ssh to the (example) server, then they’re already ahead of you by quite a bit .. especially true if ~/.ssh/authorized_keys (which is restrictive and good) has the hint of the user and host. Best of all, spend the time educating (and rather increasing awareness) the users. Username is only useful to an extent (I mean there are ways to leak that information and whether you are vulnerable to that or not is only ‘now’ and assuming you never will have that problem (begrudged user getting revenge, anyone?) is a dangerous thing).

        • PePa Aug 20, 2014 @ 17:13

          Could you expand on proper ingress and egress filtering within ssh? Are there certain non-default options that are recomended, or is this done with additional solutions?
          Regarding the long user names, it is another thing that needs to be guessed, as you said yourself, two passwords are better than one. I always laugh when I see in my logs that users named root, admin and somesuch tried to access my ssh server.

          • Cody Aug 20, 2014 @ 19:17

            Sorry – I don’t mean in ssh itself (although there might be an option for all I know). But what I mean is for two examples:
            1. network segregation (including maybe bastion host involved).
            2. firewall (whether software or hardware). of course, this includes src ip and so it may or may not always be applicable.

            As for names, yes, it is funny to see that in logs. But if you can apply 1 or 2 above (and I’m sure there are other examples – there usually are so many ways to do things in Unix and indeed Linux) then you don’t even have that.

            Either way, as for names… well, yeah. It depends on your perspective too. One more layer is always a good thing, and by no means did I mean to not restrict down to as little as possible. Always a good idea indeed to limit. I have a low profile server so I can:
            1. restrict by ip (public as well as private – have a static block)
            2. ssh keys with passphrases and different passwords for root versus users (naturally a good thing).
            3. for certain logins I also restrict command and for instance do not allow pty allocation (great combination with restricted shells, as long as you’re careful). of course, this one also is possible with ssh itself but that is more restrictive (command exactly, sort of like sudo allows).

            So yes, you’re right but I think super long isn’t necessarily any more protective than a shorter name. I mean as long as you’re not having an obvious login (of course: define “obvious” – data enumeration …) then you’re still ahead.

            Apologies on any confusion with the ingress/egress filtering. Did that clarify it ? It was more of a in addition to because indeed it is a layered thing. (On attempts you can also consider things like fail2ban, if for example you cannot restrict by IP).

  • anomie Jul 26, 2009 @ 15:56

    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.

    • Enzo Aug 3, 2011 @ 6:08

      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.

      • Philippe Petrinko Aug 3, 2011 @ 7:41


        > “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.

        • Cody Aug 3, 2011 @ 13:09

          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.

  • anomie Jul 26, 2009 @ 15:58

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

  • 🐧 nixCraft Jul 26, 2009 @ 16:27

    @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.

  • nbensa Jul 26, 2009 @ 17:50

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

    ssh nbensa@ldap
    nbensa@ldap:~$ su –

  • mossholderm Jul 26, 2009 @ 18:23

    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?!? 🙂

    • markhahn Aug 5, 2011 @ 18:54

      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.

      • CiderMark Aug 9, 2011 @ 7:33


        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!!!

      • graz Jan 22, 2012 @ 10:11

        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..

        • robsku Apr 9, 2013 @ 11:25

          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.

  • mossholderm Jul 26, 2009 @ 18:26

    @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.

  • Mouring Jul 27, 2009 @ 2:55

    #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

    • Jason Aug 3, 2014 @ 9:28

      You are right. I wasted my time trying to configure this only to find out it is not what NixCraft said it was.

  • Lawrence D'Oliveiro Jul 27, 2009 @ 11:12

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

    • Cody Feb 3, 2011 @ 14:23

      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).

  • Rob Lingle Jul 27, 2009 @ 16:48

    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.

  • Mauro Jul 27, 2009 @ 20:02

    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?

  • Chris Jul 27, 2009 @ 20:47

    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!

  • richard Jul 27, 2009 @ 22:10

    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)

  • Per H Jul 27, 2009 @ 22:14

    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.

    • Chris May 7, 2011 @ 12:57

      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?

  • Ed Jul 28, 2009 @ 16:06

    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.

  • sasdaman Jul 28, 2009 @ 22:47

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

  • Kapil Jul 29, 2009 @ 8:23

    Nice Tutorial

  • swapnil Jul 29, 2009 @ 18:24

    great.Really helpful.tahnks

  • nbensa Jul 29, 2009 @ 18:55

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

  • 🐧 nixCraft Jul 29, 2009 @ 19:57


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

  • Leszek Jul 29, 2009 @ 20:40

    Great suggestions as usual Vivek! Thanks!

  • Andrés Aquino Jul 30, 2009 @ 18:08

    thanks man, very useful…

  • lyonn Aug 4, 2009 @ 20:32

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


  • jabellon Aug 5, 2009 @ 10:54


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

    Thanks a lot

  • Dot2Kode Aug 14, 2009 @ 22:59

    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!

  • BlueNile Aug 19, 2009 @ 10:13


    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.

  • anonym2 Aug 26, 2009 @ 21:11

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

  • Lennie Aug 31, 2009 @ 1:23

    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,

  • ungeekdeplus Sep 1, 2009 @ 7:57

    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 !!

  • Ricardo Sep 14, 2009 @ 17:32

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

  • Marlon Sep 17, 2009 @ 13:46


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

  • Nina Sep 30, 2009 @ 7:44

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

  • Theodis Butler Sep 30, 2009 @ 17:18

    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.

  • Henrik Oct 2, 2009 @ 13:07

    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) ).

  • Sean Oct 3, 2009 @ 16:59

    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

  • Greg Bowyer Oct 10, 2009 @ 10:25

    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)

    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.

  • Wirasto S. Karim Oct 13, 2009 @ 13:52

    Good tutorial. Thank’s.

  • Michael Lam Oct 15, 2009 @ 5:09

    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).

  • Philippe Oct 16, 2009 @ 12:44

    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?

  • John W Oct 24, 2009 @ 6:45

    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.

  • Foamhead Oct 31, 2009 @ 5:34

    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!

  • Bhaskar Chowdhury Nov 4, 2009 @ 14:02

    Thanks vivek. Quite a handful of procedures.

  • Jim Gray Nov 9, 2009 @ 15:30

    @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.

    • roger Jan 31, 2011 @ 22:41

      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.

  • Sujit Nandi Nov 20, 2009 @ 16:03

    thanks guys.this is really good disc.

  • Stefano Nov 22, 2009 @ 16:09

    Just thanks! 🙂

  • Knut-Perry G Brumoen Dec 14, 2009 @ 1:41

    @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

  • joe Dec 27, 2009 @ 17:31

    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.

  • snap Dec 31, 2009 @ 23:05

    Uh, no PermitRootLogin without-password?
    PasswordAuthentication no?

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

  • TechiePark Feb 3, 2010 @ 11:36

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


  • 2hot6ft2 Feb 5, 2010 @ 16:16

    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:

    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.

  • Val Feb 9, 2010 @ 15:42

    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.

  • KRRAJU Mar 2, 2010 @ 16:25

    Wow awesome and Excelnt articles for Unix [Linux] .

    Thanks a lot to share with us.


  • Live Mar 21, 2010 @ 3:36

    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?


  • TheGrendle Apr 27, 2010 @ 17:48

    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.

  • someone May 10, 2010 @ 17:55

    @#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.

  • Philippe Petrinko May 11, 2010 @ 16:27

    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.

    • 🐧 nixCraft May 11, 2010 @ 20:37

      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.

  • Nathan Fisher May 14, 2010 @ 12:55

    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.

  • Anonymous Jun 22, 2010 @ 8:49

    1′ OR ‘1’=’1

    • nyuszika7h Aug 2, 2011 @ 18:38

      Nice try, but that didn’t work. 🙂

  • Aruljane Jun 28, 2010 @ 6:37

    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

    • A6RV Jan 12, 2016 @ 23:25

      Another one:
      ###iptables -A INPUT -p tcp –dport 22 -j ACCEPT ### comment this line
      iptables -A INPUT -p tcp –dport 22 -m state –state NEW -m recent –name tcp22 –set
      iptables -A INPUT -p tcp –dport 22 -m state –state NEW -m recent –name tcp22 –update –seconds 5 –hitcount 2 -j DROP
      iptables -A INPUT -p tcp –dport 22 -m state –state NEW -m recent –name tcp22 –update –seconds 180 –hitcount 3 -j ACCEPT
      Works very good.

  • Dave Jun 30, 2010 @ 23:22

    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.

    • robsku Apr 9, 2013 @ 17:44

      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.

  • Sal Sep 25, 2010 @ 20:22

    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.

  • Philippe Petrinko Sep 26, 2010 @ 8:04

    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.


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

  • Hasan Zubair Nov 6, 2010 @ 15:51

    very Nice article

  • Sreejith Sathyan Nov 25, 2010 @ 10:24

    Very nice Tutorial…..

  • zcworld Feb 16, 2011 @ 2:13

    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

  • Bhanu Feb 16, 2011 @ 4:15

    Thank you.

  • IlayarajaDharmaraj Mar 15, 2011 @ 12:03

    Very nice & usefull tutorial. Thanks

  • Zoltan SEBESTYEN Mar 30, 2011 @ 19:50

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

  • ubundom May 27, 2011 @ 13:10

    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
    #8: Firewall SSH Port # 22

    • BoBo May 27, 2011 @ 23:08


      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.

    • Cody May 27, 2011 @ 23:14

      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.

  • Johannes Jul 8, 2011 @ 10:08

    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

  • Roland Jul 21, 2011 @ 10:57

    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?

    • Cody Jul 21, 2011 @ 13:46

      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).

  • Roland Jul 21, 2011 @ 15:37

    #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.

    • Cody Jul 21, 2011 @ 15:57

      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!

      • robsku Apr 9, 2013 @ 18:30

        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 🙁

  • Pkboyz Aug 2, 2011 @ 18:49

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

  • Vietnam advisor Sep 6, 2011 @ 11:23

    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.

  • Jose Baars Oct 3, 2011 @ 16:58

    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.

    • robsku Apr 9, 2013 @ 18:50

      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.

    • JoseLargo Oct 5, 2014 @ 19:41

      Don’t know if it is still the case but it used to be true that you could create more than 1 account with the same UID. That way Jose and Beth could each have their own username / password but both be user root. (whoami would return the name of the first user in /etc/passwd regardless of who you logged in as and there were some other weirdness but it worked).

      You did this by editing the relevant files by hand. I have not tried this since the 90s.

      • Cody Oct 11, 2014 @ 0:42

        Quickly as I have to run for the day:

        effective user id (geteuid syscall) versus real user id (getuid syscall). Yes, some subtleties exist but they are quite useful (they = real versus effective uid).

        Depending on what you want, a group (wheel comes to mind) might be better. If it is just for non-privileged users (or less privileged tasks) then you could make a different group (wheel does after all have specific uses). As for what you suggest: you don’t need to edit the files at all, not with the useradd and groupadd commands (been too long since I’ve used non Linux systems, to remember what is done there or how). groupadd and useradd have an option specifically for it (if I recall it is -o).

      • PePa Oct 11, 2014 @ 7:41

        Create another root-user with login name NAME:
        useradd -r -o -u 0 -g 0 NAME
        (options meaning: -r: system account, -o: duplicate UID, -u 0: UID=0, -g 0: GID=0)

        • Cody Oct 11, 2014 @ 13:47

          Yes, that’s exactly it. I didn’t think of -r (I wasn’t thinking of system accounts either so much as accounts with same uid) but yes that is there too. And you have similar for groupadd except that there is no uid (obviously). As for creating another root user, there’s always going to be risks but that goes for everything.

          Even then though it is a good idea – whether you have more than one uid 0 or not – to require group wheel (of course if you place all users in wheel that sort of defeats the purpose, but…). Most importantly though, and this is what it comes down to in the end: don’t give access to someone you cannot trust. Especially root but even not. If they cannot be trusted they are a risk.

          Naturally you could trust them at some point and then find out later you cannot but you can save yourself a lot of trouble by always being careful and always considering risks (because they always exist).

    • Cody Oct 11, 2014 @ 0:48

      Well, no, Jose.

      sudo has it that you can allow exactly one command and its exact command line. Yes, sudo isn’t for every single thing but what is?

      Similar, with su you can only allow wheel group (for example). PAM offers a lot more.
      Even besides that there’s many other ways to solve problems in Unix… many many ways.

      But as for flaws: humans are the problem there. No getting around that.

  • vinit Nov 26, 2011 @ 12:36

    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 thanks

  • arrogant admin Nov 27, 2011 @ 10:41

    # 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.

    • Cody Feb 19, 2015 @ 1:30

      Just to remark:

      ISPs nameservers aren’t misconfigured. The problem is that most IPs are dynamic (at least, assigned to customers dynamically) and the ISP has authority over the PTR records (and all the zones related to their network). What else can they point to? There isn’t any other domain name involved and most (all ?) systems don’t name themselves after their ISP assigned ‘stock’ name. That’s understandable, though. But for instance, those who run mail servers (‘hi Cody!’) know that this is a good thing, not a bad thing (and as for name servers being down – that’s also why mail servers don’t have to reject mail when there is a temporary error although they certainly can).

      True, the setting has its downsides but in general reverse lookups do have value to them. (It might very well depend on the circumstances – not every service needs this but some do – no real comment on ssh)

  • Siddharth Dec 12, 2011 @ 19:13

    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

  • Henry Paul Dec 30, 2011 @ 6:00

    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.

  • MUNIKRISHNAN.M Jan 9, 2012 @ 6:12

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

    thank you

  • Andrew Bruce Jan 19, 2012 @ 0:59

    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).

  • precious Mar 27, 2012 @ 16:31

    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

  • Andrey Mar 29, 2012 @ 4:26

    Thank You!

  • AnomyII Apr 15, 2012 @ 17:33

    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.

  • Skaperen Apr 16, 2012 @ 19:41

    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.

  • undermined Apr 26, 2012 @ 16:29

    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…

  • Lucas Dohring Apr 28, 2012 @ 21:15

    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.

  • Peter O May 9, 2012 @ 9:17

    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.

  • C H Jun 1, 2012 @ 0:00

    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.

  • Mr Smith Jun 10, 2012 @ 8:47

    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. 🙂

  • A Jun 17, 2012 @ 1:12

    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)
    (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?


  • Haakon Løtveit Jul 8, 2012 @ 15:28

    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.

  • PFudd Oct 2, 2012 @ 5:51

    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.


    • Cody Oct 2, 2012 @ 23:29

      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.

  • AdvancedBeginner Oct 15, 2012 @ 16:14

    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…

    • Cody Feb 19, 2015 @ 1:33

      They likely already have the information from other places. Still, there is no need to include this information; they don’t care about your policy – if they’re there to root your server, they’re already disregarding the law, why would your warning make them rethink it ? The law is the law, right ? (I mean of course I’m neglecting those in authority .. the law is the law for citizens)

  • Erik Oct 18, 2012 @ 23:29

    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.

    • Cody Oct 20, 2012 @ 19:31

      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.

  • anon Oct 23, 2012 @ 16:32
    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.

  • Nathan Oct 23, 2012 @ 19:51

    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.

    • Cody Oct 23, 2012 @ 23:40

      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).

  • Chase Venters Oct 23, 2012 @ 20:04

    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.

  • Winston Weinert Oct 31, 2012 @ 16:41

    Another good option is to comment out the “auth” lines for “” and “” 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.

  • Kevin Dec 19, 2012 @ 0:50

    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.

  • Boyd Kelly Jan 19, 2013 @ 16:43

    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.

  • krnkris Feb 6, 2013 @ 15:58

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

    Based on:

  • Madhusudan Mar 25, 2013 @ 12:07

    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

  • rups Jun 17, 2013 @ 13:03

    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.


  • Anonymous Jun 18, 2013 @ 20:50

    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.


    • Cody Jun 18, 2013 @ 23:56

      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.)

  • Gaston Wagner Mar 19, 2014 @ 21:32

    md5 pass:
    echo “A great password” | md5sum

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

  • Bobba Jun 25, 2014 @ 8:27

    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.

    • Cody Jun 25, 2014 @ 16:51

      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).

  • male Jul 2, 2014 @ 7:14

    #16: Thwart SSH Crackers (Brute Force Attack)
    pam-abl is missing, which is pretty usefull thing.

  • Forrest Jul 15, 2014 @ 17:32

    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?

    • Cody Jul 16, 2014 @ 12:00

      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.


  • Azat Khanzadyan Sep 12, 2014 @ 11:34

    Thank you !!!!!!!!!!!!!!!

  • Gui Jan 8, 2015 @ 14:41

    Isnt the point about preventing root login, being still valid in 2015, to prevent an attacker to have a valid user to attemp connection to ssh server?

    I’ve been told that then the attacker must guess both username and password thus increasing security.

    • Cody Jan 25, 2015 @ 15:37

      That is one of the points, yes. Some dismiss it, though. Some have their own reasons, needs, whatever. Doesn’t mean the point you refer to is less valid though. It IS a fairly static thing, whether it is acceptable given the needs (and what they’re willing to do to solve any potential problems, and I mean solve outside of doing it the way they insist they have to (it isn’t always true but that is also how it works)) is another issue entirely. Indeed, different environments and different circumstances do change things – potentially a lot – but that is how life is with everything, is it not ?

      • Philippe Petrinko Jan 25, 2015 @ 17:16

        Let’s agree we disagree, Cody.

        I haven’t seen yet a single good reason why a responsible administrator should let “root” use ssh.

        Ah yeah, except lazyness and incompetence, that’s right! 😉


  • Cody Jan 25, 2015 @ 18:01

    Ironically I rather agree with you. On the other hand you need to improve your reading comprehension (to be fair it might also be the way I word things – that can trip people up even when I’m not doing it deliberately). I was not at all suggesting it was a good idea. Quite the opposite.

    • Philippe Petrinko Jan 25, 2015 @ 21:35


      Well, to be fair,
      Your answer was so long to me, and your wording was so unprecise, vague, ambiguous (again, to me) and that it seems that you also meant
      “yes in a way,
      but may be not,
      it depends,
      somehow, blah, blahn blah, and that’s life…”

      Anyway, to keep it short and simple (you may need to improve on this 😉 ),
      for saying a simple thing (that I tried to sum up in a punchy way : no good reason to let “root” use ssh) that I figured out :
      – either you were making a joke
      – either we disagree.

      AFAIK, TINA: there is no alternative: kill the root access through ssh, unless you want to get in trouble…


      • Cody Jan 26, 2015 @ 0:20

        Let me try explaining it then.

        I was responding to this bit: “Isnt the point about preventing root login, being still valid in 2015, to prevent an attacker to have a valid user to attemp connection to ssh server?”

        So when I write:
        “That is one of the points, yes. Some dismiss it, though. Some have their own reasons, needs, whatever. Doesn’t mean the point you refer to is less valid though.”
        It means yes, it is A point (hence one of THE). BUT some dismiss it (the second sentence as starter). Then I elaborate on how others have different needs/wants and even refuse to acknowledge the existence of other alternatives (that would solve their so called problem). That is – just as I also explain – much like so many other things in this life. No, there was no ambiguity in my points; you just didn’t follow it all – something tripped you up (I suspect the fact I was remarking on those for and those against). It really doesn’t matter what, though – what matters is you accept that. See, just like people dismissing things because they do whatever they want to (and believe what they want to and can’t admit they’re wrong when they are)… well so too can people make mistakes. The only true mistake is not accepting you can make mistakes (and if you can – which I gather you can – you can learn so much more). Basically, I was responding to all angles of the point: those for the restrictions (and they’re right and you agree) and those against it (and they’re wrong but they still have their reasons – just like everything in this world). Yes, it is asking for trouble as you rightly point out. Even if it wasn’t asking for trouble security wise, it is asking for trouble in other ways. Doesn’t mean everyone cares though!

        Does that make sense ? Maybe I shouldn’t ask…

        • Philippe Petrinko Jan 26, 2015 @ 12:08


          First, let me say I do appreciate your contributions to this site and topic.

          At least, you build a strong technical answer and give and share your experience and knowledge, that is my first agreement.

          Second, I am confortable with the fact I could make any mistake, including misinterpreting your wording. And I have no problem admitting I could be wrong and learn from my mistakes, and admitting I do not own “truth” in any way. Plus, english is not my native language, nobody’s perfect. 🙂

          Third, I am just asking : Do you know any good reasons you would _personally_ let root a direct login through ssh? (Would you please just answer a simple “No”. If you mean “Yes”, then please elaborate your personal arguments in a specific environment, just to prevent a generic answer that would lead to nowhere precise and useful – IMNSHO ).

          • Cody Jan 26, 2015 @ 13:03

            I deny it outright. Just like I deny password logins (keys + passphrases). I thought I was clear with that. So ANSWER: No. There is no valid (keyword valid) reason.

            Elaboration here: Indeed I am not at all perfect either. I find that a strength even because it means I can learn more. I actually thought I did answer that question but apparently I neglected it in the end (a consequence of wording things on the go as well as being preoccupied at the same time). Not only do I not think there’s any good reason, I KNOW there isn’t a single valid reason to allow root to log in via ssh. There is no need for it. I might have referred to that here, even (in another post in this thread). I don’t know why people think they need to. I also don’t understand it: if they can LOG IN with root (via ssh) WHY CAN’T they log in with a normal user ? root IS the privileged account so certainly if they have that the privileges that way they can obtain them after logging in ? Their logic is flawed 100%.

            But what I was trying to get at is: they’ll still make excuses. I believe one of their excuses is they need it for backups. I don’t buy that theory. Even if it IS what they do use it for, there certainly are ways around it (and if they refuse to do acknowledge it, it is as you say – they’re asking for trouble and you’re right. they’re also as I say – they’re refusing to acknowledge the problems with it and they’re making up their excuses, their different environment, blah blah.. it is all flawed though).

            As for your English: it is fine. Lastly, your original message to me, that you ended it with:

            “Ah yeah, except lazyness and incompetence, that’s right! ;-)”

            1. Just as a helpful note: laziness 🙂
            2. You’re right: it is laziness (and a workaround to a supposed problem and workarounds ignore the real issue) and indeed it is incompetency (and ignoring the seriousness of the problems they are ironically creating (when they think they’re fixing a problem)).

  • Philippe Petrinko Jan 26, 2015 @ 13:41

    @ Cody,

    Thanks for your update, you made your point quite clear, shorter and simplier than your average post I read in this topic. 😉

    Please accept my apologies for my laziness with english spelling! (Thanks for letting me know, I think I’ll recall it better now. Let’s go back to practice my merriam-webster online – I do enjoy this one, even if it’s US, not UK 🙂 ).

    • Cody Jan 26, 2015 @ 14:43

      .. ick. Merriam Webster. (Indeed the reason I say that is exactly because it is US and more than that Noah Webster and his absurd amount of changes – and attempts at further changes – in English. Language is for communication and changing a language by creating many differences (in spelling and otherwise) is hardly helpful for communication).

      (And no problem on the update. I did suggest I can easily confuse and while I wasn’t then – and don’t here in general – I do admit sometimes (probably a lot! it is really funny to me to make people think “what the hell is he saying” and even more so when I’m subtly saying something they wouldn’t expect; *shrug* no one is perfect, eh ?) I do it just out of the great amusement it gives me. I am quirky in many ways and I show it just as many ways, writing included. And for the spelling – love the pun there! No such thing as a bad pun, far as I”m concerned. No, I was only correcting you because I know many who do not speak (as first language) English like to know what is correct and what isn’t – I really find that trait commendable!).


  • Philippe Petrinko Jan 26, 2015 @ 15:22


    My Dear PenPal,
    We (I) enjoy your quirky ways.

    So, would you say Oxford English Dictionary instead of MW?

    ESLpod (English as a Second Language) is a wonderful resource to me. I download its Podcasts. (Yeah, Californian as far as I understand, so not UK, again).

    By the way, learning ESL is a tough goal, but then having to deal with _almost_ two different languages (UK vs US) is another fun part of the deal. 😉

    I have always wondered how english native speakers (UK and US) agreed on their Wikipedia single “English” vocabulary. Do you know if there has been an agreement? (for instance using UK-english only).

    — oooops — I may be quite out of scope of ssh right now…

    • Cody Jan 27, 2015 @ 15:33

      Very much so off topic. Normally I’d let it happen (that is, make sure it goes as far off topic as possible) out of the amusement it gives me, but… I’ll refrain from that here (this is a thread that should mostly remain on topic for its intended goal – it isn’t a discussion forum): I’ll just respond to two things without elaboration. Yes I like Oxford; Wiki has different authors just like this thread (am I back on topic ? 🙂 ) so it varies, I think. Now… ssh. I know I remarked on some of the points but here’s some other remarks:

      10: It cannot be stressed enough how important it is to use strong user passwords and passphrase for your keys.

      It should also be stressed that you shouldn’t reuse (reuse implies in more than one location!) passwords, passphrases or anything of the sort (of course that is beyond ssh I suppose but still relevant to the discussion).

      As for tcpwrappers – and I think I might have remarked here and same with others – it should be tcpwrappers or iptables, not both (although I have a very vague memory that they can go together it seems rather silly to configure one and then worry about the other).

      On 20: yes, you should use update managers to keep it up to date. No, you should not patch it yourself as long as (and Red Hat distributions do this as do others) the packages include backports (when not updated to most recent release). I should point out that this has multiple gains, not doing it manually, and frankly versions (and other information) can still be enumerated. But version is irrelevant: hiding version hardly stops brute force; scanners and the like really don’t care what version it is because they’ll try everything until blocked. So compiling it yourself is making things more difficult to track (and verify) and that includes available updates! If you don’t have a binary based distro, then that is another issue entirely. You might also (in any case) want to be on the security lists (to keep up to date with current issues). The latter bit goes especially if you compile it yourself but it can be of use otherwise (still not recommended to compile if you are receiving updates …).

      (Like how I did that, Philippe ?)

  • Fábio Aug 10, 2015 @ 23:49

    Very good practices, thank you for posting this!

  • Hugh Buntu Nov 5, 2015 @ 18:54

    I generally ignore advice from people who have such bad English writing skills that I have to spend an excessive amount of time decoding what they are trying to say.

    Just sayin’ – if you want to communicate, master your tool!

  • L33tSp34k3rT04n1m41s Apr 19, 2017 @ 0:31

    Quite frankly, Bob is an ID10T. If I can continue to hammer away at your “root” user until I can guess the password, your pwnd.

    Root cannot be locked out and your simple SSH config isn’t going to be enough to stop me if I really want to get in. I can just sit back and let my bot hammer away until I get it.

  • miphix Jul 25, 2017 @ 20:08

    I routinely choose to do a refresher of the basics and find nixCraft to have solid advice. I also find that the gets hammered for the advice he gives (and not gets hammered on the advice he could give.). With that said, I would like to point out, that sharing advice in general to contribute to someone else’s journey through their Linux adventure to be easier, more akin to the Linux spirit. A far cry from those that are so smart that they not only can find the time to pick his bones about details, and require the content enough to venture forth and find his guides. .

    I just wanted to pitch suggestions in addition to the guide. Understandably, a lot of those that read these guides are at home connecting to a Linux box on any particular VPS provider that fits their fancy (wallet, even. Yes, you! AWS hippies. 😛 ). I find it peculiar that a swath of ‘Linux’ nerds so aptly forget the capacity of their networking equipment. Cisco L2( <<— OSI model if you're lost) switches can mitigate spoofing visa vi MAC addressing, as well as limit multiple MACs to a specific port, and if the switch finds the MAC on its list. That or if it has too many on its list for that interface, it will elect to shut that port(<– interface, if you haven't read a book.) down.

    IP spoofing: — The primary issue with IP spoofing, is that unless the spoofing machine is on the same broadcast domain as the device that's being spoofed. The attack never receives a successful TCP handshake to keep going because the router knows where the actual IP is. Which is why it has to be on the same broadcast domain. Unless you can manipulate the ARP table of the opposite interface to return to you. UDP is mitigated by a small handful of functions embedded in the programs that are designed to converse with UDP (Go ahead, try to stream youtube to some poor fool. "derpa derp, DNS amplification!" *pets the duck-wit* "good job, you're learning").

    MiTM: — Unless you can manipulate a mid-stream router, configuring static arp to take effect after boot puts a dead stop to this being successful
    set -e
    [ "$IFACE" != "lo" ] || exit 0
    case "$ADDRFAM" in
    if [ "$IFACE" = "eth0" ]; then
    /usr/sbin/arp -s de:ad:be:ef:ca:fe
    Brute force: – fail2ban has always failed me. Personally, it has a weird habbit of bunging up the rest of my firewall rules. If you have this figured out, share in a comment (excluding comments containing, "it works for me." That's why you use it, right?). Instead of running an entire RAM chewing daemon that essentially does what can be done in a crude 5 lines of iptables (shares the same space as your network stack, anyways).

    (Input; denied: output; accepted. Established; maintained)
    # iptables -N IN_SSH
    # iptables -A INPUT -p tcp –dport ssh -m conntrack –ctstate NEW -j IN_SSH
    # iptables -A INPUT -p tcp –dport ssh -m conntrack –ctstate NEW -j IN_SSH
    # iptables -A IN_SSH -m recent –name sshbf –rttl –rcheck –hitcount 3 –seconds 10 -j DROP
    # iptables -A IN_SSH -m recent –name sshbf –rttl –rcheck –hitcount 4 –seconds 1800 -j DROP
    # iptables -A IN_SSH -m recent –name sshbf –set -j ACCEPT

    If you're crafty. You can configure a port knock that, instead of opening the inbound port, opens the outbound connection. You can cause any one without the knock sequence to initiate a TCP handshake with syn,ack. and cause the whole thing to hang without a word from sshd. just as one example that totally excludes the variety of ipset scripts out there to block known malicious IPs. And if you're sitting there with a script purring away at an SSH log-in. It's a good bet you're on that list. Just a shot in the dark, though. Why -use- one language for the keyboard while entering passwords. [host] + [space] allows you to switch between keyboards without interacting with the password mechanism.

  • Baku Tai Mar 10, 2021 @ 7:47

    Secured my FreeBSD ec2 server using it your page.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum