82 lines
2.5 KiB
Python
82 lines
2.5 KiB
Python
|
import config
|
||
|
import dpkt
|
||
|
import sys
|
||
|
import json
|
||
|
|
||
|
def fuck_it_up(filename):
|
||
|
idx = 0
|
||
|
sendme = []
|
||
|
recvme = []
|
||
|
filestream = open(filename, 'rb')
|
||
|
first_timestamp = None
|
||
|
dst_port = None
|
||
|
pcap_stream = dpkt.pcap.Reader(filestream)
|
||
|
decode = {8: decode_octet_stream, 9: decode_nyte_stream}[config.BYTE_WIDTH]
|
||
|
for timestamp, packet in pcap_stream:
|
||
|
stream = dpkt.ethernet.Ethernet(packet).ip.data
|
||
|
if first_timestamp is None:
|
||
|
first_timestamp = timestamp
|
||
|
if dst_port is None:
|
||
|
dst_port = stream.dport
|
||
|
if stream.data == '':
|
||
|
continue
|
||
|
direction = 'send' if stream.dport == dst_port else 'recv'
|
||
|
if direction == 'send':
|
||
|
print timestamp
|
||
|
sendme.append(stream.data.encode('hex'))
|
||
|
if direction == 'recv':
|
||
|
recvme.append(stream.data.encode('hex'))
|
||
|
with open('sends.json', 'w') as f:
|
||
|
json.dump(sendme, f)
|
||
|
with open('recvs.json', 'w') as f:
|
||
|
json.dump(sendme, f)
|
||
|
|
||
|
def parse_pcap(filename):
|
||
|
filestream = open(filename, 'rb')
|
||
|
first_timestamp = None
|
||
|
dst_port = None
|
||
|
pcap_stream = dpkt.pcap.Reader(filestream)
|
||
|
decode = {8: decode_octet_stream, 9: decode_nyte_stream}[config.BYTE_WIDTH]
|
||
|
for timestamp, packet in pcap_stream:
|
||
|
stream = dpkt.ethernet.Ethernet(packet).ip.data
|
||
|
if first_timestamp is None:
|
||
|
first_timestamp = timestamp
|
||
|
if dst_port is None:
|
||
|
dst_port = stream.dport
|
||
|
if stream.data == '':
|
||
|
continue
|
||
|
direction = 'send' if stream.dport == dst_port else 'recv'
|
||
|
yield {'direction': direction, 'timediff': timestamp-first_timestamp, 'data': decode(stream.data)}
|
||
|
|
||
|
def decode_octet_stream(data):
|
||
|
return map(ord, data)
|
||
|
|
||
|
def decode_nyte_stream(n):
|
||
|
bin_str = nytes_to_bit_string(n)
|
||
|
return [int(bin_str[i:i+9], 2) for i in xrange(0, len(bin_str), 9)]
|
||
|
|
||
|
def nytes_to_bit_string(n):
|
||
|
bin_str = "".join(bin(ord(c))[2:].zfill(8) for c in n)
|
||
|
num_bits = (len(n) * 8) % 9
|
||
|
return bin_str[:len(bin_str) - num_bits]
|
||
|
|
||
|
def get_streams(filename):
|
||
|
sent = []
|
||
|
recv = []
|
||
|
for thingy in parse_pcap(filename):
|
||
|
if thingy['direction'] == 'send':
|
||
|
sent.extend(thingy['data'])
|
||
|
else:
|
||
|
recv.extend(thingy['data'])
|
||
|
return sent, recv
|
||
|
|
||
|
def main(filename):
|
||
|
fuck_it_up(filename)
|
||
|
return
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
if len(sys.argv) == 2:
|
||
|
main(sys.argv[1])
|
||
|
else:
|
||
|
print 'Usage: pcap2json.py filename.pcap'
|