-
Notifications
You must be signed in to change notification settings - Fork 0
/
mbreplayd.py
executable file
·456 lines (365 loc) · 12 KB
/
mbreplayd.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
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
- author: JDaniel Jimenez
- email: [email protected]
- What is this about:
mbreplayd is a multicast & Broadcast traffic replay daemon for pseudo-bridges
(aka Layer 3 bridges).
- How it works:
The idea is quite simple. What mbreplay does is:
- sniff for traffic in iface_in
- choose the packets matcheing BPF filter
- change the source mac with the iface_out hwaddr
- send the packet to iface_out
The only point is that, in order to be useful, mbreplayd has to replay packets
received in the iface_out to the iface_in. Every packet but those ones which
src ip is the same that the IP generating this traffic. This filter is setted
up automatically from the bpf_filter
- Ideal scenario:
mbreplayd is usefull to forward broadcast and multicast traffic from iface_in
to iface_out, both of them part of a pseudo-bridge. This is a layer 3 bridge.
For sure, pseudo-bridges is not the best or event the default option to bridge
two interfaces but, sometimes, it needed. For example when a wireles interface
is a bridge member. In that case, is pretty common to need pseudo-bridges. In
my case, the upstream interface in my virtualization server was wireless, so
I decided to solve the problem with unicast traffic using parprouted but I
couldn't do the same with any other software or configuration I tried. So I
decided to write mbreplayd!.
- Known issues:
The main downside of mbreplayd is related to performance. Using python + scapy
to sniff packets, modify and replay them in realtime maybe is not the best way
to go. However, mbreplayd is not intended to be production grade software but
a way to investigate, learn, study and code and, by the way, solve a problem
with my lab environment, which is the ideal scenario for mbreplayd.
"""
import configargparse
import logging
import logging.handlers
import os
import sys
from multiprocessing import Process
from scapy.all import get_if_hwaddr, sniff, sendp
class BCReplay(object):
"""
Main bcreplayd class
"""
def __init__(
self,
iface_in,
iface_out,
src_ip,
mb_ip,
mb_port,
mb_proto='udp'
):
"""
iface_in: interface listening for original traffic
iface_out: interface where traffic will be replayed
src_ip: Source IP of original traffic
mb_ip: Broadcast or multicast dest IP
mb_port: Broadcast or multicast dest port
mb_proto: If you need to change this, mail me!
"""
# Storing vars to identify replay
self.iface_in = iface_in
self.iface_out = iface_out
self.src_ip = src_ip
self.mb_ip = mb_ip
self.mb_port = mb_port
self.mb_proto = mb_proto
self.fordarders = {}
self.fordarders['inbound'] = FWDInbound(
iface_in,
iface_out,
src_ip,
mb_ip,
mb_port,
mb_proto
)
# In and Out iface are switched!
self.fordarders['outbound'] = FWDOutbound(
iface_in,
iface_out,
src_ip,
mb_ip,
mb_port,
mb_proto
)
def __str__(self):
"""
Print replay in a human readable format
"""
return "[%s] %s >> [%s] %s:%s/%s" % (
self.iface_in,
self.src_ip,
self.iface_out,
self.mb_ip,
self.mb_port,
self.mb_proto
)
def start(self):
"""
start replaying
"""
for fwd in self.fordarders:
self.fordarders[fwd].start()
def stop(self):
"""
start replaying
"""
for fwd in self.fordarders:
self.fordarders[fwd].stop()
class Forward(object):
"""
Class to create a traffic forward. It stats listening in inbound inface and
replay traffic matching bpf filter to the outbound iface.
"""
# Base BPF filter
# Not will be only used in inbound traffic in order to prevent
# replaying already replayed traffic. If not is not defined, it will
# create a broadcast or multicast storm. You can trust me :P
BASE_BPF_FILTER = "%(not)s src host %(src_ip)s"
BASE_BPF_FILTER += " and dst port %(mb_port)s"
BASE_BPF_FILTER += " and %(mb_proto)s"
BASE_BPF_FILTER += " and dst host %(mb_ip)s"
def __init__(self, iface_in, iface_out, bpf_filter):
"""
iface_in: interface to sniff traffic in
iface_out: interface to replay sniffed packages
bpf_filter: filter to process only the matching traffic
"""
# Creating instance vars from init params
self.iface_in = iface_in
self.iface_out = iface_out
self.bpf_filter = bpf_filter
# Outbound address MAC is needed to use as src in th replayed traffic
self.iface_out_hwaddr = get_if_hwaddr(iface_out)
# var to check sniff status
self.replaying = False
# Create sniff fork
self.__sniff_fork = Process(target=self.__sniff)
def __sniff(self):
"""
Sniff method.
Callback: __replay
"""
sniff(
iface=self.iface_in,
prn=self.__replay,
filter=self.bpf_filter,
store=0
)
def __replay(self, pkt):
"""
Replay packet to iface_out changing src_mac with outbout iface mac
pkt: packet to replay
"""
pkt[0][0].src = self.iface_out_hwaddr
sendp(pkt, iface=self.iface_out, verbose=False)
def start(self):
"""
Start replaying traffic
"""
# Fork sniff
self.__sniff_fork.start()
# Set replaying status to true
self.replaying = True
def stop(self):
"""
Stop replaying traffic
"""
# Kill sniffing fork
self.__sniff_fork.terminate()
# Set replaying status to true
self.replaying = False
class FWDInbound(Forward):
"""
class managing inbound traffic (replies to src)
"""
def __init__(
self,
iface_in,
iface_out,
src_ip,
mb_ip,
mb_port,
mb_proto='udp'
):
"""
iface_in: interface to sniff traffic in
iface_out: interface to replay sniffed packages
src_ip: IP generating broadcast or multicast traffic
mb_ip: broadcast or multicast IP
mb_port: broadcast or multicast dst port
mb_proto: Changing this won't be needed (will it? [email protected])
"""
bpf_filter_args = {
"not": "",
"src_ip": src_ip,
"mb_proto": mb_proto,
"mb_ip": mb_ip,
"mb_port": mb_port
}
# BPF Filter created!!
self.bpf_filter = self.BASE_BPF_FILTER % bpf_filter_args
# Init super class with right params
super(FWDInbound, self).__init__(iface_in, iface_out, self.bpf_filter)
class FWDOutbound(Forward):
"""
class managing outbound traffic (from src)
"""
def __init__( self,
iface_in,
iface_out,
src_ip,
mb_ip,
mb_port,
mb_proto='udp'):
"""
iface_in: interface to sniff traffic in
iface_out: interface to replay sniffed packages
src_ip: IP generating broadcast or multicast traffic
mb_ip: broadcast or multicast IP
mb_port: broadcast or multicast dst port
mb_proto: Changing this won't be needed (will it? [email protected])
"""
bpf_filter_args = {
"not": "not",
"src_ip": src_ip,
"mb_proto": mb_proto,
"mb_ip": mb_ip,
"mb_port": mb_port
}
# BPF Filter created!!
self.bpf_filter = self.BASE_BPF_FILTER % bpf_filter_args
# Init super class with right params
super(FWDOutbound, self).__init__(iface_out, iface_in, self.bpf_filter)
def main():
"""
Function to run when is called as command instead of module
"""
# Define default values
DEFAULT_LOG_LEVEL = 'info'
DEFAULT_LOG_FILE = '/var/log/mbreplayd.log'
DEFAULT_CFG_FILE = [
'./mbreplayd.conf',
'~/mbreplayd.conf',
'/etc/mbreplayd.conf'
]
# Create arguments parser
# It's possible to define arguments vía command line arguments and/or
# config file. If any argument is defined more than once, this is the
# overriding order:
# 1. Command line arg
# 2. Config file specified in the command line arg
# 3. mbreplayd.conf /same directory as .py)
# 4. ~/mbreplayd.conf
# 5. /etc/mbreplayd.conf
# 6. Default config values
parser = configargparse.ArgumentParser(
description='Multicas & Broadcast traffic Replay Daemon',
default_config_files=DEFAULT_CFG_FILE
)
# Daemon mode
parser.add_argument(
"-d",
"--daemon",
action="store_true",
help="Daemon mode. If not set, logs will be printed to stdout.",
default=False
)
# Log level
parser.add_argument(
"-l",
"--log-level",
action="store",
help="Log level: [debug|info|warn|error|critical]. Default: %s"
% DEFAULT_LOG_LEVEL
)
# Log file
parser.add_argument(
"-f",
"--log-file",
action="store",
help="Path to log file. Default: %s" % DEFAULT_LOG_FILE
)
# Config file
parser.add_argument(
"-c",
"--cfg",
is_config_file=True,
help="Path to config file. Default: %s" % str(DEFAULT_CFG_FILE)
)
# As many replays as needed...
parser.add_argument(
"-r",
"--replay",
action="append",
help="""
Replay definition. Can be used more than once.
Format:
iface_in:iface_out:src_ip:mb_ip:mb_port
"""
)
# Args and cofig to cfg
cfg = parser.parse_args()
# Creates log object up to cfg settings
logfile_fullpath = os.path.abspath(cfg.log_file)
log = logging.getLogger('MBReplay')
try:
# Use int to force exception if parse.log_level is not a predefined
# log level
log.setLevel(int(logging.getLevelName(cfg.log_level.upper())))
except ValueError:
log.setLevel(int(logging.getLevelName(DEFAULT_LOG_LEVEL.upper())))
# If running in daemo mode...
if cfg.daemon:
# ...log to file
handler = logging.handlers.RotatingFileHandler(
logfile_fullpath,
maxBytes=10000000,
backupCount=5
)
else:
# if not, log to stdout
handler = logging.StreamHandler(sys.stdout)
# if stdout, time will be removed. it's easier to read...
formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# Handler added
log.addHandler(handler)
log.info("MBReplay started!")
log.debug("Config set: %s", cfg)
replays = []
log.info("Setting up replays")
for replay in cfg.replay:
log.info("Parsing replay: %s", cfg)
params = replay.split(':')
iface_in = params[0]
log.debug("Sniff iface: %s", iface_in)
iface_out = params[1]
log.debug("Forward iface: %s", iface_out)
src_ip = params[2]
log.debug("Broadcast/Multicast source IP: %s", src_ip)
mb_ip = params[3]
log.debug("Broadcast/Multicast dest IP: %s", mb_ip)
mb_port = params[4]
log.debug("Broadcast/Multicast dest port: %s", mb_port)
log.info("Creating replay object")
replays.append(
BCReplay(
iface_in,
iface_out,
src_ip,
mb_ip,
mb_port
)
)
# Start every replay
for replay in replays:
log.info("Starting replay: %s" % str(replay))
replay.start()
log.debug("Started replay: %s" % str(replay))
if __name__ == "__main__":
main()