Posts Tagged ‘ssh’

Best Practices to secure a OPENSSH/SSH Server

What are you using for remote connection?
For linux users there are two protocols which regulate remote connection. One is telnet and the other is ssh.
People use telnet to connect to remote host but problem with telnet is the whole communication between the local host and the remote host is sent in clear text which any one can see if he will put a packet sniffer and start capture the packets. Hence Telnet is not secure.
To avoid this security risk we are using OpenSSH protocol. OpenSSH uses SSH (Secure Shell) protocol which is fully secure as it uses strong encryption like 3DES, Blowfish, AES and also it uses public/private key pair for authentication.
N:B-Whatever steps given below has to be done by following the steps given below.

a.Open two terminals, One for experiment and other for safety if sshd show some problem

b.Take the backup of configuration files

c.After each change reload SSH service only after testing the configuration. You can test it by executing

                         /usr/sbin/sshd –t

d.If you are finding some error in configuration file after executing the above command you should revert back to original config file in order to prevent yourself from getting disconnected.

When configuring SSH the default files we need to edit are

i. /etc/ssh/sshd_config –configuration file for SSH server side.

ii. etc/ssh/ssh_config – Configuration file for client side.

iii.~/.ssh/ -This is the directory where all ssh keypair and authorization file stays

iii./etc/nologin – If this file exists then sshd protocol refuses all login except root login

Now we will come to our topic on configuring a secure SSH server. To make your server secure you can follow the following points. Before changing anything in the default configuration file  always make a backup copy of config files you wish to edit.
1.Change the default port number

By default SSHD protocol runs on port 22. The vast majority of ssh attacks are directed by compromised zombie machines against ssh servers listening on the default port of “22”.Your first task is to change the port for ssh. To do this follow steps below

a. open /etc/ssh/sshd_config file

b. Search for line containing Port 22

c.  Edit that line as Port 2222  //here 2222 port is my choice you can use yours

d.  Save

2.Listen to specific IP Address

In most case you need to connect to your server from your office network or from some specific machine. If you can make your SSHD protocol to listen to those specific IP address and reject others then you will minimize risk of getting attacked from outside world. To do this

a. open /etc/ssh/sshd_config file

b. Search for the line which says

ListenAddress *

c.  Now comment the above line and make entry as per your criteria. Lets say if I will give access to and to access then I have to add following two line



3. Now you need to update IP table rule to allow your allowed IP’s (, to           communicate with the custom port (port 2222 in my case).

4. You can also use IP table throttling feature to throttle the incoming connections

5.    Limit the users(allow or deny) who can access by username
We have already seen how we can limit the number of IP address which can connect to SSH server. We may have multiple users in single system from which some users do not need to access. So we have to restrict that user’s access.  To do sowe can follow the steps

a. Open  /etc/ssh/sshd_config file

b. Add the following line to allow specific user.For example allow users root ,hari,prit

AllowUsers root hari prit

c.        Also we can allow specific groups. To allow a group called ssh access add the line

AllowGroups sshaccess

d. similarly if we want to deny some specific users or groups to use ssh we can add the deny lines .Ex:-If I want to deny users navin,amiya and group kopex then I have to add lines

     DenyUsers navin amiya

     DenyGroups kopex

It all depend upon you how you want to put user access control

6.    Do not allow root login
As we know the power of root we should not allow root users to log in rather we should create some sudo users and we can limit them to doing specific task. Also if someone needs to work as root they can use su command. To disable root login

a. Open /etc/ssh/sshd_config file

b.Uncomment the following line

        PermitRootLogin no

7.Disable Empty Passwords
You should not allow remote login from accounts with empty passwords. If you do this there is chance that some bots will try to log in continuously and damage your system.To do this

a.Open /etc/ssh/sshd_config file

b.Edit the line containing PermitEmptyPasswords  to no

        PermitEmptyPasswords no

8. Configure client idle Timeout Interval
You can set idle time interval for the users who are logging through SSH so that if someone has forgotten to logout from a session the system will log him out immediately. To do this

a. Open /etc/ssh/sshd_config file

b. Set these two lines as per your requirement

               ClientAliveInterval 180         //180 is in seconds
               ClientAliveCountMax 0

9.Disable Host-Based Authentication
Avoid using this method as if you add one host it does not ask for any kind of password to login.To disable host based authentication you can do the following steps

a. Open /etc/ssh/sshd_config file

b. Edit the entry HostbasedAuthentication in the file as below

                     HostbasedAuthentication   no

10. Always use Latest version of SSH as always latest version will be having patches and more security features which makes your job easy or else you have to patch with the latest patch from the vendor.

11. User strong SSH passwords and paraphrases so that it won’t be easy for someone to crack. You can check your password strength using john the ripper tool

12. Use Authentication based on only public/private keys
You can also disable the password and use public/private key pairs to login to remote system. But it is advisable to protect your keys by giving strong paraphrases so that if someone takes your key still he needs to know paraphrase to login

To disable password logins, add the following to sshd_config:
                                                   PasswordAuthentication no

13.  Restrict users to their home directories
Using some tools or chroot concept you can restrict users to their home directories so that they cannot move or delete the configuration and system files.

14. Allow/Deny using TCP Wrappers
As ssh is associated with the library we can implement TCP wrapper concept. So we can allow/deny some specific IP/Host by putting entries into /etc/hosts.allow and /etc/hosts.deny file. For that we need to put an entry at the end of the file like
               sshd : 192.168.1. 8

to allow or deny the IP and to connect the server using SSH.

15. Disable .rhosts Files
The rhosts file specifies which remote computer or users can access a local account using rsh or
rcp commands. So you can disable this. To disable this

a. Open /etc/ssh/ sshd_config file

b. Search for the line containing IgnoreRhosts and make it to yes

         IgnoreRhosts  yes

16. Reduce MaxStartups
MaxStartup means the ability of SSH server to handle unauthorized access to a server at a given instance. This will help in coordinated attack from different server at same time. To achieve this

a. Open /etc/ssh/ sshd_config file

b. Search for the line containing MaxStartup and replace it as

MaxStartups 4:10:8

Here the 4:10:8 tells the ssh server to, “allow 4 users to attempt logging in at the same time, and to randomly and increasingly drop connection attempts between 4 and the maximum of 8”. Note: this should be increased on servers with substantial numbers of valid ssh users logging in.

17. Hide openssh version
This step is not only applicable for SSH but also applicable for all the services running on the system. As no tools/software/packages is free of bugs. This is why people release different versions. If you are running an older version of SSH and hacker knows this he will first try to find out the bugs in this version and using those info he may attack on the particular port. To achive this you have to make changes in source code of ssh and recompile it.

18.  Forward X11 only  if needed
By default, the X11Forwarding directive is set to yes. If you don’t need this, set it to no. If you don’t need this you should disable this. To disable this

a.Open /etc/ssh/ sshd_config file

b.Search for X11Forwarding  and edit as

X11Forwarding   no

For X11 forwarding to work, the ForwardX11 declaration or the ForwardX11Trusted declaration must also be set to yes in /etc/ssh/ssh_config client configuration file.SO to disable you can make it no from this file.

19.  Enable a Warning Banner
Set a warning banner for ssh connection in consultation with your legal advisor in order to warn authorized user what legel action you can take against them. To do this defines a text file location in sshd_config file which contains the warning messages. To do this

a. Open /etc/ssh/ sshd_config file

b. Search for the line containing Banner and edit as given below

Banner /etc/issue

Now you can edit the /etc/issue file to put your warnings.

20. Use Logwatch
Make sure to set LogLevel to INFO or DEBUG in sshd_config. I recommend keeping it INFO as it will give you more details. You can use logwatch to manage the SSH logs. To do this

a.Open /etc/ssh/ sshd_config file

b.Change the line containing LogLevel to info

LogLevel INFO

What else you can do?

–Install some security tools to protect your server from brute force attack

–Patch your operating system

–Remove unnecessary packages / software.

–Harden the kernel against synflood and basic DOS attacks.

–Remove common user access to compilers and fetching software (wget, fetch, lynx, etc.).

— Ensure /tmp is in its own partition with noexec, nosuid.   

–Ensure kernel and software is up to date.

–Remove unnecessary users and groups.

–Install chkrootkit and tripwire.

Lock and Delete SSH Keys for user account

Lets think of a scenario that a user wa using all your critical resources on the remote server via ssh.Now for some reason he is leaving the company.So we need to take all tha access from the user as it is a security risk.So how to do that?please find below the commands to lock and delete a user account on various systems.

The first step is to disable user login using command as follows:

In Linux

# passwd -l userName

In FreeBSD

# pw lock userName

In Solaris / HP-UX UNIX

# passwd -l userName

The next step is to Remove SSH Keys

There are two ways to accompany this task.


in linux/unix environment the ssh keys are stored inside users home direcory.You will find it at


We can simply rename the directory or delete the directory:

#mv /home/userName/.ssh /home/userName/nosshlogin
# rm -rf /home/userName/.ssh 


You can also edit $HOME/.ssh/authorized_keys file and remove public key. This will delete login from user’s computer to your server. Finally, you can always delete user from your system using the pw (FreeBSD) or userdel (Linux / UNIX) command.

Categories: Linux Tags: , , ,

Changing SSH keygen and SSH port perfectly without mistake

Now I am giong to discuss how to change the ssh keygen and port of your remote server.

It is important as setting of ssh keygen needs expertise and self confidense as it involves lots of risk.If you do it wrongly then you may lost connection to your remote server.Then your headache will start like contacting the hosting service provider or if you have a amazon cloud server you loose alla your data. Ok dont be afraid as now I am going to discuss step by step process on how to change your keygen.

Changing SSH Key:-

  • ssh to your server using good old user name and password
  • do check permissions on your ~/.ssh folder and make sure it is set to 700 or else execute

chmod 700 .ssh

  • do check permissions on your ~/.ssh/authorized_keys file and make sure it is set to 600 or else execute

chmod 600 authorized_keys

  • generate the keys on the server with something like

ssh-keygen -t dsa

(or rsa – read the man pages if your don’t know how to use ssh-keygen )

  • accept the file names it wants to use and give the correct path but make sure you type correct absolute path(/root/.ssh not .ssh)
  • enter a strong passphrase or no paraphrase
  • add the pub key to the authorized_keys file with something like

cat >> .ssh/authorized_keys

  • copy the private key (id_dsa) to your local windows machine (use winscp or sftp or some such tool)
  • NOW open puttygen.exe
  • under actions select “load” and load the id_dsa file
  • enter the passphrase you set when you generated the key on the server. Puttygen will now convert the key to something that putty will understand
  • save that file to something like


  • NOW change your putty settings under “connection > SSH > auth” to use


  • NOW try and connect
  • enter the passphrase when prompted
  • Hurray You’re now connected to the server

Changing SSH server port:-

If you won’t change your production server ssh port then you will find a lot of illegal logins to your server.This can expose your server to high security risk.So you need to change the server SSH key before putting your server online.To change the port please follow the steps as mentioned below.

1. From your terminal session, edit /etc/ssh/sshd_config

            bash-2.05b# vi /etc/ssh/sshd_config

2. Look for the following line:

              #Port 22

3. Change the line so it looks like this:

                Port 2995

4. Save and close the file

5. Load the new configuration by using the RedHat service command

         service sshd reload

Note: you will immediately lose connectivity to your server on the open ssh session you are currently running as the port get changed.

6. Test the connection

              (comp@kirti)(~/Desktop) $ ssh -p 2995

Take note of the -p 2995 flag used when connecting to the server. If you are using OS X or a Linux desktop system like Mandriva or Ubuntu, you’ll need to specify the port number when connecting. If you’re using PuTTy on Windows, you can specify the port number in the profile for you connection and then re-save the profile using the new port.

7.If you have enabled ssh service at startup then please check this also.

vi /etc/xinetd.d/sshd

              service ssh
                disable = no
                socket_type  =  stream
                 type               =  UNLISTED
             port                = 22
             protocol         = tcp
             wait                = no
                user                = root
                server             = /usr/sbin/sshd
                server_args   = -i

Change “port = 22” for the new port 2295 and restart. Now You are safe from hackers those who use port 22 to get illegal entry to your server.

Categories: Linux Tags: , , , ,