Add lock; make less verbose

This commit is contained in:
dadav 2019-11-30 10:05:43 +01:00
parent 9b594f7fb2
commit 9509dd0aa5

@ -1,6 +1,7 @@
import logging import logging
import json import json
import os import os
import threading
import requests import requests
import time import time
import pwnagotchi.plugins as plugins import pwnagotchi.plugins as plugins
@ -11,7 +12,7 @@ MOZILLA_API_URL = 'https://location.services.mozilla.com/v1/geolocate?key={api}'
class NetPos(plugins.Plugin): class NetPos(plugins.Plugin):
__author__ = 'zenzen san' __author__ = 'zenzen san'
__version__ = '2.0.1' __version__ = '2.0.2'
__license__ = 'GPL3' __license__ = 'GPL3'
__description__ = """Saves a json file with the access points with more signal __description__ = """Saves a json file with the access points with more signal
whenever a handshake is captured. whenever a handshake is captured.
@ -22,6 +23,7 @@ class NetPos(plugins.Plugin):
self.report = StatusFile('/root/.net_pos_saved', data_format='json') self.report = StatusFile('/root/.net_pos_saved', data_format='json')
self.skip = list() self.skip = list()
self.ready = False self.ready = False
self.lock = threading.Lock()
def on_loaded(self): def on_loaded(self):
if 'api_key' not in self.options or ('api_key' in self.options and self.options['api_key'] is None): if 'api_key' not in self.options or ('api_key' in self.options and self.options['api_key'] is None):
@ -45,60 +47,64 @@ class NetPos(plugins.Plugin):
saved_file.write(x + "\n") saved_file.write(x + "\n")
def on_internet_available(self, agent): def on_internet_available(self, agent):
if self.ready: with self.lock:
config = agent.config() if self.ready:
display = agent.view() config = agent.config()
reported = self.report.data_field_or('reported', default=list()) display = agent.view()
handshake_dir = config['bettercap']['handshakes'] reported = self.report.data_field_or('reported', default=list())
handshake_dir = config['bettercap']['handshakes']
all_files = os.listdir(handshake_dir) all_files = os.listdir(handshake_dir)
all_np_files = [os.path.join(handshake_dir, filename) all_np_files = [os.path.join(handshake_dir, filename)
for filename in all_files for filename in all_files
if filename.endswith('.net-pos.json')] if filename.endswith('.net-pos.json')]
new_np_files = set(all_np_files) - set(reported) - set(self.skip) new_np_files = set(all_np_files) - set(reported) - set(self.skip)
if new_np_files: if new_np_files:
logging.info("NET-POS: Found %d new net-pos files. Fetching positions ...", len(new_np_files)) logging.debug("NET-POS: Found %d new net-pos files. Fetching positions ...", len(new_np_files))
display.set('status', f"Found {len(new_np_files)} new net-pos files. Fetching positions ...") display.set('status', f"Found {len(new_np_files)} new net-pos files. Fetching positions ...")
display.update(force=True) display.update(force=True)
for idx, np_file in enumerate(new_np_files): for idx, np_file in enumerate(new_np_files):
geo_file = np_file.replace('.net-pos.json', '.geo.json')
if os.path.exists(geo_file):
# got already the position
reported.append(np_file)
self.report.update(data={'reported': reported})
continue
try:
geo_data = self._get_geo_data(np_file) # returns json obj
except requests.exceptions.RequestException as req_e:
logging.error("NET-POS: %s - RequestException: %s", np_file, req_e)
self.skip += np_file
continue
except json.JSONDecodeError as js_e:
logging.error("NET-POS: %s - JSONDecodeError: %s, removing it...", np_file, js_e)
os.remove(np_file)
continue
except OSError as os_e:
logging.error("NET-POS: %s - OSError: %s", np_file, os_e)
self.skip += np_file
continue
with open(geo_file, 'w+t') as sf:
json.dump(geo_data, sf)
geo_file = np_file.replace('.net-pos.json', '.geo.json')
if os.path.exists(geo_file):
# got already the position
reported.append(np_file) reported.append(np_file)
self.report.update(data={'reported': reported}) self.report.update(data={'reported': reported})
continue
try: display.set('status', f"Fetching positions ({idx + 1}/{len(new_np_files)})")
geo_data = self._get_geo_data(np_file) # returns json obj display.update(force=True)
except requests.exceptions.RequestException as req_e:
logging.error("NET-POS: %s - RequestException: %s", np_file, req_e)
self.skip += np_file
continue
except json.JSONDecodeError as js_e:
logging.error("NET-POS: %s - JSONDecodeError: %s", np_file, js_e)
self.skip += np_file
continue
except OSError as os_e:
logging.error("NET-POS: %s - OSError: %s", np_file, os_e)
self.skip += np_file
continue
with open(geo_file, 'w+t') as sf:
json.dump(geo_data, sf)
reported.append(np_file)
self.report.update(data={'reported': reported})
display.set('status', f"Fetching positions ({idx + 1}/{len(new_np_files)})")
display.update(force=True)
def on_handshake(self, agent, filename, access_point, client_station): def on_handshake(self, agent, filename, access_point, client_station):
netpos = self._get_netpos(agent) netpos = self._get_netpos(agent)
if not netpos['wifiAccessPoints']:
return
netpos["ts"] = int("%.0f" % time.time()) netpos["ts"] = int("%.0f" % time.time())
netpos_filename = filename.replace('.pcap', '.net-pos.json') netpos_filename = filename.replace('.pcap', '.net-pos.json')
logging.info("NET-POS: Saving net-location to %s", netpos_filename) logging.debug("NET-POS: Saving net-location to %s", netpos_filename)
try: try:
with open(netpos_filename, 'w+t') as net_pos_file: with open(netpos_filename, 'w+t') as net_pos_file:
@ -106,6 +112,7 @@ class NetPos(plugins.Plugin):
except OSError as os_e: except OSError as os_e:
logging.error("NET-POS: %s", os_e) logging.error("NET-POS: %s", os_e)
def _get_netpos(self, agent): def _get_netpos(self, agent):
aps = agent.get_access_points() aps = agent.get_access_points()
netpos = dict() netpos = dict()