示例#1
0
    def send_notification(self):
        try:
            from systemd.daemon import notify
            event = threading.Event()

            # send first notification on init
            logger.debug('[Watchdog]... everything is ok')
            notify('WATCHDOG=1')

            while not event.wait(self.interval - 1):
                main_thread_alive = threading.main_thread().is_alive()
                logger.debug(
                    '[Watchdog] is alive {}'.format(main_thread_alive))
                if main_thread_alive:
                    logger.debug('[Watchdog]...')
                    url = settings.config_http['bind']
                    resp = requests.get(url)
                    if resp.status_code == 200:
                        logger.debug('[Watchdog] everything is ok')
                        notify('WATCHDOG=1')
                    else:
                        logger.warning(
                            f'[Watchdog] Watchdog not sent. Response status: {resp.status_code}; '
                            f'Response: {resp.__dict__}')
                else:
                    logger.critical(f'[Watchdog] Main thread is not alive.')
        except (KeyError, TypeError, ValueError):
            logger.info('[Watchdog] not enabled, keep_alive missing')
        except ImportError:
            logger.warn('[Watchdog] systemd not imported {}'.format(
                traceback.format_exc(limit=5)))
        except:
            logger.alert('[Watchdog] Unexpected exception {}'.format(
                traceback.format_exc(limit=5)))
示例#2
0
 def serve_socket(self, sock, info):
     while True:
         try:
             rcv = sock.recv(1024).decode('utf-8')
             self.recv_callback(rcv)
         except Exception as e:
             self.socks.remove(sock)
             logger.critical(str(e), extra=self.log_extra)
示例#3
0
 def run(self):
     while True:
         try:
             geo_frame = self.frm_queue.get()
             self.parse_frame(geo_frame)
         except queue.Full:
             pass
         except Exception as e:
             logger.critical('{}'.format(str(e)), extra=self.log_extra)
示例#4
0
    def dispatch(self, frame):
        beacon_sample_itvl = 1 / CFG['DOT11'].getfloat('beacon_sample_rate')
        data_sample_itvl = 1 / CFG['DOT11'].getfloat('data_sample_rate')
        mgmt_sample_itvl = 1 / CFG['DOT11'].getfloat('mgmt_sample_rate')
        ctrl_sample_itvl = 1 / CFG['DOT11'].getfloat('ctrl_sample_rate')
        # Only parse 802.11 frames
        if Dot11 not in frame.layers() and Dot11FCS not in frame.layers():
            return
        sts = FrameSubType.get_type_subtype(frame)  # type/sub_type

        # only location within 10 seconds is valid
        geo = None
        if self.crnt_location['timestamp'] is not None:
            interval = time.time() - self.crnt_location['timestamp']
            if 0 <= interval <= 10:
                geo = {'longitude': self.crnt_location['longitude'],
                       'latitude': self.crnt_location['latitude']}
        geo_frame = GeoFrame(frame, geo, datetime.now())
        try:
            # Beacon frames are handled independently because it is too
            # frequent
            if sts == FrameSubType.BEACON:
                if self.frame_counters['beacon'] >= beacon_sample_itvl:
                    self.frm_queues['beacon'].put_nowait(geo_frame)
                    self.frame_counters['beacon'] = 0
                else:
                    self.frame_counters['beacon'] += 1
                    self.log_frame_counters['beacon'] += 1
            elif sts == FrameSubType.PROBE_REQ:
                self.frm_queues['probe_req'].put_nowait(geo_frame)
                self.log_frame_counters['probe_req'] += 1
            elif sts in FrameSubType.MGMT:
                if self.frame_counters['mgmt'] >= mgmt_sample_itvl:
                    self.frm_queues['mgmt'].put_nowait(geo_frame)
                    self.frame_counters['mgmt'] = 0
                else:
                    self.frame_counters['mgmt'] += 1
                    self.log_frame_counters['mgmt'] += 1
            elif sts in FrameSubType.CTRL:
                if self.frame_counters['ctrl'] >= ctrl_sample_itvl:
                    self.frm_queues['ctrl'].put_nowait(geo_frame)
                    self.frame_counters['ctrl'] = 0
                else:
                    self.frame_counters['ctrl'] += 1
                    self.log_frame_counters['ctrl'] += 1
            elif sts in FrameSubType.DATA:
                if self.frame_counters['data'] >= data_sample_itvl:
                    self.frm_queues['data'].put_nowait(geo_frame)
                    self.frame_counters['data'] = 0
                else:
                    self.frame_counters['data'] += 1
                    self.log_frame_counters['data'] += 1
        except queue.Full:
            pass
        except Exception as e:
            logger.critical('{}'.format(str(e)), extra=self.log_extra)
示例#5
0
 def __init__(self, deviceId=0, loops=1):
     """Initialize scanner."""
     self.deviceId = deviceId
     self.loops = loops
     try:
         self.sock = bluez.hci_open_dev(self.deviceId)
         blescan.hci_le_set_scan_parameters(self.sock)
         blescan.hci_enable_le_scan(self.sock)
     except Exception, e:
         logger.critical('Scan failed: {}'.format(str(e)))
         print e
示例#6
0
def start_refresher():
    """Refreshes the access token 2 days before expiry"""

    logger.debug('Starting token refresh thread ...')
    try:
        expiry_t = parser.parse(settings.block['expires'])
        current_t = datetime.now(tz.gettz(expiry_t.tzname()))
        time_diff = (expiry_t - current_t).total_seconds()
        refresh_after = time_diff - 86400 * 2

        timer = threading.Timer(refresh_after, renew_token)
        timer.daemon = True
        timer.start()
    except Exception:
        logger.critical("Token expiry check - thread failed {}".format(
            traceback.format_exc(limit=5)))
        os._exit(1)
示例#7
0
    def launch_server(self):
        logger.notice('Starting TCP server')
        tcp_settings = settings.config_tcp
        if 'ip_address' not in self.tcp_settings or 'port' not in self.tcp_settings:
            raise TCPServerNotFoundException(
                "TCP server address or port not found in config file")

        # Create a TCP/IP socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # Bind the socket to the port
        server_address = (self.tcp_settings['ip_address'],
                          int(self.tcp_settings['port']))
        logger.info(
            f'starting up on {server_address[0]} port {server_address[1]}')
        try:
            sock.bind(server_address)
            # Listen for incoming connections
            sock.listen(1)

            thread_list = []
            while True:
                if len(thread_list) >= self.tcp_settings.get(
                        'thread_pool_limit', DEFAULT_TCP_POOL_LIMIT):
                    self._clear_threads(thread_list)
                # Wait for a connection
                logger.info('Waiting for connection')
                connection, client_address = sock.accept()
                thread_ = threading.Thread(target=self.handle_connection,
                                           args=(connection, client_address))
                thread_.start()
                thread_list.append(thread_)

            self._clear_threads(thread_list)
        except OSError as e:
            logger.critical(
                f"Error connecting TCP. Probably because address already in use. "
                f"Will try to reconnect in {self.retry_wait}; Error: {e}")
        except Exception as e:
            logger.alert(
                f"Unexpected error while open TCP socket: {e}; {traceback.format_exc(limit=5)}"
            )
        finally:
            time.sleep(self.retry_wait)
            logger.warning("Recreating TCP server")
            self.kickoff()
示例#8
0
def get_implementer():
    try:
        _spec = util.spec_from_file_location("implementor",
                                             settings.skeleton_path)
        _module = util.module_from_spec(_spec)
        _spec.loader.exec_module(_module)

        for _name, _obj in inspect.getmembers(_module):
            try:
                if inspect.isclass(_obj) and issubclass(
                        _obj, (skeleton_device.SkeletonDevice,
                               skeleton_application.SkeletonApplication)):
                    logger.debug("Implementation class found: {}".format(_obj))
                    return _obj()
            except TypeError:
                continue

        raise ImplementorNotFound

    except Exception:
        logger.critical(
            f"Failed to find Skeleton implementer class {traceback.format_exc(limit=5)}, "
            f"check for missing abstract methods")
        os._exit(1)
示例#9
0
 def run(self):
     while True:
         try:
             while True:
                 event = self.event_queue.get()
                 # continue
                 if event.type == Dot11Event.MAC:
                     self.event_counters['MAC'] += 1
                     if self.handle_mac(event):
                         self.event_counters['MAC_new'] += 1
                 elif event.type == Dot11Event.SSID:
                     self.event_counters['SSID'] += 1
                     if self.handle_ssid(event):
                         self.event_counters['SSID_new'] += 1
                 elif event.type == Dot11Event.GEO:
                     self.event_counters['GEO'] += 1
                     if self.handle_geo(event):
                         self.event_counters['GEO_new'] += 1
                 elif event.type == Dot11Event.ASSOCIATION:
                     self.event_counters['ASSOCIATION'] += 1
                     if self.handle_association(event):
                         self.event_counters['ASSOCIATION_new'] += 1
         except Exception as e:
             logger.critical('{}'.format(str(e)), extra=self.log_extra)
示例#10
0
 def send_latest_captures_sys_status(self):
     data = dict()
     sql_mac = 'SELECT HEX(addr), last_seen FROM mac order by last_seen desc LIMIT 1'
     sql_ssid = 'SELECT ssid, last_seen FROM ap order by last_seen desc LIMIT 1'
     sql_association = 'SELECT HEX(mac.addr), ap.ssid, ' \
                       'association.last_seen FROM association JOIN mac ' \
                       'JOIN ap WHERE mac.id=association.mac_id AND ' \
                       'ap.id=association.ap_id ORDER BY ' \
                       'association.last_seen DESC LIMIT 1'
     sql_mac_count = 'SELECT COUNT(id) FROM mac'
     sql_ap_count = 'SELECT COUNT(id) FROM ap'
     sql_association_count = 'SELECT COUNT(id) FROM association'
     sql_geo_count = 'SELECT COUNT(id) FROM geo'
     try:
         db_conn, db_cursor = Dot11HunterUtils.connect_db()
         data['mac'] = self.fetch_data_with_lastseen(db_cursor, sql_mac)
         data['ssid'] = self.fetch_data_with_lastseen(db_cursor, sql_ssid)
         db_cursor.execute(sql_association)
         row = db_cursor.fetchall()
         if row:
             mac, ssid, date = row[0]
             if time.time() - date.timestamp() < 60:
                 data['association'] = '{} <-> {}'.format(mac, ssid)
             else:
                 data['association'] = None
         data['mac_count'] = self.fetch_data(db_cursor, sql_mac_count)
         data['ap_count'] = self.fetch_data(db_cursor, sql_ap_count)
         data['geo_count'] = self.fetch_data(db_cursor, sql_geo_count)
         data['association_count'] = self.fetch_data(db_cursor,
                                                     sql_association_count)
         db_conn.close()
         data['cpu_usage'], data['mem_usage'], data['temperature'] = \
             Dot11HunterUtils.get_sys_status()
         self.bt_server.send(json.dumps(data))
     except Exception as e:
         logger.critical(str(e), extra=self.log_extra)
示例#11
0
 def run(self):
     try:
         self.get_available_channels()
         self.switch_channel()
     except Exception as e:
         logger.critical(str(e), extra=self.log_extra)