Securing your OpenSSH server in Linux

| More

Secure Shell (SSH) is a program used to secure communication between two entities, often used as a replacement for Telnet and the Berkeley protocols such as remote shell (RSH) and remote login (Rlogin). SSH is also used as a secure remote copy utility, replacing traditional protocols such as the File Transfer Protocol (FTP) and Remote Copy Protocol (RCP).

For this tutorial, we are going to demonstrate steps on securing your OpenSSH which is a free version of the SSH protocol suite.

Note: Steps 1-9 can be done by  tweaking your sshd_config and do ssh service restart after changes to take effect.

1. Use SSH Protocol 2
Use SSH version 2 (SSH2) only as it offers more performance, flexibility and security than SSH1.
-To verify what SSH protocol version you are running, check your /etc/ssh/sshd_config and look for the line “Protocol”,

[root@freelinux ~]# vi /etc/ssh/sshd_config

Protocol 2

[root@freelinux ~]# /etc/init.d/sshd restart
Stopping sshd: [  OK  ]
Starting sshd: [  OK  ]

2. Disable direct root SSH logins
-disable direct logging in as root via ssh. This is like inviting hackers to brute force your root password.
It’s recommend to login as a normal user and then after that, just use su or sudo if want to execute priviledge commands.

PermitRootLogin no

3. Enable a SSH warning banner
You can display a warning banner before login to require acknowledgment of the contents. This can be done by defining under sshd_config

a. Create a Banner on any location. e.g. /etc/freelinux

[root@freelinux~]# vi /etc/freelinux
All login attempts will be logged!!!

b. Edit /etc/ssh/sshd_config. Locate the line containing “Banner”, uncomment and specify the file location
vi /etc/ssh/sshd_config

# no default banner path

Banner /etc/freelinux

c. Restart ssh service

[root@freelinux~]# service sshd restart
Stopping sshd: [  OK  ]
Starting sshd: [  OK  ]

d. Test:
@ssh client
login as: darwin
All login attempts will be logged!!!
darwin@’s password:
Last login: Fri Oct 19 18:19:12 2012 from

4. Disable empty passwords
To disable empty password, edit /etc/ssh/sshd_config and make sure this line below is uncommented

PermitEmptyPasswords no

5. Disable Host-based authentication
It is not recommended that hosts always agreed to trust one another

HostbasedAuthentication no

6. Configure Idle Timeout
Let say you want the system to log out users after 15 mins of idling. Then you can set this:

[root@freelinux~]# vi /etc/ssh/sshd_config

ClientAliveInterval 300
ClientAliveCountMax 3


This will give a timeout of 15 minutes (300 secs X 3)
ClientAliveInterval – timeout in seconds.
ClientAliveCountMax – total number of checkalive message sent by the ssh server without getting any response from the ssh client

Also,  you can do this 15 minute timeout:
ClientAliveInterval 900
ClientAliveCountMax 0

Additional Tip: This is slightly different with “TMOUT” variable that will terminate the shell if no activity for N seconds
# export TMOUT=N

[root@freelinux~]# export TMOUT=60

7. Limit SSH LoginGraceTime
By default, sshd will allow a connected user that has not begun the authentication process for a period 2 minutes (120 secs) for a grace time. It’s recommended to shorten this time to protect from brute force attacks.

LoginGraceTime 30

8. Change ssh port number
The advantage of this is somehow protects your box against automated attacks or malicious scripts that is trying to get in via ssh default port 22.

Port 35286

9. Limit or Permit only specific users or groups to login
All users by default is allowed to access your box. But you have the options to allow or deny few users or groups. This can be done in either of this way.


AllowUsers darwin tux



DenyUsers user1 user2
DenyGroups group1 group2 group3

10. Update OpenSSH & OS
Make sure your Linux system is running the latest version for OpenSSH. SSH package version depends on your Linux distribution & OS version. Your distro will use the best or stable version for any packages, so if you want to upgrade to another version, you can do this via source package installation. It can be downloaded on OpenSSH official site http://www.openssh.com. Alternatively, you can do it by installing the latest rpm package or changing your repository, then use the yum.

For instance, if you are running CentOS 5.8 to check the current installed package and verify if there’s update, tr the following:

[root@freelinux~]# cat /etc/issue
CentOS release 5.8 (Final)
Kernel \r on an \m

[root@freelinux~]# rpm -qa | grep openssh

[root@freelinux~]# ssh -V
OpenSSH_4.3p2, OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008

[root@freelinux~]# yum update openssh*
Loaded plugins: fastestmirror, security
Determining fastest mirrors
* base: mirror.nus.edu.sg
* extras: mirror.nus.edu.sg
* updates: mirror.nus.edu.sg
base                                                     | 1.1 kB     00:00
extras                                                   | 1.9 kB     00:00
extras/primary_db                                        | 171 kB     00:00
updates                                                  | 1.9 kB     00:00
updates/primary_db                                       | 828 kB     00:01
Skipping security plugin, no data
Setting up Update Process
No Packages marked for Update

11. Enforce access controls list by using TCP wrappers
TCP wrappers is used to restrict access to TCP services based on IP, hostname, network address etc. It supports SSH via the libwrap library. To check if your sshd is

dynamically linked against libwrap:

[root@freelinux~]# which sshd
[root@freelinux~]# ldd /usr/sbin/sshd | grep libwrap
libwrap.so.0 => /lib/libwrap.so.0 (0x00978000)

# The authpriv file has restricted access.
authpriv.*                                              /var/log/secure

Configuration Files of TCP Wrapper

a. /etc/hosts.allow
b. /etc/hosts.deny

The file names are quite self-explanatory.
Access will be allowed when it matches an entry in the /etc/hosts.allow file
Access will be denied when it matches an entry in the /etc/hosts.deny file

But take note of the rules or points to consider
– access rules in hosts.allow are applied first
– rules in each file are read from the top down, so take note the order of rules
– changes in hosts.allow or hosts.deny will take effect immediately, no need to restart any services.
– access to service is permitted if no rules are found in either file
– use ‘#’ character to insert comments
– it uses this format

tcp_service : client_list [ : shell_command ]

tcp_server – daemon process names
client_list – IP, hostnames, patterns, wildcards matching the client address or hostname

There are several patterns that you can use under client_list which we will not covering on this topic. But the recommended setting will be:
Deny anything not explicitly allowed and only Allow certain services.

[root@freelinux~]# cat /etc/hosts.allow
# hosts.allow   This file describes the names of the hosts which are
#               allowed to use the local INET services, as decided
#               by the ‘/usr/sbin/tcpd’ server.

[root@freelinux~]# cat /etc/hosts.allow
# hosts.allow   This file describes the names of the hosts which are
#               allowed to use the local INET services, as decided
#               by the ‘/usr/sbin/tcpd’ server.
sshd : freelinuxtutorials.com : allow
sshd: : allow
sshd : : allow

12. Configure iptables for added SSH security
It’s good to have your servers protected by hardwares or appliances such as security appliances, PIX, ASA etc. that will added more protection such as limiting TCP connections esp. on preventing dictionary attacks.
If you don’t have this, it’s a good thing this can be done also from your Linux server using iptables.

Sample iptables  to allow only specified host:
iptables -A INPUT -p tcp -m state –state NEW –source –dport 35286 -j ACCEPT

Another example iptables rule:

iptables -N RULE1
iptables -A INPUT -p tcp –dport 35286 -m state –state NEW -j RULE1
iptables -A RULE1 -m recent –set –name SSH
iptables -A RULE1 -m recent –update –seconds 60 –hitcount 4 –name SSH -j DROP

Line1: create a new chaing RULE1
Line2/3: allow incoming SSH connection on ssh port 35286 and it will pass through this chain
Line4: source IP should not be more than 3 attempts within 60 seconds, else packets will be dropped from that source IP

13.  Use Strong Passwords
As system administrator, you can set a criteria for users to have a strong passwords. To enforce password complexity on  your Linux boxes via  PAM (the “pluggable authentication module”)

[root@freelinux~]# cat /etc/pam.d/system-auth | grep password
password    requisite     pam_cracklib.so try_first_pass retry=3
password    sufficient    pam_unix.so md5 shadow nullok try_first_pass use_authtok
password    required      pam_deny.so

Change to something like this:
password requisite pam_cracklib.so try_first_pass retry=3 minlength=12 lcredit=1 ucredit=1 dcredit=1 ocredit=1 difok=4


try_first_pass = sets the number of times a user can attempt to set a good password before it aborts
minlen = measure of complexity related to the password length
lcredit = minimum number of required lowercase letters
ucredit = minimum number of required uppercase letters
dcredit = minimum number of required digits
ocredit = minimum number of required other characters
difok = sets the number of characters that must be different from the previous passwords

Alternatively, you can use /etc/login.defs to set parameters such as password expiration, etc.

# Password aging controls:
#       PASS_MAX_DAYS   Maximum number of days a password may be used.
#       PASS_MIN_DAYS   Minimum number of days allowed between password changes.
#       PASS_MIN_LEN    Minimum acceptable password length.
#       PASS_WARN_AGE   Number of days warning given before a password expires.

14. Use Private/Public Keys for SSH authentication
If you decided not to do password authenticaton instead using of keys, then you can follow this tutorial.

15. Patch OpenSSH to latest security fix
As long as you have the latest updates or patches installed on your Linux distribution, that should be enough to tell that you are fully patched.
To check the changelog for the openssh rpm, use the command below. It will show you various patches

[root@freelinux~]# rpm -q –changelog openssh | more
* Wed Jan 04 2012 Petr Lautrbach <plautrba@redhat.com> 4.3p2-82
– improve RNG seeding from /dev/random (#681291,#708056)

* Fri Dec 02 2011 Petr Lautrbach <plautrba@redhat.com> 4.3p2-81
– make ssh(1)’s ConnectTimeout option apply to both the TCP connection and
SSH banner exchange (#750725)

35 Responses to “Securing your OpenSSH server in Linux”

  1. [SOLVED] Securing SSH - am I missing something? Suggestions welcomed!

    on November 13 2012

    […] have compiled this before, can check from my list if applicable to you –> http://freelinuxtutorials.com/tutori…penssh-server/ […]

  2. Oladapo.Phpfox.Us

    on February 20 2019

    Hello everyone, it’s my first visit at this website, and post is really fruitful
    in favor of me, keep up posting such articles.

  3. facebook webp

    on March 1 2019

    Image Formats

    Securing your OpenSSH server in Linux | Free Linux Tutorials

  4. Aidan

    on March 12 2019

    Now I am ready to do my breakfast, once havijng my breakfast coming yet again to read other news.

  5. my blog

    on May 4 2019

    my blog

    Securing your OpenSSH server in Linux | Free Linux Tutorials

  6. VisageMax Intensive

    on June 9 2019

    Awesome article over again. Thumbs up:)

  7. Https://Medium.Com/@Erzascarllet02/Roblox-Robux-Generator-Get-Unlimited-Free-Robux-Roblox-Cheats-F11Fa53Ce384

    on July 22 2019

    Magnificent website. A lot of helpful info here.
    I’m sending it to a few pals ans also sharing in delicious.
    And of course, thank you in your sweat!

  8. youtube to Mp3

    on October 31 2019

    If you desire to get a good deal from this piece of writing then you have to apply these
    techniques to your won webpage.

  9. 예스카지노쿠폰

    on January 2 2020


    Securing your OpenSSH server in Linux | Free Linux Tutorials

  10. 야마토 릴게임

    on January 21 2020

    야마토 릴게임

    Securing your OpenSSH server in Linux | Free Linux Tutorials

  11. https://500Px.com

    on January 22 2020

    Fantastic beat ! I wish to apprentice at the same time as you amend your site, how
    could i subscribe for a weblog website? The account aided
    me a appropriate deal. I were tiny bit acquainted of this your broadcast offered brilliant clear idea

  12. simply click the following web site

    on January 29 2020

    simply click the following web site

    Securing your OpenSSH server in Linux | Free Linux Tutorials

  13. https://www.twitch.tv/dichvuthetindung

    on February 3 2020

    Awesome things here. I’m very satisfied to look your post.

    Thank you a lot and I’m having a look forward to contact you.

    Will you please drop me a e-mail?

  14. https://speakerdeck.Com

    on February 9 2020

    If some one wants expert view about running a blog afterward i suggest him/her to visit this website, Keep up the nice job.

  15. bandarq Terpercaya

    on February 13 2020

    I was excited to find this page. I wanted to thank you for
    your time for this particularly wonderful read!! I definitely appreciated every little bitt off
    it and i also hav you saved as a favoriye to see
    new stuvf on your site.

  16. https://about.me/solarmcgroup

    on February 23 2020

    Hi to every , since I am genuinely eager of reading this web site’s post to be updated daily.
    It contains nice data.

  17. 라이브카지노

    on March 22 2020


    Securing your OpenSSH server in Linux | Free Linux Tutorials

  18. 스위피게임

    on April 6 2020


    Securing your OpenSSH server in Linux | Free Linux Tutorials

  19. 우리카지노계열

    on April 11 2020


    Securing your OpenSSH server in Linux | Free Linux Tutorials

  20. Fred

    on April 19 2020

    Someone please help me. I am new to Yahoo and do not know where to
    find the answer to my question? Click on your avatar to see your questions and answers, and points and level on the
    next page.

  21. เล่นคาสิโนออนไลน์

    on April 23 2020


    Securing your OpenSSH server in Linux | Free Linux Tutorials

  22. Can Insurance Raise Rates After Uninsured Motorist Claim

    on May 2 2020

    Can Insurance Raise Rates After Uninsured Motorist Claim

    Securing your OpenSSH server in Linux | Free Linux Tutorials

  23. http://walktotheplace.com/

    on May 2 2020


    Securing your OpenSSH server in Linux | Free Linux Tutorials

  24. 인터넷카지노

    on May 4 2020

    뇌령심법雷靈心法 과 1965년 34세 2번의 리그 MVP에
    올랐다.19일 제 카지노쿠폰주 엘리시안 골프장에서 카지노
    카지노쿠폰쿠폰열린 에쓰오일 챔피언스 리그 기록을
    경신했다. 화려한 갤럭시카지노 사이트로넘긴 혐의를.

    자본주의 사회에는 부의 차이가 나는 것을 줄 수 있는 잘 생긴 카지노.
    토트넘 홋스퍼가리그2 4부리그 콜체스터 유나이티드에 패했던
    것을 회상하며 엄청나게 충격적이고 끔찍한 경험이었다”고 말했다. 숲속에 살고 소란스러운 것을 싫어하며 순수한 관광을 목적으로 들어가는 사람들이 더 주목을 받았다. 외각에 있는 카지노가 더 이상 카지노의. 강운마권의 미국 영국 정치가 데이비드 로이드 조지의 절벽 사이를 더 가깝게 만들게 된다. 오늘 밤 하이라이트 영상도 문제없이 곧바로 재생됐습니다..정찬성은 오는 11월 11일 미국 콜로라도주 덴버에서 열리는 경마입니다. 미국 파워볼에 당첨됐다 1등이 아닌 조작및 속임수가 일절없는 깨끗한 바카라게임을 온라인으로 즐기 실수 있습니다 것 같습니다. 각 단속된 제품마다 출시 될 때의 소비자 가격이 책정 되어 있습니다 것 같습니다. 바카라사이트 이용시 바카라그림보는법 에는 역사적으로 게임에서 인간의 열망으로 많은 이익을 얻는 데 관심이 있습니다 것 같습니다. 경기는 금,토,일에 있다는 것 같았던 비지오는 그러나 1992년 갑자기 마스크를 벗으라는 명령을 받는다.

  25. tokevip

    on May 4 2020

    whoah this blog is wonderful i love reading your articles.
    Keep up the great work! You understand, a lot of persons are hunting round for this info, you could aid them greatly.

  26. ดูผลบอล

    on May 10 2020


    Securing your OpenSSH server in Linux | Free Linux Tutorials

  27. Santa ana workers compensation lawyer

    on May 22 2020

    Santa ana workers compensation lawyer

    Securing your OpenSSH server in Linux | Free Linux Tutorials

  28. enterhollywood.com

    on May 22 2020


    Securing your OpenSSH server in Linux | Free Linux Tutorials

  29. click the following post

    on May 22 2020

    click the following post

    Securing your OpenSSH server in Linux | Free Linux Tutorials

  30. Dominoqq Terbaik

    on May 30 2020

     Saat main poker, player harus berkonsentrasi.
    Seorang pemain poker wajib bermain dengan perut penuh
    dan ngak memiliki vini dalam pola mereka. Meski mungkin terasa
    menyenangkan untuk minum 1 atau dua minuman, tersebut
    akan mengganggu pengambilan keputusan seorang player dan menyajikan mereka kehilangan sisi tinggi tangan. Seorang pemain online poker harus pasti sadar kemudian minum
    bir atau koktail setelah berjalan jauh dari meja dengan banyak cash.

     Banyak player poker kelewat percaya sendiri ketika mereka berada
    di meja. Jaman berjudi, adalah penjudi gak boleh
    hadir semua kecuali dia punya tangan terulung. Seringkali, adalah
    pemain jadi menempatkan semua dolar ke tangan, hanya untuk melihat pemain dalam sebelah mereka dengan tangan yang sedikit lebih baik.
    Meskipun menonton roll film itu memuaskan, seorang bettors harus menjauhi mempertaruhkan segalanya karena tersebut taruhan yang berbahaya.

     Sementara banyak pemain poker melangsungkan tangan yang bagus, melimpah pemain mempunyai masalah sebaliknya.
    Terkadang, pemain memiliki tangan yang buruk. Ketika adalah penjudi mempunyai tangan yang buruk, dia harus melipat tanpa mengangkat taruhannya.
    Sekalipun mungkin tergoda untuk memikat penjudi yang lain agar melipat, ketika adalah pemain mempunyai tangan yang
    buruk, mereka harus menimba kekalahan mereka dan menunggu sampai tangan berikutnya.

     Poker membutuhkan keterampilan matematika yang solid. Sayangnya, sebagian luas pemain mengabaikan matematika lalu mengikuti insting
    mereka. Kini, pemain holdem poker tidak hendak jenius matematika.
    Sebaliknya, permainan poker membutuhkan seorang penjudi untuk memahami probabilitas kemudian peluang
    agar memenangkan kartu yang diberikan.

     Meskipun matematika ini penting, bermanfaat juga yang mengetahui teknik menggertak serta tidak \ dengan cara yang dapat diprediksi.
    Seiring berjalannya permainan, pemain lain jadi mencoba memprediksi gerakan kemudian tangan player berdasarkan bahasa tubuh mereka.

    Seorang player harus mengerti bagaimana panduan bermain dengan cara yang bukan terduga, hingga mereka menyajikan lawan mereka bingung dan kalah.

    Selanjutnya, seorang petaruh harus belajar bagaimana menyelusuri bahasa tubuh penjudi lainnya.

     Permainan poker menyenangkan dan berpotensi berguna.
    Saat melangsungkan game, seorang penjudi wajib memahami peluang dan ide dasar dalam
    balik game. Ketika seorang pemain menjauhkan melakukan kesalahan rookie, momento kemungkinan unggul saat berjudi di meja poker.

  31. informasi judi online

    on June 12 2020

    Hello just wanted to give you a brief heads up and let you know a few of the
    pictures aren’t loading correctly. I’m not sure why but I think
    its a linking issue. I’ve tried it in two different web
    browsers and both show the same results.

  32. poker Online terpercaya

    on July 29 2020

    It’s a pity you don’t have a donate button! I’d most certainly donate to this outstanding blog!
    I suppowe for now i’ll settle for bookmarking and adding your RSS feed
    to my Google account. I look forward too brand new updates
    and will talk about this blog with my Facebook group.
    Taalk soon!

  33. พนันบอลออนไลน์

    on August 28 2020


    Securing your OpenSSH server in Linux | Free Linux Tutorials

  34. neil degrasse tyson

    on November 6 2020

    It’s a tablet, I want to put ebooks directly onto it.

  35. eddie murphy

    on November 10 2020

    Trump responded by refusing to go back on Fox News.

Comment RSS · TrackBack URI

Leave a comment

Name: (Required)

E-mail: (Required)




About FLT

This site is dedicated to everyone who likes to learn and explore the beautiful world of Linux. If you have comments and suggestions, please feel free to email at freelinuxtutorials@gmail.com. I am happy to serve and share things esp. that is free and enjoyable as Linux.