OpenSSH is the implementation of the SSH protocol. OpenSSH is recommended for remote login, making backups, remote file transfer via scp or sftp, and much more. SSH is perfect to keep confidentiality and integrity for data exchanged between two networks and systems. However, the main advantage is server authentication, through the use of public key cryptography. From time to time there are rumors about OpenSSH zero day exploit. Here are a few things you need to tweak in order to improve OpenSSH server security.
Default Config Files and SSH Port
- /etc/ssh/sshd_config - OpenSSH server configuration file.
- /etc/ssh/ssh_config - OpenSSH client configuration file.
- ~/.ssh/ - Users ssh configuration directory.
- ~/.ssh/authorized_keys or ~/.ssh/authorized_keys - Lists the public keys (RSA or DSA) that can be used to log into the user’s account
- /etc/nologin - If this file exists, sshd refuses to let anyone except root log in.
- /etc/hosts.allow and /etc/hosts.deny : Access controls lists that should be enforced by tcp-wrappers are defined here.
- SSH default port : TCP 22
#1: Disable OpenSSH Server
Workstations and laptop can work without OpenSSH server. If you need not to provide the remote login and file transfer capabilities of SSH, disable and remove the SSHD server. CentOS / RHEL / Fedora Linux user can disable and remove openssh-server with yum command:
# chkconfig sshd off
# yum erase openssh-server
Debian / Ubuntu Linux user can disable and remove the same with apt-get command:
# apt-get remove openssh-server
You may need to update your iptables script to remove ssh exception rule. Under CentOS / RHEL / Fedora edit the files /etc/sysconfig/iptables and /etc/sysconfig/ip6tables. Once done restart iptables service:
# service iptables restart
# service ip6tables restart
#2: Only Use SSH Protocol 2
SSH protocol version 1 (SSH-1) has man-in-the-middle attacks problems and security vulnerabilities. SSH-1 is obsolete and should be avoided at all cost. Open sshd_config file and make sure the following line exists:
Protocol 2
#3: Limit Users' SSH Access
By default all systems user can login via SSH using their password or public key. Sometime you create UNIX / Linux user account for ftp or email purpose. However, those user can login to system using ssh. They will have full access to system tools including compilers and scripting languages such as Perl, Python which can open network ports and do many other fancy things. One of my client has really outdated php script and an attacker was able to create a new account on the system via a php script. However, attacker failed to get into box via ssh because it wasn't in AllowUsers.
Only allow root, vivek and jerry user to use the system via SSH, add the following to sshd_config:
AllowUsers root vivek jerry
Alternatively, you can allow all users to login via SSH but deny only a few users, with the following line:
DenyUsers saroj anjali foo
You can also configure Linux PAM allows or deny login via the sshd server. You can allow list of group name to access or deny access to the ssh.
#4: Configure Idle Log Out Timeout Interval
User can login to server via ssh and you can set an idel timeout interval to avoid unattended ssh session. Open sshd_config and make sure following values are configured:
ClientAliveInterval 300 ClientAliveCountMax 0
You are setting an idle timeout interval in seconds (300 secs = 5 minutes). After this interval has passed, the idle user will be automatically kicked out (read as logged out). See how to automatically log BASH / TCSH / SSH users out after a period of inactivity for more details.
#5: Disable .rhosts Files
Don't read the user's ~/.rhosts and ~/.shosts files. Update sshd_config with the following settings:
IgnoreRhosts yes
SSH can emulate the behavior of the obsolete rsh command, just disable insecure access via RSH.
#6: Disable Host-Based Authentication
To disable host-based authentication, update sshd_config with the following option:
HostbasedAuthentication no
#7: Disable root Login via SSH
There is no need to login as root via ssh over a network. Normal users can use su or sudo (recommended) to gain root level access. This also make sure you get full auditing information about who ran privileged commands on the system via sudo. To disable root login via SSH, update sshd_config with the following line:
PermitRootLogin no
However, bob made excellent point:
Saying "don't login as root" is h******t. It stems from the days when people sniffed the first packets of sessions so logging in as yourself and su-ing decreased the chance an attacker would see the root pw, and decreast the chance you got spoofed as to your telnet host target, You'd get your password spoofed but not root's pw. Gimme a break. this is 2005 - We have ssh, used properly it's secure. used improperly none of this 1989 will make a damn bit of difference. -Bob
#8: Enable a Warning Banner
Set a warning banner by updating sshd_config with the following line:
Banner /etc/issue
Sample /etc/issue file:
---------------------------------------------------------------------------------------------- You are accessing a XYZ Government (XYZG) Information System (IS) that is provided for authorized use only. By using this IS (which includes any device attached to this IS), you consent to the following conditions: + The XYZG routinely intercepts and monitors communications on this IS for purposes including, but not limited to, penetration testing, COMSEC monitoring, network operations and defense, personnel misconduct (PM), law enforcement (LE), and counterintelligence (CI) investigations. + At any time, the XYZG may inspect and seize data stored on this IS. + Communications using, or data stored on, this IS are not private, are subject to routine monitoring, interception, and search, and may be disclosed or used for any XYZG authorized purpose. + This IS includes security measures (e.g., authentication and access controls) to protect XYZG interests--not for your personal benefit or privacy. + Notwithstanding the above, using this IS does not constitute consent to PM, LE or CI investigative searching or monitoring of the content of privileged communications, or work product, related to personal representation or services by attorneys, psychotherapists, or clergy, and their assistants. Such communications and work product are private and confidential. See User Agreement for details. ----------------------------------------------------------------------------------------------
Above is standard sample, consult your legal team for exact user agreement and legal notice details.
#8: Firewall SSH Port # 22
You need to firewall ssh port # 22 by updating iptables or pf firewall configurations. Usually, OpenSSH server must only accept connections from your LAN or other remote WAN sites only.
Netfilter (Iptables) Configuration
Update /etc/sysconfig/iptables (Redhat and friends specific file) to accept connection only from 192.168.1.0/24 and 202.54.1.5/29, enter:
-A RH-Firewall-1-INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 22 -j ACCEPT -A RH-Firewall-1-INPUT -s 202.54.1.5/29 -m state --state NEW -p tcp --dport 22 -j ACCEPT
If you've dual stacked sshd with IPv6, edit /etc/sysconfig/ip6tables (Redhat and friends specific file), enter:
-A RH-Firewall-1-INPUT -s ipv6network::/ipv6mask -m tcp -p tcp --dport 22 -j ACCEPT
Replace ipv6network::/ipv6mask with actual IPv6 ranges.
*BSD PF Firewall Configuration
If you are using PF firewall update /etc/pf.conf as follows:
pass in on $ext_if inet proto tcp from {192.168.1.0/24, 202.54.1.5/29} to $ssh_server_ip port ssh flags S/SA synproxy state
#9: Change SSH Port and Limit IP Binding
By default SSH listen to all available interfaces and IP address on the system. Limit ssh port binding and change ssh port (by default brute forcing scripts only try to connects to port # 22). To bind to 192.168.1.5 and 202.54.1.5 IPs and to port 300, add or correct the following line:
Port 300 ListenAddress 192.168.1.5 ListenAddress 202.54.1.5
A better approach to use proactive approaches scripts such as fail2ban or denyhosts (see below).
#10: Use Strong SSH Passwords and Passphrase
It cannot be stressed enough how important it is to use strong user passwords and passphrase for your keys. Brute force attack works because you use dictionary based passwords. You can force users to avoid passwords against a dictionary attack and use john the ripper tool to find out existing weak passwords. Here is a sample random password generator (put in your ~/.bashrc):
genpasswd() { local l=$1 [ "$l" == "" ] && l=20 tr -dc A-Za-z0-9_ < /dev/urandom | head -c ${l} | xargs }
Run it:
genpasswd 16
Output:
uw8CnDVMwC6vOKgW
#11: Use Public Key Based Authentication
Use public/private key pair with password protection for the private key. See how to use RSA and DSA key based authentication. Never ever use passphrase free key (passphrase key less) login.
#12: Use Keychain Based Authentication
keychain is a special bash script designed to make key-based authentication incredibly convenient and flexible. It offers various security benefits over passphrase-free keys. See how to setup and use keychain software.
#13: Chroot SSHD (Lock Down Users To Their Home Directories)
By default users are allowed to browse the server directories such as /etc/, /bin and so on. You can protect ssh, using os based chroot or use special tools such as rssh. With the release of OpenSSH 4.8p1 or 4.9p1, you no longer have to rely on third-party hacks such as rssh or complicated chroot(1) setups to lock users to their home directories. See this blog post about new ChrootDirectory directive to lock down users to their home directories.
#14: Use TCP Wrappers
TCP Wrapper is a host-based Networking ACL system, used to filter network access to Internet. OpenSSH does supports TCP wrappers. Just update your /etc/hosts.allow file as follows to allow SSH only from 192.168.1.2 172.16.23.12 :
sshd : 192.168.1.2 172.16.23.12
See this FAQ about setting and using TCP wrappers under Linux / Mac OS X and UNIX like operating systems.
#15: Disable Empty Passwords
You need to explicitly disallow remote login from accounts with empty passwords, update sshd_config with the following line:
PermitEmptyPasswords no
#16: Thwart SSH Crackers (Brute Force Attack)
Brute force is a method of defeating a cryptographic scheme by trying a large number of possibilities using a single or distributed computer network. To prevents brute force attacks against SSH, use the following softwares:
- DenyHosts is a Python based security tool for SSH servers. It is intended to prevent brute force attacks on SSH servers by monitoring invalid login attempts in the authentication log and blocking the originating IP addresses.
- Explains how to setup DenyHosts under RHEL / Fedora and CentOS Linux.
- Fail2ban is a similar program that prevents brute force attacks against SSH.
- security/sshguard-pf protect hosts from brute force attacks against ssh and other services using pf.
- security/sshguard-ipfw protect hosts from brute force attacks against ssh and other services using ipfw.
- security/sshguard-ipfilter protect hosts from brute force attacks against ssh and other services using ipfilter.
- security/sshblock block abusive SSH login attempts.
- security/sshit checks for SSH/FTP bruteforce and blocks given IPs.
- BlockHosts Automatic blocking of abusive IP hosts.
- Blacklist Get rid of those bruteforce attempts.
- Brute Force Detection A modular shell script for parsing application logs and checking for authentication failures. It does this using a rules system where application specific options are stored including regular expressions for each unique auth format.
- IPQ BDB filter May be considered as a fail2ban lite.
#17: Rate-limit Incoming Port # 22 Connections
Both netfilter and pf provides rate-limit option to perform simple throttling on incoming connections on port # 22.
Iptables Example
The following example will drop incoming connections which make more than 5 connection attempts upon port 22 within 60 seconds:
#!/bin/bash inet_if=eth1 ssh_port=22 $IPT -I INPUT -p tcp --dport ${ssh_port} -i ${inet_if} -m state --state NEW -m recent --set $IPT -I INPUT -p tcp --dport ${ssh_port} -i ${inet_if} -m state --state NEW -m recent --update --seconds 60 --hitcount 5 -j DROP
Call above script from your iptables scripts. Another config option:
$IPT -A INPUT -i ${inet_if} -p tcp --dport ${ssh_port} -m state --state NEW -m limit --limit 3/min --limit-burst 3 -j ACCEPT $IPT -A INPUT -i ${inet_if} -p tcp --dport ${ssh_port} -m state --state ESTABLISHED -j ACCEPT $IPT -A OUTPUT -o ${inet_if} -p tcp --sport ${ssh_port} -m state --state ESTABLISHED -j ACCEPT # another one line example # $IPT -A INPUT -i ${inet_if} -m state --state NEW,ESTABLISHED,RELATED -p tcp --dport 22 -m limit --limit 5/minute --limit-burst 5-j ACCEPT
See iptables man page for more details.
*BSD PF Example
The following will limits the maximum number of connections per source to 20 and rate limit the number of connections to 15 in a 5 second span. If anyone breaks our rules add them to our abusive_ips table and block them for making any further connections. Finally, flush keyword kills all states created by the matching rule which originate from the host which exceeds these limits.
sshd_server_ip="202.54.1.5" table <abusive_ips> persist block in quick from <abusive_ips> pass in on $ext_if proto tcp to $sshd_server_ip port ssh flags S/SA keep state (max-src-conn 20, max-src-conn-rate 15/5, overload <abusive_ips> flush)
#18: Use Port Knocking
Port knocking is a method of externally opening ports on a firewall by generating a connection attempt on a set of prespecified closed ports. Once a correct sequence of connection attempts is received, the firewall rules are dynamically modified to allow the host which sent the connection attempts to connect over specific port(s). A sample port Knocking example for ssh using iptables:
$IPT -N stage1 $IPT -A stage1 -m recent --remove --name knock $IPT -A stage1 -p tcp --dport 3456 -m recent --set --name knock2 $IPT -N stage2 $IPT -A stage2 -m recent --remove --name knock2 $IPT -A stage2 -p tcp --dport 2345 -m recent --set --name heaven $IPT -N door $IPT -A door -m recent --rcheck --seconds 5 --name knock2 -j stage2 $IPT -A door -m recent --rcheck --seconds 5 --name knock -j stage1 $IPT -A door -p tcp --dport 1234 -m recent --set --name knock $IPT -A INPUT -m --state ESTABLISHED,RELATED -j ACCEPT $IPT -A INPUT -p tcp --dport 22 -m recent --rcheck --seconds 5 --name heaven -j ACCEPT $IPT -A INPUT -p tcp --syn -j doo
- fwknop is an implementation that combines port knocking and passive OS fingerprinting.
- Multiple-port knocking Netfilter/IPtables only implementation.
#19: Use Log Analyzer
Read your logs using logwatch or logcheck. These tools make your log reading life easier. It will go through your logs for a given period of time and make a report in the areas that you wish with the detail that you wish. Make sure LogLevel is set to INFO or DEBUG in sshd_config:
LogLevel INFO
#20: Patch OpenSSH and Operating Systems
It is recommended that you use tools such as yum, apt-get, freebsd-update and others to keep systems up to date with the latest security patches.
Other Options
To hide openssh version, you need to update source code and compile openssh again. Make sure following options are enabled in sshd_config:
# Turn on privilege separation UsePrivilegeSeparation yes # Prevent the use of insecure home directory and key file permissions StrictModes yes # Turn on reverse name checking VerifyReverseMapping yes # Do you need port forwarding? AllowTcpForwarding no X11Forwarding no # Specifies whether password authentication is allowed. The default is yes. PasswordAuthentication no
Verify your sshd_config file before restarting / reloading changes:
# /usr/sbin/sshd -t
Tighter SSH security with two-factor or three-factor (or more) authentication.
References:
- The official OpenSSH project.
- Forum thread: Failed SSH login attempts and how to avoid brute ssh attacks
- man pages sshd_config, ssh_config, tcpd, yum, and apt-get.
If you have a technique or handy software not mentioned here, please share in the comments below to help your fellow readers keep their openssh based server secure.
Featured Articles:
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- 10 Greatest Open Source Software Of 2009
- My 10 UNIX Command Line Mistakes
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- Top 20 OpenSSH Server Best Security Practices
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Linux Video Editor Software
- Email this to a friend
- Download PDF version
- Printable version
- Comment RSS feed
- Last Updated: Dec/5/2009




{ 58 comments… read them below or add one }
A honeypot for the SSH Service.
http://kojoney.sourceforge.net/
BTW, I haven’t used it before
A very nice tutorial.
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!
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 :-)
nice one…
Hmmm again as I always say AWSOME Dude Thanks.. Really helpfull…
RGD
Charanjit Cheema
RHCT
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.
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.
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.
Should have read: “… from people who can’t communicate…”
@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.
@Geoge: if you add a local user to passwd, then you don’t need root.
ssh nbensa@ldap
nbensa@ldap:~$ su -
root@ldap:
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?!? :)
@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.
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
Strange. You say to disable host-based authentication. Yet you say to use TCP wrappers, which applies host-based permissions!
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.
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?
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!
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)
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: 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.
Thanks great post! Have been looking for a decent article on OpenSSH for a while now! Stumbled upon this by chance!
Nice Tutorial
great.Really helpful.tahnks
i don’t want more replies. how do i unsubscribe from this blog?
@nbensa,
Removed. FYI, there is link at the bottom to manage your thread subscription i.e. “Manage subscriptions” link.
Great suggestions as usual Vivek! Thanks!
thanks man, very useful…
Very effective your post, really i dont know about security of the ssh server, but now i can implements in my system.
greetings!
Hi,
What is the difference between Protocol 2 and Protocol 2,1 ?
and which is better to use and why?
Thanks a lot
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!
jabellon,
If you specify both ssh protocols, the order is significant. Only the first in the order is considered.
SSH Protocol 2 provides additional mechanisms for confidentiality (the traffic is encrypted using 3DES, Blowfish, CAST128 or Arcfour) and integrity (hmac-md5, hmac-sha1). Note that protocol 1 lacks a strong mechanism for ensuring the integrity of the connection.
Some of the major advantages of Portocol 2 over Protocol 1 are listed below.
- Separate transport, authentication, and connection protocols
- Strong cryptographic integrity check
- Any number of session channels per connection
- Supports Publick key authentication which includes DSA, RSA and OpenPGP ( RSA has been recently added)
- User authentication exchange is more flexible, and allows requiring multiple forms of authentication for access.
Use programs like denyhosts or fail2ban. Ideal for brute force attacks.
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,
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 !!
Very good, i don’t have problem!!! Surely, my openSSH is more secure
Hi,
Did you faced with situation that users scape from their resctricted shell directory using putty to send a remote “bash” command ?
Thank you, good tutorial. I’m learning Linux it is very helpful tutorial. Thank you again!!!
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.
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) ).
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
One of the things I did some time ago on one of my ssh servers was to install incrond (a daemon that listens to inotify and then runs a script)
http://inotify.aiken.cz/?section=incron&page=faq&lang=en
I then made it run a script that consitsted of “et call home” and shutdown the machine if certain special filess were touched (/bin/ls passwd /etc/shadow etc etc)
I am sure that similer tricks can be pulled of for the other OS’s.
Good tutorial. Thank’s.
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).
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?
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.
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!
Thanks vivek. Quite a handful of procedures.
@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.
thanks guys.this is really good disc.
Just thanks! :)
@Jim Gray
Have you tried MC?
If you’ve been around since the “old days” you most likely will think Norton Commander when you run it.. ;)
Midnight Commander looks very much like the old Norton Commander, or even the other graphical file manager for DOS, don’t remember the name now. That one also had a blue background just like NC and MC.
Most distros has MC in their repositories..
If not you will find the sources at midnight-commander.org
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.
Uh, no PermitRootLogin without-password?
PasswordAuthentication no?
Use public-key auth, disable passwords, and also solve the brute-force problem for free.
Hello,
I wanted to know how to enable last login in sshd_config?
Thanks
Nice writeup Vivek,
I found a couple things to tweak my SSH server in it that I hadn’t considered. 6 months and your writeup is still useful and getting responses.
There are a couple things that could be added
To #1
“Debian / Ubuntu Linux user can disable and remove the same with apt-get command:
# apt-get remove openssh-server”
That will remove the server. If you just want to stop the server then you would use:
sudo /etc/init.d/ssh stop
Just replace “stop” with “start” or “restart” depending on want you want to do.
Thought of something to add to #11 and that is that best said in this quote:
“SSH can use either “RSA” (Rivest-Shamir-Adleman) or “DSA” (“Digital Signature Algorithm”) keys. Both of these were considered state-of-the-art algorithms when SSH was invented, but DSA has come to be seen as less secure in recent years. RSA is the only recommended choice for new keys, so this guide uses “RSA key” and “SSH key” interchangeably.”
From here: https://help.ubuntu.com/community/SSH/OpenSSH/Keys
On the same page there is this:
Key Encryption Level
Note: The default is a 2048 bit key. You can increase this to 4096 bits with the -b flag (Increasing the bits makes it harder to crack the key by brute force methods).
ssh-keygen -t rsa -b 4096
Keep up the good work.
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.