多多色-多人伦交性欧美在线观看-多人伦精品一区二区三区视频-多色视频-免费黄色视屏网站-免费黄色在线

國(guó)內(nèi)最全I(xiàn)T社區(qū)平臺(tái) 聯(lián)系我們 | 收藏本站
阿里云優(yōu)惠2
您當(dāng)前位置:首頁(yè) > php開源 > php教程 > Python黑客編程3網(wǎng)絡(luò)數(shù)據(jù)監(jiān)聽和過濾

Python黑客編程3網(wǎng)絡(luò)數(shù)據(jù)監(jiān)聽和過濾

來源:程序員人生   發(fā)布時(shí)間:2016-07-14 15:30:34 閱讀次數(shù):9227次

Python黑客編程3網(wǎng)絡(luò)數(shù)據(jù)監(jiān)聽和過濾

 

  課程的實(shí)驗(yàn)環(huán)境以下:

?      操作系統(tǒng):kali Linux 2.0

?      編程工具:Wing IDE

?      Python版本:2.7.9

?      觸及到的主要python模塊:pypcapdpkt,scapyscapy-http

 

觸及到的幾個(gè)python網(wǎng)絡(luò)抓包和分析的模塊,dpktscapykali linux 2.0 中默許已被安裝,如果你的系統(tǒng)中沒有需要手動(dòng)安裝1下,下面是軟件包安裝的簡(jiǎn)單說明。

kali下安裝pypcap需要兩步(如果在其他系統(tǒng)上可能還需要安裝python-dev):

apt-get install libpcap-dev

pip install pypcap

  使用pip安裝scapy

root@kali:/home/pycharm# pip install scapy

使用pip安裝scapy-http

root@kali:/home/pycharm# pip install scapy-http

基礎(chǔ)環(huán)境準(zhǔn)備好以后,我還要再嘮叨1下你必須要掌握的基礎(chǔ)。

1.1  技術(shù)沒有黑白,網(wǎng)絡(luò)編程的基礎(chǔ)是協(xié)議

把編程掛上黑客的名義,多少有些標(biāo)題黨。代碼怎樣寫,程序怎樣用,完全是技術(shù)問題。不會(huì)由于叫網(wǎng)絡(luò)編程就低人1等,叫黑客編程也不會(huì)變得神秘或高大上,代碼就在那里,不低微也不高尚。所以學(xué)習(xí)編程,要有顆平常心。

很多聽課的同學(xué)和我反應(yīng),網(wǎng)絡(luò)編程格外的費(fèi)勁,繁瑣,要實(shí)現(xiàn)某種功能,如果Google不到類似的代碼就沒法下手。各種語言或框架針對(duì)網(wǎng)絡(luò)編程的實(shí)現(xiàn)基本都相同,由于我們接觸到網(wǎng)絡(luò)通訊都基于統(tǒng)1的規(guī)范和標(biāo)準(zhǔn),語言和框架只是在用自己的方式去描寫這個(gè)規(guī)范而已。本質(zhì)的問題來了,如果你連基本的網(wǎng)絡(luò)通訊的4層模型都不懂,對(duì)TCP/IP協(xié)議族毫無概念,那末我奉勸你先不要著急敲代碼,找本書,打開WireShark這樣的工具好好做做練習(xí)。

本次課程中的所有案例,其實(shí)都在遵守1個(gè)基本的思路(其他網(wǎng)絡(luò)通訊場(chǎng)景類似):

初始化以太網(wǎng)數(shù)據(jù)包對(duì)象à以太網(wǎng)數(shù)據(jù)包分離出ip數(shù)據(jù)包àIP數(shù)據(jù)包分離傳輸層數(shù)據(jù)包à傳輸層數(shù)據(jù)包分離利用層數(shù)據(jù)包。

只要我們具有基礎(chǔ)的網(wǎng)絡(luò)知識(shí),結(jié)合程序中各個(gè)對(duì)象提供的字段就可以得到我們想要的任何基礎(chǔ)信息,在此基礎(chǔ)上做些信息處理就可以完成大部份網(wǎng)絡(luò)監(jiān)聽和數(shù)據(jù)處理的任務(wù)。附上幾幅圖,如果這方面有欠缺的話,請(qǐng)立即去充電吧!

 

以太網(wǎng)幀格式

 

ip數(shù)據(jù)包格式

Tcp數(shù)據(jù)包格式

1.2  使用pypcap實(shí)時(shí)抓包

pypcap進(jìn)行實(shí)時(shí)的數(shù)據(jù)包捕獲,使用上很簡(jiǎn)單,我們先看1小段示例代碼:

import pcap

 

pc=pcap.pcap('wlan0')  #注,參數(shù)可為網(wǎng)卡名,如eth0

pc.setfilter('tcp port 80')    #2.設(shè)置監(jiān)聽過濾器

for ptime,pdata in pc:    #ptime為收到時(shí)間,pdata為收到數(shù)據(jù)

    print ptime,pdata    #...

在上面的代碼中,我們通過import pcap首先引入pypcap包,然后初始化1個(gè)pcap類實(shí)例,構(gòu)造函數(shù)需要傳入1個(gè)網(wǎng)卡用來監(jiān)聽,我們可以通過ifconfig獲得當(dāng)前機(jī)器上的網(wǎng)卡。

pcap類的setfilter方法用來設(shè)置監(jiān)聽過濾條件,這里我們?cè)O(shè)置過濾的數(shù)據(jù)包為tcp協(xié)議80端口的數(shù)據(jù)。以后程序就進(jìn)入監(jiān)聽狀態(tài)了。

接下來我們循環(huán)輸出接收到的數(shù)據(jù),ptime為時(shí)間,pdata的數(shù)據(jù),默許數(shù)據(jù)打印為ascii字符,效果以下:

在抓到數(shù)據(jù)包以后,下1步就需要對(duì)數(shù)據(jù)進(jìn)行解析,這里我們引入dpkt組件包。

1.3  使用dpkt 解析數(shù)據(jù)包

 

dpkt,簡(jiǎn)單來講是1個(gè)數(shù)據(jù)包解析工具,可以解析離線/實(shí)時(shí)pcap數(shù)據(jù)包。

1.3.1 實(shí)時(shí)解析

我們以下面的代碼為例,講授基本利用。

import pcap

import dpkt

 

def captData():

    pc=pcap.pcap('wlan0')  #注,參數(shù)可為網(wǎng)卡名,如eth0

    pc.setfilter('tcp port 80')    #設(shè)置監(jiān)聽過濾器

    for ptime,pdata in pc:    #ptime為收到時(shí)間,pdata為收到數(shù)據(jù)

        anlyCap(pdata);

 

def anlyCap(pdata):

    p=dpkt.ethernet.Ethernet(pdata)

    if p.data.__class__.__name__=='IP':

        ip='%d.%d.%d.%d'%tuple(map(ord,list(p.data.dst)))

        if p.data.data.__class__.__name__=='TCP':

            if p.data.data.dport==80:

                print p.data.data.data # http 要求的數(shù)據(jù)  

captData();

在上面代碼中,我們首先導(dǎo)入dpkt包。這段代碼中新增了1個(gè)anlyCap方法,該方法接收由pcap捕獲的http數(shù)據(jù)包,然后先獲得ip數(shù)據(jù)報(bào)文,從ip報(bào)文中再提取tcp數(shù)據(jù)包,最后從tcp數(shù)據(jù)包中提取http要求的數(shù)據(jù),將其打印出來。

對(duì)數(shù)據(jù)包的分析,新手可能會(huì)感到迷茫,如何選擇適合的協(xié)議和方法來分析呢?這個(gè)問題的答案不在代碼,而在于網(wǎng)絡(luò)通訊協(xié)議本身的掌握和理解。

回到上面的代碼,我們想要分析http要求的數(shù)據(jù),http是利用層協(xié)議,通過TCP協(xié)議來傳輸數(shù)據(jù),那末TCP數(shù)據(jù)又被封裝在IP數(shù)據(jù)報(bào)文中。使用dpkt的第1步就是選擇數(shù)據(jù)包類型,這里固然是要選擇以太網(wǎng)數(shù)據(jù)包了。

依照網(wǎng)絡(luò)協(xié)議,層層剝離,會(huì)解析到所有你想要的數(shù)據(jù)。

 

1.3.2 解析離線數(shù)據(jù)包

下面我們來看1個(gè)解析離線數(shù)據(jù)包的例子。

import dpkt

import socket

 

#----------------------------------------------------------------------

def printPcap(pcap):

    """"""

    for(ts,buf) in pcap:

        try:

            eth=dpkt.ethernet.Ethernet(buf);

            ip=eth.data;

            src=socket.inet_ntoa(ip.src);

            dst=socket.inet_ntoa(ip.dst);

            tcp=ip.data;#tcp.dport  tcp.sport

            print '[+]Src: '+src+ ' --->Dst: '+ dst

        except:

            pass;

#----------------------------------------------------------------------

def main():

    """"""

    f=open('/home/pcap/test.pcap');#1.open file

    pcap=dpkt.pcap.Reader(f);# init pcap obj

    printPcap(pcap);

 

if __name__ == '__main__':

    main();

    首先我準(zhǔn)備了1個(gè)測(cè)試的抓包文件—test.pcap,該文件是我使用wiresharkwindows上抓取的數(shù)據(jù)包,現(xiàn)在使用代碼對(duì)齊進(jìn)行基本的分析。在方法printPcap中,獲得ip數(shù)據(jù)報(bào)的內(nèi)容,然后獲得它的源ip和目標(biāo)ip數(shù)據(jù),通過socket.inet_ntoa方法轉(zhuǎn)換成ip字符串,最后打印出來。結(jié)果以下圖所示:

1.4 使用Scapy進(jìn)行數(shù)據(jù)監(jiān)聽

Scapy的是1個(gè)強(qiáng)大的交互式數(shù)據(jù)包處理程序(使用python編寫)。它能夠捏造或解碼大量的網(wǎng)絡(luò)協(xié)議數(shù)據(jù)包,能夠發(fā)送、捕捉、匹配要求和回復(fù)包等等。它可以很容易地處理1些典型操作,比如端口掃描,tracerouting,探測(cè),單元 測(cè)試,攻擊或網(wǎng)絡(luò)發(fā)現(xiàn)(可替換hpingNMAParpspoofARP-SKarpingtcpdumptetherealP0F等)。 最重要的他還有很多更優(yōu)秀的特性——發(fā)送無效數(shù)據(jù)幀、注入修改的802.11數(shù)據(jù)幀、在WEP上解碼加密通道(VOIP)、ARP緩存攻擊(VLAN 等,這也是其他工具沒法處理完成的。

Scapy可以單獨(dú)使用,也能夠在python中調(diào)用。

1.4.1 Scapy基本使用

了解Scapy的基本使用和支持的方法,首先我們從終端啟動(dòng)scapy,進(jìn)入交互模式。

ls()顯示scapy支持的所有協(xié)議。

ls()函數(shù)的參數(shù)還可以是上面支持的協(xié)議中的任意1個(gè)的類型屬性,也能夠是任何1個(gè)具體的數(shù)據(jù)包,如ls(TCP),ls(newpacket)等。

lsc()列出scapy支持的所有的命令

本篇文章使用的只是scapy眾多命令中的1個(gè),sniff

conf:顯示所有的配置信息。conf變量保存了scapy的配置信息。

help()顯示某1命令的使用幫助,如help(sniff)

show()顯示指定數(shù)據(jù)包的詳細(xì)信息。例如,這里我們先創(chuàng)建1個(gè)IP數(shù)據(jù)包,然后調(diào)用show方法。

sprintf()輸出某1層某個(gè)參數(shù)的取值,如果不存在就輸出”??”,具體的format格式是:%[[fmt][r],][layer[:nb].]field%,詳細(xì)的使用參考146頁(yè)。

%[[fmt][r],][layer[:nb].]field%

layer:協(xié)議層的名字,如EtherIPDot11TCP等。

filed:需要顯示的參數(shù)。

nb:當(dāng)有兩個(gè)協(xié)議層有相同的參數(shù)名時(shí),nb用于到達(dá)你想要的協(xié)議層。

r:是1個(gè)標(biāo)志。當(dāng)使用r標(biāo)志時(shí),意味著顯示的是參數(shù)的原始值。例如,TCP標(biāo)志中使用人類可瀏覽的字符串’SA’表示SYNACK標(biāo)志,而其原始值是18.

1.4.2  sniff

Scapy的功能如此強(qiáng)大,足夠?qū)憘€(gè)系列了,本文只關(guān)注sniff這1個(gè)方法。

sniff方法是用來嗅探數(shù)據(jù)的,我們首先使用help查看1下此方法的使用說明:

sniff(count=0, store=1, offline=None, prn=None, lfilter=None, L2socket=None, timeout=None, opened_socket=None, stop_filter=None, *arg, **karg)

    Sniff packets

    sniff([count=0,] [prn=None,] [store=1,] [offline=None,] [lfilter=None,] + L2ListenSocket args) -> list of packets

   

      count: number of packets to capture. 0 means infinity

      store: wether to store sniffed packets or discard them

        prn: function to apply to each packet. If something is returned,

             it is displayed. Ex:

             ex: prn = lambda x: x.summary()

    lfilter: python function applied to each packet to determine

             if further action may be done

             ex: lfilter = lambda x: x.haslayer(Padding)

    offline: pcap file to read packets from, instead of sniffing them

    timeout: stop sniffing after a given time (default: None)

    L2socket: use the provided L2socket

    opened_socket: provide an object ready to use .recv() on

    stop_filter: python function applied to each packet to determine

                 if we have to stop the capture after this packet

                 ex: stop_filter = lambda x: x.haslayer(TCP)

除上面介紹的幾個(gè)參數(shù),sniff()函數(shù)還有1個(gè)重要的參數(shù)是filter,用來表示想要捕獲數(shù)據(jù)包類型的過濾器,如只捕獲ICMP數(shù)據(jù)包,則filter=”ICMP”;只捕獲80端口的TCP數(shù)據(jù)包,則filter=”TCP and (port 80)”其他幾個(gè)重要的參數(shù)有:count表示需要不活的數(shù)據(jù)包的個(gè)數(shù);prn表示每一個(gè)數(shù)據(jù)包處理的函數(shù),可以是lambda表達(dá)式,如prn=lambda x:x.summary()timeout表示數(shù)據(jù)包捕獲的超時(shí)時(shí)間。

sniff(filter="icmp and host 66.35.250.151", count=2)

這段代碼過濾icmp協(xié)議,host地址為66.35.250.151,捕獲數(shù)據(jù)包個(gè)數(shù)為2個(gè)。

sniff(iface="wifi0", prn=lambda x: x.summary())

這段代碼綁定網(wǎng)卡wifi0,對(duì)捕獲的數(shù)據(jù)包使用summary進(jìn)行數(shù)據(jù)匯總。

sniff(iface="eth1", prn=lambda x: x.show())

這段代碼綁定網(wǎng)卡eth1,對(duì)數(shù)據(jù)包調(diào)用show方法,顯示基本信息。

下面我們看具體的1段代碼:

from scapy.all import *

 

ap_list = []

 

def PacketHandler(pkt) :

 

    if pkt.haslayer(Dot11) :

        if pkt.type == 0 and pkt.subtype == 8 :

            if pkt.addr2 not in ap_list :

                ap_list.append(pkt.addr2)

                print "AP MAC: %s with SSID: %s " %(pkt.addr2, pkt.info)

 

 

sniff(iface="wlan0mon", prn = PacketHandler)

上面這段代碼對(duì)綁定網(wǎng)卡WLAN0mon,對(duì)每一個(gè)數(shù)據(jù)包調(diào)用PacketHandler方法進(jìn)行解析。PacketHandler實(shí)際上是通過數(shù)據(jù)包過濾可訪問的無線網(wǎng)絡(luò)SSID

1.4.3 Scapy-http

Scapy-http直接將 數(shù)據(jù)包格式化成 http數(shù)據(jù)信息,免去自己構(gòu)建http數(shù)據(jù)結(jié)構(gòu)進(jìn)行解析的麻煩。

import scapy_http.http as HTTP

from scapy.all import *

from scapy.error import Scapy_Exception

 

count=0

def pktTCP(pkt):

    global count

    count=count+1

    print count

    if HTTP.HTTPRequest or HTTP.HTTPResponse in pkt:

        src=pkt[IP].src

        srcport=pkt[IP].sport

        dst=pkt[IP].dst

        dstport=pkt[IP].dport

        test=pkt[TCP].payload

        if HTTP.HTTPRequest in pkt:

            #print "HTTP Request:"

            #print test

            print "======================================================================"

        if HTTP.HTTPResponse in pkt:

            print "HTTP Response:"

            try:

                headers,body= str(test).split("\r\n\r\n", 1)

                print headers

            except Exception,e:

                print e

            print "======================================================================"

    else:

        #print pkt[IP].src,pkt[IP].sport,'->',pkt[TCP].flags

        print 'other'

 

sniff(filter='tcp and port 80',prn=pktTCP,iface='wlan0')

上面的這段代碼,我們引入scapy_http.http,該組件包可以直接將Http要求的TCP數(shù)據(jù)包格式化成HTTPRequestHTTPResponse對(duì)象,這大大方便了我們對(duì)HTTP數(shù)據(jù)的分析。

?         scapy_httpgithub上的開源地址為:https://github.com/invernizzi/scapy-http

1.4.4  綜合實(shí)例--net-creds

net-creds是1個(gè)小的開源程序,由python編寫,主要是從網(wǎng)絡(luò)或pcap中嗅探敏感數(shù)據(jù)。可以嗅探以下類型的數(shù)據(jù):

·             URLs visited

·             POST loads sent

·             HTTP form logins/passwords

·             HTTP basic auth logins/passwords

·             HTTP searches

·             FTP logins/passwords

·             IRC logins/passwords

·             POP logins/passwords

·             IMAP logins/passwords

·             Telnet logins/passwords

·             SMTP logins/passwords

·             SNMP community string

·             NTLMv1/v2 all supported protocols like HTTP, SMB, LDAP, etc

·             Kerberos

基本用法以下:

自動(dòng)選擇網(wǎng)卡進(jìn)行嗅探:

sudo python net-creds.py

指定嗅探的網(wǎng)卡:

sudo python net-creds.py -i eth0

疏忽指定IP的數(shù)據(jù)包:

sudo python net-creds.py -f 192.168.0.2

pcap文件中過濾信息:

python net-creds.py -p pcapfile

建議讀者能夠靜下心來瀏覽該程序的源碼,本身其實(shí)不是很復(fù)雜,難度不高。下面摘幾段代碼。

    ipr = Popen(['/sbin/ip', 'route'], stdout=PIPE, stderr=DN)

        for line in ipr.communicate()[0].splitlines():

            if 'default' in line:

                l = line.split()

                iface = l[4]

                return iface

上面這1段代碼是利用Popen組件和PIPE組件來自動(dòng)查找網(wǎng)卡。

def telnet_logins(src_ip_port, dst_ip_port, load, ack, seq):

    '''

    Catch telnet logins and passwords

    '''

    global telnet_stream

 

    msg = None

 

    if src_ip_port in telnet_stream:

        # Do a utf decode in case the client sends telnet options before their username

        # No one would care to see that

        try:

            telnet_stream[src_ip_port] += load.decode('utf8')

        except UnicodeDecodeError:

            pass

 

        # \r or \r\n or \n terminate commands in telnet if my pcaps are to be believed

        if '\r' in telnet_stream[src_ip_port] or '\n' in telnet_stream[src_ip_port]:

            telnet_split = telnet_stream[src_ip_port].split(' ', 1)

            cred_type = telnet_split[0]

            value = telnet_split[1].replace('\r\n', '').replace('\r', '').replace('\n', '')

            # Create msg, the return variable

            msg = 'Telnet %s: %s' % (cred_type, value)

            printer(src_ip_port, dst_ip_port, msg)

            del telnet_stream[src_ip_port]

 

    # This part relies on the telnet packet ending in

    # "login:", "password:", or "username:" and being <750 chars

   

生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)
程序員人生
------分隔線----------------------------
分享到:
------分隔線----------------------------
關(guān)閉
程序員人生
主站蜘蛛池模板: 夜夜爽www | 日韩欧美高清 | 亚洲欧美色中文字幕 | 国产精品18久久久久网站 | 国产乱辈通伦影片在线播放亚洲 | 亚洲精品456人成在线 | 免费激情视频网站 | 偷拍自拍校园春色 | 国产成人高清亚洲一区91 | 波多野结衣在线视频观看 | 日韩精品一区二区三区中文字幕 | 亚洲国语 | 亚洲精品色综合区 | 欧美一级久久久久久久大 | 亚洲视频福利 | 国产乱码精品一区二区三 | 国产精品第一页第一页 | 最近中文字幕国语免费 | 91国内精品久久久久免费影院 | 精品一区二区三区在线视频观看 | 亚洲水蜜桃久久综合网站 | 最近在线更新中文字幕1 | 一区二区视频在线播放 | 影音先锋色天使 | 手机免费在线视频 | 亚洲乱码一区 | 久久精品免费看 | 国内自拍偷拍 | ww视频在线观看 | 黄色aa视频 | 精品伊人久久大香线蕉网站 | freexxx性欧美hd丝袜 | 欧美干色| 久久五月视频 | 亚洲视频在线观看 | 国产无套免费网站 | аⅴ成人天堂中文在线 | 福利影院第一页 | 欧美黑人巨大性极品hd | 日韩精品亚洲人成在线播放 | 小说区图片区综合视频区 |