diff --git a/gui/app.py b/gui/app.py index 4493969..54cf589 100644 --- a/gui/app.py +++ b/gui/app.py @@ -72,6 +72,7 @@ from vendor_service import VendorService from sudo import SudoChecker from config import Config from gps_test import GPSTestService +from wifi_connection import WiFiConnectionError, WiFiConnectionService from gui.timezones import get_timezone_options from logging_config import ( LOG_DATE_FORMAT, @@ -253,6 +254,8 @@ def scanner_navigation_guard(): "index", "api_status", "api_network_wifi_devices", + "api_network_wifi_verify", + "api_network_wifi_connect", "scanner_stop", "api_gps_test", "gps_test_stop", @@ -295,6 +298,8 @@ gps_test_service = None gps_test_lock = threading.Lock() +wifi_connection_service = WiFiConnectionService() + def check_sudo(): try: @@ -397,6 +402,53 @@ def network_actions_busy(): gps_test_service.thread.is_alive() ) +def begin_network_action(): + + global network_action_active + + with scanner_lock: + + if network_action_active: + + return False, "Another Wi-Fi connection operation is in progress." + + if ( + scanner_starting + or + ( + scanner_process is not None + and + scanner_process.poll() is None + ) + ): + + return False, "Wi-Fi operation is unavailable while the scanner is running." + + with gps_test_lock: + + if ( + gps_test_service is not None + and + gps_test_service.thread is not None + and + gps_test_service.thread.is_alive() + ): + + return False, "Wi-Fi operation is unavailable while the GPS test is running." + + network_action_active = True + + return True, None + + +def end_network_action(): + + global network_action_active + + with scanner_lock: + + network_action_active = False + def get_scanner_status(): global scanner_health @@ -2523,6 +2575,406 @@ def api_network_wifi_devices(): } ) +def validate_network_interface(interface): + + devices, error = get_nm_wifi_devices() + + if error: + return None, error, 503 + + if not devices: + return None, "No Wi-Fi interfaces found.", 400 + + device = next( + ( + item + for item in devices + if item["device"] == interface + ), + None + ) + + if device is None: + return None, "The selected Wi-Fi interface was not found.", 400 + + if device["managed"] is not True: + return None, "NetworkManager is not managing this Wi-Fi interface.", 409 + + if device["state"] == "unavailable": + return None, "Wi-Fi interface is unavailable. Check hardware switch, rfkill or driver.", 409 + + if device["state"] == "unmanaged": + return None, "Wi-Fi interface is unmanaged.", 409 + + if device["state"] not in ("connected", "disconnected"): + return None, f"Wi-Fi interface is not ready. State: {device['state']}", 409 + + return device, None, None + + +def get_network_credential( + bssid, + password, + verified_only=False +): + + conn = connect_database() + + try: + + query = """ + SELECT + ap.id AS access_point_id, + c.id AS credential_id + FROM access_points AS ap + JOIN credentials AS c + ON c.access_point_id = ap.id + WHERE lower(ap.bssid) = lower(?) + AND c.password = ? + """ + + if verified_only: + query += " AND c.verified = 1" + + query += " LIMIT 1" + + return conn.execute( + query, + ( + bssid, + password + ) + ).fetchone() + + finally: + close_database(conn) + + +def mark_network_credential_verified( + access_point_id, + password +): + + conn = connect_database() + + try: + + cursor = conn.execute( + """ + UPDATE credentials + SET verified = 1 + WHERE access_point_id = ? + AND password = ? + """, + ( + access_point_id, + password + ) + ) + + if cursor.rowcount == 0: + + raise WiFiConnectionError( + "The credential no longer exists in the database." + ) + + conn.commit() + + except Exception: + + conn.rollback() + raise + + finally: + close_database(conn) + + +def get_network_wireguard_warning(): + + connections, error = get_active_wireguard_connections() + + if connections: + + return ( + "An active WireGuard VPN connection was detected. " + "For security and reliable local network access, " + "manually disconnect the VPN if necessary." + ) + + return None + + +@app.route( + "/api/network/verify", + methods=["POST"] +) +def api_network_wifi_verify(): + + data = request.get_json( + silent=True + ) or {} + + interface = data.get("interface") + bssid = data.get("bssid") + password = data.get("password") + + if ( + not isinstance(interface, str) + or not interface.strip() + or not isinstance(bssid, str) + or not bssid.strip() + or not isinstance(password, str) + or not password + ): + + return jsonify( + { + "ok": False, + "error": "Interface, BSSID and password are required." + } + ), 400 + + interface = interface.strip() + bssid = bssid.strip() + + acquired, error = begin_network_action() + + if not acquired: + + return jsonify( + { + "ok": False, + "error": error + } + ), 409 + + try: + + device, error, status = validate_network_interface( + interface + ) + + if error: + + return jsonify( + { + "ok": False, + "error": error + } + ), status + + credential = get_network_credential( + bssid, + password + ) + + if credential is None: + + return jsonify( + { + "ok": False, + "error": "The specified password was not found for this access point." + } + ), 404 + + result = wifi_connection_service.verify( + interface, + bssid, + password + ) + + if not result.get("success"): + + return jsonify( + { + "ok": False, + "success": False, + "error": result.get("error") or "Wi-Fi verification failed." + } + ), 401 + + mark_network_credential_verified( + credential["access_point_id"], + password + ) + + return jsonify( + { + "ok": True, + "success": True, + "interface": result["interface"], + "bssid": result["bssid"], + "ssid": result["ssid"], + "verified": True, + "wireguard_warning": get_network_wireguard_warning() + } + ) + + except WiFiConnectionError as error: + + return jsonify( + { + "ok": False, + "error": str(error) + } + ), 502 + + except Exception: + + logger.exception( + "Wi-Fi password verification API failed." + ) + + return jsonify( + { + "ok": False, + "error": "An internal error occurred during Wi-Fi verification." + } + ), 500 + + finally: + end_network_action() + + +@app.route( + "/api/network/connect", + methods=["POST"] +) +def api_network_wifi_connect(): + + data = request.get_json( + silent=True + ) or {} + + interface = data.get("interface") + bssid = data.get("bssid") + password = data.get("password") + + if ( + not isinstance(interface, str) + or not interface.strip() + or not isinstance(bssid, str) + or not bssid.strip() + or ( + password is not None + and not isinstance(password, str) + ) + ): + + return jsonify( + { + "ok": False, + "error": "A valid interface and BSSID are required." + } + ), 400 + + interface = interface.strip() + bssid = bssid.strip() + + acquired, error = begin_network_action() + + if not acquired: + + return jsonify( + { + "ok": False, + "error": error + } + ), 409 + + try: + + device, error, status = validate_network_interface( + interface + ) + + if error: + + return jsonify( + { + "ok": False, + "error": error + } + ), status + + access_point = wifi_connection_service.get_access_point( + interface, + bssid + ) + + if not access_point.is_open: + + if not isinstance(password, str) or not password: + + return jsonify( + { + "ok": False, + "error": "A password is required for this secured access point." + } + ), 400 + + credential = get_network_credential( + bssid, + password, + verified_only=True + ) + + if credential is None: + + return jsonify( + { + "ok": False, + "error": "This password has not been successfully verified for this access point." + } + ), 403 + + else: + password = None + + result = wifi_connection_service.connect( + interface, + bssid, + password, + access_point=access_point + ) + + return jsonify( + { + "ok": True, + "success": True, + "interface": result["interface"], + "bssid": result["bssid"], + "ssid": result["ssid"], + "is_open": result["is_open"], + "wireguard_warning": get_network_wireguard_warning() + } + ) + + except WiFiConnectionError as error: + + return jsonify( + { + "ok": False, + "error": str(error) + } + ), 502 + + except Exception: + + logger.exception( + "Wi-Fi connection API failed." + ) + + return jsonify( + { + "ok": False, + "error": "An internal error occurred during Wi-Fi connection." + } + ), 500 + + finally: + end_network_action() + @app.route( "/api/wifi/channels" ) diff --git a/src/wifi_connection.py b/src/wifi_connection.py index 641cd4c..59558c5 100644 --- a/src/wifi_connection.py +++ b/src/wifi_connection.py @@ -762,13 +762,22 @@ class WiFiConnectionService: self, interface, bssid, - password=None + password=None, + access_point=None ): - access_point = self.get_access_point( - interface, - bssid - ) + if access_point is None: + + access_point = self.get_access_point( + interface, + bssid + ) + + elif access_point.bssid.lower() != bssid.lower(): + + raise WiFiConnectionError( + "The supplied access point does not match the requested BSSID." + ) profile_uuid = self._create_temporary_profile( interface,