fix(interfaces): read interfaces and addresses from the gateway's status page #23

Merged
christianmanivong merged 2 commits from fix/interfaces-from-cardpage into main 2026-11-12 15:20:08 +00:00
4 changed files with 279 additions and 57 deletions

No files matched your search

+86 -39
View File
@@ -7,6 +7,7 @@ payloads through the Zyxel DAL protocol.
from __future__ import annotations
import base64
import ipaddress
import json
import logging
import os
@@ -45,6 +46,47 @@ _T = TypeVar("_T")
_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 _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."""
@@ -323,52 +365,57 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
"interface_list": iface_list,
}
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}")
return objects[0]
def get_interfaces(self) -> dict[str, dict[str, Any]]:
"""Return WAN, LAN, and WiFi interfaces from device info."""
ifaces: dict[str, dict[str, Any]] = {}
info = self._device_info or {}
wan_ip = info.get("WanIp", "")
mac = info.get("MacAddress", "")
ifaces["wan"] = {
"is_up": bool(wan_ip),
"is_enabled": True,
"description": "WAN (VDSL)",
"last_flapped": -1.0,
"mac_address": mac or "",
"speed": 1000,
"mtu": 1500,
"""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.
"""
page = self._status_page()
ifaces = {
entry["X_ZYXEL_IfName"]: _ip_interface(entry)
for entry in page.get("WanLanInfo") or []
if entry.get("X_ZYXEL_IfName")
}
ifaces["lan"] = {
"is_up": True,
"is_enabled": True,
"description": "LAN (Ethernet)",
"last_flapped": -1.0,
"mac_address": mac or "",
"speed": 1000,
"mtu": 1500,
}
for band in ("2.4GHz", "5GHz"):
key = f"wlan_{band.lower().replace('.', '_').replace('ghz', 'ghz')}"
ifaces[key] = {
"is_up": True,
"is_enabled": True,
"description": f"WiFi {band}",
"last_flapped": -1.0,
"mac_address": "",
"speed": 0,
"mtu": 1500,
ifaces.update(
{
port["Name"]: _ethernet_port(port)
for port in page.get("LanInfo") or []
if port.get("Name")
}
)
return ifaces
def get_interfaces_ip(self) -> dict[str, dict[str, Any]]:
"""Return IP addresses of WAN and LAN interfaces."""
info = self._device_info or {}
wan_ip = info.get("WanIp", "")
lan_ip = info.get("LanIp", self.hostname)
"""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]] = {}
if wan_ip:
result["wan"] = {"ipv4": {wan_ip: {"prefix_length": 24}}, "ipv6": {}}
result["lan"] = {"ipv4": {lan_ip: {"prefix_length": 24}}, "ipv6": {}}
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]]:
-4
View File
@@ -140,10 +140,6 @@ def test_a_gateway_that_lists_no_hosts_has_none():
assert driver.get_hosts() == []
def test_get_facts_lists_the_interfaces():
assert _driver({}).get_facts()["interface_list"] == ["wan", "lan", "wlan_2_4ghz", "wlan_5ghz"]
def test_get_facts_raises_when_the_interfaces_cannot_be_read():
driver = _driver({})
driver.get_interfaces = MagicMock(side_effect=RuntimeError("no interfaces"))
+192
View File
@@ -0,0 +1,192 @@
"""Interfaces and their addresses come from the gateway's own status page.
``get_interfaces`` used to report a fixed set: ``wan``, ``lan`` and two Wi-Fi radios,
all up, at 1000 Mbit/s, with the WAN's MAC on the LAN. ``get_interfaces_ip`` gave
both a /24. A VMG4005-B50A, a VDSL bridge without Wi-Fi whose LAN is a /29, showed
all of that. Both now read the DAL's ``cardpage_status``: the IP interfaces in
``WanLanInfo`` and the Ethernet ports in ``LanInfo``. IPv6 addresses are not read
yet: the gateway this was taken from has IPv6 off and so shows none to learn from.
``CARDPAGE`` is that answer from a VMG4005-B50A (V5.17(ABQA.3.1)C0), cut down to the
fields the driver reads.
"""
from __future__ import annotations
import json
from typing import Any
from unittest.mock import MagicMock
import pytest
import requests
from napalm_zyxel import ZyxelVMGDriver
CARDPAGE: dict[str, Any] = {
"result": "ZCFG_SUCCESS",
"Object": [
{
"WanLanInfo": [
{
"Enable": True,
"X_ZYXEL_Type": "LAN",
"MACAddress": "6c:4f:89:6a:bf:50",
"Status": "Up",
"X_ZYXEL_SrvName": "Default",
"Name": "LAN",
"X_ZYXEL_IfName": "br0",
"IPv4Address": [
{
"Enable": True,
"IPAddress": "192.168.1.1",
"SubnetMask": "255.255.255.248",
"Status": "Enabled",
}
],
"IPv6Address": [],
},
{
# No "Status" at all: the gateway leaves it out for this bridge.
"Enable": True,
"X_ZYXEL_Type": "WAN",
"MACAddress": "",
"X_ZYXEL_SrvName": "Bridge_ATM",
"Name": "WAN",
"X_ZYXEL_IfName": "atm0.1",
"IPv4Address": [],
"IPv6Address": [],
},
{
"Enable": True,
"X_ZYXEL_Type": "WAN",
"MACAddress": "",
"Status": "LowerLayerDown",
"X_ZYXEL_SrvName": "Bridge_PTM",
"Name": "WAN",
"X_ZYXEL_IfName": "ptm0.2",
"IPv4Address": [],
"IPv6Address": [],
},
],
"LanInfo": [
{
"Enable": True,
"Status": "Up",
"Name": "eth1",
"MACAddress": "6c:4f:89:6a:bf:53",
"MaxBitRate": 1000,
"X_ZYXEL_LanPort": "LAN1",
}
],
}
],
}
def _response(status: int, text: str = "") -> requests.Response:
resp = requests.Response()
resp.status_code = status
resp._content = text.encode()
resp.url = "http://192.168.1.1/"
return resp
def _driver(answer: dict[str, Any] | requests.Response) -> ZyxelVMGDriver:
"""A logged-in driver whose gateway answers ``cardpage_status`` with *answer*,
encrypted the way the gateway sends it."""
driver = ZyxelVMGDriver("192.168.1.1", "admin", "password")
# NAPALM's __del__ asks is_alive(), which opens a TCP connection: not in a test.
driver.is_alive = lambda: {"is_alive": False} # type: ignore[method-assign]
sealed = {"content": "SEALED", "iv": "IV"}
reply = answer if isinstance(answer, requests.Response) else _response(200, json.dumps(sealed))
def get(url: str, params: dict[str, Any] | None = None, **_: Any) -> requests.Response:
if url.endswith("cgi-bin/DAL?oid=cardpage_status"):
return reply
return _response(404)
session = MagicMock(spec=requests.Session)
session.get.side_effect = get
driver._session = session
driver._sessionkey = "1"
driver._crypto = MagicMock()
driver._crypto.decrypt_response.side_effect = lambda data: (
answer if data == sealed else pytest.fail(f"decrypted {data!r}")
)
driver._device_info = {"ModelName": "VMG4005-B50A"}
return driver
# --- get_interfaces -------------------------------------------------------------------
def test_reports_the_gateways_interfaces_and_nothing_else():
assert set(_driver(CARDPAGE).get_interfaces()) == {"br0", "atm0.1", "ptm0.2", "eth1"}
def test_an_ip_interface_is_up_only_when_the_gateway_says_so():
ifaces = _driver(CARDPAGE).get_interfaces()
assert ifaces["br0"]["is_up"] is True
assert ifaces["ptm0.2"]["is_up"] is False
assert ifaces["atm0.1"]["is_up"] is False # no status reported
def test_an_ip_interface_carries_its_own_mac_and_name():
br0 = _driver(CARDPAGE).get_interfaces()["br0"]
assert br0["mac_address"] == "6c:4f:89:6a:bf:50"
assert br0["description"] == "LAN"
assert br0["is_enabled"] is True
def test_a_wan_bridge_is_named_after_its_service():
assert _driver(CARDPAGE).get_interfaces()["ptm0.2"]["description"] == "WAN (Bridge_PTM)"
def test_an_ethernet_port_carries_its_speed_mac_and_label():
eth1 = _driver(CARDPAGE).get_interfaces()["eth1"]
assert eth1["speed"] == 1000.0
assert eth1["mac_address"] == "6c:4f:89:6a:bf:53"
assert eth1["description"] == "LAN1"
assert eth1["is_up"] is True
def test_a_speed_or_mtu_the_gateway_does_not_report_is_left_unknown():
br0 = _driver(CARDPAGE).get_interfaces()["br0"]
assert br0["speed"] == 0.0
assert br0["mtu"] == 0
def test_a_gateway_without_wifi_has_no_wifi_interfaces():
assert not [n for n in _driver(CARDPAGE).get_interfaces() if "wlan" in n]
def test_get_facts_lists_the_gateways_interfaces():
names = _driver(CARDPAGE).get_facts()["interface_list"]
assert sorted(names) == ["atm0.1", "br0", "eth1", "ptm0.2"]
# --- get_interfaces_ip ----------------------------------------------------------------
def test_the_lan_address_keeps_the_gateways_netmask():
ips = _driver(CARDPAGE).get_interfaces_ip()
assert ips == {"br0": {"ipv4": {"192.168.1.1": {"prefix_length": 29}}, "ipv6": {}}}
def test_a_disabled_address_is_not_reported():
page = json.loads(json.dumps(CARDPAGE))
page["Object"][0]["WanLanInfo"][0]["IPv4Address"][0]["Enable"] = False
assert _driver(page).get_interfaces_ip() == {}
# --- a status page that cannot be read ------------------------------------------------
def test_a_refused_status_page_raises():
with pytest.raises(RuntimeError, match="cardpage_status"):
_driver({"result": "ZCFG_NO_SUCH_OBJECT", "Object": []}).get_interfaces()
def test_a_failed_request_raises():
with pytest.raises(RuntimeError, match="500"):
_driver(_response(500)).get_interfaces()
+1 -14
View File
@@ -176,6 +176,7 @@ class TestZyxelVMGDriver:
def test_get_facts(self):
self._setup_mocked_http()
self.driver.get_interfaces = lambda: {} # type: ignore[method-assign] # tests/test_interfaces.py
facts = self.driver.get_facts()
assert facts["vendor"] == "Zyxel"
assert facts["model"] == "VMG4005-B50A"
@@ -183,20 +184,6 @@ class TestZyxelVMGDriver:
assert facts["os_version"] == "V5.13(ABKS.1)C0"
assert facts["hostname"] == "ZyxelVMG"
def test_get_interfaces(self):
self._setup_mocked_http()
ifaces = self.driver.get_interfaces()
assert "wan" in ifaces
assert "lan" in ifaces
assert "wlan_2_4ghz" in ifaces
assert "wlan_5ghz" in ifaces
def test_get_interfaces_ip(self):
self._setup_mocked_http()
ips = self.driver.get_interfaces_ip()
assert "85.2.34.56" in ips["wan"]["ipv4"]
assert "192.168.1.1" in ips["lan"]["ipv4"]
def test_get_wan_status(self):
self._setup_mocked_http()
status = self.driver.get_wan_status()