feat: scan Windows clients with the NetBox Windows Agent in listen mode

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-11-18 11:05:32 +01:00
1 parent 43c5e5e85a
commit a67b0d3e5c
8 files changed
+521 -24

No files matched your search

+114
View File
@@ -0,0 +1,114 @@
"""Query the NetBox Windows Agent in "listen" mode (protocol v1).
The agent answers ``GET /v1/info`` without authentication. The inventory at
``GET /v1/inventory`` needs a signature (HMAC-SHA256 with a key derived from
the shared scan key) over a fresh nonce and the current time, and comes back
encrypted with AES-256-GCM, so serial numbers and software lists never cross
the network in clear text even without TLS certificates.
The decrypted inventory has the same shape as the WinRM scan
(:func:`netbox_sync.core.wsman.query_client`), so it runs through the same
table and NetBox transfer as the agentless client scan.
"""
import base64
import hashlib
import hmac
import http.client
import json
import secrets
import time
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
DEFAULT_PORT = 8731
PROTOCOL = 1
AGENT_NAME = "netbox-windows-agent"
class AgentError(Exception):
"""The host answered, but not as an agent we can read (wrong key, other service …)."""
def derive_key(secret, purpose):
return hmac.new(secret.encode(), purpose.encode(), hashlib.sha256).digest()
def new_scan_key():
"""Random shared key for the agents of one customer (URL-safe, 43 characters)."""
return secrets.token_urlsafe(32)
def _get(host, port, path, headers=None, timeout=5.0):
connection = http.client.HTTPConnection(host, port, timeout=timeout)
try:
connection.request("GET", path, headers=headers or {})
response = connection.getresponse()
body = response.read(16 * 1024 * 1024)
return response.status, body
finally:
connection.close()
def _json(body):
try:
return json.loads(body.decode("utf-8"))
except (UnicodeDecodeError, ValueError) as error:
raise AgentError("keine gültige Antwort (kein NetBox-Agent?)") from error
def info(host, port=DEFAULT_PORT, timeout=3.0):
status, body = _get(host, port, "/v1/info", timeout=timeout)
data = _json(body)
if status != 200 or data.get("agent") != AGENT_NAME:
raise AgentError("kein NetBox-Agent auf diesem Port")
return data
def inventory(host, key, port=DEFAULT_PORT, timeout=60.0):
"""Decrypted inventory dict of one agent."""
nonce = secrets.token_hex(16)
ts = str(int(time.time()))
signature = hmac.new(derive_key(key, "netbox-agent auth v1"), f"GET\n/v1/inventory\n{nonce}\n{ts}".encode(),
hashlib.sha256).hexdigest()
status, body = _get(host, port, f"/v1/inventory?nonce={nonce}&ts={ts}", {"X-Agent-Signature": signature},
timeout)
data = _json(body)
if status != 200:
reason = data.get("error", f"HTTP {status}")
raise AgentError({
"wrong key": "Agent-Schlüssel stimmt nicht",
"clock skew too large": "Uhrzeit von Client und diesem Rechner weicht mehr als 5 Minuten ab",
"address not allowed": "dieser Rechner ist in allowed_networks des Agenten nicht freigegeben",
}.get(reason, f"Agent meldet: {reason}"))
try:
payload = AESGCM(derive_key(key, "netbox-agent enc v1")).decrypt(
base64.b64decode(data["iv"]), base64.b64decode(data["data"]), nonce.encode())
except Exception as error: # noqa: BLE001 - InvalidTag, KeyError, binascii.Error
raise AgentError("Antwort lässt sich nicht entschlüsseln (falscher Schlüssel?)") from error
return json.loads(payload.decode("utf-8"))
def query(host, key, port=DEFAULT_PORT, timeout=60.0):
"""Raw result for :func:`netbox_sync.core.clients.apply_scan` – never raises."""
try:
result = inventory(host, key, port, timeout)
except AgentError as error:
return {"host": host, "ok": False, "error": str(error)}
except (OSError, http.client.HTTPException) as error:
return {"host": host, "ok": False, "error": f"Agent nicht erreichbar: {error}"}
result.update(host=host, ok=True)
return result
def agent_config(key, port=DEFAULT_PORT, allowed_networks=(), collect_software=True):
"""``config.json`` for agents in listen mode (no NetBox access needed on the clients)."""
return {
"mode": "listen",
"listen_port": port,
"scan_key": key,
"allowed_networks": list(allowed_networks),
"inventory_cache_seconds": 300,
"collect_software": collect_software,
"max_software_entries": 250,
}
+18 -6
View File
@@ -21,7 +21,7 @@ WINRM_HTTPS_PORT = 5986
MAX_RANGE = 4096
DEFAULT_CLIENT_OPTIONS = {
"mode": "ad", # ad | hosts
"mode": "ad", # ad | hosts | agent
"ad_server": "", # domain or domain controller, empty = own domain
"ad_base": "", # search base (OU DN), empty = whole domain
"include_servers": False,
@@ -31,6 +31,10 @@ DEFAULT_CLIENT_OPTIONS = {
"use_current_user": False,
"username": "", # remembered for the logon prompt, never the password
"use_ssl": False,
# NetBox Windows Agent in listen mode (the key itself is a profile secret).
"agent_targets": "",
"agent_port": 8731,
"agent_networks": "", # allowed_networks written into the agent configuration
# Last choices in the NetBox transfer dialog.
"netbox_site": None,
"netbox_role": "Client",
@@ -269,6 +273,11 @@ def apply_scan(row, raw, now=None):
"os_architecture": raw.get("os_architecture", ""),
"installed": raw.get("installed", ""),
"last_boot": raw.get("last_boot", ""),
"source": raw.get("source", "winrm"),
"agent_version": raw.get("agent_version", ""),
"software_count": len(raw.get("software") or []),
"disks": [{"model": disk.get("model", ""), "size": int(disk.get("size") or 0)}
for disk in raw.get("disks") or []],
# Only real adapters: VPN/TAP drivers report no MAC or are not physical.
"interfaces": [_interface(nic) for nic in raw.get("nics") or [] if nic.get("physical") and nic.get("mac")],
})
@@ -358,11 +367,14 @@ def friendly_error(text):
# --------------------------------------------------------------------------
def scan_clients(rows, credential=None, use_ssl=False, parallel=8, timeout=30, log=lambda *_args: None,
on_result=lambda _row: None, cancelled=lambda: False, query=None):
"""Query every row's host. ``on_result`` is called for each finished row (any thread)."""
on_result=lambda _row: None, cancelled=lambda: False, query=None, port=None, service="WinRM"):
"""Query every row's host. ``on_result`` is called for each finished row (any thread).
``query``/``port``/``service`` replace the WinRM query, e.g. by the NetBox Windows Agent.
"""
if sys.platform != "win32" and query is None:
raise ClientScanError("Die Abfrage von Windows-Clients ist nur unter Windows verfügbar.")
port = WINRM_HTTPS_PORT if use_ssl else WINRM_HTTP_PORT
port = port or (WINRM_HTTPS_PORT if use_ssl else WINRM_HTTP_PORT)
results = []
def scan(row):
@@ -374,7 +386,7 @@ def scan_clients(rows, credential=None, use_ssl=False, parallel=8, timeout=30, l
scanned_at=time.time())
if not port_open(host, port):
return dict(row, status="offline", scanned_at=time.time(),
message=f"Nicht erreichbar – ausgeschaltet oder WinRM-Port {port} geschlossen.")
message=f"Nicht erreichbar – ausgeschaltet oder {service}-Port {port} geschlossen.")
if cancelled():
return None
if query is not None:
@@ -386,7 +398,7 @@ def scan_clients(rows, credential=None, use_ssl=False, parallel=8, timeout=30, l
raw = wsman.query_client(host, credential, use_ssl, port, timeout)
return apply_scan(row, raw)
log(f"Frage {len(rows)} Client(s) über WinRM (Port {port}) ab …")
log(f"Frage {len(rows)} Client(s) über {service} (Port {port}) ab …")
with ThreadPoolExecutor(max_workers=max(1, min(parallel, len(rows) or 1))) as pool:
futures = [pool.submit(scan, row) for row in rows]
for future in as_completed(futures):
+5
View File
@@ -115,6 +115,8 @@ def empty_profile(name):
"netbox_url": "",
"netbox_token": "",
"netbox_ignore_ssl": False,
# Shared key of the NetBox Windows Agents of this customer (listen mode).
"agent_key": "",
"sources": [],
"switches": [],
# Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name.
@@ -176,6 +178,8 @@ class ProfileStore:
profile.update({
"netbox_url": record.get("netbox_url", ""),
"netbox_token": self._decrypt(record.get("netbox_token_encrypted", ""), f"{name}: NetBox-Token"),
"agent_key": self._decrypt(record.get("agent_key_encrypted", ""), f"{name}: Agent-Schlüssel")
if record.get("agent_key_encrypted") else "",
"netbox_ignore_ssl": bool(record.get("netbox_ignore_ssl", record.get("ignore_ssl_errors", False))),
"cluster_map": dict(record.get("cluster_map", {})),
"host_map": dict(record.get("host_map", {})),
@@ -253,6 +257,7 @@ class ProfileStore:
"name": name,
"netbox_url": profile.get("netbox_url", ""),
"netbox_token_encrypted": protect(profile.get("netbox_token", "")),
"agent_key_encrypted": protect(profile.get("agent_key", "")) if profile.get("agent_key") else "",
"netbox_ignore_ssl": bool(profile.get("netbox_ignore_ssl", False)),
"sources": [self._encrypt_record(source) for source in profile.get("sources", [])],
"switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])],