-
Notifications
You must be signed in to change notification settings - Fork 0
/
sniffer.py
executable file
·483 lines (398 loc) · 13.6 KB
/
sniffer.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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
#!/usr/bin/env python
"""
This application listens for traffic on a BACnet/MQTT network by subscribing
to the entire network topic family and decodes each of the packets it
receives.
"""
import sys
import ssl
from bacpypes.debugging import bacpypes_debugging, ModuleLogger, btox
from bacpypes.consolelogging import ArgumentParser
from bacpypes.core import run, enable_sleeping
from bacpypes.pdu import LocalBroadcast, PDU
from bacpypes.npdu import NPDU, npdu_types
from bacpypes.apdu import (
APDU,
apdu_types,
confirmed_request_types,
unconfirmed_request_types,
complex_ack_types,
error_types,
ConfirmedRequestPDU,
UnconfirmedRequestPDU,
SimpleAckPDU,
ComplexAckPDU,
SegmentAckPDU,
ErrorPDU,
RejectPDU,
AbortPDU,
)
import paho.mqtt.client as _paho_mqtt
from bacpypes_mqtt import (
BROADCAST_TOPIC,
topic2addr,
default_lan_name,
default_broker_host,
default_broker_port,
default_broker_keepalive,
BVLPDU,
bvl_pdu_types,
EncapsulatedNPDU,
)
# some debugging
_debug = 0
_log = ModuleLogger(globals())
# globals
args = None
#
# decode_packet
#
@bacpypes_debugging
def decode_packet(data, destination):
"""decode the data, return some kind of PDU."""
if _debug:
decode_packet._debug("decode_packet %r %r", data, destination)
# build a PDU
pdu = PDU(data, destination=destination)
# decode the BVLCI header
xpdu = BVLPDU()
xpdu.decode(pdu)
pdu = xpdu
# make a more focused interpretation
atype = bvl_pdu_types.get(pdu.bvlciFunction)
if not atype:
if _debug:
decode_packet._debug(" - unknown BVLL type: %r", pdu.bvlciFunction)
return pdu
if _debug:
decode_packet._debug(" - atype: %r", atype)
# decode it as one of the basic types
try:
xpdu = pdu
bpdu = atype()
bpdu.decode(pdu)
if _debug:
decode_packet._debug(" - bpdu: %r", bpdu)
pdu = bpdu
# source address in the packet
pdu.pduSource = pdu.bvlciAddress
# no deeper decoding for some
if atype != EncapsulatedNPDU:
return pdu
except Exception as err:
if _debug:
decode_packet._debug(" - %r decoding error: %r", atype, err)
return xpdu
# check for version number (Python2.7 hack)
if pdu.pduData[0] not in ("\1", 0x01):
if _debug:
decode_packet._debug(
" - not a version 1 packet: %s...", btox(pdu.pduData[:30], ".")
)
return None
# it's an NPDU
try:
npdu = NPDU()
npdu.decode(pdu)
except Exception as err:
if _debug:
decode_packet._debug(" - NPUD decoding error: %r", err)
return None
# application or network layer message
if npdu.npduNetMessage is None:
if _debug:
decode_packet._debug(" - not a network layer message, try as an APDU")
# decode as a generic APDU
try:
xpdu = APDU()
xpdu.decode(npdu)
apdu = xpdu
except Exception as err:
if _debug:
decode_packet._debug(" - APDU decoding error: %r", err)
return npdu
# "lift" the source and destination address
if npdu.npduSADR:
apdu.pduSource = npdu.npduSADR
else:
apdu.pduSource = npdu.pduSource
if npdu.npduDADR:
apdu.pduDestination = npdu.npduDADR
else:
apdu.pduDestination = npdu.pduDestination
# make a more focused interpretation
atype = apdu_types.get(apdu.apduType)
if not atype:
if _debug:
decode_packet._debug(" - unknown APDU type: %r", apdu.apduType)
return apdu
# decode it as one of the basic types
try:
xpdu = apdu
apdu = atype()
apdu.decode(xpdu)
except Exception as err:
if _debug:
decode_packet._debug(" - %r decoding Error: %r", atype, err)
return xpdu
# decode it at the next level
if isinstance(apdu, ConfirmedRequestPDU):
atype = confirmed_request_types.get(apdu.apduService)
if not atype:
if _debug:
decode_packet._debug(
" - no confirmed request decoder: %r", apdu.apduService
)
return apdu
elif isinstance(apdu, UnconfirmedRequestPDU):
atype = unconfirmed_request_types.get(apdu.apduService)
if not atype:
if _debug:
decode_packet._debug(
" - no unconfirmed request decoder: %r", apdu.apduService
)
return apdu
elif isinstance(apdu, SimpleAckPDU):
atype = None
elif isinstance(apdu, ComplexAckPDU):
atype = complex_ack_types.get(apdu.apduService)
if not atype:
if _debug:
decode_packet._debug(
" - no complex ack decoder: %r", apdu.apduService
)
return apdu
elif isinstance(apdu, SegmentAckPDU):
atype = None
elif isinstance(apdu, ErrorPDU):
atype = error_types.get(apdu.apduService)
if not atype:
if _debug:
decode_packet._debug(" - no error decoder: %r", apdu.apduService)
return apdu
elif isinstance(apdu, RejectPDU):
atype = None
elif isinstance(apdu, AbortPDU):
atype = None
if _debug:
decode_packet._debug(" - atype: %r", atype)
# deeper decoding
try:
if atype:
xpdu = apdu
apdu = atype()
apdu.decode(xpdu)
except Exception as err:
if _debug:
decode_packet._debug(" - %r decoding error: %r", atype, err)
return xpdu
# success
return apdu
else:
# make a more focused interpretation
ntype = npdu_types.get(npdu.npduNetMessage)
if not ntype:
if _debug:
decode_packet._debug(
" - no network layer decoder: %r", npdu.npduNetMessage
)
return npdu
if _debug:
decode_packet._debug(" - ntype: %r", ntype)
# deeper decoding
try:
xpdu = npdu
npdu = ntype()
npdu.decode(xpdu)
except Exception as err:
if _debug:
decode_packet._debug(" - %r decoding error: %r", ntype, err)
return xpdu
# success
return npdu
#
# MQTTSniffer
#
# This class is a mapping between the client/server pattern and the
# MQTT API.
#
@bacpypes_debugging
class MQTTSniffer:
def __init__(
self,
lan,
host=default_broker_host,
port=default_broker_port,
username=None,
password=None,
keepalive=default_broker_keepalive,
cafile=None,
):
if _debug:
MQTTSniffer._debug("__init__ %r %r %r %r", lan, host, port, keepalive)
# save the lan
self.lan = lan
# save the connection parameters
self.host = host
self.port = port
self.username = username
self.password = password
self.keepalive = keepalive
self.cafile = cafile
# create a client and set the callbacks
self.mqtt_client = _paho_mqtt.Client()
self.mqtt_client.on_connect = self.on_connect
self.mqtt_client.on_disconnect = self.on_disconnect
self.mqtt_client.on_subscribe = self.on_subscribe
self.mqtt_client.on_message = self.on_message
self.mqtt_client.on_publish = self.on_publish
self.mqtt_client.on_unsubscribe = self.on_unsubscribe
# use TLS
if self.cafile:
self.mqtt_client.tls_set(
ca_certs=self.cafile, cert_reqs=ssl.CERT_REQUIRED, tls_version=None
)
if _debug:
MQTTSniffer._debug(" - tls set")
# we are not connected
self.mqtt_connected = False
def startup(self):
if _debug:
MQTTSniffer._debug("startup")
# username and password authentication
if self.username and self.password:
if _debug:
MQTTSniffer._debug(
" - username, password: %r, %r", self.username, self.password
)
self.mqtt_client.username_pw_set(
username=self.username, password=self.password
)
# queue up a start the connection process
response = self.mqtt_client.connect(self.host, self.port, self.keepalive)
if _debug:
MQTTSniffer._debug(" - connect: %r", response)
result, mid = self.mqtt_client.subscribe(self.lan + "/#", qos=1)
if _debug:
MQTTSniffer._debug(" - subscribe result, mid: %r, %r", result, mid)
# start the client loop
response = self.mqtt_client.loop_start()
if _debug:
MQTTSniffer._debug(" - loop_start: %r", response)
def shutdown(self):
if _debug:
MQTTSniffer._debug("shutdown")
# stop listening
result, mid = self.mqtt_client.unsubscribe(self.lan + "/#")
if _debug:
MQTTSniffer._debug(
" - broadcast unsubscribe result, mid: %r, %r", result, mid
)
# disconnect
response = self.mqtt_client.disconnect()
if _debug:
MQTTSniffer._debug(" - disconnect: %r", response)
# stop the client loop
response = self.mqtt_client.loop_stop()
if _debug:
MQTTSniffer._debug(" - loop_stop: %r", response)
def on_connect(self, client, userdata, flags, rc):
"""Callback for when the client receives a CONNACK response from the server.
"""
if _debug:
MQTTSniffer._debug("on_connect %r %r %r %r", client, userdata, flags, rc)
# we are connected
if rc == 0:
if _debug:
MQTTClient._debug(" - connected")
self.mqtt_connected = True
def on_disconnect(self, client, userdata, rc):
"""Callback for when the client is disconnected from the server.
"""
if _debug:
MQTTSniffer._debug("on_disconnect %r %r %r", client, userdata, rc)
# we are connected
if rc == 0:
if _debug:
MQTTClient._debug(" - normal disconnect")
# we are no longer connected
self.mqtt_connected = False
def on_subscribe(self, client, userdata, mid, granted_qos):
if _debug:
MQTTSniffer._debug(
"on_subscribe %r %r %r %r", client, userdata, mid, granted_qos
)
def on_message(self, client, userdata, msg):
"""Callback for when a PUBLISH message is received from the server.
"""
if _debug:
MQTTSniffer._debug("on_message ...")
MQTTSniffer._debug(" - msg.topic: %r", msg.topic)
MQTTSniffer._debug(" - payload: %r", btox(msg.payload))
topic_address = msg.topic.split("/")[-1]
if _debug:
MQTTSniffer._debug(" - topic_address: %r", topic_address)
# make destination a little more abstact
if topic_address == BROADCAST_TOPIC:
topic_address = LocalBroadcast()
else:
topic_address = topic2addr(topic_address)
packet_data = decode_packet(msg.payload, topic_address)
print(packet_data)
packet_data.debug_contents(file=sys.stdout)
def on_publish(self, client, userdata, mid):
"""Callback for when the data is published."""
if _debug:
MQTTSniffer._debug("on_publish ...")
def on_unsubscribe(self, client, userdata, mid):
if _debug:
MQTTSniffer._debug("on_unsubscribe ...")
#
# __main__
#
def main():
global args, this_device, this_application
# build a parser, add some options
parser = ArgumentParser(description=__doc__)
parser.add_argument("--lan", type=str, default=default_lan_name, help="lan name")
parser.add_argument(
"--host", type=str, default=default_broker_host, help="broker host address"
)
parser.add_argument(
"--port", type=int, default=default_broker_port, help="broker port"
)
parser.add_argument("--username", type=str, default=None, help="broker username")
parser.add_argument("--password", type=str, default=None, help="broker password")
parser.add_argument(
"--keepalive",
type=int,
default=default_broker_keepalive,
help="maximum period in seconds allowed between communications with the broker",
)
parser.add_argument("--cafile", type=str, default=None, help="server certificate")
# parse the command line arguments
args = parser.parse_args()
if _debug:
_log.debug("initialization")
_log.debug(" - args: %r", args)
# make a simple application
this_application = MQTTSniffer(
args.lan,
args.host,
args.port,
args.username,
args.password,
args.keepalive,
args.cafile,
)
# enable sleeping will help with threads
enable_sleeping()
# start up the client
this_application.startup()
_log.debug("running")
run()
# shutdown the client
this_application.shutdown()
_log.debug("fini")
if __name__ == "__main__":
main()