summaryrefslogtreecommitdiff
path: root/plugin.py
blob: e4d182dde603902bebe703aa082a9d08f30d5517 (plain)
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
from mitmproxy import ctx
from mitmproxy import tcp
from hexdump import hexdump
from mqtt import read_packets

import traceback


def log_hexdump(buf: bytes):
    for line in hexdump(buf, result='return').split("\n"):
        ctx.log.debug(line.strip())


def tcp_message(flow: tcp.TCPFlow):
    message = flow.messages[-1]

    ports = (flow.client_conn.address[1], flow.server_conn.address[1])
    if 8883 not in ports:
        return

    try:
        packets = read_packets(message.content)
    except:
        ctx.log.error(f'Failed to parse message.content')
        ctx.log.error(traceback.format_exc().strip())
        log_hexdump(message.content)
        return

    for packet in packets:
        try:
            packet.parse()

            # This should be info(), but I use warn() to make it yellow
            ctx.log.warn(packet.pprint())
        except:
            ctx.log.error(f'Failed to parse {packet.packet_type_human}')
            ctx.log.error(traceback.format_exc().strip())
            log_hexdump(packet.buf)


    # This way we can save topics
    # if mqtt_packet.packet_type == mqtt_packet.PUBLISH:
    #     with open("topics.txt", "a") as f:
    #         f.write(f"{mqtt_packet.topic_name}\n")
    # elif mqtt_packet.packet_type == mqtt_packet.SUBSCRIBE:
    #     with open("topics.txt", "a") as f:
    #         f.write(f"{mqtt_packet.topic_filters}\n")