fix(dal): decrypt the DAL's answer before reading it (#25)
A GET of the DAL answers sealed ({"content", "iv"}), like a PUT does.
_read_dal_or_page parsed the envelope as it came, so hosts, the ARP
table, port forwards and the Wi-Fi getters found nothing on every
gateway, and since nothing raised the HTML fallback never ran either.
Every DAL GET now goes through one helper that decrypts the answer,
checks for ZCFG_SUCCESS and returns its Object list; the status page
and the System page share the decryption. Hosts are read from
lanhosts and port forwards from nat, the names the gateway's web
interface uses: LAN_HOSTS and NAT_PORTMAP are answered like any
unknown name, with an empty Object. The new parsers live in
napalm_zyxel/parsers.py, under strict mypy.
Tests seal recorded, anonymised answers of a VMG4005-B50A
(V5.17(ABQA.3.1)C0) with a real ZyxelCrypto, so the driver decrypts
them. The Wi-Fi DAL names stay unverified: that gateway has no Wi-Fi.
Closes #25
This commit is contained in:
1 parent
e05101f282
commit
a47f9c3970
13 files changed
+675
-180
No files matched your search
@@ -0,0 +1,62 @@
|
||||
"""Pure parsers: the gateway's decrypted DAL answers in, NAPALM's typed dicts out."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types.models import HostDict, PortForwardDict
|
||||
|
||||
#: The name ``lanhosts`` gives a host the gateway has no name for.
|
||||
_UNKNOWN_HOST = "Unknown"
|
||||
|
||||
#: ``Protocol`` of a ``nat`` rule, as the protocols it forwards.
|
||||
_FORWARD_PROTOCOLS = {"TCP": ("TCP",), "UDP": ("UDP",), "ALL": ("TCP", "UDP")}
|
||||
|
||||
|
||||
def _host(entry: dict[str, Any]) -> HostDict:
|
||||
"""One host of the DAL's ``lanhosts`` answer."""
|
||||
name = str(entry.get("HostName") or "")
|
||||
connection = str(entry.get("X_ZYXEL_ConnectionType") or "")
|
||||
host: HostDict = {
|
||||
"mac": str(entry.get("PhysAddress") or "").lower(),
|
||||
"ip": str(entry.get("IPAddress") or ""),
|
||||
"hostname": "" if name == _UNKNOWN_HOST else name,
|
||||
"interface_type": "WLAN" if "Wi-Fi" in connection else "LAN",
|
||||
"is_active": bool(entry.get("Active")),
|
||||
}
|
||||
if entry.get("AddressSource") == "DHCP":
|
||||
host["lease_time_remaining"] = int(entry.get("LeaseTimeRemaining") or 0)
|
||||
return host
|
||||
|
||||
|
||||
def hosts(objects: list[dict[str, Any]]) -> list[HostDict]:
|
||||
"""The hosts of the DAL's ``lanhosts`` answer (``Object[].lanhosts[]``)."""
|
||||
return [
|
||||
_host(entry)
|
||||
for obj in objects
|
||||
for entry in obj.get("lanhosts") or []
|
||||
if isinstance(entry, dict)
|
||||
]
|
||||
|
||||
|
||||
def port_forwards(objects: list[dict[str, Any]]) -> list[PortForwardDict]:
|
||||
"""The rules of the DAL's ``nat`` answer, one per protocol they forward.
|
||||
|
||||
A port range is reported by its first port.
|
||||
"""
|
||||
forwards: list[PortForwardDict] = []
|
||||
for rule in objects:
|
||||
protocol = str(rule.get("Protocol") or "").upper()
|
||||
for proto in _FORWARD_PROTOCOLS.get(protocol, (protocol,)):
|
||||
forward: PortForwardDict = {
|
||||
"name": str(rule.get("Description") or ""),
|
||||
"protocol": proto,
|
||||
"external_port": int(rule.get("ExternalPortStart") or 0),
|
||||
"internal_ip": str(rule.get("InternalClient") or ""),
|
||||
"internal_port": int(rule.get("InternalPortStart") or 0),
|
||||
"enabled": bool(rule.get("Enable")),
|
||||
}
|
||||
if rule.get("SetOriginatingIP") and rule.get("OriginatingIpAddress"):
|
||||
forward["remote_host"] = str(rule["OriginatingIpAddress"])
|
||||
forwards.append(forward)
|
||||
return forwards
|
||||
+62
-101
@@ -36,6 +36,8 @@ from napalm_device_types.models import (
|
||||
WirelessClientDict,
|
||||
)
|
||||
|
||||
from napalm_zyxel import parsers
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: Answers that mean the session is not (or no longer) accepted.
|
||||
@@ -171,6 +173,10 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
_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).
|
||||
@@ -359,12 +365,46 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
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[[Any], _T], parse_page: Callable[[str], _T]
|
||||
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(json.loads(self._fetch_page(f"cgi-bin/DAL?oid={oid}")))
|
||||
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))
|
||||
@@ -397,15 +437,7 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
|
||||
The answer is a one-entry list, sealed ``{"content", "iv"}`` like a DAL answer.
|
||||
"""
|
||||
text = self._fetch_page(self._SYSTEM_PATH)
|
||||
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"{self._SYSTEM_PATH} on {self._base_url}: {exc}") from exc
|
||||
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 = (
|
||||
@@ -414,23 +446,10 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
return hostname, domain
|
||||
|
||||
def _status_page(self) -> dict[str, Any]:
|
||||
"""The DAL's ``cardpage_status``, decrypted; raises when it cannot be read.
|
||||
|
||||
A GET of the DAL answers sealed, ``{"content", "iv"}``, like the PUT does.
|
||||
"""
|
||||
text = self._fetch_page("cgi-bin/DAL?oid=cardpage_status")
|
||||
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"DAL cardpage_status on {self._base_url}: {exc}") from exc
|
||||
result = answer.get("result") if isinstance(answer, dict) else None
|
||||
objects = answer.get("Object") if result == "ZCFG_SUCCESS" else None
|
||||
if not objects or not isinstance(objects[0], dict):
|
||||
raise RuntimeError(f"DAL cardpage_status on {self._base_url} answered {result!r}")
|
||||
"""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]]:
|
||||
@@ -626,35 +645,11 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
}
|
||||
|
||||
def get_port_forwards(self) -> list[PortForwardDict]:
|
||||
"""Return port forwarding rules from DAL or HTML fallback."""
|
||||
"""The gateway's port forwards (DAL ``nat``), else the status page's."""
|
||||
return self._read_dal_or_page(
|
||||
"NAT_PORTMAP",
|
||||
"Status.htm",
|
||||
self._parse_port_forwards_dal,
|
||||
self._parse_port_forwards_html,
|
||||
self._NAT_OID, "Status.htm", parsers.port_forwards, self._parse_port_forwards_html
|
||||
)
|
||||
|
||||
def _parse_port_forwards_dal(self, data: dict) -> list[PortForwardDict]:
|
||||
forwards: list[PortForwardDict] = []
|
||||
rules = data.get("rules", data.get("NATPortMap", data.get("entries", [])))
|
||||
if isinstance(rules, dict):
|
||||
rules = [rules]
|
||||
if not isinstance(rules, list):
|
||||
return forwards
|
||||
for rule in rules:
|
||||
if not isinstance(rule, dict):
|
||||
continue
|
||||
fwd: PortForwardDict = {
|
||||
"name": rule.get("Description", rule.get("name", "")),
|
||||
"protocol": rule.get("Protocol", rule.get("protocol", "TCP")),
|
||||
"external_port": int(rule.get("ExternalPort", rule.get("external_port", 0)) or 0),
|
||||
"internal_ip": rule.get("InternalIP", rule.get("internal_ip", "")),
|
||||
"internal_port": int(rule.get("InternalPort", rule.get("internal_port", 0)) or 0),
|
||||
"enabled": bool(rule.get("Enabled", rule.get("enabled", True))),
|
||||
}
|
||||
forwards.append(fwd)
|
||||
return forwards
|
||||
|
||||
_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*"
|
||||
@@ -678,33 +673,14 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
return forwards
|
||||
|
||||
def get_hosts(self) -> list[HostDict]:
|
||||
"""Return DHCP host entries from DAL or HTML fallback."""
|
||||
return self._read_dal_or_page(
|
||||
"LAN_HOSTS", "dhcp.htm", self._parse_hosts_dal, self._parse_hosts_html
|
||||
)
|
||||
"""The hosts the gateway knows on its LAN (DAL ``lanhosts``), else the DHCP page's.
|
||||
|
||||
def _parse_hosts_dal(self, data: dict) -> list[HostDict]:
|
||||
hosts: list[HostDict] = []
|
||||
entries = data.get("hosts", data.get("LANHosts", data.get("entries", [])))
|
||||
if isinstance(entries, dict):
|
||||
entries = [entries]
|
||||
if not isinstance(entries, list):
|
||||
return hosts
|
||||
for entry in entries:
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
host: HostDict = {
|
||||
"mac": (entry.get("MACAddress", entry.get("mac", "")) or "").lower(),
|
||||
"ip": entry.get("IPAddress", entry.get("ip", "")),
|
||||
"hostname": entry.get("HostName", entry.get("hostname", "")),
|
||||
"interface_type": entry.get("InterfaceType", entry.get("interface_type", "lan")),
|
||||
"is_active": bool(entry.get("Active", entry.get("active", True))),
|
||||
}
|
||||
lease = entry.get("LeaseTime", entry.get("lease_time"))
|
||||
if lease is not None:
|
||||
host["lease_time_remaining"] = int(lease)
|
||||
hosts.append(host)
|
||||
return hosts
|
||||
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]+)"
|
||||
@@ -760,16 +736,11 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
self._parse_wireless_clients_html,
|
||||
)
|
||||
|
||||
def _parse_wireless_clients_dal(self, data: dict) -> list[WirelessClientDict]:
|
||||
def _parse_wireless_clients_dal(
|
||||
self, entries: list[dict[str, Any]]
|
||||
) -> list[WirelessClientDict]:
|
||||
clients: list[WirelessClientDict] = []
|
||||
entries = data.get("clients", data.get("assoc", data.get("entries", [])))
|
||||
if isinstance(entries, dict):
|
||||
entries = [entries]
|
||||
if not isinstance(entries, list):
|
||||
return clients
|
||||
for entry in entries:
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
client: WirelessClientDict = {
|
||||
"mac": (entry.get("MACAddress", entry.get("mac", "")) or "").lower(),
|
||||
"ssid": entry.get("SSID", entry.get("ssid", "")),
|
||||
@@ -818,16 +789,9 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
"WIFI_SSIDS", "wireless.htm", self._parse_ssids_dal, self._parse_ssids_html
|
||||
)
|
||||
|
||||
def _parse_ssids_dal(self, data: dict) -> dict[str, SSIDDict]:
|
||||
def _parse_ssids_dal(self, entries: list[dict[str, Any]]) -> dict[str, SSIDDict]:
|
||||
ssids: dict[str, SSIDDict] = {}
|
||||
entries = data.get("ssids", data.get("entries", []))
|
||||
if isinstance(entries, dict):
|
||||
entries = [entries]
|
||||
if not isinstance(entries, list):
|
||||
return ssids
|
||||
for entry in entries:
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
ssid_name = (entry.get("SSID", entry.get("ssid", "")) or "").strip()
|
||||
if not ssid_name:
|
||||
continue
|
||||
@@ -866,12 +830,9 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
self._parse_radio_status_html,
|
||||
)
|
||||
|
||||
def _parse_radio_status_dal(self, data: dict) -> dict[str, RadioStatusDict]:
|
||||
def _parse_radio_status_dal(self, entries: list[dict[str, Any]]) -> dict[str, RadioStatusDict]:
|
||||
radios: dict[str, RadioStatusDict] = {}
|
||||
entries = data.get("radios", data.get("entries", []))
|
||||
if isinstance(entries, dict):
|
||||
entries = [entries]
|
||||
for entry in entries if isinstance(entries, list) else []:
|
||||
for entry in entries:
|
||||
name = entry.get("Name", entry.get("name", ""))
|
||||
channel = int(entry.get("Channel", entry.get("channel", 0)) or 0)
|
||||
radios[name] = {
|
||||
|
||||
Reference in new issue
Block a user