Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
06ece68de6 | ||
|
|
a37802cf88 | ||
|
|
9ff75eb152 | ||
|
|
b6668eddbd | ||
|
|
3213dfaaaa | ||
|
|
a47f9c3970 | ||
|
|
e05101f282 | ||
|
|
a282836bd2 | ||
|
|
23dbfb7650 | ||
|
|
1fda222d56 | ||
|
|
56a832b9d1 | ||
|
|
61a6e4f7ba | ||
|
|
ca67c08736 | ||
|
|
094cfa9c3e | ||
|
|
ec76c1d6e8 | ||
|
|
63f92561eb | ||
|
|
fe7c3fc7f9 | ||
|
|
ca8d02233a | ||
|
|
e5ce4e32b1 | ||
|
|
5f0c7c76b3 | ||
|
|
745946387f | ||
|
|
98f9df188e | ||
|
|
ded19238c0 | ||
|
|
da9e303e45 | ||
|
|
6f9b91ae9b | ||
|
|
f6b3887121 | ||
|
|
fcee6d7ddd | ||
|
|
f7002114ae | ||
|
|
d5362fd382 | ||
|
|
7fbb7034d3 | ||
|
|
48fdda1904 | ||
|
|
d0f2576510 | ||
|
|
0ebd69b739 | ||
|
|
cd2670bf5f |
No files matched your search
@@ -6,6 +6,86 @@ All notable changes to this driver. The format follows
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Changed
|
||||
- `load_replace_candidate` is `None` instead of a method that raises
|
||||
`NotImplementedError`, so a caller that asks whether the driver can replace a
|
||||
configuration gets no. netOrk offered a config restore for these devices that
|
||||
could only fail (NetOrk/netork#2503).
|
||||
- Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver
|
||||
on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6).
|
||||
- The floor on napalm is 5.1: older releases import `pkg_resources`, which a Python
|
||||
3.12 venv no longer has.
|
||||
|
||||
### Fixed
|
||||
- `get_wan_status()` reports the gateway's uplink as the gateway does (#29). It read
|
||||
`WanIp`, `WanAccessType`, `SystemUpTime`, `MaxUpstream` and `MaxDownstream` from
|
||||
`getBasicInformation`, which a VMG4005-B50A does not send them in, and reported
|
||||
every uplink as down, with no address and no sync rate. It now reads the DAL's
|
||||
`cardpage_status`: a bridge is connected when its DSL line is in sync and has no
|
||||
external address of its own; a router is connected when a WAN interface that is
|
||||
not a bridge is up with an address, which is then `external_ip`. `link_status` is
|
||||
`"Up"` while the DSL line is in sync, the sync rates are those of the channels in
|
||||
sync (added up for bonded lines), and `connection_type` is `"DSL"` for a bridge,
|
||||
the WAN's encapsulation (`"PPPoE"`, `"IPoE"`) for a router. Byte counters are not
|
||||
read and stay `0`.
|
||||
- `get_nat_translations()` translates to the gateway's WAN address from the same page,
|
||||
and to `0.0.0.0` when it has none; it reported `":<port>"` (#29).
|
||||
- `get_hosts()`, `get_arp_table()` and `get_port_forwards()` report what the gateway
|
||||
has (#25). They parsed the DAL's answer without decrypting it, found none of their
|
||||
keys in the sealed envelope and reported nothing, on every gateway; the Wi-Fi
|
||||
getters did the same. Every DAL answer is now decrypted and read from its `Object`.
|
||||
Hosts come from `lanhosts` and port forwards from `nat`, the names the gateway's own
|
||||
web interface reads them by: the gateway answers the names the driver used
|
||||
(`LAN_HOSTS`, `NAT_PORTMAP`) like any name it does not know, with nothing. A host
|
||||
the gateway has no name for (`"Unknown"`) has the host name `""`, a host's
|
||||
interface type is `LAN` or `WLAN`, only a DHCP host reports the time left on its
|
||||
lease, a TCP-and-UDP forward is reported once per protocol, and a forward limited
|
||||
to one source address reports it as `remote_host`.
|
||||
- `get_facts()` reports the gateway's serial number and uptime (#27). It read them
|
||||
from `getBasicInformation`, which a VMG4005-B50A does not send them in, and reported
|
||||
`""` and `0`. They now come from `DeviceInfo` in the DAL's `cardpage_status`, the
|
||||
answer the interfaces are read from; `get_facts()` reads that answer once for both.
|
||||
- `get_facts()` reports the gateway's host name and domain (#24): `hostname` is the
|
||||
name on the gateway's System page (`GET /cgi-bin/System?oid=snmp`), `fqdn` that name
|
||||
with its domain (`VMG4005-B50A.home`). Both were read from `getBasicInformation`, which a
|
||||
VMG4005-B50A does not send them in, so they fell back to the address the driver
|
||||
connects to and netOrk kept the device named `192.168.1.1`. A gateway with no name
|
||||
set reports `""`; `get_facts()` raises when the System page cannot be read.
|
||||
- `is_alive()` returns `False` without touching the network when the driver has no
|
||||
open session (never opened, or closed), and with an open session reports whether the
|
||||
gateway still answers on its port (#19). It connected to the gateway in every case,
|
||||
so each garbage-collected driver (NAPALM's `__del__` asks `is_alive()`) connected
|
||||
once more and could stall for up to five seconds.
|
||||
- A failed request to the gateway raises instead of reading as empty data (#15). A
|
||||
timeout, a refused session or an HTTP error made `get_hosts`, `get_arp_table`,
|
||||
`get_port_forwards`, `get_nat_translations`, `get_wireless_clients`, `get_ssids`,
|
||||
`get_radio_status` and `get_diagnostics` report a gateway with nothing configured.
|
||||
They raise `ConnectionException` when the gateway does not answer or refuses the
|
||||
session (HTTP 401/403) and `RuntimeError` naming the request otherwise. A getter
|
||||
whose DAL request fails still reads the HTML page, and raises when that fails too.
|
||||
`get_facts` no longer reports an empty interface list when the interfaces cannot be
|
||||
read, and `reboot_host` / `restart_wifi` raise the same way when the request fails.
|
||||
- `get_arp_table()` reports an unknown age as `-1.0` (napalm-device-types'
|
||||
`ARP_AGE_UNKNOWN`) instead of `0.0`, which means "confirmed just now": the host
|
||||
list says a host is active, not when the gateway last saw it (NetOrk/netork#1327).
|
||||
- The HTTP fingerprint no longer counts `gs1920` and `gs2210` as evidence for this
|
||||
driver: they are Zyxel switches, and discovery offered this gateway driver for
|
||||
them (#4).
|
||||
- Discovery tells a DAL gateway from any other Zyxel device (#13). The Zyxel
|
||||
enterprise OID, a Zyxel OUI and "zyxel" on the web page fit every Zyxel switch,
|
||||
firewall or NAS, and together they were this driver's whole maximum score. Discovery
|
||||
now also fetches `/getRSAPublickKey` on ports 80 and 443 (the key exchange the
|
||||
driver logs in with, answered without a login), and its `"RSAPublicKey"` answer
|
||||
weighs 24. Vendor-wide evidence alone comes to 28 of 52, below "high"; a gateway
|
||||
with SNMP scores 52 of 52, one without SNMP 37 of 52.
|
||||
- Every HTTP request to the gateway carries the driver's `timeout`. It was set on
|
||||
the session, where requests ignores it, so an unresponsive gateway could hang a
|
||||
call indefinitely (#3).
|
||||
- `ping()` no longer reports every target as alive. The DAL only acknowledges a
|
||||
`PINGTEST` request and never says whether the target answered, so `ping()` now
|
||||
returns an error and the driver opts out of ping sweeps (`SUPPORTS_PING = False`):
|
||||
a LAN scan through this gateway marked every address alive (#2).
|
||||
|
||||
## [0.3.0] - 2026-10-23
|
||||
|
||||
The first release on PyPI.
|
||||
|
||||
@@ -35,25 +35,32 @@ with driver("192.0.2.1", "admin", "secret", optional_args={"use_tls": True}) as
|
||||
|
||||
| Getter / action | Source |
|
||||
|---|---|
|
||||
| `get_facts` | basic device information |
|
||||
| `get_facts` | basic device information (model, firmware), the System page (host name, domain), DAL `cardpage_status` (serial number, uptime, interfaces) |
|
||||
| `get_interfaces`, `get_interfaces_ip` | basic device information (WAN, LAN, Wi-Fi) |
|
||||
| `get_arp_table` | derived from the active LAN hosts |
|
||||
| `get_wan_status` | basic device information |
|
||||
| `get_hosts` | DAL `LAN_HOSTS`, else the DHCP page |
|
||||
| `get_port_forwards`, `get_nat_translations` | DAL `NAT_PORTMAP`, else the status page |
|
||||
| `get_wan_status` | DAL `cardpage_status`: the DSL line and the WAN interfaces |
|
||||
| `get_hosts` | DAL `lanhosts`, else the DHCP page |
|
||||
| `get_port_forwards`, `get_nat_translations` | DAL `nat`, else the status page |
|
||||
| `get_wireless_clients`, `get_ssids`, `get_radio_status` | DAL, else the wireless page |
|
||||
| `get_diagnostics` | DAL `DIAGNOSTICS` |
|
||||
| `ping` | DAL `PINGTEST` |
|
||||
| `is_alive` | TCP connect to the web port |
|
||||
| `is_alive` | the session is open and the web port answers; without a session `False`, no connection |
|
||||
| `reboot_host` | DAL `REBOOT` |
|
||||
| `restart_wifi` | DAL `WIFI_RESTART` |
|
||||
|
||||
Every DAL answer is read the way the gateway sends it: AES-encrypted, with its data
|
||||
under `Object`. The Wi-Fi getters read `WIFI_CLIENTS`, `WIFI_SSIDS` and `WIFI_RADIO`,
|
||||
names that have not been checked against a gateway with Wi-Fi yet; a VMG4005-B50A
|
||||
has no Wi-Fi.
|
||||
|
||||
## Not supported
|
||||
|
||||
Configuration changes (`load_merge_candidate` and `load_replace_candidate` raise
|
||||
`NotImplementedError`), `get_config`, LLDP, BGP, NTP, SNMP, users, routes, MAC address
|
||||
Configuration changes (`load_replace_candidate` is `None`, `load_merge_candidate`
|
||||
raises `NotImplementedError`), `get_config`, LLDP, BGP, NTP, SNMP, users, routes, MAC address
|
||||
table, optics, environment, traceroute, VPN tunnels and the CLI.
|
||||
|
||||
`ping` returns an error and `SUPPORTS_PING` is `False`: the DAL accepts a `PINGTEST`
|
||||
request but does not report whether the target answered.
|
||||
|
||||
## Development
|
||||
|
||||
The rules are in [STANDARDS.md](https://git.netork.io/NAPALM/driver-standard/src/branch/main/STANDARDS.md).
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""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, WANStatusDict
|
||||
|
||||
#: 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
|
||||
|
||||
|
||||
def _channels_in_sync(page: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""The DSL channels of a ``cardpage_status`` page that are in sync."""
|
||||
return [
|
||||
channel
|
||||
for channel in page.get("DslChannelInfo") or []
|
||||
if isinstance(channel, dict) and channel.get("Status") == "Up"
|
||||
]
|
||||
|
||||
|
||||
def _routed_wans(page: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""The enabled WAN interfaces of a ``cardpage_status`` page that are not bridges."""
|
||||
return [
|
||||
entry
|
||||
for entry in page.get("WanLanInfo") or []
|
||||
if isinstance(entry, dict)
|
||||
and entry.get("X_ZYXEL_Type") == "WAN"
|
||||
and entry.get("Enable")
|
||||
and entry.get("X_ZYXEL_ConnectionType") != "IP_Bridged"
|
||||
]
|
||||
|
||||
|
||||
def _address(entry: dict[str, Any]) -> str:
|
||||
"""The first enabled IPv4 address of a ``WanLanInfo`` entry, else ``""``."""
|
||||
for addr in entry.get("IPv4Address") or []:
|
||||
if isinstance(addr, dict) and addr.get("Enable") and addr.get("IPAddress"):
|
||||
return str(addr["IPAddress"])
|
||||
return ""
|
||||
|
||||
|
||||
def _connected_wan(page: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""The routed WAN interface that is up with an address, if there is one."""
|
||||
for entry in _routed_wans(page):
|
||||
if entry.get("Status") == "Up" and _address(entry):
|
||||
return entry
|
||||
return None
|
||||
|
||||
|
||||
def wan_address(page: dict[str, Any]) -> str:
|
||||
"""The gateway's own WAN address on a ``cardpage_status`` page; ``""`` for a bridge
|
||||
or a router whose WAN is not up."""
|
||||
wan = _connected_wan(page)
|
||||
return _address(wan) if wan is not None else ""
|
||||
|
||||
|
||||
def _seconds(value: Any) -> int:
|
||||
"""*value* as a number of seconds; ``0`` (unknown) when it is not a number."""
|
||||
text = str(value if value is not None else "").strip()
|
||||
return int(text) if text.isdigit() else 0
|
||||
|
||||
|
||||
def _uplink(page: dict[str, Any], channels: list[dict[str, Any]]) -> tuple[bool, str, int]:
|
||||
"""Whether the uplink is connected, its type and how long it has been up."""
|
||||
routed = _routed_wans(page)
|
||||
if not routed: # a bridge: the DSL line is the uplink
|
||||
uptime = _seconds(channels[0].get("DSLUpTime")) if channels else 0
|
||||
return bool(channels), "DSL", uptime
|
||||
wan = _connected_wan(page)
|
||||
connection_type = str(routed[0].get("Encapsulation") or "")
|
||||
if wan is None:
|
||||
return False, connection_type, 0
|
||||
return True, connection_type, _seconds(wan.get("X_ZYXEL_UpTime"))
|
||||
|
||||
|
||||
def wan_status(page: dict[str, Any]) -> WANStatusDict:
|
||||
"""The uplink of a ``cardpage_status`` page.
|
||||
|
||||
A router (a WAN interface that is not ``IP_Bridged``) is connected when such an
|
||||
interface is up with an address. A bridge has no WAN address of its own: it is
|
||||
connected when its DSL line is in sync. The sync rates (kbit/s) are those of the
|
||||
channels in sync, added up for bonded lines; a channel out of sync keeps the rates
|
||||
of its last sync, which are not reported.
|
||||
"""
|
||||
channels = _channels_in_sync(page)
|
||||
connected, connection_type, uptime = _uplink(page, channels)
|
||||
return {
|
||||
"connection_type": connection_type,
|
||||
"is_connected": connected,
|
||||
"external_ip": wan_address(page),
|
||||
"uptime": uptime,
|
||||
"bytes_sent": 0,
|
||||
"bytes_received": 0,
|
||||
"max_bitrate_up": sum(int(c.get("UpstreamCurrRate") or 0) for c in channels),
|
||||
"max_bitrate_down": sum(int(c.get("DownstreamCurrRate") or 0) for c in channels),
|
||||
"link_status": "Up" if channels else "Down",
|
||||
}
|
||||
+316
-269
@@ -7,11 +7,14 @@ 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 typing import Any
|
||||
from collections.abc import Callable
|
||||
from typing import Any, TypeVar
|
||||
from urllib.parse import urljoin
|
||||
|
||||
import requests
|
||||
@@ -21,7 +24,7 @@ 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, ResidentialGatewayDriver
|
||||
from napalm_device_types import FingerprintRule, PortSpec, ResidentialGatewayDriver
|
||||
from napalm_device_types.models import (
|
||||
HostDict,
|
||||
NATTranslationDict,
|
||||
@@ -33,6 +36,80 @@ 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.
|
||||
_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."""
|
||||
@@ -93,17 +170,33 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
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"]
|
||||
HTTP_FINGERPRINT = [
|
||||
FingerprintRule("zyxel", weight=7.0, mandatory=True),
|
||||
FingerprintRule("gs1920", weight=6.0),
|
||||
FingerprintRule("gs2210", weight=6.0),
|
||||
]
|
||||
|
||||
_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,
|
||||
@@ -137,7 +230,6 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
"""Open a connection and authenticate with the Zyxel device."""
|
||||
self._session = requests.Session()
|
||||
self._session.verify = self.verify
|
||||
self._session.timeout = self.timeout
|
||||
self._session.trust_env = False
|
||||
|
||||
info = self._get_basic_info()
|
||||
@@ -166,6 +258,7 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
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())
|
||||
@@ -187,6 +280,7 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
self._session.get(
|
||||
self._url(self._LOGOUT_PATH),
|
||||
params={"sessionKey": self._sessionkey},
|
||||
timeout=self.timeout,
|
||||
)
|
||||
except requests.RequestException:
|
||||
pass
|
||||
@@ -196,7 +290,13 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
self._device_info = None
|
||||
|
||||
def is_alive(self) -> dict[str, bool]:
|
||||
"""Check if the device is reachable via TCP connection."""
|
||||
"""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()
|
||||
@@ -208,7 +308,7 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
if self._session is None:
|
||||
return None
|
||||
try:
|
||||
resp = self._session.get(self._url(self._BASIC_INFO_PATH))
|
||||
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):
|
||||
@@ -218,13 +318,14 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
if self._session is None:
|
||||
return None
|
||||
try:
|
||||
resp = self._session.get(self._url(self._RSA_KEY_PATH))
|
||||
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 | 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:
|
||||
@@ -235,93 +336,152 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
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 Exception:
|
||||
return None
|
||||
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 | None:
|
||||
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:
|
||||
return None
|
||||
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."""
|
||||
"""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 {}
|
||||
try:
|
||||
iface_list = list(self.get_interfaces().keys())
|
||||
except Exception:
|
||||
iface_list = []
|
||||
page = self._status_page()
|
||||
device = page.get("DeviceInfo") or {}
|
||||
hostname, domain = self._system_name()
|
||||
return {
|
||||
"vendor": self.VENDOR,
|
||||
"model": info.get("ModelName", ""),
|
||||
"serial_number": info.get("SerialNumber", ""),
|
||||
"serial_number": str(device.get("SerialNumber") or ""),
|
||||
"os_version": info.get("SoftwareVersion", ""),
|
||||
"hostname": info.get("HostName", self.hostname),
|
||||
"fqdn": self.hostname,
|
||||
"uptime": int(info.get("SystemUpTime", 0) or 0),
|
||||
"interface_list": iface_list,
|
||||
"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]]:
|
||||
"""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,
|
||||
}
|
||||
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,
|
||||
}
|
||||
return ifaces
|
||||
"""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]]:
|
||||
"""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]]:
|
||||
"""Return the ARP table derived from DHCP host entries."""
|
||||
"""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"]:
|
||||
@@ -331,7 +491,7 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
"interface": host["interface_type"],
|
||||
"mac": host["mac"],
|
||||
"ip": host["ip"],
|
||||
"age": 0.0,
|
||||
"age": -1.0,
|
||||
}
|
||||
)
|
||||
return arp
|
||||
@@ -344,16 +504,6 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
"""Not supported on Zyxel VMG."""
|
||||
return {}
|
||||
|
||||
def get_config(
|
||||
self,
|
||||
retrieve: str = "all",
|
||||
full: bool = False,
|
||||
sanitized: bool = False,
|
||||
format: str = "text",
|
||||
) -> dict[str, Any]:
|
||||
"""Not supported on Zyxel VMG."""
|
||||
return {}
|
||||
|
||||
def get_environment(self) -> dict[str, Any]:
|
||||
"""Not supported on Zyxel VMG."""
|
||||
return {}
|
||||
@@ -385,28 +535,12 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
vrf: str = "",
|
||||
source_interface: str = "",
|
||||
) -> dict[str, Any]:
|
||||
"""Ping a destination via the device's DAL diagnostics."""
|
||||
result = self._dal_query(
|
||||
"PINGTEST",
|
||||
{
|
||||
"ProtocolVersion": "IPv4",
|
||||
"Host": destination,
|
||||
"DiagnosticsState": "Requested",
|
||||
"DNSServer": "",
|
||||
"NumberOfRepetitions": count,
|
||||
"type": 0,
|
||||
},
|
||||
)
|
||||
if result is None:
|
||||
return {"success": {}, "error": "Ping not supported via DAL"}
|
||||
return {
|
||||
"success": {
|
||||
"results": [{"rtt": 0}],
|
||||
"probes_sent": count,
|
||||
"probes_received": count,
|
||||
},
|
||||
"error": "",
|
||||
}
|
||||
"""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,
|
||||
@@ -480,11 +614,9 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
"""Not supported on Zyxel VMG."""
|
||||
pass
|
||||
|
||||
def load_replace_candidate(
|
||||
self, filename: str | None = None, config: str | None = None
|
||||
) -> None:
|
||||
"""Not supported on Zyxel VMG."""
|
||||
raise NotImplementedError("Zyxel VMG does not support config replacement via NAPALM")
|
||||
#: 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."""
|
||||
@@ -499,55 +631,19 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
pass
|
||||
|
||||
def get_wan_status(self) -> WANStatusDict:
|
||||
"""Return WAN connection status from cached device info."""
|
||||
info = self._device_info or {}
|
||||
wan_ip = info.get("WanIp", "")
|
||||
return {
|
||||
"connection_type": info.get("WanAccessType", "VDSL"),
|
||||
"is_connected": bool(wan_ip),
|
||||
"external_ip": wan_ip,
|
||||
"uptime": int(info.get("SystemUpTime", 0) or 0),
|
||||
"bytes_sent": 0,
|
||||
"bytes_received": 0,
|
||||
"max_bitrate_up": int(info.get("MaxUpstream", 0) or 0) // 1000,
|
||||
"max_bitrate_down": int(info.get("MaxDownstream", 0) or 0) // 1000,
|
||||
"link_status": "Up" if wan_ip else "Down",
|
||||
}
|
||||
"""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]:
|
||||
"""Return port forwarding rules from DAL or HTML fallback."""
|
||||
html = self._fetch_page("cgi-bin/DAL?oid=NAT_PORTMAP")
|
||||
if html is not None:
|
||||
try:
|
||||
data = json.loads(html)
|
||||
return self._parse_port_forwards_dal(data)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
html = self._fetch_page("Status.htm")
|
||||
if html is not None:
|
||||
return self._parse_port_forwards_html(html)
|
||||
return []
|
||||
|
||||
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
|
||||
"""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*"
|
||||
@@ -572,41 +668,14 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
return forwards
|
||||
|
||||
def get_hosts(self) -> list[HostDict]:
|
||||
"""Return DHCP host entries from DAL or HTML fallback."""
|
||||
html = self._fetch_page("cgi-bin/DAL?oid=LAN_HOSTS")
|
||||
if html is not None:
|
||||
try:
|
||||
data = json.loads(html)
|
||||
return self._parse_hosts_dal(data)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
html = self._fetch_page("dhcp.htm")
|
||||
if html is not None:
|
||||
return self._parse_hosts_html(html)
|
||||
return []
|
||||
"""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]+)"
|
||||
@@ -631,12 +700,17 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
return hosts
|
||||
|
||||
def get_nat_translations(self) -> list[NATTranslationDict]:
|
||||
"""Return NAT translations derived from enabled port forwards."""
|
||||
wan_ip = (self._device_info or {}).get("WanIp", "")
|
||||
"""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 self.get_port_forwards():
|
||||
if not forward["enabled"]:
|
||||
continue
|
||||
for forward in forwards:
|
||||
translations.append(
|
||||
{
|
||||
"protocol": forward["protocol"].lower(),
|
||||
@@ -655,28 +729,18 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
|
||||
def get_wireless_clients(self) -> list[WirelessClientDict]:
|
||||
"""Return connected wireless clients from DAL or HTML fallback."""
|
||||
html = self._fetch_page("cgi-bin/DAL?oid=WIFI_CLIENTS")
|
||||
if html is not None:
|
||||
try:
|
||||
data = json.loads(html)
|
||||
return self._parse_wireless_clients_dal(data)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
html = self._fetch_page("wireless.htm")
|
||||
if html is not None:
|
||||
return self._parse_wireless_clients_html(html)
|
||||
return []
|
||||
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, 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", "")),
|
||||
@@ -721,28 +785,13 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
|
||||
def get_ssids(self) -> dict[str, SSIDDict]:
|
||||
"""Return WiFi SSID configurations from DAL or HTML fallback."""
|
||||
html = self._fetch_page("cgi-bin/DAL?oid=WIFI_SSIDS")
|
||||
if html is not None:
|
||||
try:
|
||||
data = json.loads(html)
|
||||
return self._parse_ssids_dal(data)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
html = self._fetch_page("wireless.htm")
|
||||
if html is not None:
|
||||
return self._parse_ssids_html(html)
|
||||
return {}
|
||||
return self._read_dal_or_page(
|
||||
"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
|
||||
@@ -774,54 +823,52 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
|
||||
|
||||
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] = {}
|
||||
html = self._fetch_page("cgi-bin/DAL?oid=WIFI_RADIO")
|
||||
if html is not None:
|
||||
try:
|
||||
data = json.loads(html)
|
||||
entries = data.get("radios", data.get("entries", []))
|
||||
if isinstance(entries, dict):
|
||||
entries = [entries]
|
||||
for entry in entries if isinstance(entries, list) else []:
|
||||
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
|
||||
except (json.JSONDecodeError, TypeError, ValueError):
|
||||
pass
|
||||
html = self._fetch_page("wireless.htm")
|
||||
if html is not None:
|
||||
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,
|
||||
}
|
||||
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 is None or result.get("result") != "ZCFG_SUCCESS":
|
||||
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 is None or result.get("result") != "ZCFG_SUCCESS":
|
||||
if result.get("result") != "ZCFG_SUCCESS":
|
||||
raise RuntimeError(f"the gateway refused to restart Wi-Fi ({band}): {result}")
|
||||
|
||||
def get_diagnostics(self) -> dict:
|
||||
|
||||
+4
-6
@@ -8,22 +8,20 @@ version = "0.3.0"
|
||||
description = "NAPALM driver for Zyxel VMG series residential gateways (VMG4005-B50A and similar)."
|
||||
readme = "README.md"
|
||||
license = "Apache-2.0"
|
||||
requires-python = ">=3.10"
|
||||
requires-python = ">=3.12"
|
||||
authors = [
|
||||
{ name = "Christian Manivong" },
|
||||
]
|
||||
classifiers = [
|
||||
"Topic :: Utilities",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
"Operating System :: POSIX :: Linux",
|
||||
"Operating System :: MacOS",
|
||||
]
|
||||
dependencies = [
|
||||
"napalm>=4.0.0",
|
||||
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
|
||||
"napalm-device-types>=4.21.1",
|
||||
"requests>=2.28.0",
|
||||
]
|
||||
@@ -48,7 +46,7 @@ napalm_zyxel = ["py.typed"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py310"
|
||||
target-version = "py312"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "UP", "B"]
|
||||
@@ -58,7 +56,7 @@ select = ["E", "F", "I", "UP", "B"]
|
||||
"tests/**" = ["E501"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.10"
|
||||
python_version = "3.12"
|
||||
strict = true
|
||||
# napalm itself is untyped, so every driver subclasses Any.
|
||||
disallow_subclassing_any = false
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Shared test setup: unit tests never open a socket (#17)."""
|
||||
|
||||
import gc
|
||||
import socket
|
||||
from collections.abc import Iterator
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
_attempts: list[str] = []
|
||||
|
||||
|
||||
def _refuse_create_connection(address: Any, *args: Any, **kwargs: Any) -> socket.socket:
|
||||
_attempts.append(f"create_connection{address!r}")
|
||||
raise OSError("unit tests never open a socket")
|
||||
|
||||
|
||||
def _refuse_connect(self: socket.socket, address: Any) -> None:
|
||||
_attempts.append(f"connect{address!r}")
|
||||
raise OSError("unit tests never open a socket")
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _no_network() -> Iterator[None]:
|
||||
"""Refuse every connection and fail the run if anything tried one.
|
||||
|
||||
A connection attempted from ``__del__`` (NAPALM's ``NetworkDriver.__del__`` calls
|
||||
``is_alive()``, and this driver's ``is_alive()`` connects to the gateway) is
|
||||
swallowed there, so the attempts are recorded and checked once every driver has
|
||||
been collected.
|
||||
"""
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setattr(socket, "create_connection", _refuse_create_connection)
|
||||
mp.setattr(socket.socket, "connect", _refuse_connect)
|
||||
yield
|
||||
gc.collect()
|
||||
assert not _attempts, f"unit tests tried to open a socket: {_attempts}"
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"result": "ZCFG_SUCCESS",
|
||||
"ReplyMsg": "",
|
||||
"ReplyMsgMultiLang": "",
|
||||
"Object": []
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
{
|
||||
"result": "ZCFG_SUCCESS",
|
||||
"ReplyMsg": "DeviceSource",
|
||||
"ReplyMsgMultiLang": "",
|
||||
"Object": [
|
||||
{
|
||||
"WanLanInfo": [
|
||||
{
|
||||
"Enable": true,
|
||||
"IpIfacePath": "IP.Interface.1",
|
||||
"wanIdx": 1,
|
||||
"BindToIntfGrp": false,
|
||||
"X_ZYXEL_Type": "LAN",
|
||||
"Encapsulation": "",
|
||||
"MACAddress": "6c:4f:89:00:00:50",
|
||||
"LowerlayerUp": "",
|
||||
"pppConnectionStatus": "",
|
||||
"wanpppIdx": 0,
|
||||
"DHCPtr181Path": "Device.DHCPv4.Server.Pool.1",
|
||||
"Status": "Up",
|
||||
"X_ZYXEL_ConnectionType": "IP_Routed",
|
||||
"X_ZYXEL_SrvName": "Default",
|
||||
"Name": "LAN",
|
||||
"Type": "Normal",
|
||||
"IPv4Enable": true,
|
||||
"IPv6Enable": false,
|
||||
"X_ZYXEL_IfName": "br0",
|
||||
"X_ZYXEL_UpTime": 13554113,
|
||||
"IPv6Origin": "DelegateFromWan",
|
||||
"IPv6PrefixDelegateWAN": "Default",
|
||||
"X_ZYXEL_DefaultGatewayIface": false,
|
||||
"X_ZYXEL_IPv6LocalAddress": "fe80::6e4f:89ff:fe00:50",
|
||||
"IPv4Address": [
|
||||
{
|
||||
"Enable": true,
|
||||
"Alias": "",
|
||||
"IPAddress": "192.0.2.1",
|
||||
"SubnetMask": "255.255.255.248",
|
||||
"Status": "Enabled",
|
||||
"AddressingType": "Static",
|
||||
"X_ZYXEL_IfName": "",
|
||||
"X_ZYXEL_Alias": false,
|
||||
"X_ZYXEL_Dhcp4Subnet_Ref": "",
|
||||
"ipIfaceIdx": 1
|
||||
}
|
||||
],
|
||||
"IPv6Address": [],
|
||||
"IPv6Prefix": [],
|
||||
"v4Gateway": "192.0.2.2",
|
||||
"dnsv4Server": [],
|
||||
"dnsv6Server": [],
|
||||
"rtinfoIntf": [],
|
||||
"ipoeConnectionUpTime": 13554213,
|
||||
"BridgingBrPath": "Bridging.Bridge.1",
|
||||
"Group_WAN_IpIface": "",
|
||||
"DHCPStatus": "Disable",
|
||||
"Gateway": "",
|
||||
"LeaseTime": 0,
|
||||
"LeaseTimeRemaining": 0,
|
||||
"DHCPoption42Enable": false,
|
||||
"DHCPoption43Enable": false,
|
||||
"DHCPoption60Enable": false,
|
||||
"DHCPoption42Value": "",
|
||||
"DHCPoption43Value": "",
|
||||
"DHCPoption60Value": ""
|
||||
},
|
||||
{
|
||||
"Enable": true,
|
||||
"IpIfacePath": "IP.Interface.2",
|
||||
"wanIdx": 2,
|
||||
"BindToIntfGrp": false,
|
||||
"X_ZYXEL_Type": "WAN",
|
||||
"Encapsulation": "IPoE",
|
||||
"MACAddress": "",
|
||||
"LowerlayerUp": "",
|
||||
"pppConnectionStatus": "",
|
||||
"wanpppIdx": 0,
|
||||
"DHCPtr181Path": "",
|
||||
"X_ZYXEL_ConnectionType": "IP_Bridged",
|
||||
"X_ZYXEL_SrvName": "Bridge_ATM",
|
||||
"Name": "WAN",
|
||||
"Type": "Normal",
|
||||
"IPv4Enable": false,
|
||||
"IPv6Enable": false,
|
||||
"X_ZYXEL_IfName": "atm0.1",
|
||||
"IPv6Origin": "",
|
||||
"IPv6PrefixDelegateWAN": "Default",
|
||||
"X_ZYXEL_DefaultGatewayIface": false,
|
||||
"X_ZYXEL_IPv6LocalAddress": "",
|
||||
"IPv4Address": [],
|
||||
"IPv6Address": [],
|
||||
"IPv6Prefix": [],
|
||||
"dnsv4Server": [],
|
||||
"dnsv6Server": [],
|
||||
"rtinfoIntf": [],
|
||||
"ipoeConnectionUpTime": 0,
|
||||
"LinkType": "ATM",
|
||||
"DHCPStatus": "Disable",
|
||||
"Gateway": "",
|
||||
"LeaseTime": 0,
|
||||
"LeaseTimeRemaining": 0,
|
||||
"DHCPoption42Enable": false,
|
||||
"DHCPoption43Enable": false,
|
||||
"DHCPoption60Enable": false,
|
||||
"DHCPoption42Value": "",
|
||||
"DHCPoption43Value": "",
|
||||
"DHCPoption60Value": ""
|
||||
},
|
||||
{
|
||||
"Enable": true,
|
||||
"IpIfacePath": "IP.Interface.3",
|
||||
"wanIdx": 3,
|
||||
"BindToIntfGrp": false,
|
||||
"X_ZYXEL_Type": "WAN",
|
||||
"Encapsulation": "IPoE",
|
||||
"MACAddress": "",
|
||||
"LowerlayerUp": "",
|
||||
"pppConnectionStatus": "",
|
||||
"wanpppIdx": 0,
|
||||
"DHCPtr181Path": "",
|
||||
"Status": "LowerLayerDown",
|
||||
"X_ZYXEL_ConnectionType": "IP_Bridged",
|
||||
"X_ZYXEL_SrvName": "Bridge_PTM",
|
||||
"Name": "WAN",
|
||||
"Type": "Normal",
|
||||
"IPv4Enable": false,
|
||||
"IPv6Enable": false,
|
||||
"X_ZYXEL_IfName": "ptm0.2",
|
||||
"X_ZYXEL_UpTime": 0,
|
||||
"IPv6Origin": "",
|
||||
"IPv6PrefixDelegateWAN": "Default",
|
||||
"X_ZYXEL_DefaultGatewayIface": false,
|
||||
"X_ZYXEL_IPv6LocalAddress": "",
|
||||
"IPv4Address": [],
|
||||
"IPv6Address": [],
|
||||
"IPv6Prefix": [],
|
||||
"dnsv4Server": [],
|
||||
"dnsv6Server": [],
|
||||
"rtinfoIntf": [],
|
||||
"ipoeConnectionUpTime": 0,
|
||||
"LinkType": "PTM",
|
||||
"DHCPStatus": "Disable",
|
||||
"Gateway": "",
|
||||
"LeaseTime": 0,
|
||||
"LeaseTimeRemaining": 0,
|
||||
"DHCPoption42Enable": false,
|
||||
"DHCPoption43Enable": false,
|
||||
"DHCPoption60Enable": false,
|
||||
"DHCPoption42Value": "",
|
||||
"DHCPoption43Value": "",
|
||||
"DHCPoption60Value": ""
|
||||
}
|
||||
],
|
||||
"DeviceInfo": {
|
||||
"Manufacturer": "ZYXEL",
|
||||
"ManufacturerOUI": "6C4F89",
|
||||
"FixManufacturerOUI": "",
|
||||
"ModelName": "VMG4005-B50A",
|
||||
"Description": "VDSL2 17a Bonding and 35b Single Line Bridge",
|
||||
"ProductClass": "VMG4005-B50A",
|
||||
"SerialNumber": "S000Y00000001",
|
||||
"HardwareVersion": "VMG4005-B50A",
|
||||
"SoftwareVersion": "V5.17(ABQA.3.1)C0",
|
||||
"AdditionalHardwareVersion": "",
|
||||
"AdditionalSoftwareVersion": "",
|
||||
"ProvisioningCode": "",
|
||||
"X_ZYXEL_ProvisioningCodeIntf": "",
|
||||
"X_ZYXEL_ProvisioningKey": "",
|
||||
"X_ZYXEL_GponSerialNumber": "",
|
||||
"X_ZYXEL_Ploam_Password": "",
|
||||
"UpTime": 13554213,
|
||||
"FirstUseDate": "0001-01-01T00:00:00Z",
|
||||
"VendorConfigFileNumberOfEntries": 0,
|
||||
"SupportedDataModelNumberOfEntries": 0,
|
||||
"ProcessorNumberOfEntries": 0,
|
||||
"VendorLogFileNumberOfEntries": 0,
|
||||
"LocationNumberOfEntries": 0,
|
||||
"BootVersion": "",
|
||||
"WiFiDriverVersion": "",
|
||||
"DSLVersion": ""
|
||||
},
|
||||
"LanPortInfo": {
|
||||
"LanMac": "6c:4f:89:00:00:53",
|
||||
"ethPortExist": false
|
||||
},
|
||||
"Dhcp4SerPoolInfo": {
|
||||
"Enable": false,
|
||||
"X_ZYXEL_SetEnable": false,
|
||||
"X_ZYXEL_AutoReserveLanIp": false,
|
||||
"Status": "Enabled",
|
||||
"Alias": "",
|
||||
"Order": 1,
|
||||
"Interface": "IP.Interface.1",
|
||||
"VendorClassID": "",
|
||||
"VendorClassIDExclude": false,
|
||||
"VendorClassIDMode": "",
|
||||
"ClientID": "",
|
||||
"ClientIDExclude": false,
|
||||
"UserClassID": "",
|
||||
"ChaddrExclude": false,
|
||||
"Chaddr": "",
|
||||
"ChaddrMask": "",
|
||||
"MinAddress": "192.0.2.2",
|
||||
"MaxAddress": "192.0.2.254",
|
||||
"ReservedAddresses": "",
|
||||
"SubnetMask": "255.255.255.0",
|
||||
"DNSServers": "192.0.2.1",
|
||||
"X_ZYXEL_ServerConfigurable": true,
|
||||
"X_ZYXEL_DNS_Type": "DNS Proxy",
|
||||
"DomainName": "",
|
||||
"IPRouters": "",
|
||||
"LeaseTime": 86400,
|
||||
"X_ZYXEL_STB_VENDORID": "",
|
||||
"X_ZYXEL_STB_URL": "",
|
||||
"X_ZYXEL_STB_PrCode": "",
|
||||
"X_ZYXEL_STB_URL_subcode": 1,
|
||||
"X_ZYXEL_STB_PrCode_subcode": 2,
|
||||
"StaticAddressNumberOfEntries": 0,
|
||||
"OptionNumberOfEntries": 0,
|
||||
"ClientNumberOfEntries": 0
|
||||
},
|
||||
"LanInfo": [
|
||||
{
|
||||
"Enable": true,
|
||||
"Status": "Up",
|
||||
"Alias": "",
|
||||
"Name": "eth1",
|
||||
"LastChange": 13554195,
|
||||
"LowerLayers": "",
|
||||
"Upstream": false,
|
||||
"MACAddress": "6c:4f:89:00:00:53",
|
||||
"IntfEnable": true,
|
||||
"IntfStatus": "Up",
|
||||
"MaxBitRate": 1000,
|
||||
"DuplexMode": "Full",
|
||||
"EEECapability": false,
|
||||
"EEEEnable": true,
|
||||
"X_ZYXEL_DuplexMode": "Auto",
|
||||
"X_ZYXEL_MaxBitRate": -1,
|
||||
"X_ZYXEL_LanPort": "LAN1",
|
||||
"X_ZYXEL_SFP": false,
|
||||
"X_ZYXEL_SwitchToWAN": false,
|
||||
"X_ZYXEL_Upstream": false,
|
||||
"X_ZYXEL_UpTime": 13554195,
|
||||
"X_ZYXEL_LastChangeTime": 18
|
||||
}
|
||||
],
|
||||
"DslChannelInfo": [
|
||||
{
|
||||
"Enable": true,
|
||||
"Status": "Down",
|
||||
"Alias": "",
|
||||
"Name": "",
|
||||
"LastChange": 0,
|
||||
"LowerLayers": "DSL.Line.1",
|
||||
"LinkEncapsulationSupported": "G.992.3_Annex_K_ATM",
|
||||
"LinkEncapsulationUsed": "G.992.3_Annex_K_ATM",
|
||||
"LPATH": 0,
|
||||
"INTLVDEPTH": 0,
|
||||
"INTLVBLOCK": 0,
|
||||
"ActualInterleavingDelay": 0,
|
||||
"ACTINP": 0,
|
||||
"INPREPORT": false,
|
||||
"NFEC": 0,
|
||||
"RFEC": 0,
|
||||
"LSYMB": 0,
|
||||
"UpstreamCurrRate": 0,
|
||||
"DownstreamCurrRate": 0,
|
||||
"DSLUpTime": "",
|
||||
"X_ZYXEL_BondingLineNumber": 0
|
||||
},
|
||||
{
|
||||
"Enable": true,
|
||||
"Status": "LowerLayerDown",
|
||||
"Alias": "",
|
||||
"Name": "",
|
||||
"LastChange": 0,
|
||||
"LowerLayers": "DSL.Line.1",
|
||||
"LinkEncapsulationSupported": "G.992.3_Annex_K_PTM",
|
||||
"LinkEncapsulationUsed": "G.992.3_Annex_K_PTM",
|
||||
"LPATH": 0,
|
||||
"INTLVDEPTH": 0,
|
||||
"INTLVBLOCK": 0,
|
||||
"ActualInterleavingDelay": 0,
|
||||
"ACTINP": 0,
|
||||
"INPREPORT": false,
|
||||
"NFEC": 0,
|
||||
"RFEC": 0,
|
||||
"LSYMB": 0,
|
||||
"UpstreamCurrRate": 0,
|
||||
"DownstreamCurrRate": 0,
|
||||
"DSLUpTime": "",
|
||||
"X_ZYXEL_BondingLineNumber": 0
|
||||
},
|
||||
{
|
||||
"Enable": true,
|
||||
"Status": "Down",
|
||||
"Alias": "",
|
||||
"Name": "",
|
||||
"LastChange": 0,
|
||||
"LowerLayers": "DSL.Line.2",
|
||||
"LinkEncapsulationSupported": "G.992.3_Annex_K_ATM",
|
||||
"LinkEncapsulationUsed": "G.992.3_Annex_K_ATM",
|
||||
"LPATH": 0,
|
||||
"INTLVDEPTH": 0,
|
||||
"INTLVBLOCK": 0,
|
||||
"ActualInterleavingDelay": 0,
|
||||
"ACTINP": 0,
|
||||
"INPREPORT": false,
|
||||
"NFEC": 0,
|
||||
"RFEC": 0,
|
||||
"LSYMB": 0,
|
||||
"UpstreamCurrRate": 0,
|
||||
"DownstreamCurrRate": 0,
|
||||
"DSLUpTime": "",
|
||||
"X_ZYXEL_BondingLineNumber": 1
|
||||
},
|
||||
{
|
||||
"Enable": true,
|
||||
"Status": "LowerLayerDown",
|
||||
"Alias": "",
|
||||
"Name": "",
|
||||
"LastChange": 0,
|
||||
"LowerLayers": "DSL.Line.2",
|
||||
"LinkEncapsulationSupported": "G.992.3_Annex_K_PTM",
|
||||
"LinkEncapsulationUsed": "G.992.3_Annex_K_PTM",
|
||||
"LPATH": 0,
|
||||
"INTLVDEPTH": 0,
|
||||
"INTLVBLOCK": 0,
|
||||
"ActualInterleavingDelay": 0,
|
||||
"ACTINP": 0,
|
||||
"INPREPORT": false,
|
||||
"NFEC": 0,
|
||||
"RFEC": 0,
|
||||
"LSYMB": 0,
|
||||
"UpstreamCurrRate": 45875,
|
||||
"DownstreamCurrRate": 274098,
|
||||
"DSLUpTime": "",
|
||||
"X_ZYXEL_BondingLineNumber": 1
|
||||
}
|
||||
],
|
||||
"OptIntfInfo": [],
|
||||
"GponStatsInfo": {
|
||||
"RxPowerSignal": "0",
|
||||
"TxPowerSignal": "0",
|
||||
"Temperature": "0",
|
||||
"SFP_Vendor": "",
|
||||
"SFP_Model": "",
|
||||
"SFP_Serial": "",
|
||||
"SFP_Presence": false
|
||||
},
|
||||
"WanType": "",
|
||||
"WanRate_RX": "",
|
||||
"WanRate_TX": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"result": "ZCFG_SUCCESS",
|
||||
"ModelName": "VMG4005-B50A",
|
||||
"SoftwareVersion": "V5.17(ABQA.3.1)C0",
|
||||
"CurrentLanguage": "de",
|
||||
"AvailableLanguages": "en,cz,it,nl,pt,ru,tr,fr,de,es",
|
||||
"RememberPassword": 0,
|
||||
"FWUpgradeProgressST": 0
|
||||
}
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
{
|
||||
"result": "ZCFG_SUCCESS",
|
||||
"ReplyMsg": "DeviceSource",
|
||||
"ReplyMsgMultiLang": "",
|
||||
"Object": [
|
||||
{
|
||||
"wanInfo": {
|
||||
"wanStatus": 0,
|
||||
"wanIfaceExist": 1,
|
||||
"wanType": ""
|
||||
},
|
||||
"lanhosts": [
|
||||
{
|
||||
"Alias": "",
|
||||
"PhysAddress": "02:00:00:00:00:02",
|
||||
"IPAddress": "192.0.2.2",
|
||||
"IPAddress6": "",
|
||||
"IPLinkLocalAddress6": "N/A",
|
||||
"AddressSource": "Static",
|
||||
"DHCPClient": "",
|
||||
"LeaseTimeRemaining": 0,
|
||||
"AssociatedDevice": "",
|
||||
"Layer1Interface": "Device.Ethernet.Interface.1",
|
||||
"Layer3Interface": "Device.IP.Interface.1",
|
||||
"VendorClassID": "",
|
||||
"ClientID": "",
|
||||
"UserClassID": "",
|
||||
"HostName": "Unknown",
|
||||
"Active": true,
|
||||
"X_ZYXEL_DeleteLease": false,
|
||||
"X_ZYXEL_ConnectionType": "Ethernet",
|
||||
"X_ZYXEL_ConnectedAP": "",
|
||||
"X_ZYXEL_HostType": "",
|
||||
"X_ZYXEL_CapabilityType": "",
|
||||
"X_ZYXEL_PhyRate": 1000,
|
||||
"X_ZYXEL_WiFiStatus": false,
|
||||
"X_ZYXEL_SignalStrength": 0,
|
||||
"X_ZYXEL_SNR": 0,
|
||||
"X_ZYXEL_RSSI": 0,
|
||||
"X_ZYXEL_SoftwareVersion": "",
|
||||
"X_ZYXEL_LastUpdate": 1769202204,
|
||||
"X_ZYXEL_Address6Source": "",
|
||||
"X_ZYXEL_DHCP6Client": "",
|
||||
"X_ZYXEL_BytesSent": 0,
|
||||
"X_ZYXEL_BytesReceived": 0,
|
||||
"X_ZYXEL_OperatingStandard": "",
|
||||
"X_ZYXEL_LastDataDownlinkRate": 0,
|
||||
"X_ZYXEL_LastDataUplinkRate": 0,
|
||||
"IPv4AddressNumberOfEntries": 0,
|
||||
"IPv6AddressNumberOfEntries": 0,
|
||||
"ClientDuid": "",
|
||||
"ExpireTime": "",
|
||||
"SupportedFrequencyBands": "",
|
||||
"WiFiname": "",
|
||||
"DeviceSource": "HOSTS_HOST",
|
||||
"DeviceIcon": "",
|
||||
"Internet_Blocking_Enable": false,
|
||||
"DeviceName": "Unknown",
|
||||
"curHostName": "",
|
||||
"dhcp4PoolExist": true,
|
||||
"dhcp4PoolIid": [
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"dhcp4StaticAddrExist": false,
|
||||
"dhcp4StaticAddrIid": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"dhcp4StaticAddrEnable": false,
|
||||
"dhcp4StaticAddr": "",
|
||||
"dhcp4StaticAddrNum": 0,
|
||||
"dhcp4StaticAddrUsedByOtherHost": false,
|
||||
"icon": "ipc",
|
||||
"staticIP": ""
|
||||
},
|
||||
{
|
||||
"Alias": "",
|
||||
"PhysAddress": "02:00:00:00:00:03",
|
||||
"IPAddress": "192.0.2.3",
|
||||
"IPAddress6": "",
|
||||
"IPLinkLocalAddress6": "N/A",
|
||||
"AddressSource": "Static",
|
||||
"DHCPClient": "",
|
||||
"LeaseTimeRemaining": 0,
|
||||
"AssociatedDevice": "",
|
||||
"Layer1Interface": "",
|
||||
"Layer3Interface": "Device.IP.Interface.1",
|
||||
"VendorClassID": "",
|
||||
"ClientID": "",
|
||||
"UserClassID": "",
|
||||
"HostName": "Unknown",
|
||||
"Active": true,
|
||||
"X_ZYXEL_DeleteLease": false,
|
||||
"X_ZYXEL_ConnectionType": "Ethernet",
|
||||
"X_ZYXEL_ConnectedAP": "",
|
||||
"X_ZYXEL_HostType": "",
|
||||
"X_ZYXEL_CapabilityType": "",
|
||||
"X_ZYXEL_PhyRate": 0,
|
||||
"X_ZYXEL_WiFiStatus": false,
|
||||
"X_ZYXEL_SignalStrength": 0,
|
||||
"X_ZYXEL_SNR": 0,
|
||||
"X_ZYXEL_RSSI": 0,
|
||||
"X_ZYXEL_SoftwareVersion": "",
|
||||
"X_ZYXEL_LastUpdate": 1769202204,
|
||||
"X_ZYXEL_Address6Source": "",
|
||||
"X_ZYXEL_DHCP6Client": "",
|
||||
"X_ZYXEL_BytesSent": 0,
|
||||
"X_ZYXEL_BytesReceived": 0,
|
||||
"X_ZYXEL_OperatingStandard": "",
|
||||
"X_ZYXEL_LastDataDownlinkRate": 0,
|
||||
"X_ZYXEL_LastDataUplinkRate": 0,
|
||||
"IPv4AddressNumberOfEntries": 0,
|
||||
"IPv6AddressNumberOfEntries": 0,
|
||||
"ClientDuid": "",
|
||||
"ExpireTime": "",
|
||||
"SupportedFrequencyBands": "",
|
||||
"WiFiname": "",
|
||||
"DeviceSource": "HOSTS_HOST",
|
||||
"DeviceIcon": "",
|
||||
"Internet_Blocking_Enable": false,
|
||||
"DeviceName": "Unknown",
|
||||
"curHostName": "",
|
||||
"dhcp4PoolExist": true,
|
||||
"dhcp4PoolIid": [
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"dhcp4StaticAddrExist": false,
|
||||
"dhcp4StaticAddrIid": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"dhcp4StaticAddrEnable": false,
|
||||
"dhcp4StaticAddr": "",
|
||||
"dhcp4StaticAddrNum": 0,
|
||||
"dhcp4StaticAddrUsedByOtherHost": false,
|
||||
"icon": "ipc",
|
||||
"staticIP": ""
|
||||
}
|
||||
],
|
||||
"STBVendorID": {
|
||||
"STBVendorID1": "",
|
||||
"STBVendorID2": "",
|
||||
"STBVendorID3": "",
|
||||
"STBVendorID4": "",
|
||||
"STBVendorID5": ""
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"result": "ZCFG_SUCCESS",
|
||||
"ReplyMsg": "InternalClient",
|
||||
"ReplyMsgMultiLang": "",
|
||||
"Object": []
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
"""A logged-in driver whose gateway answers GETs from recorded fixtures, sealed.
|
||||
|
||||
The fixtures in ``fixtures/`` are a VMG4005-B50A's (firmware V5.17(ABQA.3.1)C0)
|
||||
answers, anonymised: addresses under 192.0.2.0/24, MAC addresses replaced by
|
||||
placeholders, the serial number replaced, the provisioning key and PLOAM password
|
||||
emptied. The gateway seals a DAL answer as ``{"content", "iv"}``; :func:`driver`
|
||||
seals each fixture with a real :class:`ZyxelCrypto` and the driver's own key, so
|
||||
what the driver reads has gone through the decryption.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import requests
|
||||
|
||||
from napalm_zyxel import ZyxelVMGDriver
|
||||
from napalm_zyxel.zyxel_driver import ZyxelCrypto
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
FIRMWARE = "vmg4005-b50a-ABQA.3.1"
|
||||
AES_KEY = bytes(range(32))
|
||||
|
||||
|
||||
def fixture(name: str) -> Any:
|
||||
"""The recorded answer *name* (``cardpage_status``, ``lanhosts``, ...)."""
|
||||
return json.loads((FIXTURES / f"{FIRMWARE}-{name}.json").read_text())
|
||||
|
||||
|
||||
def dal(oid: str) -> str:
|
||||
"""The path a DAL GET of *oid* is sent to."""
|
||||
return f"cgi-bin/DAL?oid={oid}"
|
||||
|
||||
|
||||
def response(status: int, text: str = "") -> requests.Response:
|
||||
resp = requests.Response()
|
||||
resp.status_code = status
|
||||
resp._content = text.encode()
|
||||
resp.url = "http://192.0.2.1/"
|
||||
return resp
|
||||
|
||||
|
||||
def _crypto() -> ZyxelCrypto:
|
||||
crypto = ZyxelCrypto()
|
||||
crypto.aes_key = AES_KEY
|
||||
return crypto
|
||||
|
||||
|
||||
def sealed(answer: Any) -> requests.Response:
|
||||
"""*answer* the way the gateway sends it: AES-encrypted, ``{"content", "iv"}``."""
|
||||
envelope = _crypto().encrypt_json(answer)
|
||||
return response(200, json.dumps({"content": envelope["content"], "iv": envelope["iv"]}))
|
||||
|
||||
|
||||
def driver(answers: dict[str, Any]) -> ZyxelVMGDriver:
|
||||
"""A logged-in driver whose gateway answers a GET of each path in *answers*:
|
||||
a response as it is, anything else sealed. Any other path answers 404."""
|
||||
drv = ZyxelVMGDriver("192.0.2.1", "admin", "password")
|
||||
# NAPALM's __del__ asks is_alive(), which opens a TCP connection: not in a test.
|
||||
drv.is_alive = lambda: {"is_alive": False} # type: ignore[method-assign]
|
||||
|
||||
def get(url: str, params: dict[str, Any] | None = None, **_: Any) -> requests.Response:
|
||||
for path, answer in answers.items():
|
||||
if url.endswith(f"/{path}"):
|
||||
return answer if isinstance(answer, requests.Response) else sealed(answer)
|
||||
return response(404)
|
||||
|
||||
session = MagicMock(spec=requests.Session)
|
||||
session.get.side_effect = get
|
||||
drv._session = session
|
||||
drv._sessionkey = "1"
|
||||
drv._crypto = _crypto()
|
||||
drv._device_info = fixture("getBasicInformation")
|
||||
return drv
|
||||
|
||||
|
||||
def requested(drv: ZyxelVMGDriver) -> list[str]:
|
||||
"""The URLs the driver sent a GET to, in order."""
|
||||
return [call.args[0] for call in drv._session.get.call_args_list] # type: ignore[union-attr]
|
||||
@@ -1,9 +1,6 @@
|
||||
{
|
||||
"coverage_floor": 68.0,
|
||||
"function_complexity": {
|
||||
"napalm_zyxel/zyxel_driver.py::ZyxelVMGDriver._parse_wireless_clients_dal": 12,
|
||||
"napalm_zyxel/zyxel_driver.py::ZyxelVMGDriver.get_radio_status": 14
|
||||
},
|
||||
"function_complexity": {},
|
||||
"function_lines": {},
|
||||
"mypy_relaxed": [
|
||||
"napalm_zyxel.zyxel_driver"
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
"""The driver cannot replace a device's configuration, and says so by not having the method.
|
||||
|
||||
A ``load_replace_candidate`` that only raises 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 (NetOrk/netork#2503). ``None`` is how a driver switches off a method
|
||||
it would otherwise inherit, the convention of napalm-device-types and netOrk's
|
||||
capability checks.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from napalm_zyxel import ZyxelVMGDriver
|
||||
|
||||
|
||||
def test_the_driver_has_no_config_replace():
|
||||
assert ZyxelVMGDriver.load_replace_candidate is None
|
||||
assert not callable(getattr(ZyxelVMGDriver, "load_replace_candidate", None))
|
||||
@@ -0,0 +1,229 @@
|
||||
"""A DAL GET is read the way the gateway sends it: sealed, with its data under ``Object`` (#25).
|
||||
|
||||
``_read_dal_or_page`` parsed the answer to ``GET /cgi-bin/DAL?oid=...`` as it came,
|
||||
but the gateway seals it (``{"content", "iv"}``) like the answer to a PUT. The
|
||||
parsers found none of their keys in the envelope and reported no hosts, ARP
|
||||
entries, port forwards, SSIDs, radios or Wi-Fi clients, and since nothing raised,
|
||||
the HTML fallback never ran either.
|
||||
|
||||
Decrypted, the answer is ``{"result": "ZCFG_SUCCESS", "Object": [...]}``. The host
|
||||
list is the one the gateway's own web interface reads, ``oid=lanhosts``: the
|
||||
driver asked for ``LAN_HOSTS``, a name the gateway does not know and answers, like
|
||||
any unknown name, with an empty ``Object``. Port forwards are ``oid=nat`` (the
|
||||
driver asked for ``NAT_PORTMAP``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
|
||||
from tests.gateway import dal, driver, fixture, requested, response
|
||||
|
||||
LANHOSTS = fixture("lanhosts")
|
||||
|
||||
|
||||
def _with_host(**changes: Any) -> dict[str, Any]:
|
||||
"""The recorded host list, its first host changed by *changes*."""
|
||||
answer = copy.deepcopy(LANHOSTS)
|
||||
answer["Object"][0]["lanhosts"][0].update(changes)
|
||||
return answer
|
||||
|
||||
|
||||
#: A port forward as the gateway's web interface edits it (the rule object its NAT
|
||||
#: page sends to ``oid=nat``). The recorded gateway is a bridge and has none, so the
|
||||
#: values are placeholders; the field names are the gateway's.
|
||||
RULE: dict[str, Any] = {
|
||||
"Index": 1,
|
||||
"Enable": True,
|
||||
"Protocol": "TCP",
|
||||
"Description": "web",
|
||||
"Interface": "IP.Interface.3",
|
||||
"ExternalPortStart": 8443,
|
||||
"ExternalPortEnd": 8443,
|
||||
"InternalPortStart": 443,
|
||||
"InternalPortEnd": 443,
|
||||
"InternalClient": "192.0.2.3",
|
||||
"SetOriginatingIP": False,
|
||||
"OriginatingIpAddress": "",
|
||||
"OriginatingSubnetMask": "255.255.255.255",
|
||||
"WANIP": "",
|
||||
"X_ZYXEL_AutoDetectWanStatus": False,
|
||||
}
|
||||
|
||||
|
||||
def _nat(*rules: dict[str, Any]) -> dict[str, Any]:
|
||||
return {**fixture("nat"), "Object": list(rules)}
|
||||
|
||||
|
||||
# --- the sealed answer ------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_sealed_host_list_is_decrypted_and_read():
|
||||
hosts = driver({dal("lanhosts"): LANHOSTS}).get_hosts()
|
||||
assert [(h["mac"], h["ip"]) for h in hosts] == [
|
||||
("02:00:00:00:00:02", "192.0.2.2"),
|
||||
("02:00:00:00:00:03", "192.0.2.3"),
|
||||
]
|
||||
|
||||
|
||||
def test_the_host_list_is_the_one_the_web_interface_reads():
|
||||
drv = driver({dal("lanhosts"): LANHOSTS})
|
||||
drv.get_hosts()
|
||||
assert requested(drv) == ["http://192.0.2.1:80/cgi-bin/DAL?oid=lanhosts"]
|
||||
|
||||
|
||||
def test_an_unsealed_answer_is_read_as_it_is():
|
||||
hosts = driver({dal("lanhosts"): response(200, json.dumps(LANHOSTS))}).get_hosts()
|
||||
assert len(hosts) == 2
|
||||
|
||||
|
||||
def test_an_answer_the_gateway_refused_falls_back_to_the_page():
|
||||
refused = {"result": "ZCFG_NO_SUCH_OBJECT", "Object": []}
|
||||
page = response(200, "192.0.2.4 02:00:00:00:00:04 tablet")
|
||||
hosts = driver({dal("lanhosts"): refused, "dhcp.htm": page}).get_hosts()
|
||||
assert [h["ip"] for h in hosts] == ["192.0.2.4"]
|
||||
|
||||
|
||||
def test_an_answer_that_cannot_be_decrypted_falls_back_to_the_page():
|
||||
garbled = response(
|
||||
200, json.dumps({"content": "bm90IHNlYWxlZA==", "iv": "AAAAAAAAAAAAAAAAAAAAAA=="})
|
||||
)
|
||||
page = response(200, "192.0.2.4 02:00:00:00:00:04 tablet")
|
||||
hosts = driver({dal("lanhosts"): garbled, "dhcp.htm": page}).get_hosts()
|
||||
assert [h["ip"] for h in hosts] == ["192.0.2.4"]
|
||||
|
||||
|
||||
def test_a_gateway_with_no_hosts_has_none():
|
||||
empty = copy.deepcopy(LANHOSTS)
|
||||
empty["Object"][0]["lanhosts"] = []
|
||||
assert driver({dal("lanhosts"): empty}).get_hosts() == []
|
||||
|
||||
|
||||
# --- the hosts --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_recorded_host_reads_as_it_is_on_the_gateway():
|
||||
host = driver({dal("lanhosts"): LANHOSTS}).get_hosts()[0]
|
||||
assert host == {
|
||||
"mac": "02:00:00:00:00:02",
|
||||
"ip": "192.0.2.2",
|
||||
"hostname": "", # the gateway says "Unknown"
|
||||
"interface_type": "LAN",
|
||||
"is_active": True,
|
||||
}
|
||||
|
||||
|
||||
def test_a_host_name_the_gateway_knows_is_reported():
|
||||
hosts = driver({dal("lanhosts"): _with_host(HostName="printer")}).get_hosts()
|
||||
assert hosts[0]["hostname"] == "printer"
|
||||
|
||||
|
||||
def test_a_wifi_host_is_on_the_wlan():
|
||||
answer = _with_host(X_ZYXEL_ConnectionType="Wi-Fi 2.4GHz")
|
||||
assert driver({dal("lanhosts"): answer}).get_hosts()[0]["interface_type"] == "WLAN"
|
||||
|
||||
|
||||
def test_only_a_dhcp_host_has_a_lease():
|
||||
answer = _with_host(AddressSource="DHCP", LeaseTimeRemaining=3600)
|
||||
hosts = driver({dal("lanhosts"): answer}).get_hosts()
|
||||
assert hosts[0]["lease_time_remaining"] == 3600
|
||||
assert "lease_time_remaining" not in hosts[1] # AddressSource "Static"
|
||||
|
||||
|
||||
def test_an_inactive_host_is_reported_inactive():
|
||||
hosts = driver({dal("lanhosts"): _with_host(Active=False)}).get_hosts()
|
||||
assert hosts[0]["is_active"] is False
|
||||
|
||||
|
||||
def test_the_arp_table_holds_the_active_hosts():
|
||||
drv = driver({dal("lanhosts"): _with_host(Active=False)})
|
||||
assert drv.get_arp_table() == [
|
||||
{"interface": "LAN", "mac": "02:00:00:00:00:03", "ip": "192.0.2.3", "age": -1.0}
|
||||
]
|
||||
|
||||
|
||||
# --- port forwards ----------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_recorded_bridge_has_no_port_forwards():
|
||||
assert driver({dal("nat"): fixture("nat")}).get_port_forwards() == []
|
||||
|
||||
|
||||
def test_a_port_forward_reads_as_the_gateway_lists_it():
|
||||
forwards = driver({dal("nat"): _nat(RULE)}).get_port_forwards()
|
||||
assert forwards == [
|
||||
{
|
||||
"name": "web",
|
||||
"protocol": "TCP",
|
||||
"external_port": 8443,
|
||||
"internal_ip": "192.0.2.3",
|
||||
"internal_port": 443,
|
||||
"enabled": True,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def test_a_forward_for_tcp_and_udp_is_one_per_protocol():
|
||||
forwards = driver({dal("nat"): _nat({**RULE, "Protocol": "ALL"})}).get_port_forwards()
|
||||
assert [f["protocol"] for f in forwards] == ["TCP", "UDP"]
|
||||
|
||||
|
||||
def test_a_disabled_forward_is_reported_disabled():
|
||||
forwards = driver({dal("nat"): _nat({**RULE, "Enable": False})}).get_port_forwards()
|
||||
assert forwards[0]["enabled"] is False
|
||||
|
||||
|
||||
def test_a_forward_limited_to_one_source_names_it():
|
||||
rule = {**RULE, "SetOriginatingIP": True, "OriginatingIpAddress": "198.51.100.7"}
|
||||
forwards = driver({dal("nat"): _nat(rule)}).get_port_forwards()
|
||||
assert forwards[0]["remote_host"] == "198.51.100.7"
|
||||
|
||||
|
||||
def test_port_forwards_are_read_from_the_nat_oid():
|
||||
drv = driver({dal("nat"): fixture("nat")})
|
||||
drv.get_port_forwards()
|
||||
assert requested(drv) == ["http://192.0.2.1:80/cgi-bin/DAL?oid=nat"]
|
||||
|
||||
|
||||
# --- Wi-Fi ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("getter", "oid", "empty"),
|
||||
[
|
||||
("get_wireless_clients", "WIFI_CLIENTS", []),
|
||||
("get_ssids", "WIFI_SSIDS", {}),
|
||||
("get_radio_status", "WIFI_RADIO", {}),
|
||||
],
|
||||
)
|
||||
def test_a_sealed_wifi_answer_is_decrypted(getter, oid, empty):
|
||||
"""The recorded gateway has no Wi-Fi: it answers these with an empty ``Object``."""
|
||||
assert getattr(driver({dal(oid): fixture("LAN_HOSTS")}), getter)() == empty
|
||||
|
||||
|
||||
def test_a_wifi_answer_without_object_falls_back_to_the_page():
|
||||
answer = {"result": "ZCFG_SUCCESS"}
|
||||
drv = driver({dal("WIFI_SSIDS"): answer, "wireless.htm": response(200, "")})
|
||||
drv.get_ssids()
|
||||
assert requested(drv)[-1].endswith("/wireless.htm")
|
||||
|
||||
|
||||
def test_a_wifi_client_under_object_is_read():
|
||||
"""Not recorded: the field names are the parser's, not yet checked against a gateway."""
|
||||
client = {"MACAddress": "02:00:00:00:00:05", "SSID": "guest", "Signal": -61}
|
||||
answer = {"result": "ZCFG_SUCCESS", "Object": [client]}
|
||||
clients = driver({dal("WIFI_CLIENTS"): answer}).get_wireless_clients()
|
||||
assert [(c["mac"], c["signal"]) for c in clients] == [("02:00:00:00:00:05", -61)]
|
||||
|
||||
|
||||
def test_a_failed_request_still_raises():
|
||||
drv = driver({dal("lanhosts"): requests.Response()})
|
||||
drv._session.get.side_effect = requests.ConnectTimeout("timed out") # type: ignore[union-attr]
|
||||
with pytest.raises(ConnectionException, match="timed out"):
|
||||
drv.get_hosts()
|
||||
@@ -0,0 +1,203 @@
|
||||
"""The gateway's host name comes from its System page.
|
||||
|
||||
``get_facts`` read ``HostName`` from ``getBasicInformation``, which a VMG4005-B50A
|
||||
(V5.17(ABQA.3.1)C0) does not send, and fell back to the address the driver connects
|
||||
to: netOrk kept the device named ``192.168.1.1``. The gateway's own Maintenance >
|
||||
System page reads the name with ``GET /cgi-bin/System?oid=snmp``, sealed like a DAL
|
||||
answer; the driver now reads it there too.
|
||||
|
||||
Serial number and uptime are not in ``getBasicInformation`` either; they come from
|
||||
``DeviceInfo`` in the DAL's ``cardpage_status``, the answer the interfaces are read
|
||||
from (#27).
|
||||
|
||||
``BASIC_INFO`` and ``SYSTEM`` are those two answers from that gateway (the SNMP
|
||||
community strings the System answer can carry are left out), ``STATUS`` its
|
||||
``cardpage_status`` cut down to ``DeviceInfo`` and one interface, with the serial
|
||||
number replaced by a placeholder.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from napalm_zyxel import ZyxelVMGDriver
|
||||
from tests import gateway
|
||||
|
||||
BASIC_INFO: dict[str, Any] = {
|
||||
"result": "ZCFG_SUCCESS",
|
||||
"ModelName": "VMG4005-B50A",
|
||||
"SoftwareVersion": "V5.17(ABQA.3.1)C0",
|
||||
"CurrentLanguage": "de",
|
||||
"AvailableLanguages": "en,cz,it,nl,pt,ru,tr,fr,de,es",
|
||||
"RememberPassword": 0,
|
||||
"FWUpgradeProgressST": 0,
|
||||
}
|
||||
|
||||
SYSTEM: list[dict[str, Any]] = [
|
||||
{"HostName": "VMG4005-B50A", "DomainName": "home", "Location": "Taiwan", "Contact": ""}
|
||||
]
|
||||
|
||||
STATUS: dict[str, Any] = {
|
||||
"result": "ZCFG_SUCCESS",
|
||||
"Object": [
|
||||
{
|
||||
"DeviceInfo": {
|
||||
"ModelName": "VMG4005-B50A",
|
||||
"SerialNumber": "S000Y00000001",
|
||||
"SoftwareVersion": "V5.17(ABQA.3.1)C0",
|
||||
"UpTime": 13544274,
|
||||
},
|
||||
"WanLanInfo": [{"X_ZYXEL_IfName": "br0", "Name": "LAN", "Status": "Up"}],
|
||||
"LanInfo": [],
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
SYSTEM_PATH = "cgi-bin/System?oid=snmp"
|
||||
STATUS_PATH = "cgi-bin/DAL?oid=cardpage_status"
|
||||
|
||||
|
||||
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(system: Any = SYSTEM, status: Any = STATUS) -> ZyxelVMGDriver:
|
||||
"""A logged-in driver whose gateway answers the System page with *system* and
|
||||
``cardpage_status`` with *status*, each sealed the way the gateway sends it, or
|
||||
with the answer itself when it is a response."""
|
||||
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]
|
||||
answers = {SYSTEM_PATH: system, STATUS_PATH: status}
|
||||
|
||||
def get(url: str, params: dict[str, Any] | None = None, **_: Any) -> requests.Response:
|
||||
for path, answer in answers.items():
|
||||
if url.endswith(path):
|
||||
if isinstance(answer, requests.Response):
|
||||
return answer
|
||||
return _response(200, json.dumps({"content": path, "iv": "IV"}))
|
||||
return _response(404)
|
||||
|
||||
def decrypt(data: dict[str, Any]) -> Any:
|
||||
if data.get("content") not in answers:
|
||||
pytest.fail(f"decrypted {data!r}")
|
||||
return answers[data["content"]]
|
||||
|
||||
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 = decrypt
|
||||
driver._device_info = BASIC_INFO
|
||||
return driver
|
||||
|
||||
|
||||
def _status_reads(driver: ZyxelVMGDriver) -> int:
|
||||
return sum(
|
||||
call.args[0].endswith(STATUS_PATH)
|
||||
for call in driver._session.get.call_args_list # type: ignore[union-attr]
|
||||
)
|
||||
|
||||
|
||||
def test_the_host_name_is_the_one_on_the_system_page():
|
||||
assert _driver().get_facts()["hostname"] == "VMG4005-B50A"
|
||||
|
||||
|
||||
def test_the_fqdn_joins_the_host_name_and_the_domain():
|
||||
assert _driver().get_facts()["fqdn"] == "VMG4005-B50A.home"
|
||||
|
||||
|
||||
def test_without_a_domain_the_fqdn_is_the_host_name():
|
||||
facts = _driver(system=[{**SYSTEM[0], "DomainName": ""}]).get_facts()
|
||||
assert facts["fqdn"] == "VMG4005-B50A"
|
||||
|
||||
|
||||
def test_a_gateway_without_a_name_reports_none_not_its_address():
|
||||
facts = _driver(system=[{**SYSTEM[0], "HostName": "", "DomainName": ""}]).get_facts()
|
||||
assert (facts["hostname"], facts["fqdn"]) == ("", "")
|
||||
|
||||
|
||||
def test_the_page_is_also_read_unsealed():
|
||||
facts = _driver(system=_response(200, json.dumps(SYSTEM))).get_facts()
|
||||
assert facts["hostname"] == "VMG4005-B50A"
|
||||
|
||||
|
||||
def test_get_facts_raises_when_the_system_page_cannot_be_read():
|
||||
with pytest.raises(RuntimeError, match="System"):
|
||||
_driver(system=_response(500)).get_facts()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("answer", [[], {"result": "ZCFG_SUCCESS"}, ["VMG4005-B50A"]])
|
||||
def test_get_facts_raises_on_a_system_page_it_cannot_read(answer: Any):
|
||||
with pytest.raises(RuntimeError, match="System"):
|
||||
_driver(system=_response(200, json.dumps(answer))).get_facts()
|
||||
|
||||
|
||||
# --- serial number and uptime (#27) ---------------------------------------------------
|
||||
|
||||
|
||||
def test_the_serial_number_is_the_one_on_the_status_page():
|
||||
assert _driver().get_facts()["serial_number"] == "S000Y00000001"
|
||||
|
||||
|
||||
def test_the_uptime_is_the_one_on_the_status_page():
|
||||
assert _driver().get_facts()["uptime"] == 13544274
|
||||
|
||||
|
||||
def test_model_and_firmware_still_come_from_the_basic_information():
|
||||
facts = _driver().get_facts()
|
||||
assert (facts["model"], facts["os_version"]) == ("VMG4005-B50A", "V5.17(ABQA.3.1)C0")
|
||||
|
||||
|
||||
def test_a_status_page_without_device_info_reports_them_unknown():
|
||||
status = {"result": "ZCFG_SUCCESS", "Object": [{"WanLanInfo": [], "LanInfo": []}]}
|
||||
facts = _driver(status=status).get_facts()
|
||||
assert (facts["serial_number"], facts["uptime"]) == ("", 0)
|
||||
|
||||
|
||||
def test_get_facts_reads_the_status_page_once():
|
||||
driver = _driver()
|
||||
facts = driver.get_facts()
|
||||
assert facts["interface_list"] == ["br0"]
|
||||
assert _status_reads(driver) == 1
|
||||
|
||||
|
||||
def test_get_facts_raises_when_the_status_page_cannot_be_read():
|
||||
with pytest.raises(RuntimeError, match="cardpage_status"):
|
||||
_driver(status=_response(500)).get_facts()
|
||||
|
||||
|
||||
# --- the recorded answers (#24) ---------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_facts_of_the_recorded_gateway():
|
||||
"""``getBasicInformation`` gives model and firmware only; nothing else is read from
|
||||
it. The status page is the full recorded one, sealed (``tests/gateway.py``)."""
|
||||
drv = gateway.driver(
|
||||
{gateway.dal("cardpage_status"): gateway.fixture("cardpage_status"), SYSTEM_PATH: SYSTEM}
|
||||
)
|
||||
assert drv._device_info == gateway.fixture("getBasicInformation")
|
||||
assert drv.get_facts() == {
|
||||
"vendor": "Zyxel",
|
||||
"model": "VMG4005-B50A",
|
||||
"serial_number": "S000Y00000001",
|
||||
"os_version": "V5.17(ABQA.3.1)C0",
|
||||
"hostname": "VMG4005-B50A",
|
||||
"fqdn": "VMG4005-B50A.home",
|
||||
"uptime": 13554213,
|
||||
"interface_list": ["br0", "atm0.1", "ptm0.2", "eth1"],
|
||||
}
|
||||
|
||||
|
||||
def test_basic_information_is_the_recorded_answer():
|
||||
assert BASIC_INFO == gateway.fixture("getBasicInformation")
|
||||
@@ -0,0 +1,147 @@
|
||||
"""A failed request to the gateway raises; it is not read as "nothing configured" (#15).
|
||||
|
||||
``_dal_query`` and ``_fetch_page`` returned ``None`` for any failure, and the getters
|
||||
turned that into empty data: a timeout or an expired session read as a gateway with
|
||||
no hosts, port forwards, SSIDs or Wi-Fi clients. Empty data is now the answer of a
|
||||
gateway that answered with none; a getter whose DAL request fails still reads the
|
||||
HTML page, and raises when that fails too.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
|
||||
from napalm_zyxel import ZyxelVMGDriver
|
||||
from tests.gateway import fixture
|
||||
|
||||
HOSTS_DAL = fixture("lanhosts") # tests/gateway.py
|
||||
HOSTS_PAGE = "192.168.1.34 aa:bb:cc:dd:ee:02 tablet"
|
||||
|
||||
|
||||
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(answers: dict[str, requests.Response | Exception]) -> ZyxelVMGDriver:
|
||||
"""A logged-in driver whose session answers each path as told; 404 otherwise."""
|
||||
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]
|
||||
session = MagicMock(spec=requests.Session)
|
||||
|
||||
def answer(url: str, params: dict[str, Any] | None = None, **_: Any) -> requests.Response:
|
||||
path = url.removeprefix("http://192.168.1.1:80/")
|
||||
oid = (params or {}).get("oid")
|
||||
reply = answers.get(f"{path}?oid={oid}" if oid else path, _response(404))
|
||||
if isinstance(reply, Exception):
|
||||
raise reply
|
||||
return reply
|
||||
|
||||
session.get.side_effect = answer
|
||||
session.put.side_effect = answer
|
||||
driver._session = session
|
||||
driver._sessionkey = "1"
|
||||
driver._crypto = MagicMock()
|
||||
driver._crypto.decrypt_response.side_effect = lambda data: data
|
||||
driver._device_info = {"ModelName": "VMG4005-B50A"}
|
||||
return driver
|
||||
|
||||
|
||||
# --- _dal_query --------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_dal_query_returns_the_gateways_answer():
|
||||
driver = _driver({"cgi-bin/DAL?oid=DIAGNOSTICS": _response(200, '{"result": "ZCFG_SUCCESS"}')})
|
||||
assert driver._dal_query("DIAGNOSTICS") == {"result": "ZCFG_SUCCESS"}
|
||||
|
||||
|
||||
def test_dal_query_raises_when_the_gateway_does_not_answer():
|
||||
driver = _driver({"cgi-bin/DAL?oid=DIAGNOSTICS": requests.ConnectTimeout("timed out")})
|
||||
with pytest.raises(ConnectionException, match="timed out"):
|
||||
driver._dal_query("DIAGNOSTICS")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", [401, 403])
|
||||
def test_dal_query_raises_connection_exception_for_a_refused_session(status):
|
||||
driver = _driver({"cgi-bin/DAL?oid=DIAGNOSTICS": _response(status)})
|
||||
with pytest.raises(ConnectionException, match=str(status)):
|
||||
driver._dal_query("DIAGNOSTICS")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reply", [_response(500), _response(200, "<html>busy</html>")])
|
||||
def test_dal_query_names_the_endpoint_of_any_other_failure(reply):
|
||||
driver = _driver({"cgi-bin/DAL?oid=DIAGNOSTICS": reply})
|
||||
with pytest.raises(RuntimeError, match="DIAGNOSTICS"):
|
||||
driver._dal_query("DIAGNOSTICS")
|
||||
|
||||
|
||||
def test_get_diagnostics_raises_when_the_dal_request_fails():
|
||||
driver = _driver({"cgi-bin/DAL?oid=DIAGNOSTICS": _response(500)})
|
||||
with pytest.raises(RuntimeError):
|
||||
driver.get_diagnostics()
|
||||
|
||||
|
||||
def test_a_reboot_that_fails_to_reach_the_gateway_raises():
|
||||
driver = _driver({"cgi-bin/DAL?oid=REBOOT": requests.ConnectionError("refused")})
|
||||
with pytest.raises(ConnectionException):
|
||||
driver.reboot_host()
|
||||
|
||||
|
||||
# --- the getters ---------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("getter", "oid", "page"),
|
||||
[
|
||||
("get_hosts", "lanhosts", "dhcp.htm"),
|
||||
("get_port_forwards", "nat", "Status.htm"),
|
||||
("get_wireless_clients", "WIFI_CLIENTS", "wireless.htm"),
|
||||
("get_ssids", "WIFI_SSIDS", "wireless.htm"),
|
||||
("get_radio_status", "WIFI_RADIO", "wireless.htm"),
|
||||
],
|
||||
)
|
||||
def test_a_getter_raises_when_neither_the_dal_nor_the_page_can_be_read(getter, oid, page):
|
||||
driver = _driver(
|
||||
{f"cgi-bin/DAL?oid={oid}": requests.ReadTimeout("read timed out"), page: _response(500)}
|
||||
)
|
||||
with pytest.raises((ConnectionException, RuntimeError)):
|
||||
getattr(driver, getter)()
|
||||
|
||||
|
||||
def test_get_arp_table_raises_when_the_hosts_cannot_be_read():
|
||||
driver = _driver({"cgi-bin/DAL?oid=lanhosts": _response(500), "dhcp.htm": _response(500)})
|
||||
with pytest.raises(RuntimeError):
|
||||
driver.get_arp_table()
|
||||
|
||||
|
||||
def test_a_failed_dal_request_falls_back_to_the_page():
|
||||
driver = _driver(
|
||||
{"cgi-bin/DAL?oid=lanhosts": _response(500), "dhcp.htm": _response(200, HOSTS_PAGE)}
|
||||
)
|
||||
assert [h["ip"] for h in driver.get_hosts()] == ["192.168.1.34"]
|
||||
|
||||
|
||||
def test_the_dal_answer_is_used_when_there_is_one():
|
||||
driver = _driver({"cgi-bin/DAL?oid=lanhosts": _response(200, json.dumps(HOSTS_DAL))})
|
||||
assert [h["ip"] for h in driver.get_hosts()] == ["192.0.2.2", "192.0.2.3"]
|
||||
|
||||
|
||||
def test_a_gateway_that_lists_no_hosts_has_none():
|
||||
answer = {"result": "ZCFG_SUCCESS", "Object": [{"lanhosts": []}]}
|
||||
driver = _driver({"cgi-bin/DAL?oid=lanhosts": _response(200, json.dumps(answer))})
|
||||
assert driver.get_hosts() == []
|
||||
|
||||
|
||||
def test_get_facts_raises_when_the_interfaces_cannot_be_read():
|
||||
with pytest.raises(RuntimeError, match="cardpage_status"):
|
||||
_driver({}).get_facts()
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Discovery tells a DAL gateway from any other Zyxel device (#13).
|
||||
|
||||
The driver's evidence was all vendor-wide: Zyxel's enterprise OID, Zyxel OUIs and the
|
||||
word "zyxel" on the web page. Every managed Zyxel device (switch, firewall, NAS, access
|
||||
point) has all three, and under discovery's normalisation they made up the driver's
|
||||
whole maximum: 28 of 28, confidence "high".
|
||||
|
||||
What only a gateway this driver can talk to has is the DAL's key exchange: an
|
||||
unauthenticated ``GET /getRSAPublickKey`` that answers ``{"RSAPublicKey": ...}``. The
|
||||
driver cannot log in without it (``ZyxelVMGDriver.open``).
|
||||
|
||||
``_netork_confidence`` mirrors how netOrk scores a driver
|
||||
(``netork/jobs/tasks/discovery_fingerprint.py``: ``_score_driver``,
|
||||
``_max_possible_score``, ``norm = score / max``, "high" from 0.7, "medium" from 0.4).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import rules_max_weight
|
||||
|
||||
from napalm_zyxel import ZyxelVMGDriver
|
||||
|
||||
#: What netOrk adds for a matching sysObjectID prefix and for a matching OUI.
|
||||
OID_WEIGHT = 15.0
|
||||
OUI_WEIGHT = 6.0
|
||||
|
||||
ZYXEL_OID = "1.3.6.1.4.1.890.1.5.8.20"
|
||||
ZYXEL_MAC = "00:13:49:aa:bb:cc"
|
||||
OTHER_MAC = "00:00:5e:00:53:01"
|
||||
|
||||
SWITCH_PAGE = "<title>ZyXEL GS1920-24HP</title> zyxel web configurator"
|
||||
#: The gateway's landing page and its answer to ``GET /getRSAPublickKey``, as the
|
||||
#: probe accumulates them (it fetches every path of a scheme into one body).
|
||||
GATEWAY_PAGE = (
|
||||
"<title>Zyxel VMG4005-B50A</title> zyxel "
|
||||
'{"RSAPublicKey": "-----BEGIN PUBLIC KEY-----\\nMIIBIjANBgkq...\\n-----END PUBLIC KEY-----\\n"}'
|
||||
)
|
||||
|
||||
|
||||
def _netork_score(cls: type[ZyxelVMGDriver], oid: str | None, mac: str | None, page: str) -> float:
|
||||
score = 0.0
|
||||
if mac and mac[:8].upper() in (p.upper() for p in cls.OUI_PREFIXES):
|
||||
score += OUI_WEIGHT
|
||||
if oid:
|
||||
if not oid.startswith(cls.SNMP_OBJECT_ID_PREFIX):
|
||||
return 0.0
|
||||
score += OID_WEIGHT
|
||||
combined = re.sub(r"\s+", " ", page.lower())
|
||||
for rule in cls.HTTP_FINGERPRINT:
|
||||
matched = rule.pattern in combined
|
||||
if rule.mandatory and not matched:
|
||||
return 0.0
|
||||
if matched:
|
||||
score += -rule.weight if rule.negative else rule.weight
|
||||
return score
|
||||
|
||||
|
||||
def _netork_max(cls: type[ZyxelVMGDriver]) -> float:
|
||||
total = sum(spec.weight for spec in cls.PORT_SPECS or [])
|
||||
total += OID_WEIGHT if cls.SNMP_OBJECT_ID_PREFIX else 0.0
|
||||
total += OUI_WEIGHT if cls.OUI_PREFIXES else 0.0
|
||||
rules = (*cls.SNMP_FINGERPRINT, *cls.SSH_FINGERPRINT, *cls.HTTP_FINGERPRINT)
|
||||
return total + rules_max_weight(rules) or 1.0
|
||||
|
||||
|
||||
def _netork_confidence(oid: str | None, mac: str | None, page: str) -> tuple[float, str]:
|
||||
norm = _netork_score(ZyxelVMGDriver, oid, mac, page) / _netork_max(ZyxelVMGDriver)
|
||||
return norm, "high" if norm >= 0.7 else "medium" if norm >= 0.4 else "low"
|
||||
|
||||
|
||||
def test_vendor_wide_evidence_alone_stays_below_high():
|
||||
"""A Zyxel switch: Zyxel OID, Zyxel OUI, "zyxel" on its page."""
|
||||
norm, confidence = _netork_confidence(ZYXEL_OID, ZYXEL_MAC, SWITCH_PAGE)
|
||||
|
||||
assert norm < 0.7
|
||||
assert confidence != "high"
|
||||
|
||||
|
||||
def test_a_gateway_with_snmp_scores_the_maximum():
|
||||
assert _netork_confidence(ZYXEL_OID, ZYXEL_MAC, GATEWAY_PAGE) == (1.0, "high")
|
||||
|
||||
|
||||
def test_a_gateway_without_snmp_is_still_high():
|
||||
"""Residential gateways often answer no SNMP; the DAL answer carries them."""
|
||||
assert _netork_confidence(None, ZYXEL_MAC, GATEWAY_PAGE)[1] == "high"
|
||||
|
||||
|
||||
def test_the_dal_answer_outweighs_snmp_and_oui_together():
|
||||
"""A gateway behind a router (no OUI) without SNMP beats a switch with both."""
|
||||
gateway, _ = _netork_confidence(None, OTHER_MAC, GATEWAY_PAGE)
|
||||
switch, _ = _netork_confidence(ZYXEL_OID, ZYXEL_MAC, SWITCH_PAGE)
|
||||
|
||||
assert gateway > switch
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("scheme", "port"), [("http", 80), ("https", 443)])
|
||||
def test_discovery_fetches_the_dal_key_exchange_without_counting_the_port(scheme, port):
|
||||
specs = [s for s in ZyxelVMGDriver.PORT_SPECS or [] if (s.scheme, s.port) == (scheme, port)]
|
||||
|
||||
assert [(s.paths, s.weight, s.mandatory) for s in specs] == [
|
||||
(("/getRSAPublickKey",), 0.0, False)
|
||||
]
|
||||
|
||||
|
||||
def test_the_probed_path_is_the_one_the_driver_logs_in_with():
|
||||
assert ZyxelVMGDriver._RSA_KEY_PATH == "getRSAPublickKey"
|
||||
@@ -0,0 +1,194 @@
|
||||
"""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, with placeholder MAC addresses under Zyxel's OUI.
|
||||
"""
|
||||
|
||||
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:00:00: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:00:00: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:00:00: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:00:00: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():
|
||||
driver = _driver(CARDPAGE)
|
||||
driver._system_name = lambda: ("VMG4005-B50A", "home") # type: ignore[method-assign] # test_facts.py
|
||||
names = driver.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()
|
||||
@@ -0,0 +1,56 @@
|
||||
"""is_alive() reports the driver's own session; without one it asks nobody (#19).
|
||||
|
||||
It opened a TCP connection to the gateway whether or not the driver was opened, and
|
||||
after close() too. NAPALM's ``__del__`` calls it, so every collected driver connected
|
||||
to the gateway once more and could block for up to five seconds.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from napalm_zyxel import ZyxelVMGDriver
|
||||
|
||||
|
||||
def _open_driver() -> ZyxelVMGDriver:
|
||||
driver = ZyxelVMGDriver("192.168.1.1", "admin", "password")
|
||||
driver._session = MagicMock(spec=requests.Session)
|
||||
driver._sessionkey = "1"
|
||||
driver._crypto = MagicMock()
|
||||
return driver
|
||||
|
||||
|
||||
def _closed(driver: ZyxelVMGDriver) -> ZyxelVMGDriver:
|
||||
driver.close()
|
||||
return driver
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"driver",
|
||||
[
|
||||
pytest.param(lambda: ZyxelVMGDriver("192.168.1.1", "admin", "password"), id="never opened"),
|
||||
pytest.param(lambda: _closed(_open_driver()), id="closed"),
|
||||
],
|
||||
)
|
||||
def test_without_a_session_it_is_not_alive_and_opens_no_socket(driver):
|
||||
with patch("socket.create_connection") as connect:
|
||||
assert driver().is_alive() == {"is_alive": False}
|
||||
connect.assert_not_called()
|
||||
|
||||
|
||||
def test_with_an_open_session_it_reports_the_gateway_answering():
|
||||
driver = _open_driver()
|
||||
with patch("socket.create_connection") as connect:
|
||||
assert driver.is_alive() == {"is_alive": True}
|
||||
connect.assert_called_once_with(("192.168.1.1", 80), timeout=5)
|
||||
driver._session = None # nothing left for __del__ to check
|
||||
|
||||
|
||||
def test_with_an_open_session_it_reports_a_gateway_that_stopped_answering():
|
||||
driver = _open_driver()
|
||||
with patch("socket.create_connection", side_effect=OSError("refused")):
|
||||
assert driver.is_alive() == {"is_alive": False}
|
||||
driver._session = None
|
||||
@@ -0,0 +1,192 @@
|
||||
"""The uplink's state is the gateway's own: the DSL line and the WAN interfaces (#29).
|
||||
|
||||
``get_wan_status`` built its answer from ``WanIp``, ``WanAccessType``,
|
||||
``SystemUpTime``, ``MaxUpstream`` and ``MaxDownstream`` in ``getBasicInformation``.
|
||||
A VMG4005-B50A sends none of them there, so every gateway's uplink read as down,
|
||||
with no address and no sync rate, whatever its line did. ``get_nat_translations``
|
||||
built ``inside_global`` from the same ``WanIp`` and reported ``":<port>"``.
|
||||
|
||||
The line state is in the DAL's ``cardpage_status``: ``DslChannelInfo[]`` (a channel
|
||||
whose ``Status`` is ``Up`` is in sync; its rates are in kbit/s) and the
|
||||
``WanLanInfo[]`` entries of ``X_ZYXEL_Type`` ``WAN``. A bridge has no WAN address
|
||||
of its own: there, connected means the DSL line is in sync.
|
||||
|
||||
``STATUS`` is that answer from a VMG4005-B50A bridge whose line was not in sync
|
||||
when it was recorded (``tests/gateway.py``). The other states change it the way
|
||||
TR-181 and the recorded fields describe them: they were not recorded.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.gateway import dal, driver, fixture, requested, response
|
||||
|
||||
STATUS = fixture("cardpage_status")
|
||||
PTM_LINE_2 = 3 # DslChannelInfo: the channel that carries the recorded sync rates
|
||||
|
||||
|
||||
def _status(
|
||||
channels: dict[int, dict[str, Any]] | None = None, wan: dict[str, Any] | None = None
|
||||
) -> dict[str, Any]:
|
||||
"""The recorded status page with *channels* (index: changes) and *wan* (changes to
|
||||
the ``ptm0.2`` WAN interface) applied."""
|
||||
answer = copy.deepcopy(STATUS)
|
||||
page = answer["Object"][0]
|
||||
for index, changes in (channels or {}).items():
|
||||
page["DslChannelInfo"][index].update(changes)
|
||||
for entry in page["WanLanInfo"]:
|
||||
if entry["X_ZYXEL_IfName"] == "ptm0.2":
|
||||
entry.update(wan or {})
|
||||
return answer
|
||||
|
||||
|
||||
IN_SYNC = _status({PTM_LINE_2: {"Status": "Up"}}, {"Status": "Up"})
|
||||
|
||||
ROUTED = {
|
||||
"X_ZYXEL_ConnectionType": "IP_Routed",
|
||||
"Encapsulation": "PPPoE",
|
||||
"Status": "Up",
|
||||
"X_ZYXEL_UpTime": 7200,
|
||||
"IPv4Address": [
|
||||
{
|
||||
"Enable": True,
|
||||
"IPAddress": "203.0.113.10",
|
||||
"SubnetMask": "255.255.255.255",
|
||||
"Status": "Enabled",
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _wan(answer: dict[str, Any]) -> Any:
|
||||
return driver({dal("cardpage_status"): answer}).get_wan_status()
|
||||
|
||||
|
||||
# --- a bridge -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_bridge_whose_line_is_not_in_sync_is_down():
|
||||
assert _wan(STATUS) == {
|
||||
"connection_type": "DSL",
|
||||
"is_connected": False,
|
||||
"external_ip": "",
|
||||
"uptime": 0,
|
||||
"bytes_sent": 0,
|
||||
"bytes_received": 0,
|
||||
"max_bitrate_up": 0,
|
||||
"max_bitrate_down": 0,
|
||||
"link_status": "Down",
|
||||
}
|
||||
|
||||
|
||||
def test_a_bridge_whose_line_is_in_sync_is_connected():
|
||||
status = _wan(IN_SYNC)
|
||||
assert (status["is_connected"], status["link_status"]) == (True, "Up")
|
||||
assert status["external_ip"] == "" # a bridge has no WAN address
|
||||
|
||||
|
||||
def test_the_sync_rates_are_the_channels_in_kbit_per_second():
|
||||
status = _wan(IN_SYNC)
|
||||
assert (status["max_bitrate_up"], status["max_bitrate_down"]) == (45875, 274098)
|
||||
|
||||
|
||||
def test_the_rates_of_a_line_out_of_sync_are_not_reported():
|
||||
"""The recorded channel keeps the rates of its last sync while it is down."""
|
||||
status = _wan(STATUS)
|
||||
assert (status["max_bitrate_up"], status["max_bitrate_down"]) == (0, 0)
|
||||
|
||||
|
||||
def test_bonded_lines_add_up():
|
||||
rates = {"UpstreamCurrRate": 40000, "DownstreamCurrRate": 100000}
|
||||
answer = _status({1: {"Status": "Up", **rates}, PTM_LINE_2: {"Status": "Up"}})
|
||||
status = _wan(answer)
|
||||
assert (status["max_bitrate_up"], status["max_bitrate_down"]) == (85875, 374098)
|
||||
|
||||
|
||||
def test_the_line_uptime_is_reported_when_the_gateway_gives_one():
|
||||
answer = _status({PTM_LINE_2: {"Status": "Up", "DSLUpTime": "5400"}})
|
||||
assert _wan(answer)["uptime"] == 5400
|
||||
|
||||
|
||||
def test_a_line_uptime_that_is_not_a_number_is_unknown():
|
||||
answer = _status({PTM_LINE_2: {"Status": "Up", "DSLUpTime": ""}})
|
||||
assert _wan(answer)["uptime"] == 0
|
||||
|
||||
|
||||
# --- a router -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_router_with_a_wan_address_is_connected_with_it():
|
||||
status = _wan(_status({PTM_LINE_2: {"Status": "Up"}}, ROUTED))
|
||||
assert status["is_connected"] is True
|
||||
assert status["external_ip"] == "203.0.113.10"
|
||||
assert status["connection_type"] == "PPPoE"
|
||||
assert status["uptime"] == 7200
|
||||
|
||||
|
||||
def test_a_router_whose_line_is_in_sync_but_its_wan_down_is_not_connected():
|
||||
wan = {**ROUTED, "Status": "Down", "IPv4Address": []}
|
||||
status = _wan(_status({PTM_LINE_2: {"Status": "Up"}}, wan))
|
||||
assert (status["is_connected"], status["link_status"]) == (False, "Up")
|
||||
assert status["external_ip"] == ""
|
||||
|
||||
|
||||
def test_a_disabled_wan_address_is_not_the_external_one():
|
||||
addresses = [{**ROUTED["IPv4Address"][0], "Enable": False}]
|
||||
status = _wan(_status({PTM_LINE_2: {"Status": "Up"}}, {**ROUTED, "IPv4Address": addresses}))
|
||||
assert (status["is_connected"], status["external_ip"]) == (False, "")
|
||||
|
||||
|
||||
# --- reading ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_basic_information_is_not_read_for_it():
|
||||
drv = driver({dal("cardpage_status"): IN_SYNC})
|
||||
drv._device_info = {**fixture("getBasicInformation"), "WanIp": "198.51.100.1"}
|
||||
assert drv.get_wan_status()["external_ip"] == ""
|
||||
|
||||
|
||||
def test_get_wan_status_raises_when_the_status_page_cannot_be_read():
|
||||
with pytest.raises(RuntimeError, match="cardpage_status"):
|
||||
_wan(response(500)) # type: ignore[arg-type]
|
||||
|
||||
|
||||
# --- NAT translations ---------------------------------------------------------------------
|
||||
|
||||
RULE = {
|
||||
"Enable": True,
|
||||
"Protocol": "TCP",
|
||||
"Description": "web",
|
||||
"ExternalPortStart": 8443,
|
||||
"InternalPortStart": 443,
|
||||
"InternalClient": "192.0.2.3",
|
||||
}
|
||||
|
||||
|
||||
def _nat_driver(status: Any) -> Any:
|
||||
return driver(
|
||||
{dal("nat"): {**fixture("nat"), "Object": [RULE]}, dal("cardpage_status"): status}
|
||||
)
|
||||
|
||||
|
||||
def test_a_translation_is_to_the_wan_address():
|
||||
status = _status({PTM_LINE_2: {"Status": "Up"}}, ROUTED)
|
||||
nat = _nat_driver(status).get_nat_translations()
|
||||
assert [(t["inside_local"], t["inside_global"]) for t in nat] == [
|
||||
("192.0.2.3:443", "203.0.113.10:8443")
|
||||
]
|
||||
|
||||
|
||||
def test_without_a_wan_address_a_translation_is_to_any_address():
|
||||
nat = _nat_driver(STATUS).get_nat_translations()
|
||||
assert [t["inside_global"] for t in nat] == ["0.0.0.0:8443"]
|
||||
|
||||
|
||||
def test_without_port_forwards_the_status_page_is_not_read():
|
||||
drv = driver({dal("nat"): fixture("nat")})
|
||||
assert drv.get_nat_translations() == []
|
||||
assert requested(drv) == ["http://192.0.2.1:80/cgi-bin/DAL?oid=nat"]
|
||||
+159
-118
@@ -6,20 +6,11 @@ import requests
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
|
||||
from napalm_zyxel import ZyxelVMGDriver
|
||||
from tests.gateway import fixture
|
||||
|
||||
MOCK_BASIC_INFO = {
|
||||
"ModelName": "VMG4005-B50A",
|
||||
"SoftwareVersion": "V5.13(ABKS.1)C0",
|
||||
"SerialNumber": "S220L12345678",
|
||||
"HostName": "ZyxelVMG",
|
||||
"WanIp": "85.2.34.56",
|
||||
"LanIp": "192.168.1.1",
|
||||
"MacAddress": "00:1A:2B:3C:4D:5E",
|
||||
"SystemUpTime": "1234567",
|
||||
"WanAccessType": "VDSL",
|
||||
"MaxUpstream": "30000000",
|
||||
"MaxDownstream": "100000000",
|
||||
}
|
||||
#: The recorded getBasicInformation answer of a VMG4005-B50A: model and firmware, no
|
||||
#: serial number, host name, uptime, MAC or WAN state (#24). tests/gateway.py
|
||||
MOCK_BASIC_INFO = fixture("getBasicInformation")
|
||||
|
||||
MOCK_RSA_KEY = (
|
||||
"-----BEGIN PUBLIC KEY-----\n"
|
||||
@@ -41,6 +32,17 @@ MOCK_LOGIN_RESPONSE = {
|
||||
}
|
||||
|
||||
|
||||
def _offline(driver: ZyxelVMGDriver) -> ZyxelVMGDriver:
|
||||
"""*driver*, with an is_alive() that opens no socket (#17).
|
||||
|
||||
NAPALM's ``__del__`` asks ``is_alive()``, which connects to the gateway while the
|
||||
driver has a session; many tests give it a mock one and never close it. The tests
|
||||
of ``is_alive()`` itself call the class's method (and ``tests/test_is_alive.py``).
|
||||
"""
|
||||
driver.is_alive = lambda: {"is_alive": False} # type: ignore[method-assign]
|
||||
return driver
|
||||
|
||||
|
||||
class MockResponse:
|
||||
def __init__(self, json_data, status_code=200, text=""):
|
||||
self._json = json_data
|
||||
@@ -61,11 +63,7 @@ class MockResponse:
|
||||
|
||||
class TestZyxelVMGDriver:
|
||||
def setup_method(self):
|
||||
self.driver = ZyxelVMGDriver(
|
||||
"192.168.1.1",
|
||||
"admin",
|
||||
"password",
|
||||
)
|
||||
self.driver = _offline(ZyxelVMGDriver("192.168.1.1", "admin", "password"))
|
||||
|
||||
def _setup_mocked_http(self, monkeypatch_crypto=True):
|
||||
session = MagicMock(spec=requests.Session)
|
||||
@@ -80,6 +78,10 @@ class TestZyxelVMGDriver:
|
||||
return MockResponse(MOCK_BASIC_INFO)
|
||||
if "getRSAPublickKey" in url:
|
||||
return MockResponse({"RSAPublicKey": MOCK_RSA_KEY})
|
||||
if "cgi-bin/System?oid=snmp" in url: # tests/test_facts.py
|
||||
return MockResponse([{"HostName": "VMG4005-B50A", "DomainName": "home"}])
|
||||
if "cgi-bin/DAL?oid=cardpage_status" in url: # tests/test_facts.py
|
||||
return MockResponse(fixture("cardpage_status"))
|
||||
if "UserLogout" in url:
|
||||
return MockResponse({})
|
||||
return MockResponse({})
|
||||
@@ -156,44 +158,27 @@ class TestZyxelVMGDriver:
|
||||
assert self.driver._sessionkey is None
|
||||
|
||||
def test_is_alive(self):
|
||||
self._setup_mocked_http()
|
||||
with patch("socket.create_connection") as mock_conn:
|
||||
mock_conn.return_value.__enter__.return_value = MagicMock()
|
||||
assert self.driver.is_alive()["is_alive"] is True
|
||||
assert ZyxelVMGDriver.is_alive(self.driver)["is_alive"] is True
|
||||
|
||||
def test_is_alive_fail(self):
|
||||
self._setup_mocked_http()
|
||||
with patch("socket.create_connection") as mock_conn:
|
||||
mock_conn.side_effect = OSError("refused")
|
||||
assert self.driver.is_alive()["is_alive"] is False
|
||||
assert ZyxelVMGDriver.is_alive(self.driver)["is_alive"] is False
|
||||
|
||||
def test_get_facts(self):
|
||||
self._setup_mocked_http()
|
||||
facts = self.driver.get_facts()
|
||||
assert facts["vendor"] == "Zyxel"
|
||||
assert facts["model"] == "VMG4005-B50A"
|
||||
assert facts["serial_number"] == "S220L12345678"
|
||||
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()
|
||||
assert status["is_connected"] is True
|
||||
assert status["external_ip"] == "85.2.34.56"
|
||||
assert status["connection_type"] == "VDSL"
|
||||
assert facts["serial_number"] == "S000Y00000001"
|
||||
assert facts["os_version"] == "V5.17(ABQA.3.1)C0"
|
||||
assert facts["hostname"] == "VMG4005-B50A"
|
||||
assert facts["fqdn"] == "VMG4005-B50A.home"
|
||||
assert facts["uptime"] == 13554213
|
||||
|
||||
def test_get_port_forwards_empty(self):
|
||||
self._setup_mocked_http()
|
||||
@@ -278,6 +263,20 @@ class TestZyxelVMGDriver:
|
||||
self._setup_mocked_http()
|
||||
assert self.driver.get_arp_table() == []
|
||||
|
||||
def test_an_arp_entry_has_no_known_age(self):
|
||||
"""The host list says a host is active, not when the gateway last saw it;
|
||||
0.0 would read as "confirmed just now" (NetOrk/netork#1327)."""
|
||||
self.driver.get_hosts = lambda: [
|
||||
{
|
||||
"mac": "aa:bb:cc:dd:ee:ff",
|
||||
"ip": "192.168.1.33",
|
||||
"hostname": "laptop",
|
||||
"interface_type": "lan",
|
||||
"is_active": True,
|
||||
}
|
||||
]
|
||||
assert [e["age"] for e in self.driver.get_arp_table()] == [-1.0]
|
||||
|
||||
def test_reboot_host_is_the_contract_the_application_calls(self):
|
||||
"""It was reboot(), which nothing looks for: the gateway could not be
|
||||
restarted from the application (#5)."""
|
||||
@@ -293,11 +292,6 @@ class TestZyxelVMGDriver:
|
||||
assert not hasattr(type(self.driver), "run_device_action")
|
||||
assert not hasattr(type(self.driver), "reboot")
|
||||
|
||||
def test_load_replace_candidate_raises(self):
|
||||
self._setup_mocked_http()
|
||||
with pytest.raises(NotImplementedError):
|
||||
self.driver.load_replace_candidate()
|
||||
|
||||
def test_load_merge_candidate_raises(self):
|
||||
self._setup_mocked_http()
|
||||
with pytest.raises(NotImplementedError):
|
||||
@@ -319,61 +313,20 @@ class TestZyxelVMGDriver:
|
||||
with pytest.raises(ConnectionClosedException):
|
||||
self.driver._dal_query("PINGTEST", {})
|
||||
|
||||
def test_parse_port_forwards_dal(self):
|
||||
self._setup_mocked_http()
|
||||
data = {
|
||||
"NATPortMap": [
|
||||
{
|
||||
"Description": "Web Server",
|
||||
"Protocol": "TCP",
|
||||
"ExternalPort": 80,
|
||||
"InternalIP": "192.168.1.10",
|
||||
"InternalPort": 8080,
|
||||
"Enabled": True,
|
||||
}
|
||||
]
|
||||
}
|
||||
result = self.driver._parse_port_forwards_dal(data)
|
||||
assert len(result) == 1
|
||||
assert result[0]["name"] == "Web Server"
|
||||
assert result[0]["external_port"] == 80
|
||||
assert result[0]["internal_ip"] == "192.168.1.10"
|
||||
|
||||
def test_parse_hosts_dal(self):
|
||||
self._setup_mocked_http()
|
||||
data = {
|
||||
"LANHosts": [
|
||||
{
|
||||
"MACAddress": "aa:bb:cc:dd:ee:ff",
|
||||
"IPAddress": "192.168.1.100",
|
||||
"HostName": "laptop",
|
||||
"InterfaceType": "lan",
|
||||
"Active": True,
|
||||
}
|
||||
]
|
||||
}
|
||||
result = self.driver._parse_hosts_dal(data)
|
||||
assert len(result) == 1
|
||||
assert result[0]["mac"] == "aa:bb:cc:dd:ee:ff"
|
||||
assert result[0]["ip"] == "192.168.1.100"
|
||||
assert result[0]["hostname"] == "laptop"
|
||||
|
||||
def test_parse_wireless_clients_dal(self):
|
||||
self._setup_mocked_http()
|
||||
data = {
|
||||
"assoc": [
|
||||
{
|
||||
"MACAddress": "11:22:33:44:55:66",
|
||||
"SSID": "MyWiFi",
|
||||
"Radio": "wlan0",
|
||||
"Signal": -45,
|
||||
"TxRate": 300.0,
|
||||
"RxRate": 150.0,
|
||||
"Uptime": 3600,
|
||||
"IPAddress": "192.168.1.50",
|
||||
}
|
||||
]
|
||||
}
|
||||
data = [
|
||||
{
|
||||
"MACAddress": "11:22:33:44:55:66",
|
||||
"SSID": "MyWiFi",
|
||||
"Radio": "wlan0",
|
||||
"Signal": -45,
|
||||
"TxRate": 300.0,
|
||||
"RxRate": 150.0,
|
||||
"Uptime": 3600,
|
||||
"IPAddress": "192.168.1.50",
|
||||
}
|
||||
]
|
||||
result = self.driver._parse_wireless_clients_dal(data)
|
||||
assert len(result) == 1
|
||||
assert result[0]["mac"] == "11:22:33:44:55:66"
|
||||
@@ -382,28 +335,116 @@ class TestZyxelVMGDriver:
|
||||
|
||||
def test_parse_ssids_dal(self):
|
||||
self._setup_mocked_http()
|
||||
data = {
|
||||
"ssids": [
|
||||
{
|
||||
"SSID": "MyWiFi",
|
||||
"Radio": "wlan0",
|
||||
"BSSID": "00:1a:2b:3c:4d:5e",
|
||||
"Encryption": "WPA2",
|
||||
"Enabled": True,
|
||||
"Hidden": False,
|
||||
"Clients": 3,
|
||||
}
|
||||
]
|
||||
}
|
||||
data = [
|
||||
{
|
||||
"SSID": "MyWiFi",
|
||||
"Radio": "wlan0",
|
||||
"BSSID": "00:1a:2b:3c:4d:5e",
|
||||
"Encryption": "WPA2",
|
||||
"Enabled": True,
|
||||
"Hidden": False,
|
||||
"Clients": 3,
|
||||
}
|
||||
]
|
||||
result = self.driver._parse_ssids_dal(data)
|
||||
assert "MyWiFi" in result
|
||||
assert result["MyWiFi"]["encryption"] == "WPA2"
|
||||
assert result["MyWiFi"]["clients"] == 3
|
||||
|
||||
def test_get_config(self):
|
||||
self._setup_mocked_http()
|
||||
assert self.driver.get_config() == {}
|
||||
def test_get_config_is_left_to_napalms_stub(self):
|
||||
"""A VMG has no configuration export: the driver must not override
|
||||
get_config, so NAPALM's stub tells callers it is not supported. A stub
|
||||
returning {} read as a backup that came back empty."""
|
||||
from napalm.base import NetworkDriver
|
||||
|
||||
assert ZyxelVMGDriver.get_config is NetworkDriver.get_config
|
||||
with pytest.raises(NotImplementedError):
|
||||
self.driver.get_config()
|
||||
|
||||
def test_cli(self):
|
||||
self._setup_mocked_http()
|
||||
assert self.driver.cli(["show version"]) == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("switch_model", ["gs1920", "gs2210"])
|
||||
def test_a_zyxel_switch_page_adds_no_evidence_for_this_gateway(switch_model):
|
||||
"""GS1920 and GS2210 are Zyxel switches, not VMG gateways."""
|
||||
page = f"zyxel {switch_model}-24hp web configurator"
|
||||
matching = [
|
||||
rule.pattern
|
||||
for rule in ZyxelVMGDriver.HTTP_FINGERPRINT
|
||||
if not rule.negative and rule.pattern != "zyxel" and rule.pattern in page
|
||||
]
|
||||
assert matching == []
|
||||
|
||||
|
||||
class TestEveryRequestHasATimeout:
|
||||
"""requests ignores a ``timeout`` attribute on a Session; it must go with each call."""
|
||||
|
||||
def _driver_with_session(self):
|
||||
driver = _offline(ZyxelVMGDriver("192.168.1.1", "admin", "password", timeout=7))
|
||||
session = MagicMock(spec=requests.Session)
|
||||
session.get.return_value = MockResponse(MOCK_BASIC_INFO)
|
||||
session.post.return_value = MockResponse(MOCK_LOGIN_RESPONSE)
|
||||
session.put.return_value = MockResponse({})
|
||||
return driver, session
|
||||
|
||||
@staticmethod
|
||||
def _timeouts(session):
|
||||
calls = session.get.call_args_list + session.post.call_args_list
|
||||
calls += session.put.call_args_list
|
||||
assert calls
|
||||
return {call.kwargs.get("timeout") for call in calls}
|
||||
|
||||
def test_open_login_and_logout(self):
|
||||
driver, session = self._driver_with_session()
|
||||
crypto = MagicMock()
|
||||
crypto.encrypt_json.return_value = {"content": "ENC", "iv": "IV", "key": ""}
|
||||
crypto.decrypt_response.return_value = {"result": "ZCFG_SUCCESS", "sessionkey": "1"}
|
||||
session.get.side_effect = lambda url, **kw: MockResponse(
|
||||
{"RSAPublicKey": MOCK_RSA_KEY} if "getRSAPublickKey" in url else MOCK_BASIC_INFO
|
||||
)
|
||||
with (
|
||||
patch("napalm_zyxel.zyxel_driver.ZyxelCrypto", return_value=crypto),
|
||||
patch("napalm_zyxel.zyxel_driver.requests.Session", return_value=session),
|
||||
):
|
||||
driver.open()
|
||||
driver.close()
|
||||
assert self._timeouts(session) == {7}
|
||||
|
||||
def test_dal_query_and_page_fetch(self):
|
||||
driver, session = self._driver_with_session()
|
||||
driver._session = session
|
||||
driver._sessionkey = "1"
|
||||
driver._crypto = MagicMock()
|
||||
driver._dal_query("LAN_HOSTS")
|
||||
driver._fetch_page("Status.htm")
|
||||
assert self._timeouts(session) == {7}
|
||||
|
||||
|
||||
class TestPingReportsNoTargetAlive:
|
||||
"""The DAL PINGTEST call only acknowledges the request; it carries no reply count."""
|
||||
|
||||
def _connected_driver(self):
|
||||
driver = _offline(ZyxelVMGDriver("192.168.1.1", "admin", "password"))
|
||||
driver._session = MagicMock(spec=requests.Session)
|
||||
driver._session.put.return_value = MockResponse({})
|
||||
driver._sessionkey = "1"
|
||||
driver._crypto = MagicMock()
|
||||
driver._crypto.decrypt_response.return_value = {"result": "ZCFG_SUCCESS"}
|
||||
return driver
|
||||
|
||||
def test_the_driver_opts_out_of_ping_sweeps(self):
|
||||
assert ZyxelVMGDriver.supports_ping() is False
|
||||
|
||||
def test_an_accepted_request_is_not_a_reply(self):
|
||||
driver = self._connected_driver()
|
||||
reply = driver.ping("192.0.2.77")
|
||||
assert "success" not in reply
|
||||
assert reply["error"]
|
||||
assert driver._parse_ping_reply("192.0.2.77", reply)["alive"] is False
|
||||
|
||||
def test_ping_starts_no_diagnostic_on_the_gateway(self):
|
||||
driver = self._connected_driver()
|
||||
driver.ping("192.0.2.77")
|
||||
driver._session.put.assert_not_called()
|
||||
Reference in new issue
Block a user