歡迎光臨
每天分享高質量文章

Python大法之告彆指令碼小子—資訊資產收集類指令碼編寫

作者:阿甫哥哥
來源:i春秋社群

前言

在採集到URL之後,要做的就是對標的進行資訊資產收集了,收集的越好,你挖到洞也就越多了…………當然這一切的前提,就是要有耐心了!!!由於要寫工具較多,SO,我會分兩部分寫……


埠掃描指令碼編寫


埠掃描的原理:

埠掃描,顧名思義,就是逐個對一段埠或指定的埠進行掃描。透過掃描結果可以知道一臺計算機上都提供了哪些服務,然後就可以透過所提供的這些服務的己知漏洞就可進行攻擊。其原理是當一個主機向遠端一個伺服器的某一個埠提出建立一個連線的請求,如果對方有此項服務,就會應答,如果對方未安裝此項服務時,即使你向相應的埠發出請求,對方仍無應答,利用這個原理,如果對所有熟知埠或自己選定的某個範圍內的熟知埠分別建立連線,並記錄下遠端伺服器所給予的應答,透過檢視一記錄就可以知道標的伺服器上都安裝了哪些服務,這就是埠掃描,透過埠掃描,就可以蒐集到很多關於標的主機的各種很有參考價值的資訊。例如,對方是否提供FPT服務、WWW服務或其它服務。


代理伺服器還有很多常用的埠
比如HTTP協議常用的就是:80/8080/3128/8081/9080,FTP協議常用的就是:21,Telnet協議常用的是23等等
來個較全的…

代理伺服器常用以下埠:
⑴. HTTP協議代理伺服器常用埠號:80/8080/3128/8081/9080
⑵. SOCKS代理協議伺服器常用埠號:1080
⑶. FTP(檔案傳輸)協議代理伺服器常用埠號:21
⑷. Telnet(遠端登入)協議代理伺服器常用埠:23
HTTP伺服器,預設的埠號為80/tcp(木馬Executor開放此埠);
HTTPS(securely transferring web pages)伺服器,預設的埠號為443/tcp 443/udp;
Telnet(不安全的文字傳送),預設埠號為23/tcp(木馬Tiny Telnet Server所開放的埠);
FTP,預設的埠號為21/tcp(木馬Doly Trojan、Fore、Invisible FTP、WebEx、WinCrash和Blade Runner所開放的埠);
TFTP(Trivial File Transfer Protocol),預設的埠號為69/udp;
SSH(安全登入)、SCP(檔案傳輸)、埠重定向,預設的埠號為22/tcp;
SMTP Simple Mail Transfer Protocol (E-mail),預設的埠號為25/tcp(木馬Antigen、Email Password Sender、Haebu Coceda、Shtrilitz Stealth、WinPC、WinSpy都開放這個埠);
POP3 Post Office Protocol (E-mail) ,預設的埠號為110/tcp;
WebLogic,預設的埠號為7001;
Webshpere應用程式,預設的埠號為9080;
webshpere管理工具,預設的埠號為9090;
JBOSS,預設的埠號為8080;
TOMCAT,預設的埠號為8080;
WIN2003遠端登陸,預設的埠號為3389;
Symantec AV/Filter for MSE,預設埠號為 8081;
Oracle 資料庫,預設的埠號為1521;
ORACLE EMCTL,預設的埠號為1158;
Oracle XDB(XML 資料庫),預設的埠號為8080;
Oracle XDB FTP服務,預設的埠號為2100;
MS SQL*SERVER資料庫server,預設的埠號為1433/tcp 1433/udp;
MS SQL*SERVER資料庫monitor,預設的埠號為1434/tcp 1434/udp;
QQ,預設的埠號為1080/udp
等等,更具體的去百度吧,啊哈哈

埠的三種狀態

OPEN  –埠是開放的,可以訪問,有行程
CLOSED  –埠不會傳回任何東西..可能有waf
FILTERED  –可以訪問,但是沒有程式監聽


這裡用一個工具–nmap舉下慄子吧…

C:\Users\Administrator>nmap -sV localhost
Starting Nmap 7.70 ( [url]https://nmap.org[/url] ) at 2018-07-03 17:10 ?D1ú±ê×?ê±??
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00053s latency).
Other addresses for localhost (not scanned): ::1
Not shown: 990 closed ports
PORT      STATE SERVICE           VERSION
80/tcp    open  http              Apache httpd 2.4.23 ((Win32) OpenSSL/1.0.2j PHP/5.4.45)
135/tcp   open  msrpc             Microsoft Windows RPC
443/tcp   open  ssl/https         VMware Workstation SOAP API 14.1.1
445/tcp   open  microsoft-ds      Microsoft Windows 7 – 10 microsoft-ds (workgroup: WorkGroup)
903/tcp   open  ssl/vmware-auth   VMware Authentication Daemon 1.10 (Uses VNC, SOAP)
1080/tcp  open  http-proxy        Polipo
3306/tcp  open  mysql             MySQL 5.5.53
8088/tcp  open  radan-http?
10000/tcp open  snet-sensor-mgmt?
65000/tcp open  tcpwrapped


說的差不多了,咱們開始用Python實現它….埠掃描在Python中可以用的模組有很多,本文用socket模組演示單執行緒的在之前的文章有說過,具體傳送門:
一個精壯的代購騙子被我徹底征服

#-*- coding: UTF-8 -*-
import socket
  
def Get_ip(domain): 
    try: 
        return socket.gethostbyname(domain) 
    except socket.error,e: 
        print ‘%s: %s’%(domain,e) 
        return 0
  
def PortScan(ip):
    result_list=list()
    port_list=range(1,65535)
    for port in port_list:
        try:
            s=socket.socket()
            s.settimeout(0.1)
            s.connect((ip,port))
            openstr= ” PORT:”+str(port) +” OPEN “
            print openstr
            result_list.append(port)
            s.close()
        except:
            pass
    print result_list
def main():
    domain = raw_input(“PLEASE INPUT YOUR TARGET:”)
    ip = Get_ip(domain)
    print ‘IP:’+ip
    PortScan(ip)
if __name__==’__main__’: 
    main()


速度是不是巨慢,既然是告彆指令碼小子,寫個單執行緒的。。肯定是不行的,啊哈哈
放出多執行緒版本

#-*- coding: UTF-8 -*-
import socket
import threading
 
lock = threading.Lock()
threads = []
def Get_ip(domain): 
    try: 
        return socket.gethostbyname(domain) 
    except socket.error,e: 
        print ‘[-]%s: %s’%(domain,e) 
        return 0
  
def PortScan(ip,port):
    try:
        s=socket.socket()
        s.settimeout(0.1)
        s.connect((ip,port))
        lock.acquire()
        openstr= “[-] PORT:”+str(port) +” OPEN “
        print openstr
        lock.release()
        s.close()
    except:
        pass
def main():
    banner = ”’
                      _                      
     _ __   ___  _ __| |_ ___  ___ __ _ _ __ 
    | ‘_ \ / _ \| ‘__| __/ __|/ __/ _` | ‘_ \
    | |_) | (_) | |  | |_\__ \ (_| (_| | | | |
    | .__/ \___/|_|   \__|___/\___\__,_|_| |_|
    |_|                                      
 
            ”’
    print banner
    domain = raw_input(“PLEASE INPUT YOUR TARGET:”)
    ip = Get_ip(domain)
    print ‘[-] IP:’+ip
    for n in range(1,76):
        for p in range((n-1)*880,n*880):
            t = threading.Thread(target=PortScan,args=(ip,p))
            threads.append(t)
            t.start()    
 
        for t in threads:
            t.join()
    print ‘ This scan completed !’
if __name__==’__main__’: 
    main()


很簡單的,我都不知道該怎麼講。。。如果你基礎知識還不夠牢固,請移步至初級篇
Python大法從入門到編寫POC


子域名採集指令碼編寫

採集子域名可以在測試範圍內發現更多的域或子域,這將增大漏洞發現的機率。採集的方法也有很多方法,本文就不再過多的敘述了,採集方法的方法可以參考這篇文章:子域名蒐集思路與技巧梳理


其實lijiejie大佬的subdomainbrute就夠用了…..當然了,i春秋也有影片教程的。。。
Python安全工具開發應用


本文就演示三種吧
第一種是透過字典爆破,這個方法主要靠的是字典了….採集的多少取決於字典的大小了…
演示個單執行緒的吧

#-*- coding: UTF-8 -*-
import requests
import re
import sys
 
def writtarget(target):
        print target
        file = open(‘result.txt’,’a’)
        with file as f:
                f.write(target+’\n’)
 
        file.close()
 
 
def targetopen(httptarget , httpstarget):
 
 
        essay-header = {
                        ‘Connection’: ‘keep-alive’,
                        ‘Pragma’: ‘no-cache’,
                        ‘Cache-Control’: ‘no-cache’,
                        ‘Upgrade-Insecure-Requests’: ‘1’,
                    ‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36’,
 ‘Accept’: ‘text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8’,
                        ‘DNT’: ‘1’,
                        ‘Accept-Encoding’: ‘gzip, deflate’,
                 ‘Accept-Language’: ‘zh-CN,zh;q=0.9,en;q=0.8’
                }
 
        try:
            reponse_http = requests.get(httptarget, timeout=3, essay-headers=essay-header)
            code_http = reponse_http.status_code
 
 
if (code_http == 200):
httptarget_result = re.findall(‘//.*’, httptarget)
 
writtarget(httptarget_result[0][2:])
 
else:
reponse_https = requests.get(httpstarget, timeout=3, essay-headers=essay-header)
code_https = reponse_https.status_code
                        if (code_https == 200):
                    httpstarget_result = re.findall(‘//.*’, httpstarget)
 
                      writtarget(httpstarget_result[0][2:])
 
 
     except:
                pass
 
def domainscan(target):
 
        f = open(‘domain.txt’,’r’)
        for line in f:
                httptarget_result = ‘http://’+ line.strip() + ‘.’+target
                httpstarget_result = ‘https://’+ line.strip() + ‘.’+target
 
                targetopen(httptarget_result, httpstarget_result)
 
        f.close()
 
if __name__ == “__main__”:
        print ‘ ____                        _       ____             _       ‘
        print ‘|  _ \  ___  _ __ ___   __ _(_)_ __ | __ ) _ __ _   _| |_ ___ ‘
        print “| | | |/ _ \| ‘_ ` _ \ / _` | | ‘_ \|  _ \| ‘__| | | | __/ _ \  “
        print “| |_| | (_) | | | | | | (_| | | | | | |_) | |  | |_| | ||  __/”
        print ‘|____/ \___/|_| |_| |_|\__,_|_|_| |_|____/|_|   \__,_|\__\___|’
                                                               
        file = open(‘result.txt’,’w+’)
        file.truncate()
        file.close()
        target = raw_input(‘PLEASE INPUT YOUR DOMAIN(Eg:ichunqiu.com):’)
        print ‘Starting………’
        domainscan(target)
        print ‘Done ! Results in result.txt’

第二種是透過搜尋引擎採集子域名,不過有些子域名不會收錄在搜尋引擎中…..


參考這篇文章
工具| 手把手教你資訊收集之子域名收集器
我覺得這篇文章介紹的還可以的….我也懶得寫了,直接貼過來吧

#-*-coding:utf-8-*-
import requests
import re
key=”qq.com”
sites=[]
match=’style=”text-decoration:none;”>(.*?)/’
for i in range(48):
   i=i*10
url=”http://www.baidu.com.cn/s?wd=site:”+key+”&cl;=3&pn;=%s”%i
   response=requests.get(url).content
   subdomains=re.findall(match,response)
   sites += list(subdomains)
site=list(set(sites))   #set()實現去重
print site
print “The number of sites is %d”%len(site)
for i in site:         
   print i


第三種就是透過一些第三方網站..實現方法類似於第二種
在之前的文章中介紹過,我就直接取用過來了
不會的話,就看這篇文章,很詳細…
Python大法之從HELL0 MOMO到編寫POC(五)

import requests
import re
import sys
  
def get(domain):
        url = ‘http://i.links.cn/subdomain/’
        payload = (“domain={domain}&b2;=1&b3;=1&b4;=1”.format(domain=domain))
        r = requests.post(url=url,params=payload)
        con = r.text.encode(‘ISO-8859-1’)
        a = re.compile(‘value=”(.+?)”>        result = a.findall(con)
        list = ‘\n’.join(result)
        print list
if __name__ == ‘__main__’:
        command= sys.argv[1:]
        f = “”.join(command)
        get(f)


CMS指紋識彆指令碼編寫

現在有很多開源的指紋識別程式,w3af,whatweb,wpscan,joomscan等,常見的識別的幾種方式:

1:網頁中發現關鍵字
2:特定檔案的MD5(主要是靜態檔案、不一定要是MD5)
3:指定URL的關鍵字
4:指定URL的TAG樣式

i春秋也有相應的課程
Python安全工具開發應用
本著買不起課程初心,啊哈哈,我就不講ADO老師講的方法了。。。啊哈哈
不過寫的都差不多,只是用的模組不同。。。
本文我介紹兩種方法,一種是透過API的。。另一種就是純粹的指紋識別了,識別的多少看字典的大小了。。。


先說第一種。。。
說白了,就是傳送個post請求,把關鍵字取出來就ok了,完全沒有難度。。
我用的指紋識別網站是:http://whatweb.bugscaner.com/look/,我怎麼感覺有種打廣告的感覺。。。抓個包。。然後就一頓老套路

#-*- coding: UTF-8 -*-
import requests
import json
 
def what_cms(url):
        essay-headers = {
                ‘Connection’: ‘keep-alive’,
                ‘Pragma’: ‘no-cache’,
                ‘Cache-Control’: ‘no-cache’,
                ‘Upgrade-Insecure-Requests’: ‘1’,
         ‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36’,
  

‘Accept’: ‘text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8’,
                ‘DNT’: ‘1’,
                ‘Accept-Encoding’: ‘gzip, deflate’,
                ‘Accept-Language’: ‘zh-CN,zh;q=0.9,en;q=0.8’
                    }
        post={
                ‘hash’:’0eca8914342fc63f5a2ef5246b7a3b14_7289fd8cf7f420f594ac165e475f1479′,
                ‘url’:url,
        }
r=requests.post(url=’http://whatweb.bugscaner.com/what/’, 

data=post, essay-headers=essay-headers)
        dic=json.loads(r.text)
                 if dic[‘cms’]==”:
                print ‘Sorry,Unidentified……..’
        else:
                print ‘CMS:’ + dic[‘cms’]
if __name__ == ‘__main__’:
             url=raw_input(‘PLEASE INPUT YOUR TARGET:’)
             what_cms(url)


cool。。

接下來,就是CMS指紋識別的第二種方法了。。。
我用的匹配關鍵字的方法。。。
找了個dedecms的匹配字典

範例:連結||||關鍵字||||CMS別稱
/data/admin/allowurl.txt||||dedecms||||DedeCMS(織夢)
/data/index.html||||dedecms||||DedeCMS(織夢)
/data/js/index.html||||dedecms||||DedeCMS(織夢)
/data/mytag/index.html||||dedecms||||DedeCMS(織夢)
/data/sessions/index.html||||dedecms||||DedeCMS(織夢)
/data/textdata/index.html||||dedecms||||DedeCMS(織夢)
/dede/action/css_body.css||||dedecms||||DedeCMS(織夢)
/dede/css_body.css||||dedecms||||DedeCMS(織夢)
/dede/templets/article_coonepage_rule.htm||||dedecms||||DedeCMS(織夢)
/include/alert.htm||||dedecms||||DedeCMS(織夢)
/member/images/base.css||||dedecms||||DedeCMS(織夢)
/member/js/box.js||||dedecms||||DedeCMS(織夢)
/php/modpage/readme.txt||||dedecms||||DedeCMS(織夢)
/plus/sitemap.html||||dedecms||||DedeCMS(織夢)
/setup/license.html||||dedecms||||DedeCMS(織夢)
/special/index.html||||dedecms||||DedeCMS(織夢)
/templets/default/style/dedecms.css||||dedecms||||DedeCMS(織夢)
/company/template/default/search_list.htm||||dedecms||||DedeCMS(織夢)


全的字典去百度吧,小弟不才……小弟用的是deepin,win的報錯太雞肋,實在懶得解決。。。。

#-*- coding: UTF-8 -*-
import os
import threading
import urllib2
 
identification = False
g_index = 0
lock = threading.Lock()
 
def list_file(dir):
    files = os.listdir(dir)
    return  files
 
def request_url(url=”, data=None, essay-header={}):
    page_content = ”
    request = urllib2.Request(url, data, essay-header)
 
try:
        response = urllib2.urlopen(request)
        page_content = response.read()
    except Exception, e:
        pass
 
    return page_content
 
def whatweb(target):
    global identification
    global g_index
    global cms
 
while True:
        if identification:
            break
 
        if g_index > len(cms)-1:
            break
 
        lock.acquire()
        eachline = cms[g_index]
        g_index = g_index + 1
        lock.release()
 
        if len(eachline.strip())==0 or eachline.startswith(‘#’):
            pass
        else:
            url, pattern, cmsname = eachline.split(‘||||’)
            html = request_url(target+url)
            rate = float(g_index)/float(len(cms))
            ratenum = int(100*rate)
 
if pattern.upper() in html.upper():
                identification = True
         print ” CMS:%s,Matched URL:%s” % (cmsname.strip(‘\n’).strip(‘\r’), url)
                break
    return
 
 if __name__ == ‘__main__’:
    print ”’
          __        ___           _    ____ __  __ ____ 
          \ \      / / |__   __ _| |_ / ___|  \/  / ___|
           \ \ /\ / /| ‘_ \ / _` | __| |   | |\/| \___ \
            \ V  V / | | | | (_| | |_| |___| |  | |___) |
             \_/\_/  |_| |_|\__,_|\__|\____|_|  |_|____/
    ”’
threadnum = int(raw_input(‘ Please input your threadnum:’))
target_url = raw_input(‘ Please input your target:’)
 
f = open(‘./cms.txt’)
cms = f.readlines()
threads = []
 
if target_url.endswith(‘/’):
target_url = target_url[:-1]
 
iftarget_url.startswith(‘http://’)or target_url.startswith(‘https://’):
pass
else:
target_url = ‘http://’ + target_url
 
for i in range(threadnum):
t = threading.Thread(target=whatweb, args=(target_url,))
        threads.append(t)
 
print ‘ The number of threads is %d’ % threadnum
print ‘Matching…….’
for t in threads:
t.start()
 
for t in threads:
t.join()
 
print ” All threads exit”

cool。。。這樣就簡單的實現CMS識別。。。
最近好久不寫文章,手法生疏了,各位dalao見諒。。。。

《Python人工智慧和全棧開發》2018年07月23日即將在北京開課,120天衝擊Python年薪30萬,改變速約~~~~

*宣告:推送內容及圖片來源於網路,部分內容會有所改動,版權歸原作者所有,如來源資訊有誤或侵犯權益,請聯絡我們刪除或授權事宜。

– END –


更多Python好文請點選【閱讀原文】哦

↓↓↓

贊(0)

分享創造快樂