Linux uses Hosts.deny to prevent brute force ssh

Source: Internet
Author: User
Tags install openssl log log stop script system log ssh server

First, SSH brute force hack

The use of professional crack program, with the password dictionary, login user name, try to log on the server, to crack the password, this method, although slow, but very effective.

Second, violent cracking demo

2.1. Basic Environment: 2 Linux hosts (CentOS 7 system), development Tools.

Host ip:192.168.30.64 (server side), 192.168.30.63 (client + brute force hack "Hydra")

Brute force hack on 30.63 30.64

2.2 Install cracked program Hydra on the client. Please go to the official website for details about the program.

The environment on which the software is installed:

[email protected] ~]# Yum install openssl-devel pcre-devel ncpfs-devel postgresql-devel libssh-devel subversion-devel li Bncurses-devel-y

Download the Hydra software (you can enter the link directly in the browser (Windows) to download the software if it cannot be downloaded directly from Linux wget)

[Email protected] ~]# wget https://www.thc.org/download.php?t=r&f=hydra-8.1.tar.gz

Unzip, compile, install (note: You need to be aware of the error class when compiling the installation, or it may cause the Hydra program to be unusable)

[[Email protected] ~]# tar zxvf hydra-8.1.tar.gz[[email protected] ~]# CD Hydra-8.1[[email protected] hydra-8.1]#./config Ure[[email protected] hydra-8.1]# make && make install

Normal installation, you can use it.

2.3 Hydra Common Commands

[[email protected] ~]# Hydrahydra v8.1 (c) by Van Hauser/thc-please does not use in military or Secret Service Organi Zations, or for illegal purposes. Syntax:hydra [[[-L LOGIN|-L file] [-P pass|-p file] | [-c FILE]] [-E NSR] [-O FILE] [-T TASKS] [-M FILE [-t TASKS]] [-W Time] [-W Time] [-F]
[-S PORT] [-X MIN:MAX:CHARSET] [-SUVVD46] [service://server[:P Ort][/opt]] Options:-L login or-l file LOGIN with login name, or load several logins from file
#-L login Username or-l login user Name list file
-P Pass or-p file try password PASS, or load several passwords from file
#-P login password or-p password dictionary file
-C FILE Colon separated "login:pass" format, instead of-l/-p options
# Use user name: password combination of cracked files.
-m FILE list of servers to attack, one entry per line, ': ' To specify port
# Specify the target list file one line at a record
-t tasks run tasks number of connects in parallel (per host, default:16)
# Number of concurrently running threads, default is 16
-U Service Module usage details
# Service Module Usage details
-H Command Line options
# More Command options
Server The Target:dns, IP or 192.168.0.0/24 (this or the-m option)
#支持扫描 domain, IP, and network segments
Service the service to crack (see below for supported protocols)
# Hack the scanned protocol
OPT Some service modules support additional input (-U for module Help)
# More extension options See-u option supported services:asterisk Cisco cisco-enable CVS ftp FTPs http[s]-{head|get} http[s]-{get|post}-form H Ttp-proxy Http-proxy-urlenum ICQ
Imap[s] IRC ldap2[s] ldap3[-{cram|digest}md5][s] MSSQL MySQL (v4) NNTP Oracle-listener oracle-sid pcanywhere PCNFS Pop3[s] Postgres RDP Redis
Rexec rlogin rsh s7-300 sip SMB smtp[s] smtp-enum snmp socks5 ssh sshkey svn teamspeak telnet[s] VMAUTHD vnc Xmpphydra is A tool to guess/crack valid Login/password pairs. Licensed under AGPLv3.0. The newest version is all available at Http://www.thc.org/thc-hydraDon ' t if use in military or Secret service organization s, or for illegal purposes. Example:hydra-l user-p passlist.txt ftp://192.168.0.1
#示例: Try to hack 192.168.0.1 FTP server with user, plus passlist.txt password dictionary

2.4 Test Hack (operation on 192.168.30.63)

Create a directory to hold user files and password dictionaries and create Users.txt, passwd.txt files

[Email protected] ssh-test]# Pwd/root/ssh-test[[email protected] ssh-test]# cat Users.txt Rootmysqlftpapachersyncttadmin[[email protected] ssh-test]# cat Passwd.txt 123456123admin123456789helloworld

Run a command to crack, you can see the penultimate line, the hint has found 1 valid passwords. The penultimate line is a valid user name and password (if you add the-VV option to the command, it will output more detailed information about the cracked run)

[Email protected] ssh-test]# hydra-l users.txt-p passwd.txt Ssh://192.168.30.64hydra v8.1 (c) by Van Hauser/thc- Military or Secret Service organizations, or for illegal purposes. Hydra (Http://www.thc.org/thc-hydra) starting at 2016-05-03 19:04:33[warning] Many SSH configurations limit the number of Parallel tasks, it's recommended to reduce the tasks:use-t 4[data] Max tasks per 1 server, overall + tasks, Logi N Tries (L:7/p:5), ~0 tries per Task[data] attacking service SSH on port 22[22][ssh] host:192.168.30.64   login:root
   password:1234561 of 1 target successfully completed, 1 valid password Foundhydra (Http://www.thc.org/thc-hydra) finish Ed at 2016-05-03 19:04:39

Run the-o option to save the resulting valid user name and password to a file, as follows:

[Email protected] ssh-test]# hydra-l users.txt-p passwd.txt-vv ssh://192.168.30.64-o valid-info.txt[[email protected] ssh-test]# Cat Valid-info.txt # Hydra v8.1 run at 2016-05-03 19:08:14 on 192.168.30.64 ssh (hydra-l users.txt-p passwd. Txt-vv-o valid-info.txt ssh://192.168.30.64) [22][ssh] host:192.168.30.64   login:root   password:123456

The above is the process of brute force, in addition Hydra program supports more protocols, such as FTP, Web username login, Cisco, POP3, RDP, Telnet ... Wait, wait. Interested can Google search under usage. Don't use it to do bad things, take precautions.

Third, how to prevent their own server was SSH brute force hack it?

3.1 Here to use the Linux system log, do not know that we found that every time we log on to the server, if there is a failure to login authentication, the server's/var/log/secure file will be recorded in the log. The error log is as follows:

[Email protected] deny]# tail-3f/var/log/securemay  3 19:14:49 test sshd[23060]: Pam_unix (Sshd:auth): Authentication failure; Logname= uid=0 euid=0 tty=ssh ruser= rhost=192.168.30.63  user=rootmay  3 19:14:49 test sshd[23060]: pam_succeed_  if (Sshd:auth): requirement "UID >= +" not met by user "root" could  3 19:14:51 test sshd[23060]: Failed password for Root from 192.168.30.63 Port 50704 ssh2

Through the above log we can see, is 30.63 this host SSH login failed, if it failed to log in too many times, we can prohibit it to land?

3.2 The Linux Hosts.deny (using tcp_wrappers) file is used here. Reference article: I am good

Hosts.deny Introduction: Generally speaking, Linux password we will use shadow to protect. Email probably some people will also say that using PGP, but is the general network connection? Someone might be holding a hand to answer the fire wall, what does the fire wall have to do with tcp_wrappers? The pen person thinks that if firewall is the first line of defense, the second line of defense is probably tcp_wrappers, we can use different protection programs to increase the ability to protect, and can also increase the difficulty of the hackers customer broken platform. It's not easy to design a perfect fire wall, but we can easily make it easier for beginners to connect to the beautiful new world of Linux with a simple, easy-to-program dilemma.

3.3 The script with the task schedule to detect the/var/log/secure file periodically, when the discovery of a large number of failure logs, the IP is appended to the Hosts.deny in order to prevent the purpose of brute force. (Operation on 192.168.30.64 server)

Script content:

View Code

Task schedule: (runs the program every minute)

[Email protected] deny]# CRONTAB-L*/1 * * * */usr/bin/sh/root/deny/autodeny.sh

Restart Crond Service

[Email protected] deny]# systemctl restart Crond

We first look at the next/etc/hosts.deny file, the default content should be empty, as follows

[[email protected] deny]# tail-2f/etc/hosts.deny# see        "Man TCPD" for information on tcp_wrappers#

3.4 Hack on the client. (Operation on 192.168.30.63)

First run hack command

The second time the connection port fails when you continue with the operation (denied by the server join Deny. )

You can go to the server to check the contents of the Hosts.deny file. See if there is a client's IP appended to the inside

Indicates that the script is working properly and can reject IP that would like to brute-force our servers.

How to use denyhosts software to protect Linux system more intelligently, the official website:

4.1 Introduction: Excerpt from Wiki

DenyHosts is a log-based intrusion prevention security tool for SSH servers, written in Python. It prevents brute-force hacking of the SSH server by monitoring failed login attempts in the authentication log log, shielding the IP addresses of these logins. DenyHosts, developed by Phil Schwartz, is also a developer of the Kodos regular expression debugger.

Principle: DenyHosts To obtain recent failed login attempts by monitoring the end of the authentication logon log. DenyHosts logs information about the login's IP address and compares the number of failed login attempts to the user-specified threshold. If the number of failed login attempts is too many, DenyHosts assumes a dictionary attack, and by adding IP addresses to the/etc/hosts.deny on the server, masks the associated IP to prevent further attacks. DenyHosts 2.0 and later supports centralized synchronization, which prevents repeat offenders from attacking too many computers. From multiple computers, DenyHosts 2.0 and above support centralized synchronization, so duplicate criminals will be blocked. The Denyhosts.net Web site collects statistics from the computer on which the software is running.

4.2 The program is still installed on the server, operating on the 192.168.30.64

Download Decompression Installation: Because it is a Python program, need to use Python installation, and there is a Python environment, now the Linux system default Python environment, if not, need yum install-y python

[Email protected]]# wget http://sourceforge.net/projects/denyhosts/files/denyhosts/2.6/denyhosts-2.6.tar.gz[[ Email protected]]# TAR-ZXVF denyhosts-2.6.tar.gz[[email protected] denyhosts-2.6]# CD Denyhosts-2.6[[email protected] D enyhosts-2.6]# python setup.py install[[email protected] denyhosts-2.6]# cd/usr/share/denyhosts/

Look at the files in the current directory

[Email protected] denyhosts]# lsCHANGELOG.txt  daemon-control-dist  data  denyhosts.cfg-dist  LICENSE.txt  plugins  README.txt  scripts  setup.py

The Daemon-control-dist file is the start-stop script for the program, written in Python language. We add it to the boot.

[Email protected] denyhosts]# Cp/usr/share/denyhosts/daemon-control-dist/etc/init.d/denyhosts[[email protected] denyhosts]# chkconfig denyhosts on add command to System command, easy to use [[email protected] denyhosts]# cd/bin[[email protected] bin]# ln-s/US R/share/denyhosts/daemon-control-dist Denyhosts[[email protected] bin]# CD ~ test: [[email protected] ~]# Denyhostsusage: /usr/bin/denyhosts {start [args] | stop | Restart [args ...] | status | debug | condrestart [args ...]} For a list of valid ' args ' refer to:$ denyhosts.py--help

After the start command is done, we edit the configuration file under DenyHosts. The files are stored in/usr/share/denyhosts/denyhosts.cfg. The contents are as follows:

View Code

After the editing configuration is complete, you can start the server, run denyhosts start directly or stop denyhosts stop and so on. or enter denyhosts directly to view Help

[Email protected] ~]# denyhosts startstarting denyhosts:    /usr/bin/env python/usr/bin/denyhosts.py--daemon-- Config=/usr/share/denyhosts/denyhosts.cfg

Check the service log, program process PID 3704

[Email protected] ~]# tail-f/var/log/denyhosts 2016-05-04 17:39:28,300-denyhosts   : INFO     launching DenyHosts D Aemon (version 2.6) ... 2016-05-04 17:39:28,305-denyhosts   : INFO     denyhosts Daemon is now running, pid:37042016-05-04 17:39:28,305-den Yhosts   : Info     Send daemon process a term signal to terminate cleanly2016-05-04 17:39:28,305-denyhosts   : Info       eg.  Kill-term 37042016-05-04 17:39:28,306-denyhosts   : INFO     monitoring log:/var/log/secure2016-05-04 17:39:28,306-denyhosts   : Info     sync_time:36002016-05-04 17:39:28,306-denyhosts   : info     daemon_ Purge:      36002016-05-04 17:39:28,306-denyhosts   : INFO     daemon_sleep:      302016-05-04 17:39:28,306- DenyHosts   : Info     purge_sleep_ratio:1202016-05-04 17:39:28,306-denyhosts   : info     denyhosts Synchronization disabled

For the following verification, we will first stop the service and then add the Debug option to start the DenyHosts service in debug mode, as follows:

[Email protected] ~]# denyhosts startstarting denyhosts:    /usr/bin/env python/usr/bin/denyhosts.py--daemon-- Config=/usr/share/denyhosts/denyhosts.cfg[[email protected] ~]# denyhosts debugsent denyhosts SIGUSR1

4.3 Authentication, operation on the client (192.168.30.63):

The denyhosts log files on the 4.4 server, as well as the Hosts.deny files, have been recorded as follows


Hosts.deny file

4.5 In addition I tried to login with invalid user name, you can find another client, directly using non-existent users to try to login, will be added to the Hosts.deny file after the first login. The software also has other features to learn. In case of doubt, you can always leave a message to exchange ha. Got off work. \ (?ω? ') o

Five, matters needing attention

1. In the above experiment, there may be a quick scan to the account number and password, does not play a role in preventing violence, it is because my password file is already inside, and the user name and password on a few. But in the real world, hackers can't scan that fast, unless your password is weak ...

2. The software in the above experiment comes from the Internet.

Linux uses Hosts.deny to prevent brute force ssh

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.