-
Notifications
You must be signed in to change notification settings - Fork 10
/
community-id-pcap
executable file
·235 lines (192 loc) · 7.31 KB
/
community-id-pcap
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#! /usr/bin/env python
"""
This script computes Community ID hashes for network flows in
provided pcaps. Provide pcaps (not pcapng) to the script and it will
report the following for each packet in the traces, separated by "|":
- the timestamp
- the community ID
- a flow tuple summary
Currently supported protocols include IP, IPv6, ICMP, ICMPv6, TCP,
UDP, SCTP.
Please note: the protocol parsing implemented in this script relies
on the dpkt module and is somewhat simplistic:
- dpkt seems to struggle with some SCTP packets, for which it fails
to register SCTP even though its header is correctly present.
- The script doesn't try to get nested network layers (IP over IPv6,
IP in IP, etc) right. It expects either IP or IPv6, and it expects
a transport-layer protocol (including the ICMPs here) as the
immediate next layer.
"""
import argparse
import base64
import gzip
import hashlib
import json
import socket
import struct
import sys
import communityid
try:
import dpkt
except ImportError:
print('This needs the dpkt Python module')
sys.exit(1)
from dpkt.ethernet import Ethernet #pylint: disable=import-error
from dpkt.ip import IP #pylint: disable=import-error
from dpkt.ip6 import IP6 #pylint: disable=import-error
from dpkt.icmp import ICMP #pylint: disable=import-error
from dpkt.icmp6 import ICMP6 #pylint: disable=import-error
from dpkt.tcp import TCP #pylint: disable=import-error
from dpkt.udp import UDP #pylint: disable=import-error
from dpkt.sctp import SCTP #pylint: disable=import-error
class PcapIterator(object):
def __init__(self, commid, pcap, do_json=False):
self._commid = commid
self._pcap = pcap
self._do_json = do_json
self._json = {}
def process(self, do_json=False):
if self._pcap.endswith('.gz'):
opener=gzip.open
else:
opener=open
self._json = {}
with opener(self._pcap, 'r+b') as hdl:
reader = dpkt.pcap.Reader(hdl)
for tstamp, pktdata in reader:
self._process_packet(tstamp, pktdata)
if self._do_json:
obj = [self._json[tpl] for tpl in self._json]
print(json.dumps(obj))
def _process_packet(self, tstamp, pktdata):
pkt = self._packet_parse(pktdata)
if not pkt:
self._print_result(tstamp, pkt, '<not IP>')
return
if IP in pkt:
saddr = pkt[IP].src
daddr = pkt[IP].dst
elif IP6 in pkt:
saddr = pkt[IP6].src
daddr = pkt[IP6].dst
else:
self._print_result(tstamp, pkt, '<not IP (???)>')
return
tpl = None
if TCP in pkt:
tpl = communityid.FlowTuple(
dpkt.ip.IP_PROTO_TCP, saddr, daddr,
pkt[TCP].sport, pkt[TCP].dport)
elif UDP in pkt:
tpl = communityid.FlowTuple(
dpkt.ip.IP_PROTO_UDP, saddr, daddr,
pkt[UDP].sport, pkt[UDP].dport)
elif SCTP in pkt:
tpl = communityid.FlowTuple(
dpkt.ip.IP_PROTO_SCTP, saddr, daddr,
pkt[SCTP].sport, pkt[SCTP].dport)
elif ICMP in pkt:
tpl = communityid.FlowTuple(
dpkt.ip.IP_PROTO_ICMP, saddr, daddr,
pkt[ICMP].type, pkt[ICMP].code)
elif ICMP6 in pkt:
tpl = communityid.FlowTuple(
dpkt.ip.IP_PROTO_ICMP6, saddr, daddr,
pkt[ICMP6].type, pkt[ICMP6].code)
if tpl is None:
# Fallbacks to other IP protocols:
if IP in pkt:
tpl = communityid.FlowTuple(pkt[IP].p, saddr, daddr)
elif IP6 in pkt:
tpl = communityid.FlowTuple(pkt[IP].nxt, saddr, daddr)
if tpl is None:
self._print_result(tstamp, pkt, '<not IP (???)>')
return
data = tpl.get_data()
res = self._commid.calc(tpl)
self._json[repr(tpl)] = {
'proto': data.proto,
'saddr': data.saddr,
'daddr': data.daddr,
'sport': data.sport,
'dport': data.dport,
'communityid': res,
}
self._print_result(tstamp, pkt, res)
def _packet_to_str(self, pkt):
"""
Helper that returns flow tuple string of given packet, as-is (no
canonicalization).
"""
parts = []
if IP in pkt:
parts.append(socket.inet_ntop(socket.AF_INET, pkt[IP].src))
parts.append(socket.inet_ntop(socket.AF_INET, pkt[IP].dst))
parts.append(pkt[IP].p)
elif IP6 in pkt:
parts.append(socket.inet_ntop(socket.AF_INET6, pkt[IP6].src))
parts.append(socket.inet_ntop(socket.AF_INET6, pkt[IP6].dst))
parts.append(pkt[IP6].nxt)
if ICMP in pkt:
parts.append(pkt[ICMP].type)
parts.append(pkt[ICMP].code)
elif ICMP6 in pkt:
parts.append(pkt[ICMP6].type)
parts.append(pkt[ICMP6].code)
elif TCP in pkt:
parts.append(pkt[TCP].sport)
parts.append(pkt[TCP].dport)
elif UDP in pkt:
parts.append(pkt[UDP].sport)
parts.append(pkt[UDP].dport)
elif SCTP in pkt:
parts.append(pkt[SCTP].sport)
parts.append(pkt[SCTP].dport)
return ' '.join(str(part) for part in parts)
def _packet_parse(self, pktdata):
"""
Parses the protocols in the given packet data and returns the
resulting packet (here, as a dict indexed by the protocol layers
in form of dpkt classes).
"""
layer = Ethernet(pktdata)
pkt = {}
if isinstance(layer.data, IP):
pkt[IP] = layer = layer.data
elif isinstance(layer.data, IP6):
# XXX This does not correctly skip IPv6 extension headers
pkt[IP6] = layer = layer.data
else:
return pkt
if isinstance(layer.data, ICMP):
pkt[ICMP] = layer.data
elif isinstance(layer.data, ICMP6):
pkt[ICMP6] = layer.data
elif isinstance(layer.data, TCP):
pkt[TCP] = layer.data
elif isinstance(layer.data, UDP):
pkt[UDP] = layer.data
elif isinstance(layer.data, SCTP):
pkt[SCTP] = layer.data
return pkt
def _print_result(self, tstamp, pkt, res):
if not self._do_json:
print('%10.6f | %s | %s' % (tstamp, res, self._packet_to_str(pkt)))
def main():
parser = argparse.ArgumentParser(description='Community ID pcap processor')
parser.add_argument('pcaps', metavar='PCAP', nargs='+',
help='PCAP packet capture files')
parser.add_argument('--seed', type=int, default=0, metavar='NUM',
help='Seed value for hash operations')
parser.add_argument('--no-base64', action='store_true', default=False,
help="Don't base64-encode the SHA1 binary value")
parser.add_argument('--json', action='store_true', default=False,
help="Render Community ID inputs & results in JSON")
args = parser.parse_args()
commid = communityid.CommunityID(args.seed, not args.no_base64)
for pcap in args.pcaps:
itr = PcapIterator(commid, pcap, args.json)
itr.process()
return 0
if __name__ == '__main__':
sys.exit(main())