forked from klein0r/probemon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
probemon.py
212 lines (175 loc) · 7.33 KB
/
probemon.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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from logging.handlers import RotatingFileHandler
from pprint import pprint
from scapy.all import *
import argparse
import time
from datetime import datetime
import netaddr
import os
import sys
import time
import paho.mqtt.client as mqtt
import json
import struct
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
NAME = 'probemon'
DESCRIPTION = "a command line tool for logging 802.11 probe request frames"
client = mqtt.Client()
sensor_data = {'macaddress': "", 'time': "", 'make': "", 'ssid': "", 'rssi': 0}
DEBUG = False
def parse_rssi(packet):
# parse dbm_antsignal from radiotap header
# borrowed from python-radiotap module
radiotap_header_fmt = '<BBHI'
radiotap_header_len = struct.calcsize(radiotap_header_fmt)
version, pad, radiotap_len, present = struct.unpack_from(
radiotap_header_fmt, packet)
start = radiotap_header_len
bits = [int(b) for b in bin(present)[2:].rjust(32, '0')]
bits.reverse()
if bits[5] == 0:
return 0
while present & (1 << 31):
present, = struct.unpack_from('<I', packet, start)
start += 4
offset = start
if bits[0] == 1:
offset = (offset + 8 - 1) & ~(8 - 1)
offset += 8
if bits[1] == 1:
offset += 1
if bits[2] == 1:
offset += 1
if bits[3] == 1:
offset = (offset + 2 - 1) & ~(2 - 1)
offset += 4
if bits[4] == 1:
offset += 2
dbm_antsignal, = struct.unpack_from('<b', packet, offset)
return dbm_antsignal
def build_packet_callback(time_fmt, logger, delimiter, mac_info, ssid, rssi,ignoreMac, mqtt_topic):
def packet_callback(packet):
global sensor_data
global client
# we are looking for management frames with a probe subtype
# if neither match we are done here
if packet.type != 0 or packet.subtype != 0x04 or packet.type is None:
return
# Mac address is on ignore list
if packet.addr2.upper() in ignoreMac:
return
# list of output fields
fields = []
# determine preferred time format
log_time = str(int(time.time()))
if time_fmt == 'iso':
log_time = datetime.now().isoformat()
fields.append(log_time)
# append the mac address itself
fields.append(packet.addr2)
# parse mac address and look up the organization from the vendor octets
if mac_info:
try:
parsed_mac = netaddr.EUI(packet.addr2)
mac_make = parsed_mac.oui.registration().org
except netaddr.core.NotRegisteredError as e:
mac_make = 'UNKNOWN'
fields.append(mac_make)
# include the SSID in the probe frame
if ssid:
fields.append(packet.info.decode(encoding='utf-8', errors='replace'))
if rssi:
if sys.version_info > (3,):
rssi_val = parse_rssi(memoryview(bytes(packet)))
else:
rssi_val = parse_rssi(buffer(str(packet)))
fields.append(str(rssi_val))
else:
rssi_val = 0
sensor_data['macaddress'] = packet.addr2
sensor_data['time'] = log_time
sensor_data['make'] = mac_make
sensor_data['ssid'] = packet.info.decode(encoding='utf-8', errors='replace')
sensor_data['uppercaseSSID'] = packet.info.decode(encoding='utf-8', errors='replace').upper()
sensor_data['rssi'] = rssi_val
logger.info(delimiter.join(fields))
client.publish(mqtt_topic, json.dumps(sensor_data), 1)
return packet_callback
def main():
global topic
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument('-i', '--interface', help="capture interface")
parser.add_argument('-I', '--ignore-mac', default='',
help="comma sepperated list with mac-adresses to ignore")
parser.add_argument('-I2', '--ignore-mac2', default='',
help="comma sepperated list with mac-adresses to ignore")
parser.add_argument('-t', '--time', default='iso',
help="output time format (unix, iso)")
parser.add_argument('-b', '--max-bytes', default=5000000,
help="maximum log size in bytes before rotating")
parser.add_argument('-c', '--max-backups', default=99999,
help="maximum number of log files to keep")
parser.add_argument('-d', '--delimiter', default='\t',
help="output field delimiter")
parser.add_argument('-f', '--mac-info', action='store_true',
help="include MAC address manufacturer")
parser.add_argument('-s', '--ssid', action='store_true',
help="include probe SSID in output")
parser.add_argument('-r', '--rssi', action='store_true',
help="include rssi in output")
parser.add_argument('-D', '--debug', action='store_true',
help="enable debug output")
parser.add_argument('-l', '--log', action='store_true',
help="enable scrolling live view of the logfile")
parser.add_argument('-x', '--mqtt-broker', default='',
help="mqtt broker server")
parser.add_argument('-o', '--mqtt-port', default='1883',
help="mqtt broker port")
parser.add_argument('-u', '--mqtt-user', default='', help="mqtt user")
parser.add_argument('-p', '--mqtt-password',
default='', help="mqtt password")
parser.add_argument('-m', '--mqtt-topic',
default='probemon/request', help="mqtt topic")
parser.add_argument('-P', '--pid', default='', help="PID File")
args = parser.parse_args()
if not args.interface:
print("error: capture interface not given, try --help")
sys.exit(-1)
DEBUG = args.debug
# PID speichern
if args.pid:
if os.path.isfile(args.pid):
print("%s already exists, exiting" % args.pid)
sys.exit()
pid = str(os.getpid())
open(args.pid, 'w').write(pid)
try:
if args.mqtt_user and args.mqtt_password:
client.username_pw_set(args.mqtt_user, args.mqtt_password)
if args.mqtt_broker:
print("using mqtt broker ", args.mqtt_broker," and topic ",args.mqtt_topic)
client.connect(args.mqtt_broker, int(args.mqtt_port), 1)
client.loop_start()
# setup our rotating logger
logger = logging.getLogger(NAME)
logger.setLevel(logging.INFO)
if args.log:
logger.addHandler(logging.StreamHandler(sys.stdout))
macIgnoreList = args.ignore_mac.split(',')
macIgnoreList = [item.strip().upper() for item in macIgnoreList]
for val in args.ignore_mac2.split(','):
macIgnoreList.append(val.strip().upper())
for val in macIgnoreList:
print('Ignoring messages from: ' + val)
built_packet_cb = build_packet_callback(args.time, logger,
args.delimiter, args.mac_info, args.ssid, args.rssi,macIgnoreList, args.mqtt_topic)
sniff(iface=args.interface, prn=built_packet_cb, store=0, monitor=True)
finally:
# Remove PID File on Exit
if args.pid:
os.unlink(args.pid)
if __name__ == '__main__':
main()