Update public source
This commit is contained in:
@@ -0,0 +1,812 @@
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import shlex
|
||||
import subprocess
|
||||
import tempfile
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
NM_SERVICE = "org.freedesktop.NetworkManager"
|
||||
NM_DEVICE_WIRELESS = "org.freedesktop.NetworkManager.Device.Wireless"
|
||||
NM_ACCESS_POINT = "org.freedesktop.NetworkManager.AccessPoint"
|
||||
|
||||
AP_FLAGS_PRIVACY = 0x00000001
|
||||
|
||||
AP_SEC_KEY_MGMT_PSK = 0x00000100
|
||||
AP_SEC_KEY_MGMT_802_1X = 0x00000200
|
||||
AP_SEC_KEY_MGMT_SAE = 0x00000400
|
||||
AP_SEC_KEY_MGMT_OWE = 0x00000800
|
||||
AP_SEC_KEY_MGMT_OWE_TM = 0x00001000
|
||||
AP_SEC_KEY_MGMT_EAP_SUITE_B_192 = 0x00002000
|
||||
|
||||
|
||||
class WiFiConnectionError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class NetworkCommandError(WiFiConnectionError):
|
||||
pass
|
||||
|
||||
|
||||
class UnsupportedSecurityError(WiFiConnectionError):
|
||||
pass
|
||||
|
||||
|
||||
class NetworkRestoreError(WiFiConnectionError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AccessPoint:
|
||||
bssid: str
|
||||
ssid: str
|
||||
flags: int
|
||||
wpa_flags: int
|
||||
rsn_flags: int
|
||||
key_mgmt: str | None
|
||||
|
||||
@property
|
||||
def is_open(self):
|
||||
return (
|
||||
not self.flags & AP_FLAGS_PRIVACY
|
||||
and not self.wpa_flags
|
||||
and not self.rsn_flags
|
||||
)
|
||||
|
||||
|
||||
class WiFiConnectionService:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
command_runner=None,
|
||||
command_timeout=30
|
||||
):
|
||||
self.command_runner = (
|
||||
command_runner
|
||||
or
|
||||
subprocess.run
|
||||
)
|
||||
|
||||
self.command_timeout = command_timeout
|
||||
|
||||
@staticmethod
|
||||
def _validate_interface(interface):
|
||||
|
||||
if not re.fullmatch(
|
||||
r"[a-zA-Z0-9_.:-]{1,64}",
|
||||
interface or ""
|
||||
):
|
||||
raise WiFiConnectionError(
|
||||
"Invalid Wi-Fi interface."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _validate_bssid(bssid):
|
||||
|
||||
if not re.fullmatch(
|
||||
r"(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}",
|
||||
bssid or ""
|
||||
):
|
||||
raise WiFiConnectionError(
|
||||
"Invalid BSSID."
|
||||
)
|
||||
|
||||
def _run(
|
||||
self,
|
||||
command,
|
||||
timeout=None
|
||||
):
|
||||
|
||||
try:
|
||||
|
||||
result = self.command_runner(
|
||||
command,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=(
|
||||
timeout
|
||||
or
|
||||
self.command_timeout
|
||||
),
|
||||
env={
|
||||
**os.environ,
|
||||
"LC_ALL": "C"
|
||||
}
|
||||
)
|
||||
|
||||
except subprocess.TimeoutExpired as error:
|
||||
|
||||
raise NetworkCommandError(
|
||||
"NetworkManager command timed out."
|
||||
) from error
|
||||
|
||||
except OSError as error:
|
||||
|
||||
raise NetworkCommandError(
|
||||
f"Cannot execute {command[0]}: {error}"
|
||||
) from error
|
||||
|
||||
if result.returncode != 0:
|
||||
|
||||
message = (
|
||||
result.stderr.strip()
|
||||
or
|
||||
result.stdout.strip()
|
||||
or
|
||||
f"Command exited with code {result.returncode}."
|
||||
)
|
||||
|
||||
raise NetworkCommandError(message)
|
||||
|
||||
return result.stdout.strip()
|
||||
|
||||
def _nmcli(self, *arguments, timeout=None):
|
||||
|
||||
return self._run(
|
||||
[
|
||||
"nmcli",
|
||||
*arguments
|
||||
],
|
||||
timeout=timeout
|
||||
)
|
||||
|
||||
def _busctl(self, *arguments):
|
||||
|
||||
return self._run(
|
||||
[
|
||||
"busctl",
|
||||
"--system",
|
||||
*arguments
|
||||
]
|
||||
)
|
||||
|
||||
def _device_path(self, interface):
|
||||
|
||||
self._validate_interface(
|
||||
interface
|
||||
)
|
||||
|
||||
output = self._nmcli(
|
||||
"--get-values",
|
||||
"GENERAL.DBUS-PATH",
|
||||
"device",
|
||||
"show",
|
||||
interface
|
||||
)
|
||||
|
||||
if not output.startswith("/org/freedesktop/NetworkManager/Devices/"):
|
||||
raise WiFiConnectionError(
|
||||
"NetworkManager did not return a valid device D-Bus path."
|
||||
)
|
||||
|
||||
return output
|
||||
|
||||
def _get_property(
|
||||
self,
|
||||
object_path,
|
||||
interface,
|
||||
property_name
|
||||
):
|
||||
|
||||
output = self._busctl(
|
||||
"get-property",
|
||||
NM_SERVICE,
|
||||
object_path,
|
||||
interface,
|
||||
property_name
|
||||
)
|
||||
|
||||
try:
|
||||
parts = shlex.split(
|
||||
output
|
||||
)
|
||||
|
||||
if not parts:
|
||||
raise ValueError("Empty D-Bus property.")
|
||||
|
||||
return parts
|
||||
|
||||
except ValueError as error:
|
||||
|
||||
raise WiFiConnectionError(
|
||||
f"Cannot parse D-Bus property {property_name}."
|
||||
) from error
|
||||
|
||||
def _get_integer_property(
|
||||
self,
|
||||
object_path,
|
||||
property_name
|
||||
):
|
||||
|
||||
parts = self._get_property(
|
||||
object_path,
|
||||
NM_ACCESS_POINT,
|
||||
property_name
|
||||
)
|
||||
|
||||
if len(parts) != 2 or parts[0] != "u":
|
||||
raise WiFiConnectionError(
|
||||
f"Unexpected D-Bus type for {property_name}."
|
||||
)
|
||||
|
||||
try:
|
||||
return int(parts[1])
|
||||
|
||||
except ValueError as error:
|
||||
|
||||
raise WiFiConnectionError(
|
||||
f"Invalid value for {property_name}."
|
||||
) from error
|
||||
|
||||
def _get_ssid(self, object_path):
|
||||
|
||||
parts = self._get_property(
|
||||
object_path,
|
||||
NM_ACCESS_POINT,
|
||||
"Ssid"
|
||||
)
|
||||
|
||||
if not parts or parts[0] != "ay":
|
||||
raise WiFiConnectionError(
|
||||
"Unexpected D-Bus type for SSID."
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
count = int(parts[1])
|
||||
values = [
|
||||
int(value)
|
||||
for value in parts[2:]
|
||||
]
|
||||
|
||||
if (
|
||||
count != len(values)
|
||||
or
|
||||
any(value < 0 or value > 255 for value in values)
|
||||
):
|
||||
raise ValueError("Invalid SSID byte array.")
|
||||
|
||||
ssid = bytes(
|
||||
values
|
||||
).decode(
|
||||
"utf-8",
|
||||
errors="replace"
|
||||
)
|
||||
|
||||
except (ValueError, IndexError) as error:
|
||||
|
||||
raise WiFiConnectionError(
|
||||
"Cannot decode SSID from NetworkManager."
|
||||
) from error
|
||||
|
||||
if not ssid:
|
||||
raise WiFiConnectionError(
|
||||
"The access point does not advertise its SSID."
|
||||
)
|
||||
|
||||
return ssid
|
||||
|
||||
@staticmethod
|
||||
def _select_key_mgmt(
|
||||
flags,
|
||||
wpa_flags,
|
||||
rsn_flags
|
||||
):
|
||||
|
||||
security_flags = (
|
||||
wpa_flags
|
||||
|
|
||||
rsn_flags
|
||||
)
|
||||
|
||||
if not flags & AP_FLAGS_PRIVACY and not security_flags:
|
||||
return None
|
||||
|
||||
has_psk = bool(
|
||||
security_flags
|
||||
&
|
||||
AP_SEC_KEY_MGMT_PSK
|
||||
)
|
||||
|
||||
has_sae = bool(
|
||||
security_flags
|
||||
&
|
||||
AP_SEC_KEY_MGMT_SAE
|
||||
)
|
||||
|
||||
if has_psk:
|
||||
return "wpa-psk"
|
||||
|
||||
if has_sae:
|
||||
return "sae"
|
||||
|
||||
raise UnsupportedSecurityError(
|
||||
"This access point does not advertise WPA Personal PSK or SAE security."
|
||||
)
|
||||
|
||||
def get_access_point(
|
||||
self,
|
||||
interface,
|
||||
bssid
|
||||
):
|
||||
|
||||
self._validate_interface(
|
||||
interface
|
||||
)
|
||||
|
||||
self._validate_bssid(
|
||||
bssid
|
||||
)
|
||||
|
||||
device_path = self._device_path(
|
||||
interface
|
||||
)
|
||||
|
||||
output = self._busctl(
|
||||
"call",
|
||||
NM_SERVICE,
|
||||
device_path,
|
||||
NM_DEVICE_WIRELESS,
|
||||
"GetAccessPoints"
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
parts = shlex.split(
|
||||
output
|
||||
)
|
||||
|
||||
if len(parts) < 2 or parts[0] != "ao":
|
||||
raise ValueError("Unexpected GetAccessPoints result.")
|
||||
|
||||
count = int(
|
||||
parts[1]
|
||||
)
|
||||
|
||||
paths = parts[2:]
|
||||
|
||||
if count != len(paths):
|
||||
raise ValueError("Invalid access point count.")
|
||||
|
||||
except ValueError as error:
|
||||
|
||||
raise WiFiConnectionError(
|
||||
"Cannot parse NetworkManager access point list."
|
||||
) from error
|
||||
|
||||
for object_path in paths:
|
||||
|
||||
ap_bssid_parts = self._get_property(
|
||||
object_path,
|
||||
NM_ACCESS_POINT,
|
||||
"HwAddress"
|
||||
)
|
||||
|
||||
if (
|
||||
len(ap_bssid_parts) != 2
|
||||
or
|
||||
ap_bssid_parts[0] != "s"
|
||||
):
|
||||
continue
|
||||
|
||||
ap_bssid = ap_bssid_parts[1]
|
||||
|
||||
if ap_bssid.lower() != bssid.lower():
|
||||
continue
|
||||
|
||||
flags = self._get_integer_property(
|
||||
object_path,
|
||||
"Flags"
|
||||
)
|
||||
|
||||
wpa_flags = self._get_integer_property(
|
||||
object_path,
|
||||
"WpaFlags"
|
||||
)
|
||||
|
||||
rsn_flags = self._get_integer_property(
|
||||
object_path,
|
||||
"RsnFlags"
|
||||
)
|
||||
|
||||
ssid = self._get_ssid(
|
||||
object_path
|
||||
)
|
||||
|
||||
key_mgmt = self._select_key_mgmt(
|
||||
flags,
|
||||
wpa_flags,
|
||||
rsn_flags
|
||||
)
|
||||
|
||||
return AccessPoint(
|
||||
bssid=ap_bssid.upper(),
|
||||
ssid=ssid,
|
||||
flags=flags,
|
||||
wpa_flags=wpa_flags,
|
||||
rsn_flags=rsn_flags,
|
||||
key_mgmt=key_mgmt
|
||||
)
|
||||
|
||||
raise WiFiConnectionError(
|
||||
f"Access point {bssid} is not currently visible to NetworkManager."
|
||||
)
|
||||
|
||||
def _get_active_connection_uuid(self, interface):
|
||||
|
||||
output = self._nmcli(
|
||||
"--get-values",
|
||||
"GENERAL.CON-UUID",
|
||||
"device",
|
||||
"show",
|
||||
interface
|
||||
)
|
||||
|
||||
if not output or output == "--":
|
||||
return None
|
||||
|
||||
return output
|
||||
|
||||
def _create_temporary_profile(
|
||||
self,
|
||||
interface,
|
||||
access_point
|
||||
):
|
||||
|
||||
profile_name = (
|
||||
"wifi-gps-mapper-"
|
||||
+
|
||||
secrets.token_hex(8)
|
||||
)
|
||||
|
||||
arguments = [
|
||||
"connection",
|
||||
"add",
|
||||
"type",
|
||||
"wifi",
|
||||
"ifname",
|
||||
interface,
|
||||
"con-name",
|
||||
profile_name,
|
||||
"ssid",
|
||||
access_point.ssid,
|
||||
"mode",
|
||||
"infrastructure",
|
||||
"autoconnect",
|
||||
"no",
|
||||
"save",
|
||||
"no",
|
||||
"wifi.bssid",
|
||||
access_point.bssid
|
||||
]
|
||||
|
||||
if access_point.key_mgmt:
|
||||
|
||||
arguments.extend(
|
||||
[
|
||||
"wifi-sec.key-mgmt",
|
||||
access_point.key_mgmt
|
||||
]
|
||||
)
|
||||
|
||||
self._nmcli(
|
||||
*arguments
|
||||
)
|
||||
|
||||
output = self._nmcli(
|
||||
"--get-values",
|
||||
"connection.uuid",
|
||||
"connection",
|
||||
"show",
|
||||
profile_name
|
||||
)
|
||||
|
||||
if not re.fullmatch(
|
||||
r"[0-9a-fA-F-]{36}",
|
||||
output
|
||||
):
|
||||
raise WiFiConnectionError(
|
||||
"NetworkManager created a profile but returned an invalid UUID."
|
||||
)
|
||||
|
||||
return output
|
||||
|
||||
@staticmethod
|
||||
def _create_password_file(password):
|
||||
|
||||
if (
|
||||
not isinstance(password, str)
|
||||
or
|
||||
not password
|
||||
or
|
||||
"\n" in password
|
||||
or
|
||||
"\r" in password
|
||||
):
|
||||
raise WiFiConnectionError(
|
||||
"Invalid Wi-Fi password."
|
||||
)
|
||||
|
||||
file_descriptor, filename = tempfile.mkstemp(
|
||||
prefix="wifi-gps-mapper-",
|
||||
suffix=".psk",
|
||||
dir="/tmp"
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
os.fchmod(
|
||||
file_descriptor,
|
||||
0o600
|
||||
)
|
||||
|
||||
with os.fdopen(
|
||||
file_descriptor,
|
||||
"w",
|
||||
encoding="utf-8"
|
||||
) as password_file:
|
||||
|
||||
password_file.write(
|
||||
"802-11-wireless-security.psk:"
|
||||
+
|
||||
password
|
||||
+
|
||||
"\n"
|
||||
)
|
||||
|
||||
except Exception:
|
||||
|
||||
try:
|
||||
os.close(
|
||||
file_descriptor
|
||||
)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
try:
|
||||
os.unlink(
|
||||
filename
|
||||
)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
raise
|
||||
|
||||
return filename
|
||||
|
||||
def _activate_profile(
|
||||
self,
|
||||
profile_uuid,
|
||||
interface,
|
||||
access_point,
|
||||
password=None
|
||||
):
|
||||
|
||||
arguments = [
|
||||
"connection",
|
||||
"up",
|
||||
"uuid",
|
||||
profile_uuid,
|
||||
"ifname",
|
||||
interface,
|
||||
"ap",
|
||||
access_point.bssid
|
||||
]
|
||||
|
||||
password_file = None
|
||||
|
||||
try:
|
||||
|
||||
if access_point.key_mgmt:
|
||||
|
||||
if password is None:
|
||||
raise WiFiConnectionError(
|
||||
"A password is required for this access point."
|
||||
)
|
||||
|
||||
password_file = self._create_password_file(
|
||||
password
|
||||
)
|
||||
|
||||
arguments.extend(
|
||||
[
|
||||
"passwd-file",
|
||||
password_file
|
||||
]
|
||||
)
|
||||
|
||||
elif password is not None:
|
||||
|
||||
raise WiFiConnectionError(
|
||||
"An open access point does not require a password."
|
||||
)
|
||||
|
||||
self._nmcli(
|
||||
*arguments,
|
||||
timeout=90
|
||||
)
|
||||
|
||||
finally:
|
||||
|
||||
if password_file:
|
||||
|
||||
try:
|
||||
os.unlink(
|
||||
password_file
|
||||
)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _delete_profile(self, profile_uuid):
|
||||
|
||||
if not profile_uuid:
|
||||
return
|
||||
|
||||
try:
|
||||
|
||||
self._nmcli(
|
||||
"connection",
|
||||
"delete",
|
||||
"uuid",
|
||||
profile_uuid
|
||||
)
|
||||
|
||||
except NetworkCommandError:
|
||||
pass
|
||||
|
||||
def connect(
|
||||
self,
|
||||
interface,
|
||||
bssid,
|
||||
password=None
|
||||
):
|
||||
|
||||
access_point = self.get_access_point(
|
||||
interface,
|
||||
bssid
|
||||
)
|
||||
|
||||
profile_uuid = self._create_temporary_profile(
|
||||
interface,
|
||||
access_point
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
self._activate_profile(
|
||||
profile_uuid,
|
||||
interface,
|
||||
access_point,
|
||||
password
|
||||
)
|
||||
|
||||
except Exception:
|
||||
|
||||
self._delete_profile(
|
||||
profile_uuid
|
||||
)
|
||||
|
||||
raise
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"interface": interface,
|
||||
"bssid": access_point.bssid,
|
||||
"ssid": access_point.ssid,
|
||||
"profile_uuid": profile_uuid,
|
||||
"is_open": access_point.is_open
|
||||
}
|
||||
|
||||
def verify(
|
||||
self,
|
||||
interface,
|
||||
bssid,
|
||||
password
|
||||
):
|
||||
|
||||
access_point = self.get_access_point(
|
||||
interface,
|
||||
bssid
|
||||
)
|
||||
|
||||
if access_point.is_open:
|
||||
raise WiFiConnectionError(
|
||||
"Open access points do not require password verification."
|
||||
)
|
||||
|
||||
if not access_point.key_mgmt:
|
||||
raise UnsupportedSecurityError(
|
||||
"Password verification is not supported for this security type."
|
||||
)
|
||||
|
||||
previous_uuid = self._get_active_connection_uuid(
|
||||
interface
|
||||
)
|
||||
|
||||
profile_uuid = None
|
||||
success = False
|
||||
error_message = None
|
||||
restore_error = None
|
||||
|
||||
try:
|
||||
|
||||
profile_uuid = self._create_temporary_profile(
|
||||
interface,
|
||||
access_point
|
||||
)
|
||||
|
||||
self._activate_profile(
|
||||
profile_uuid,
|
||||
interface,
|
||||
access_point,
|
||||
password
|
||||
)
|
||||
|
||||
success = True
|
||||
|
||||
except NetworkCommandError as error:
|
||||
|
||||
error_message = str(
|
||||
error
|
||||
)
|
||||
|
||||
finally:
|
||||
|
||||
if profile_uuid:
|
||||
|
||||
try:
|
||||
|
||||
if previous_uuid:
|
||||
|
||||
self._nmcli(
|
||||
"connection",
|
||||
"up",
|
||||
"uuid",
|
||||
previous_uuid,
|
||||
"ifname",
|
||||
interface,
|
||||
timeout=90
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
try:
|
||||
|
||||
self._nmcli(
|
||||
"connection",
|
||||
"down",
|
||||
"uuid",
|
||||
profile_uuid
|
||||
)
|
||||
|
||||
except NetworkCommandError:
|
||||
pass
|
||||
|
||||
except NetworkCommandError as error:
|
||||
|
||||
restore_error = str(
|
||||
error
|
||||
)
|
||||
|
||||
finally:
|
||||
|
||||
self._delete_profile(
|
||||
profile_uuid
|
||||
)
|
||||
|
||||
if restore_error:
|
||||
|
||||
raise NetworkRestoreError(
|
||||
"The Wi-Fi verification attempt finished, but the previous connection "
|
||||
f"could not be restored: {restore_error}"
|
||||
)
|
||||
|
||||
return {
|
||||
"success": success,
|
||||
"interface": interface,
|
||||
"bssid": access_point.bssid,
|
||||
"ssid": access_point.ssid,
|
||||
"error": error_message
|
||||
}
|
||||
Reference in New Issue
Block a user