Web漏洞扫描工具-python

这是去年毕设做的一个Web漏洞扫描小工具,主要针对简单的SQL注入漏洞、SQL盲注和XSS漏洞,代码是看过github外国大神(听说是SMAP的编写者之一)的两个小工具源码,根据里面的思路自己写的。以下是使用说明和源代码。

一、使用说明:

1.运行环境:

Linux命令行界面+Python2.7

2.程序源码:

Vim scanner//建立一个名为scanner的文件

Chmod a+xscanner//修改文件权限为可执行的

3.运行程序:

Python scanner//运行文件

若没有携带目标URL信息,界面输出帮助信息,提醒可以可输入的参数。

参数包括:

--h 输出帮助信息

--url 扫描的URL

--data POST请求方法的参数

--cookie HTTP请求头Cookie值

--user-agent HTTP请求头User-Agent值

--random-agent 是否使用浏览器伪装

--referer 目标URL的上一层界面

--proxy HTTP请求头代理值

例如扫描“http://127.0.0.1/dvwa/vulnerabilities/sqli/?id=&Submit=Submit”

Python scanner--url="http://127.0.0.1/dvwa/vulnerabilities/sqli/?id=&Submit=Submit"--cookie="security=low;PHPSESSID=menntb9b2isj7qha739ihg9of1"

输出扫描结果如下:

结果显示:

存在XSS漏洞,漏洞匹配漏洞特征库“”>.XSS.<””,属于嵌入标签外的类型。

存在SQL注入漏洞,目标网站服务器的数据库类型为MYSQL。

存在BLIND SQL注入漏洞。

二、源代码:

代码验证过可以运行,我个人推荐用DVWA测试吧。

#!-*-coding:UTF-8-*-
import  optparse, random, re, string, urllib, urllib2,difflib,itertools,httplib
NAME    = "Scanner for RXSS and SQLI"
AUTHOR  = "Lishuze"
PREFIXES = (" ", ") ", "' ", "') ", "\"")
SUFFIXES = ("", "-- -", "#")
BOOLEAN_TESTS = ("AND %d=%d", "OR NOT (%d=%d)")
TAMPER_SQL_CHAR_POOL = ('(', ')', '\'', '"')
TAMPER_XSS_CHAR_POOL = ('\'', '"', '>', '<', ';')
GET, POST            = "GET", "POST"
COOKIE, UA, REFERER  = "Cookie", "User-Agent", "Referer"
TEXT, HTTPCODE, TITLE, HTML = xrange(4)
_headers = {}                                                

USER_AGENTS = (
    "Mozilla/5.0 (X11; Linux i686; rv:38.0) Gecko/20100101 Firefox/38.0",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36",
    "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_7_0; en-US) AppleWebKit/534.21 (KHTML, like Gecko) Chrome/11.0.678.0 Safari/534.21",
)

XSS_PATTERNS = (
    (r"<!--[^>]*%(chars)s|%(chars)s[^<]*-->","\"<!--.'.xss.'.-->\", inside the comment", None),
    (r"(?s)<script[^>]*>[^<]*?'[^<']*%(chars)s|%(chars)s[^<']*'[^<]*</script>","\"<script>.'.xss.'.</script>\", enclosed by <script> tags, inside single-quotes", None),
    (r'(?s)<script[^>]*>[^<]*?"[^<"]*%(chars)s|%(chars)s[^<"]*"[^<]*</script>',"'<script>.\".xss.\".</script>', enclosed by <script> tags, inside double-quotes", None),
    (r"(?s)<script[^>]*>[^<]*?%(chars)s|%(chars)s[^<]*</script>","\"<script>.xss.</script>\", enclosed by <script> tags", None),
    (r">[^<]*%(chars)s[^<]*(<|\Z)", "\">.xss.<\", outside of tags", r"(?s)<script.+?</script>|<!--.*?-->"),
    (r"<[^>]*'[^>']*%(chars)s[^>']*'[^>]*>", "\"<.'.xss.'.>\", inside the tag, inside single-quotes", r"(?s)<script.+?</script>|<!--.*?-->"),
    (r'<[^>]*"[^>"]*%(chars)s[^>"]*"[^>]*>', "'<.\".xss.\".>', inside the tag, inside double-quotes", r"(?s)<script.+?</script>|<!--.*?-->"),
    (r"<[^>]*%(chars)s[^>]*>", "\"<.xss.>\", inside the tag, outside of quotes", r"(?s)<script.+?</script>|<!--.*?-->")
)

DBMS_ERRORS = {
    "MySQL": (r"SQL syntax.*MySQL", r"Warning.*mysql_.*", r"valid MySQL result", r"MySqlClient\."),
    "Microsoft SQL Server": (r"Driver.* SQL[\-\_\ ]*Server", r"OLE DB.* SQL Server", r"(\W|\A)SQL Server.*Driver", r"Warning.*mssql_.*", r"(\W|\A)SQL Server.*[0-9a-fA-F]{8}", r"(?s)Exception.*\WSystem\.Data\.SqlClient\.", r"(?s)Exception.*\WRoadhouse\.Cms\."),
    "Microsoft Access": (r"Microsoft Access Driver", r"JET Database Engine", r"Access Database Engine"),
    "Oracle": (r"ORA-[0-9][0-9][0-9][0-9]", r"Oracle error", r"Oracle.*Driver", r"Warning.*\Woci_.*", r"Warning.*\Wora_.*")
}

def _retrieve_content_xss(url, data=None):
    surl=""
    for i in xrange(len(url)):
        if i > url.find('?'):
            surl+=surl.join(url[i]).replace(' ',"%20")
        else:
            surl+=surl.join(url[i])
    try:
    	req = urllib2.Request(surl, data, _headers)
    	retval = urllib2.urlopen(req, timeout=30).read()
    except Exception, ex:
        retval = getattr(ex, "message", "")
    return retval or ""

def _retrieve_content_sql(url, data=None):
    retval = {HTTPCODE: httplib.OK}
    surl=""
    for i in xrange(len(url)):
        if i > url.find('?'):
            surl+=surl.join(url[i]).replace(' ',"%20")
        else:
            surl+=surl.join(url[i])
    try:
    	req = urllib2.Request(surl, data, _headers)
    	retval[HTML] = urllib2.urlopen(req, timeout=30).read()
    except Exception, ex:
        retval[HTTPCODE] = getattr(ex, "code", None)
        retval[HTML] = getattr(ex, "message", "")
    match = re.search(r"<title>(?P<result>[^<]+)</title>", retval[HTML], re.I)
    retval[TITLE] = match.group("result") if match else None
    retval[TEXT] = re.sub(r"(?si)<script.+?</script>|<!--.+?-->|<style.+?</style>|<[^>]+>|\s+", " ", retval[HTML])
    return retval

def scan_page_xss(url, data=None):
    print "Start scanning RXSS:\n"
    retval, usable = False, False
    url = re.sub(r"=(&|\Z)", "=1\g<1>", url) if url else url
    data=re.sub(r"=(&|\Z)", "=1\g<1>", data) if data else data
    try:
        for phase in (GET, POST):
	    current = url if phase is GET else (data or "")
            for match in re.finditer(r"((\A|[?&])(?P<parameter>[\w]+)=)(?P<value>[^&]+)", current):
                found, usable = False, True
                print "Scanning %s parameter '%s'" % (phase, match.group("parameter"))
                prefix = ("".join(random.sample(string.ascii_lowercase, 5)))
                suffix = ("".join(random.sample(string.ascii_lowercase, 5)))
                if not found:
                    tampered = current.replace(match.group(0), "%s%s" % (match.group(0), urllib.quote("%s%s%s%s" % ("'", prefix, "".join(random.sample(TAMPER_XSS_CHAR_POOL, len(TAMPER_XSS_CHAR_POOL))), suffix))))
                    content = _retrieve_content_xss(tampered, data) if phase is GET else _retrieve_content_xss(url, tampered)
                    for sample in re.finditer("%s([^ ]+?)%s" % (prefix, suffix), content, re.I):
		    #print sample.group()
                        for regex, info, content_removal_regex in XSS_PATTERNS:
                            context = re.search(regex % {"chars": re.escape(sample.group(0))}, re.sub(content_removal_regex or "", "", content), re.I)
                            if context and not found and sample.group(1).strip():
                                print "!!!%s parameter '%s' appears to be XSS vulnerable (%s)" % (phase, match.group("parameter"), info)
                                found = retval = True
        if not usable:
            print " (x) no usable GET/POST parameters found"
    except KeyboardInterrupt:
        print "\r (x) Ctrl-C pressed"
    return retval

def scan_page_sql(url, data=None):
    print "Start scanning SQLI:\n"
    retval, usable = False, False
    url = re.sub(r"=(&|\Z)", "=1\g<1>", url) if url else url
    data=re.sub(r"=(&|\Z)", "=1\g<1>", data) if data else data
    try:
        for phase in (GET, POST):
	    current = url if phase is GET else (data or "")
            for match in re.finditer(r"((\A|[?&])(?P<parameter>\w+)=)(?P<value>[^&]+)", current):
                vulnerable, usable = False, True
                original=None
                print "Scanning %s parameter '%s'" % (phase, match.group("parameter"))
                tampered = current.replace(match.group(0), "%s%s" % (match.group(0), urllib.quote("".join(random.sample(TAMPER_SQL_CHAR_POOL, len(TAMPER_SQL_CHAR_POOL))))))
                content = _retrieve_content_sql(tampered, data) if phase is GET else _retrieve_content_sql(url, tampered)
		for (dbms, regex) in ((dbms, regex) for dbms in DBMS_ERRORS for regex in DBMS_ERRORS[dbms]):
                    if not vulnerable and re.search(regex, content[HTML], re.I):
                        print "!!!%s parameter '%s' could be error SQLi vulnerable (%s)" % (phase, match.group("parameter"), dbms)
                        retval = vulnerable = True
                vulnerable = False
		original = original or (_retrieve_content_sql(current, data) if phase is GET else _retrieve_content_sql(url, current))
                for prefix,boolean,suffix in itertools.product(PREFIXES,BOOLEAN_TESTS,SUFFIXES):
                    if not vulnerable:
                        template = "%s%s%s" % (prefix,boolean, suffix)
                        payloads = dict((_, current.replace(match.group(0), "%s%s" % (match.group(0), urllib.quote(template % (1 if _ else 2, 1), safe='%')))) for _ in (True, False))
                        contents = dict((_, _retrieve_content_sql(payloads[_], data) if phase is GET else _retrieve_content_sql(url, payloads[_])) for _ in (False, True))
                        if all(_[HTTPCODE] for _ in (original, contents[True], contents[False])) and (any(original[_] == contents[True][_] != contents[False][_] for _ in (HTTPCODE, TITLE))):
                            vulnerable = True
                        else:
                            ratios = dict((_, difflib.SequenceMatcher(None, original[TEXT], contents[_][TEXT]).quick_ratio()) for _ in (True, False))
                            vulnerable = all(ratios.values()) and ratios[True] > 0.95 and ratios[False] < 0.95
                        if vulnerable:
                            print "!!!%s parameter '%s' could be error Blind SQLi vulnerable" % (phase, match.group("parameter"))
                            retval = True
        if not usable:
            print " (x) no usable GET/POST parameters found"
    except KeyboardInterrupt:
        print "\r (x) Ctrl-C pressed"
    return retval

def init_options(proxy=None, cookie=None, ua=None, referer=None):
    global _headers
    _headers = dict(filter(lambda _: _[1], ((COOKIE, cookie), (UA, ua or NAME), (REFERER, referer))))
    urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler({'http': proxy})) if proxy else None)

if __name__ == "__main__":
    print "----------------------------------------------------------------------------------"
    print "%s\nBy:%s" % (NAME, AUTHOR)
    print "----------------------------------------------------------------------------------"
    parser = optparse.OptionParser()
    parser.add_option("--url", dest="url", help="Target URL")
    parser.add_option("--data", dest="data", help="POST data")
    parser.add_option("--cookie", dest="cookie", help="HTTP Cookie header value")
    parser.add_option("--user-agent", dest="ua", help="HTTP User-Agent header value")
    parser.add_option("--random-agent", dest="randomAgent", action="store_true", help="Use randomly selected HTTP User-Agent header value")
    parser.add_option("--referer", dest="referer", help="HTTP Referer header value")
    parser.add_option("--proxy", dest="proxy", help="HTTP proxy address")
    options, _ = parser.parse_args()
    if options.url:
        init_options(options.proxy, options.cookie, options.ua if not options.randomAgent else random.choice(USER_AGENTS), options.referer)
        result_xss= scan_page_xss(options.url if options.url.startswith("http") else "http://%s" % options.url, options.data)
        print "\nScan results: %s vulnerabilities found" % ("possible" if result_xss else "no")
        print "----------------------------------------------------------------------------------"
        result_sql = scan_page_sql(options.url if options.url.startswith("http") else "http://%s" % options.url, options.data)
        print "\nScan results: %s vulnerabilities found" % ("possible" if result_sql else "no")
        print "----------------------------------------------------------------------------------"
    else:
        parser.print_help()

最后,有意向把这个当毕业设计的,可以加QQ29027646买论文看原理。

时间: 2024-10-11 00:34:28

Web漏洞扫描工具-python的相关文章

Web漏洞扫描工具(批量破壳、反序列化、CMS)?

web漏洞扫描工具 一,Nikto,一款开源软件,不仅可用于扫描发现网页文件漏洞,还支持检查网页服务器和CGI的安全问题.它支持指定特定类型漏洞的扫描.绕过IDC检测等配置.该工具已集成于Kali Linux系统. nikto可以扫描软件版本信息,存在安全问题的文件,服务器配置问题,WEB Application层面的安全隐患,避免404误判等 扫了一下我自己的网站,好多问题...有XST攻击(XST是利用XSS和HTTP TRACE方法的组合.),apache的MultiViews利用 Mul

web漏洞扫描工具AWVS使用

AWVS AWVS简介:Acunetix Web Vulnerability Scanner(简称AWVS)是一款知名的网络漏洞扫描工具,它通过网络爬虫测试你的网站安全,检测流行安全漏洞,如交叉站点脚本,sql 注入等.在被黑客攻击前扫描购物车,表格.安全区域和其他Web应用程序.75% 的互联网攻击目标是基于Web的应用程序.因为他们时常接触机密数据并且被放置在防火墙之前. AWVS的主要功能 Web Scanner 核心功能 web安全漏洞扫描 Site Crawler 爬虫功能 遍历站点目

(转译)2019年WEB漏洞扫描工具和软件前十名推荐

这些工具都有助于发现漏洞,从而最大限度地提高测试人员的时间和效率.这些工具,2019年更新,也可用于寻找漏洞. 为何扫描? 这资源是什么? Web应用程序对黑客具有极大的吸引力,并且出于百万种不同的原因,尤其是因为当它们管理不当和未修补时,它们突然变得非常容易攻击.我们在这个资源中所做的就是列出一堆能够渗透并点击网站的Web应用程序黑客软件(例如).按优先顺序,我们注意到这些是当今最流行的内容管理系统. WordPress 28.6% Joomla 3.3% Drupal 2.3% Magnet

python之web路径扫描工具

# coding: UTF-8 import sys, os, time, httplibimport relist_http=[]  #http数组 def open_httptxt():  #打开TXT文本写入数组    try:        passlist = []        list_passlist=[]        xxx = file('http.txt', 'r')        for xxx_line in xxx.readlines():            #

小型Web应用扫描工具Grabber

小型Web应用扫描工具Grabber Grabber是Kali Linux集成的一款Web应用扫描工具.该工具适合中小Web应用,如个人博客.论坛等.该工具使用Python语言编写,支持常见的漏洞检测,如XSS.SQL注入.文件包含.备份文件检测.Ajax检测.Crytal Ball检测等功能.该工具只进行扫描,不实施漏洞利用.由于功能简单,所以使用非常方便,用户只要指定扫描目标和检测项目后,就可以进行扫描了.

十大web安全扫描工具

01 – Unhide Unhide 是一个查寻隐藏了进程和端口的Rootkits/LKMs或其它隐藏技术的探测鉴定工具.Unhide可以运行于linux/Unix和windows系统. 链接: http://www.unhide-forensics.info 评论: “非常完整好用的工具.轻松找到隐藏文件和端口等” “linux 系统里找容易程序的工具,怒赞!” “基于unix的系统里,查找rootkits的好工具” 02 – OWASP ZAP – Zed Attack Proxy Proj

【收藏】十大Webserver漏洞扫描工具

如今有很多消息令我们感到Web的危急性,因此,当前怎样构建一个安全的Web环境成为网管员和安全管理员们义不容辞的责任.可是巧妇难为无米之炊,该选择哪些安全工具呢? 扫描程序能够在帮助造我们造就安全的Web网站上助一臂之力,也就是说在黑客"黑"你之前,先測试一下自己系统中的漏洞.我们在此推荐十大Web漏洞扫描程序,供您參考. 1. Nikto 这是一个开源的Webserver扫描程序,它能够对Webserver的多种项目(包含3500个潜在的危急文件/CGI,以及超过900个server

小白日记28:kali渗透测试之Web渗透-扫描工具-Nikto

扫描工具-Nikto #WEB渗透 靶机:metasploitable 靶场:DVWA[默认账号/密码:admin/password] #新手先将DVWA的安全性,调到最低,可容易发现漏洞 侦察[减少与目标系统交互] Httrack:将WEB可下载的页面下载到本机,再进行本地检查[kali下安装] ##可到此网站获取代理:hidemyass.com[免费代理需小心] 扫描工具-Nikto #基于WEB的扫描工具,基本都支持两种扫描模式.代理截断模式,主动扫描模式 手动扫描:作为用户操作发现页面存

XSS漏洞扫描工具:BruteXSS

下载Brute,一个xss漏洞扫描工具:https://codeload.github.com/shawarkhanethicalhacker/BruteXSS/legacy.zip/master 我是丢在python目录下 下载四个攻击字典:https://github.com/ym2011/penetration/tree/master/BruteXSS,可以点击Raw,然后另存为. 进cmd窗口,切换目录到BruteXSS下,运行brutexss.py 选择get还是post,我这里填了g