#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Server-side search for WiFi GPS Mapper reports. Search criteria are intentionally represented as a dictionary so that new search blocks can be added without redesigning the search layer. """ import json from html import escape from reports.utils import ( format_datetime as format_report_datetime, ) from reports.map_popups import build_standard_popup MAP_STYLE_URL = ( "http://127.0.0.1:8080/styles/server-map/style.json" ) # ============================================================ # Search criteria # ============================================================ def normalize_criteria( vendor=None, essid=None, bssid=None, ): criteria = {} for key, value in ( ("vendor", vendor), ("essid", essid), ("bssid", bssid), ): if value is not None: value = str(value).strip() if value: criteria[key] = value return criteria def build_where_clause(criteria): conditions = [] parameters = [] vendor = criteria.get("vendor") if vendor: conditions.append( """ LOWER( REPLACE( REPLACE( REPLACE( REPLACE( REPLACE( COALESCE(ap.vendor, ''), '-', '' ), ' ', '' ), '_', '' ), '.', '' ), '/', '' ) ) LIKE '%' || LOWER( REPLACE( REPLACE( REPLACE( REPLACE( REPLACE( ?, '-', '' ), ' ', '' ), '_', '' ), '.', '' ), '/', '' ) ) || '%' """ ) parameters.append( vendor ) essid = criteria.get("essid") if essid: conditions.append( """ LOWER( COALESCE(ap.essid, '') ) LIKE '%' || LOWER(?) || '%' """ ) parameters.append( essid ) bssid = criteria.get("bssid") if bssid: conditions.append( """ LOWER( REPLACE( REPLACE( COALESCE(ap.bssid, ''), ':', '' ), '-', '' ) ) LIKE '%' || LOWER( REPLACE( REPLACE( ?, ':', '' ), '-', '' ) ) || '%' """ ) parameters.append( bssid ) if not conditions: raise ValueError( "At least one search criterion is required." ) return ( " AND ".join(conditions), parameters ) # ============================================================ # Popular vendors # ============================================================ def get_popular_vendors( conn, limit=20, ): rows = conn.execute( """ SELECT vendor, COUNT(*) AS count FROM access_points WHERE vendor IS NOT NULL AND TRIM(vendor) != '' GROUP BY vendor ORDER BY count DESC, vendor COLLATE NOCASE ASC LIMIT ? """, ( limit, ) ).fetchall() return [ { "vendor": row["vendor"], "count": row["count"], } for row in rows ] def get_matching_vendors( conn, criteria, limit=20, ): where_clause, parameters = ( build_where_clause(criteria) ) rows = conn.execute( f""" SELECT ap.vendor, COUNT(*) AS count FROM access_points AS ap WHERE {where_clause} AND ap.vendor IS NOT NULL AND TRIM(ap.vendor) != '' GROUP BY ap.vendor ORDER BY count DESC, ap.vendor COLLATE NOCASE ASC LIMIT ? """, parameters + [limit] ).fetchall() return [ { "vendor": row["vendor"], "count": row["count"], } for row in rows ] # ============================================================ # Access point search # ============================================================ def search_access_points( conn, criteria, ): where_clause, parameters = ( build_where_clause(criteria) ) return conn.execute( f""" SELECT ap.id, ap.bssid, ap.essid, ap.encryption, ap.cipher, ap.akm, ap.country, ap.channel, ap.frequency, ap.vendor, ap.first_seen, ap.last_seen, ap.times_seen, ap.last_rssi, ap.last_latitude, ap.last_longitude, ap.last_speed, ap.has_handshake, ap.has_pmkid, ap.is_cracked FROM access_points AS ap WHERE {where_clause} ORDER BY ap.vendor COLLATE NOCASE, ap.essid COLLATE NOCASE, ap.bssid """, parameters ).fetchall() # ============================================================ # Credentials # ============================================================ def load_credentials( conn, criteria, ): where_clause, parameters = ( build_where_clause(criteria) ) rows = conn.execute( f""" SELECT c.access_point_id, c.password, c.source, c.created_at, c.verified FROM credentials AS c INNER JOIN access_points AS ap ON ap.id = c.access_point_id WHERE {where_clause} ORDER BY c.access_point_id, c.password """, parameters ).fetchall() result = {} for row in rows: access_point_id = row["access_point_id"] result.setdefault( access_point_id, [] ).append( { "password": row["password"], "source": row["source"], "created_at": row["created_at"], "verified": bool( row["verified"] ), } ) return result # ============================================================ # Handshakes / PMKIDs # ============================================================ def load_handshakes( conn, criteria, ): where_clause, parameters = ( build_where_clause(criteria) ) rows = conn.execute( f""" SELECT h.id, h.access_point_id, h.type, h.hash22000, h.message_pair, h.captured_at FROM handshakes AS h INNER JOIN access_points AS ap ON ap.id = h.access_point_id WHERE {where_clause} ORDER BY h.access_point_id, h.captured_at """, parameters ).fetchall() result = {} for row in rows: access_point_id = row["access_point_id"] result.setdefault( access_point_id, [] ).append( { "id": row["id"], "type": row["type"], "hash22000": row["hash22000"], "message_pair": row["message_pair"], "captured_at": row["captured_at"], } ) return result # ============================================================ # Category # ============================================================ def get_category( access_point, ): if access_point["is_cracked"]: return "password" if ( access_point["has_handshake"] or access_point["has_pmkid"] ): return "handshake" if ( str(access_point["encryption"] or "").strip().upper() == "OPEN" ): return "open" return "other" # ============================================================ # Popup helpers # ============================================================ def search_display(value): if value is None or str(value).strip() == "": return "—" return escape( str(value), quote=True ) def build_search_popup( access_point, category_class, category_label, credentials=None, handshakes=None, include_capture_times=False, ): standard_popup = build_standard_popup( essid=access_point["essid"], bssid=access_point["bssid"], vendor=access_point["vendor"], encryption=access_point["encryption"], cipher=access_point["cipher"], akm=access_point["akm"], channel=access_point["channel"], rssi=access_point["last_rssi"], passwords=credentials or [], handshakes=handshakes or [], observed_at=format_report_datetime( access_point["last_seen"] ), latitude=access_point["last_latitude"], longitude=access_point["last_longitude"], access_point_url=( f"/reports/access-points/{access_point['bssid']}" ), ) category_html = ( '