Files
napalm-zyxel/napalm_zyxel/zyxel_driver.py
T
Christian Manivong a37802cf88
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 11s
driver / test (3.12) (pull_request) Successful in 49s
driver / types (pull_request) Successful in 51s
driver / test (3.13) (pull_request) Successful in 45s
driver / lowest (pull_request) Successful in 22s
driver / build (pull_request) Successful in 26s
driver / security (pull_request) Successful in 56s
CI / driver (pull_request) Successful in 2m13s
driver / publish (pull_request) Skipped
fix(driver): load_replace_candidate is None, not a stub that raises (NetOrk/netork#2503)
The driver cannot replace a device's configuration, and said so with a
load_replace_candidate that raised NotImplementedError. A method that only
raises still looks like a replace to anyone who asks whether the driver has
one: netOrk offered a config restore for these devices that could only fail.

None is how a driver switches off a method, the convention netOrk's
capability checks and napalm-device-types follow, so asking now says no.
Nothing in the driver calls it.
2026-11-13 21:45:24 +01:00

877 lines
34 KiB
Python

"""NAPALM driver for Zyxel VMG series residential gateways.
Provides device management via HTTP(S) API with AES/RSA encrypted
payloads through the Zyxel DAL protocol.
"""
from __future__ import annotations
import base64
import ipaddress
import json
import logging
import os
import re
import socket
from collections.abc import Callable
from typing import Any, TypeVar
from urllib.parse import urljoin
import requests
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding as asym_padding
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from napalm.base.exceptions import ConnectionClosedException, ConnectionException
from napalm_device_types import FingerprintRule, PortSpec, ResidentialGatewayDriver
from napalm_device_types.models import (
HostDict,
NATTranslationDict,
PortForwardDict,
RadioStatusDict,
SSIDDict,
VPNTunnelDict,
WANStatusDict,
WirelessClientDict,
)
from napalm_zyxel import parsers
logger = logging.getLogger(__name__)
#: Answers that mean the session is not (or no longer) accepted.
_SESSION_REFUSED = (401, 403)
_T = TypeVar("_T")
#: The inside-global address of a port forward when the gateway has no WAN address
#: (an address reported, not one bound to).
_ANY_ADDRESS = "0.0.0.0" # nosec B104
_PING_UNSUPPORTED = "Not supported on Zyxel VMG: the DAL does not report ping replies"
def _ip_interface(entry: dict[str, Any]) -> dict[str, Any]:
"""One ``WanLanInfo`` entry of ``cardpage_status`` as a NAPALM interface."""
label = entry.get("Name") or entry["X_ZYXEL_IfName"]
service = entry.get("X_ZYXEL_SrvName")
if entry.get("X_ZYXEL_Type") == "WAN" and service:
label = f"{label} ({service})"
return {
"is_up": entry.get("Status") == "Up",
"is_enabled": bool(entry.get("Enable")),
"description": label,
"last_flapped": -1.0,
"mac_address": entry.get("MACAddress") or "",
"speed": 0.0,
"mtu": 0,
}
def _ethernet_port(port: dict[str, Any]) -> dict[str, Any]:
"""One ``LanInfo`` entry of ``cardpage_status`` as a NAPALM interface."""
return {
"is_up": port.get("Status") == "Up",
"is_enabled": bool(port.get("Enable")),
"description": port.get("X_ZYXEL_LanPort") or port["Name"],
"last_flapped": -1.0,
"mac_address": port.get("MACAddress") or "",
"speed": float(port.get("MaxBitRate") or 0),
"mtu": 0,
}
def _interfaces(page: dict[str, Any]) -> dict[str, dict[str, Any]]:
"""The IP interfaces (``WanLanInfo``) and Ethernet ports (``LanInfo``) of a
``cardpage_status`` answer, keyed by the gateway's own interface name."""
ifaces = {
entry["X_ZYXEL_IfName"]: _ip_interface(entry)
for entry in page.get("WanLanInfo") or []
if entry.get("X_ZYXEL_IfName")
}
ifaces.update(
{
port["Name"]: _ethernet_port(port)
for port in page.get("LanInfo") or []
if port.get("Name")
}
)
return ifaces
def _ipv4_addresses(entry: dict[str, Any]) -> dict[str, dict[str, int]]:
"""The enabled IPv4 addresses of one ``WanLanInfo`` entry, with their prefix length."""
return {
addr["IPAddress"]: {
"prefix_length": ipaddress.IPv4Network(f"0.0.0.0/{addr['SubnetMask']}").prefixlen
}
for addr in entry.get("IPv4Address") or []
if addr.get("Enable") and addr.get("IPAddress") and addr.get("SubnetMask")
}
class ZyxelCrypto:
"""AES-256-CBC encryption wrapper for Zyxel DAL protocol payloads."""
_AES_KEY_SIZE = 32
_IV_SIZE = 16
_DEFAULT_IV = b"\x42" * 16
def __init__(self) -> None:
self.aes_key = os.urandom(self._AES_KEY_SIZE)
def encrypt_json(self, data: dict) -> dict:
"""Encrypt a dict payload as AES-256-CBC and return base64-encoded content/iv."""
iv = self._DEFAULT_IV
payload = json.dumps(data).encode("ascii")
pad_len = self._AES_KEY_SIZE - (len(payload) % self._AES_KEY_SIZE)
payload += bytes([pad_len] * pad_len)
cipher = Cipher(algorithms.AES(self.aes_key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
content = encryptor.update(payload) + encryptor.finalize()
return {
"content": base64.b64encode(content).decode("ascii"),
"iv": base64.b64encode(iv).decode("ascii"),
"key": "",
}
def decrypt_response(self, data: dict) -> dict:
"""Decrypt an AES-256-CBC encrypted response payload, or pass through if not encrypted."""
if not isinstance(data, dict) or "content" not in data:
return data
iv = base64.b64decode(data["iv"])[: self._IV_SIZE]
content = base64.b64decode(data["content"])
cipher = Cipher(algorithms.AES(self.aes_key), modes.CBC(iv), backend=default_backend())
decryptor = cipher.decryptor()
padded = decryptor.update(content) + decryptor.finalize()
pad_len = padded[-1]
plain = padded[:-pad_len] if 0 < pad_len <= self._AES_KEY_SIZE else padded
return json.loads(plain.decode("ascii"))
def encrypt_aes_key_with_rsa(self, pubkey_pem: str) -> str:
"""Encrypt the AES key with the device's RSA public key for key exchange."""
pubkey = serialization.load_pem_public_key(
pubkey_pem.encode("ascii"), backend=default_backend()
)
if not isinstance(pubkey, rsa.RSAPublicKey):
raise ValueError("Not an RSA public key")
encrypted = pubkey.encrypt(
base64.b64encode(self.aes_key),
asym_padding.PKCS1v15(),
)
return base64.b64encode(encrypted).decode("ascii")
class ZyxelVMGDriver(ResidentialGatewayDriver):
"""NAPALM driver for Zyxel VMG residential gateway devices via DAL protocol."""
VENDOR = "Zyxel"
DRIVER_NAME = "zyxel"
SNMP_OBJECT_ID_PREFIX = "1.3.6.1.4.1.890"
OUI_PREFIXES = ["00:13:49", "1C:74:0D", "C8:6C:87", "B0:B2:DC", "28:28:5D"]
_LOGIN_PATH = "UserLogin"
_LOGOUT_PATH = "cgi-bin/UserLogout"
_RSA_KEY_PATH = "getRSAPublickKey"
_BASIC_INFO_PATH = "getBasicInformation"
_DAL_PATH = "cgi-bin/DAL"
_SYSTEM_PATH = "cgi-bin/System?oid=snmp"
_STATUS_OID = "cardpage_status"
#: The DAL names the gateway's own web interface reads hosts and port forwards by.
_HOSTS_OID = "lanhosts"
_NAT_OID = "nat"
#: Discovery also fetches the DAL's key exchange, which answers without a login
#: (``open()`` needs it). The port answering is no evidence; the answer is (#13).
PORT_SPECS = [
PortSpec("http", 80, (f"/{_RSA_KEY_PATH}",), weight=0.0),
PortSpec("https", 443, (f"/{_RSA_KEY_PATH}",), weight=0.0),
]
#: OID, OUI and "zyxel" fit every Zyxel product and stay below "high" together;
#: only a DAL gateway answers with an ``RSAPublicKey`` (#13).
HTTP_FINGERPRINT = [
FingerprintRule("zyxel", weight=7.0, mandatory=True),
FingerprintRule('"rsapublickey"', weight=24.0),
]
#: The DAL accepts a PINGTEST request but its answer carries no reply count or
#: round-trip time, so this driver cannot tell an answering host from a silent one.
SUPPORTS_PING = False
def __init__(
self,
hostname: str,
username: str,
password: str,
timeout: int = 60,
optional_args: dict[str, Any] | None = None,
) -> None:
self.hostname = hostname
self.username = username
self.password = password
self.timeout = timeout
self.optional_args = optional_args or {}
self.force_no_enable = True
self.use_canonical_interface = False
self.use_tls = bool(self.optional_args.get("use_tls", False))
self.port = int(self.optional_args.get("port") or (443 if self.use_tls else 80))
self.verify = bool(self.optional_args.get("verify", False))
self._session: requests.Session | None = None
self._sessionkey: str | None = None
self._crypto: ZyxelCrypto | None = None
self._base_url: str = f"{'https' if self.use_tls else 'http'}://{self.hostname}:{self.port}"
def _url(self, path: str) -> str:
return urljoin(f"{self._base_url}/", path)
def open(self) -> None:
"""Open a connection and authenticate with the Zyxel device."""
self._session = requests.Session()
self._session.verify = self.verify
self._session.trust_env = False
info = self._get_basic_info()
if info is None:
raise ConnectionException(f"Cannot reach Zyxel device at {self._base_url}")
self._device_info = info
crypto = ZyxelCrypto()
pubkey = self._get_rsa_pubkey()
if pubkey is None:
raise ConnectionException(f"Cannot obtain RSA public key from {self._base_url}")
enc_key = crypto.encrypt_aes_key_with_rsa(pubkey)
login_data = {
"Input_Account": self.username,
"Input_Passwd": base64.b64encode(self.password.encode("ascii")).decode("ascii"),
"RememberPassword": 0,
# A flag telling the gateway how Input_Passwd is encoded, not a password.
"SHA512_password": False, # nosec B105
}
enc_payload = crypto.encrypt_json(login_data)
enc_payload["key"] = enc_key
try:
resp = self._session.post(
self._url(self._LOGIN_PATH),
json=enc_payload,
timeout=self.timeout,
)
resp.raise_for_status()
result = crypto.decrypt_response(resp.json())
except (requests.RequestException, json.JSONDecodeError, TypeError, KeyError) as e:
raise ConnectionException(f"Login failed at {self._base_url}: {e}") from e
if result.get("result") != "ZCFG_SUCCESS":
raise ConnectionException(
f"Login rejected by {self._base_url}: {result.get('result', 'unknown')}"
)
self._sessionkey = result.get("sessionkey")
self._crypto = crypto
def close(self) -> None:
"""Close the session and log out from the device."""
if self._session is not None and self._sessionkey is not None:
try:
self._session.get(
self._url(self._LOGOUT_PATH),
params={"sessionKey": self._sessionkey},
timeout=self.timeout,
)
except requests.RequestException:
pass
self._session = None
self._sessionkey = None
self._crypto = None
self._device_info = None
def is_alive(self) -> dict[str, bool]:
"""Whether this driver's session is open and the gateway still answers on its port.
Without an open session (never opened, or closed) it is not alive, and no
connection is made: NAPALM's ``__del__`` asks this of every collected driver (#19).
"""
if self._session is None or self._sessionkey is None:
return {"is_alive": False}
try:
sock = socket.create_connection((self.hostname, self.port), timeout=5)
sock.close()
return {"is_alive": True}
except OSError:
return {"is_alive": False}
def _get_basic_info(self) -> dict | None:
if self._session is None:
return None
try:
resp = self._session.get(self._url(self._BASIC_INFO_PATH), timeout=self.timeout)
resp.raise_for_status()
return resp.json()
except (requests.RequestException, json.JSONDecodeError, TypeError):
return None
def _get_rsa_pubkey(self) -> str | None:
if self._session is None:
return None
try:
resp = self._session.get(self._url(self._RSA_KEY_PATH), timeout=self.timeout)
resp.raise_for_status()
return resp.json().get("RSAPublicKey")
except (requests.RequestException, json.JSONDecodeError, TypeError):
return None
def _dal_query(self, oid: str, data: dict | None = None) -> dict:
"""The gateway's decrypted answer to DAL *oid*; a failed request raises (#15)."""
if self._session is None or self._sessionkey is None or self._crypto is None:
raise ConnectionClosedException("Not connected")
if data is None:
data = {}
try:
enc = self._crypto.encrypt_json(data)
resp = self._session.put(
self._url(self._DAL_PATH),
params={"oid": oid, "sessionkey": self._sessionkey},
json=enc,
timeout=self.timeout,
)
resp.raise_for_status()
return self._crypto.decrypt_response(resp.json())
except (requests.RequestException, ValueError, TypeError, KeyError) as exc:
raise self._request_failed(f"DAL {oid}", exc) from exc
def _fetch_page(self, path: str) -> str:
"""The text of *path*; a failed request raises (#15)."""
if self._session is None or self._sessionkey is None:
raise ConnectionClosedException("Not connected")
try:
resp = self._session.get(
self._url(path),
params={"sessionKey": self._sessionkey},
timeout=self.timeout,
)
resp.raise_for_status()
return resp.text
except requests.RequestException as exc:
raise self._request_failed(f"GET {path}", exc) from exc
def _request_failed(self, what: str, exc: Exception) -> Exception:
"""``ConnectionException`` when the gateway did not answer or refused the session,
``RuntimeError`` naming *what* for any other failure."""
detail = f"{what} on {self._base_url} failed: {exc}"
if isinstance(exc, ValueError | TypeError | KeyError): # an answer, but not one we read
return RuntimeError(detail)
status = exc.response.status_code if getattr(exc, "response", None) is not None else None
if status is None or status in _SESSION_REFUSED:
return ConnectionException(detail)
return RuntimeError(detail)
def _unseal(self, text: str, what: str) -> Any:
"""*text* as JSON, decrypted when the gateway sealed it as ``{"content", "iv"}``.
A GET of the DAL or the System page answers sealed, like a DAL PUT does (#25).
"""
if self._crypto is None:
raise ConnectionClosedException("Not connected")
try:
answer = json.loads(text)
if isinstance(answer, dict) and {"content", "iv"} <= answer.keys():
answer = self._crypto.decrypt_response(answer)
except (ValueError, TypeError, KeyError) as exc:
raise RuntimeError(f"{what} on {self._base_url}: {exc}") from exc
return answer
def _dal_get(self, oid: str) -> list[dict[str, Any]]:
"""The ``Object`` list of the DAL's answer to a GET of *oid*, decrypted.
Raises when the request fails or the gateway does not answer ``ZCFG_SUCCESS``
with an ``Object`` list. A name the gateway does not know is answered with an
empty ``Object``, like a known one with nothing in it.
"""
what = f"DAL {oid}"
answer = self._unseal(self._fetch_page(f"{self._DAL_PATH}?oid={oid}"), what)
result = answer.get("result") if isinstance(answer, dict) else None
objects = answer.get("Object") if result == "ZCFG_SUCCESS" else None
if not isinstance(objects, list):
raise RuntimeError(f"{what} on {self._base_url} answered {result!r}")
return [obj for obj in objects if isinstance(obj, dict)]
def _read_dal_or_page(
self,
oid: str,
page: str,
parse_dal: Callable[[list[dict[str, Any]]], _T],
parse_page: Callable[[str], _T],
) -> _T:
"""The DAL's answer to *oid*, else the HTML *page*; raises when neither can be read."""
try:
return parse_dal(self._dal_get(oid))
except (ConnectionException, RuntimeError, ValueError, TypeError) as exc:
logger.debug("DAL %s not read (%s), reading %s", oid, exc, page)
return parse_page(self._fetch_page(page))
def get_facts(self) -> dict[str, Any]:
"""Return device facts such as model, serial, OS version, and uptime.
``getBasicInformation`` carries model and firmware only. The host name and
domain are the ones on the gateway's System page; serial number and uptime
are the status page's ``DeviceInfo``, read with the interfaces (#27).
"""
info = self._device_info or {}
page = self._status_page()
device = page.get("DeviceInfo") or {}
hostname, domain = self._system_name()
return {
"vendor": self.VENDOR,
"model": info.get("ModelName", ""),
"serial_number": str(device.get("SerialNumber") or ""),
"os_version": info.get("SoftwareVersion", ""),
"hostname": hostname,
"fqdn": f"{hostname}.{domain}" if hostname and domain else hostname,
"uptime": int(device.get("UpTime") or 0),
"interface_list": list(_interfaces(page)),
}
def _system_name(self) -> tuple[str, str]:
"""The gateway's host name and domain, as its System page reads them
(``GET /cgi-bin/System?oid=snmp``); raises when they cannot be read.
The answer is a one-entry list, sealed ``{"content", "iv"}`` like a DAL answer.
"""
answer = self._unseal(self._fetch_page(self._SYSTEM_PATH), self._SYSTEM_PATH)
if not isinstance(answer, list) or not answer or not isinstance(answer[0], dict):
raise RuntimeError(f"{self._SYSTEM_PATH} on {self._base_url} answered {answer!r}")
hostname, domain = (
str(answer[0].get(key) or "").strip() for key in ("HostName", "DomainName")
)
return hostname, domain
def _status_page(self) -> dict[str, Any]:
"""The DAL's ``cardpage_status``, decrypted; raises when it cannot be read."""
objects = self._dal_get(self._STATUS_OID)
if not objects:
raise RuntimeError(f"DAL {self._STATUS_OID} on {self._base_url} answered no object")
return objects[0]
def get_interfaces(self) -> dict[str, dict[str, Any]]:
"""The gateway's IP interfaces (``WanLanInfo``) and Ethernet ports (``LanInfo``).
Keyed by the gateway's own interface name (``br0``, ``ptm0.2``, ``eth1``). A
speed or MTU the gateway does not report is 0: unknown.
"""
return _interfaces(self._status_page())
def get_interfaces_ip(self) -> dict[str, dict[str, Any]]:
"""The IPv4 addresses of the gateway's IP interfaces, with their netmask.
IPv6 addresses are not read yet: no gateway seen so far had IPv6 on.
"""
result: dict[str, dict[str, Any]] = {}
for entry in self._status_page().get("WanLanInfo") or []:
ipv4 = _ipv4_addresses(entry)
if entry.get("X_ZYXEL_IfName") and ipv4:
result[entry["X_ZYXEL_IfName"]] = {"ipv4": ipv4, "ipv6": {}}
return result
def get_arp_table(self, vrf: str = "") -> list[dict[str, Any]]:
"""Return the ARP table derived from DHCP host entries.
The host list does not say when the gateway last saw a host, so ``age``
is ``-1.0`` (unknown, napalm-device-types' ``ARP_AGE_UNKNOWN``).
"""
arp: list[dict[str, Any]] = []
for host in self.get_hosts():
if not host["is_active"] or not host["mac"] or not host["ip"]:
continue
arp.append(
{
"interface": host["interface_type"],
"mac": host["mac"],
"ip": host["ip"],
"age": -1.0,
}
)
return arp
def get_lldp_neighbors(self) -> dict[str, Any]:
"""Not supported on Zyxel VMG."""
return {}
def get_lldp_neighbors_detail(self, interface: str = "") -> dict[str, Any]:
"""Not supported on Zyxel VMG."""
return {}
def get_environment(self) -> dict[str, Any]:
"""Not supported on Zyxel VMG."""
return {}
def get_optics(self) -> dict[str, Any]:
"""Not supported on Zyxel VMG."""
return {}
def get_ntp_peers(self) -> dict[str, str | None]:
"""Not supported on Zyxel VMG."""
return {}
def get_ntp_servers(self) -> dict[str, str | None]:
"""Not supported on Zyxel VMG."""
return {}
def get_ntp_stats(self) -> list[dict[str, Any]]:
"""Not supported on Zyxel VMG."""
return []
def ping(
self,
destination: str,
source: str = "",
ttl: int = 255,
timeout: int = 2,
size: int = 100,
count: int = 5,
vrf: str = "",
source_interface: str = "",
) -> dict[str, Any]:
"""Not supported: the DAL does not report whether a target answered.
Returns NAPALM's ``error`` reply without contacting the gateway; see
:attr:`SUPPORTS_PING`.
"""
return {"error": _PING_UNSUPPORTED}
def traceroute(
self,
destination: str,
source: str = "",
ttl: int = 255,
timeout: int = 2,
vrf: str = "",
) -> dict[str, Any]:
"""Not supported on Zyxel VMG."""
return {"success": {}, "error": "Not supported on Zyxel VMG"}
def get_route_to(
self,
destination: str = "",
protocol: str = "",
longer: bool = False,
) -> dict[str, Any]:
"""Not supported on Zyxel VMG."""
return {}
def get_snmp_information(self) -> dict[str, Any]:
"""Not supported on Zyxel VMG."""
return {}
def get_users(self) -> dict[str, Any]:
"""Not supported on Zyxel VMG."""
return {}
def get_network_instances(self, name: str = "") -> dict[str, Any]:
"""Not supported on Zyxel VMG."""
return {}
def get_bgp_config(self, group: str = "", neighbor: str = "") -> dict[str, Any]:
"""Not supported on Zyxel VMG."""
return {}
def get_bgp_neighbors(self) -> dict[str, Any]:
"""Not supported on Zyxel VMG."""
return {}
def get_bgp_neighbors_detail(self, neighbor_address: str = "") -> dict[str, Any]:
"""Not supported on Zyxel VMG."""
return {}
def get_probes_config(self) -> dict[str, Any]:
"""Not supported on Zyxel VMG."""
return {}
def get_probes_results(self) -> dict[str, Any]:
"""Not supported on Zyxel VMG."""
return {}
def get_mac_address_table(self) -> list[dict[str, Any]]:
"""Not supported on Zyxel VMG."""
return []
def get_firewall_policies(self) -> dict[str, Any]:
"""Not supported on Zyxel VMG."""
return {}
def cli(self, commands: list[str], encoding: str = "text") -> dict[str, Any]:
"""Not supported on Zyxel VMG."""
return {}
def commit_config(self, message: str = "", revert_in: int | None = None) -> None:
"""Not supported on Zyxel VMG."""
pass
def discard_config(self) -> None:
"""Not supported on Zyxel VMG."""
pass
#: No config replace: switched off rather than a stub that raises, so asking
#: whether the driver has one says no (NetOrk/netork#2503).
load_replace_candidate = None # type: ignore[assignment]
def load_merge_candidate(self, filename: str | None = None, config: str | None = None) -> None:
"""Not supported on Zyxel VMG."""
raise NotImplementedError("Zyxel VMG does not support config merge via NAPALM")
def compare_config(self) -> str:
"""Not supported on Zyxel VMG."""
return ""
def rollback(self) -> None:
"""Not supported on Zyxel VMG."""
pass
def get_wan_status(self) -> WANStatusDict:
"""The uplink as the gateway's status page (``cardpage_status``) reports it (#29).
A bridge is connected when its DSL line is in sync and has no external address;
a router is connected when its WAN interface is up with an address. Byte
counters are not read: 0.
"""
return parsers.wan_status(self._status_page())
def get_port_forwards(self) -> list[PortForwardDict]:
"""The gateway's port forwards (DAL ``nat``), else the status page's."""
return self._read_dal_or_page(
self._NAT_OID, "Status.htm", parsers.port_forwards, self._parse_port_forwards_html
)
_PORT_FORWARD_RE = re.compile(
r"(?P<name>[^|]+?)\s*\|\s*(?P<proto>TCP|UDP|BOTH)\s*\|\s*"
r"(?P<ext_port>\d+)\s*\|\s*(?P<int_ip>[0-9.]+)\s*\|\s*"
r"(?P<int_port>\d+)",
re.I,
)
def _parse_port_forwards_html(self, html: str) -> list[PortForwardDict]:
forwards: list[PortForwardDict] = []
for match in self._PORT_FORWARD_RE.finditer(html):
forwards.append(
{
"name": match.group("name").strip(),
"protocol": match.group("proto").upper(),
"external_port": int(match.group("ext_port")),
"internal_ip": match.group("int_ip"),
"internal_port": int(match.group("int_port")),
"enabled": True,
}
)
return forwards
def get_hosts(self) -> list[HostDict]:
"""The hosts the gateway knows on its LAN (DAL ``lanhosts``), else the DHCP page's.
A host the gateway has no name for (``"Unknown"``) has ``hostname`` ``""``; only a
host that got its address by DHCP has ``lease_time_remaining``.
"""
return self._read_dal_or_page(
self._HOSTS_OID, "dhcp.htm", parsers.hosts, self._parse_hosts_html
)
_HOST_RE = re.compile(
r"(?P<ip>[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)"
r"\s+"
r"(?P<mac>[0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2}){5})"
r"\s+"
r"(?P<hostname>\S+)?",
)
def _parse_hosts_html(self, html: str) -> list[HostDict]:
hosts: list[HostDict] = []
for match in self._HOST_RE.finditer(html):
hosts.append(
{
"mac": match.group("mac").lower(),
"ip": match.group("ip"),
"hostname": match.group("hostname") or "",
"interface_type": "lan",
"is_active": True,
}
)
return hosts
def get_nat_translations(self) -> list[NATTranslationDict]:
"""The enabled port forwards as translations to the gateway's WAN address.
Without a WAN address of its own (a bridge, or a WAN that is down) the
translation is to any address, ``0.0.0.0``.
"""
forwards = [forward for forward in self.get_port_forwards() if forward["enabled"]]
if not forwards:
return []
wan_ip = parsers.wan_address(self._status_page()) or _ANY_ADDRESS
translations: list[NATTranslationDict] = []
for forward in forwards:
translations.append(
{
"protocol": forward["protocol"].lower(),
"inside_local": f"{forward['internal_ip']}:{forward['internal_port']}",
"inside_global": f"{wan_ip}:{forward['external_port']}",
"outside_local": "0.0.0.0:0",
"outside_global": "0.0.0.0:0",
"age": 0.0,
}
)
return translations
def get_vpn_tunnels(self) -> dict[str, VPNTunnelDict]:
"""Not supported on Zyxel VMG."""
return {}
def get_wireless_clients(self) -> list[WirelessClientDict]:
"""Return connected wireless clients from DAL or HTML fallback."""
return self._read_dal_or_page(
"WIFI_CLIENTS",
"wireless.htm",
self._parse_wireless_clients_dal,
self._parse_wireless_clients_html,
)
def _parse_wireless_clients_dal(
self, entries: list[dict[str, Any]]
) -> list[WirelessClientDict]:
clients: list[WirelessClientDict] = []
for entry in entries:
client: WirelessClientDict = {
"mac": (entry.get("MACAddress", entry.get("mac", "")) or "").lower(),
"ssid": entry.get("SSID", entry.get("ssid", "")),
"radio": entry.get("Radio", entry.get("radio", "")),
"signal": int(entry.get("Signal", entry.get("signal", 0)) or 0),
"noise": int(entry.get("Noise", entry.get("noise", 0)) or 0),
"tx_rate": float(entry.get("TxRate", entry.get("tx_rate", 0)) or 0),
"rx_rate": float(entry.get("RxRate", entry.get("rx_rate", 0)) or 0),
"uptime": int(entry.get("Uptime", entry.get("uptime", 0)) or 0),
}
ip = entry.get("IPAddress", entry.get("ip", ""))
if ip:
client["ip"] = ip
clients.append(client)
return clients
_WIFI_CLIENT_RE = re.compile(
r"(?P<mac>[0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2}){5})"
r"\s+"
r"(?P<ip>[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)"
r"\s+"
r"(?P<rssi>-?\d+)",
)
def _parse_wireless_clients_html(self, html: str) -> list[WirelessClientDict]:
clients: list[WirelessClientDict] = []
for match in self._WIFI_CLIENT_RE.finditer(html):
clients.append(
{
"mac": match.group("mac").lower(),
"ssid": "",
"radio": "wlan0",
"signal": int(match.group("rssi")),
"noise": 0,
"tx_rate": 0.0,
"rx_rate": 0.0,
"uptime": 0,
"ip": match.group("ip"),
}
)
return clients
def get_ssids(self) -> dict[str, SSIDDict]:
"""Return WiFi SSID configurations from DAL or HTML fallback."""
return self._read_dal_or_page(
"WIFI_SSIDS", "wireless.htm", self._parse_ssids_dal, self._parse_ssids_html
)
def _parse_ssids_dal(self, entries: list[dict[str, Any]]) -> dict[str, SSIDDict]:
ssids: dict[str, SSIDDict] = {}
for entry in entries:
ssid_name = (entry.get("SSID", entry.get("ssid", "")) or "").strip()
if not ssid_name:
continue
ssids[ssid_name] = {
"enabled": bool(entry.get("Enabled", entry.get("enabled", True))),
"radio": entry.get("Radio", entry.get("radio", "")),
"bssid": (entry.get("BSSID", entry.get("bssid", "")) or "").lower(),
"encryption": entry.get("Encryption", entry.get("encryption", "")),
"hidden": bool(entry.get("Hidden", entry.get("hidden", False))),
"clients": int(entry.get("Clients", entry.get("clients", 0)) or 0),
}
return ssids
def _parse_ssids_html(self, html: str) -> dict[str, SSIDDict]:
ssids: dict[str, SSIDDict] = {}
pattern = re.compile(r"SSID[^:]*:\s*(\S+)", re.I)
for match in pattern.finditer(html):
name = match.group(1)
if name and name not in ssids:
ssids[name] = {
"enabled": True,
"radio": "wlan0",
"bssid": "",
"encryption": "",
"hidden": False,
"clients": 0,
}
return ssids
def get_radio_status(self) -> dict[str, RadioStatusDict]:
"""Return WiFi radio status from DAL or HTML fallback."""
return self._read_dal_or_page(
"WIFI_RADIO",
"wireless.htm",
self._parse_radio_status_dal,
self._parse_radio_status_html,
)
def _parse_radio_status_dal(self, entries: list[dict[str, Any]]) -> dict[str, RadioStatusDict]:
radios: dict[str, RadioStatusDict] = {}
for entry in entries:
name = entry.get("Name", entry.get("name", ""))
channel = int(entry.get("Channel", entry.get("channel", 0)) or 0)
radios[name] = {
"enabled": bool(entry.get("Enabled", entry.get("enabled", True))),
"band": "2.4GHz" if channel <= 14 else "5GHz",
"channel": channel,
"channel_width": int(entry.get("ChannelWidth", entry.get("channel_width", 0)) or 0),
"tx_power": int(entry.get("TxPower", entry.get("tx_power", 0)) or 0),
"frequency": float(entry.get("Frequency", entry.get("frequency", 0)) or 0),
}
return radios
def _parse_radio_status_html(self, html: str) -> dict[str, RadioStatusDict]:
radios: dict[str, RadioStatusDict] = {}
for band, pat in [("2.4GHz", r"2\.4[Gg]"), ("5GHz", r"5[Gg]")]:
if re.search(pat, html):
radios[band] = {
"enabled": True,
"band": band,
"channel": 0,
"channel_width": 0,
"tx_power": 0,
"frequency": 0.0,
}
return radios
def reboot_host(self) -> None:
"""Restart the gateway (``HostRebootMixin``); raises when it refuses."""
result = self._dal_query("REBOOT", {"Command": "reboot"})
if result.get("result") != "ZCFG_SUCCESS":
raise RuntimeError(f"the gateway refused to reboot: {result}")
def restart_wifi(self, band: str = "both") -> None:
"""Restart the radios of *band* (``2.4G``, ``5G`` or ``both``); raises when refused."""
result = self._dal_query("WIFI_RESTART", {"Band": band})
if result.get("result") != "ZCFG_SUCCESS":
raise RuntimeError(f"the gateway refused to restart Wi-Fi ({band}): {result}")
def get_diagnostics(self) -> dict:
"""What the gateway's diagnostics page reports; empty when it reports nothing."""
return self._dal_query("DIAGNOSTICS", {}) or {}