-
Notifications
You must be signed in to change notification settings - Fork 310
/
Copy pathpcap.py
executable file
·202 lines (180 loc) · 6.69 KB
/
pcap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# pcap.py - Base class to save messages from pcap files in Redis.
#
# Copyright (c) Bitnodes <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
Base class to save messages from pcap files in Redis.
"""
import glob
import logging
import os
import socket
import time
from collections import defaultdict
from queue import PriorityQueue
import dpkt
from protocol import (
HeaderTooShortError,
PayloadTooShortError,
ProtocolError,
Serializer,
)
class Stream(object):
"""
Implements a stream object with generator function to iterate over the
queued segments while keeping track of captured timestamp.
"""
def __init__(self, segments=None):
self.segments = segments
self.timestamp = 0 # milliseconds
def data(self):
"""
Generator to iterate over the segments in this stream. Duplicated
segments are ignored.
"""
seqs = set()
while not self.segments.empty():
(seq, (self.timestamp, tcp_pkt_data)) = self.segments.get()
if seq in seqs:
continue
yield tcp_pkt_data
seqs.add(seq)
class Cache(object):
"""
Base caching mechanic to cache messages from pcap file in Redis.
"""
def __init__(self, filepath, magic_number=None, tor_proxies=None, redis_conn=None):
self.start_t = time.time()
self.filepath = filepath
self.tor_proxies = tor_proxies or []
self.redis_conn = redis_conn
if redis_conn:
self.redis_pipe = redis_conn.pipeline()
else:
self.redis_pipe = None
self.serializer = Serializer(magic_number=magic_number)
self.streams = defaultdict(PriorityQueue)
self.stream = Stream()
def __del__(self):
logging.debug(f"Elapsed: {time.time() - self.start_t}")
def extract_streams(self):
"""
Extracts TCP streams with data from the pcap file. TCP segments in
each stream are queued according to their sequence number.
"""
with open(self.filepath, "rb") as pcap_file:
pcap_reader = dpkt.pcap.Reader(pcap_file)
for timestamp, buf in pcap_reader:
try:
frame = dpkt.ethernet.Ethernet(buf)
except dpkt.dpkt.UnpackError:
continue
ip_pkt = frame.data
if not isinstance(ip_pkt, dpkt.ip.IP) and not isinstance(
ip_pkt, dpkt.ip6.IP6
):
continue
if not isinstance(ip_pkt.data, dpkt.tcp.TCP):
continue
ip_ver = socket.AF_INET
if ip_pkt.v == 6:
ip_ver = socket.AF_INET6
tcp_pkt = ip_pkt.data
stream_id = (
socket.inet_ntop(ip_ver, ip_pkt.src),
tcp_pkt.sport,
socket.inet_ntop(ip_ver, ip_pkt.dst),
tcp_pkt.dport,
)
if len(tcp_pkt.data) > 0:
timestamp = int(timestamp * 1000) # milliseconds
self.streams[stream_id].put(
(tcp_pkt.seq, (timestamp, tcp_pkt.data))
)
logging.debug(f"Streams: {len(self.streams)}")
def cache_messages(self):
"""
Reconstructs messages from TCP streams and caches them in Redis.
"""
try:
self.extract_streams()
except dpkt.dpkt.NeedData:
logging.warning(f"Need data: {self.filepath}")
for stream_id, self.stream.segments in self.streams.items():
data = self.stream.data()
_data = next(data)
while True:
try:
(msg, _data) = self.serializer.deserialize_msg(_data)
except (HeaderTooShortError, PayloadTooShortError) as err:
logging.debug(f"{stream_id}: {err}")
try:
_data += next(data)
except StopIteration:
break
except ProtocolError as err:
logging.debug(f"{stream_id}: {err}")
try:
_data = next(data)
except StopIteration:
break
else:
src = (stream_id[0], stream_id[1])
dst = (stream_id[2], stream_id[3])
node = src
is_tor = False
if src in self.tor_proxies:
# dst port will be used to restore .onion node.
node = dst
is_tor = True
self.cache_message(node, self.stream.timestamp, msg, is_tor=is_tor)
def cache_message(self, node, timestamp, msg, is_tor=False):
"""
Subclass to implement method to cache message from the specified node.
"""
raise NotImplementedError()
def get_pcap_file(pcap_dir, pcap_suffix):
"""
Returns the oldest available pcap file for processing.
"""
try:
oldest = min(glob.iglob(f"{pcap_dir}/*.{pcap_suffix}"))
except ValueError as err:
logging.error(err)
return None
try:
latest = max(glob.iglob(f"{pcap_dir}/*.{pcap_suffix}"))
except ValueError as err:
logging.error(err)
return None
if oldest == latest:
return None
tmp = oldest
dump = tmp.replace(f".{pcap_suffix}", f".{pcap_suffix}_")
try:
os.rename(tmp, dump) # Mark file as being read.
except OSError as err:
logging.error(err)
return None
return dump