From a67b0d3e5c45cbde3f19d089e41ff98be887bcb3 Mon Sep 17 00:00:00 2001 From: Louis Date: Wed, 18 Nov 2026 11:05:32 +0100 Subject: [PATCH] feat: scan Windows clients with the NetBox Windows Agent in listen mode Co-Authored-By: Claude Opus 5.5 --- README.md | 14 +++ netbox_sync/core/agent_client.py | 114 +++++++++++++++++++++ netbox_sync/core/clients.py | 24 +++-- netbox_sync/core/config.py | 5 + netbox_sync/ui/actions.py | 26 ++++- netbox_sync/ui/client_help.py | 76 ++++++++++++++ netbox_sync/ui/pages/clients.py | 168 ++++++++++++++++++++++++++++--- tests/test_agent_client.py | 118 ++++++++++++++++++++++ 8 files changed, 521 insertions(+), 24 deletions(-) create mode 100644 netbox_sync/core/agent_client.py create mode 100644 tests/test_agent_client.py diff --git a/README.md b/README.md index a5e7f69..f33c4b1 100644 --- a/README.md +++ b/README.md @@ -219,6 +219,20 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox. permissions, common errors, check commands and a connection test for single clients +### Windows clients with the NetBox Windows Agent + +- Third target mode **NetBox-Agent (Netzwerk-Scan)**: scans IP ranges for the + [NetBox Windows Agent](https://git.mrblake.cc/MrBlake/Netbox-Client-Agent-for-Windows) + in listen mode – no WinRM, no admin account and no NetBox access needed on the + clients; only hosts with an answering agent are listed +- One shared key per profile (encrypted with DPAPI); requests are signed with + HMAC-SHA256, the inventory comes back encrypted with AES-256-GCM +- "Agent-Konfiguration speichern …" writes the ready `config.json` (port, + key, optional allowed networks) for unattended deployment with Intune or a + Group Policy startup script; the setup guide has a tab with all steps +- The agent data runs through the same table and NetBox transfer as the WinRM + scan, plus disks and the number of installed programs in the tooltip + ### Offline mode (without NetBox) - "Offline mode (without NetBox)" checkbox in the sidebar — global, independent diff --git a/netbox_sync/core/agent_client.py b/netbox_sync/core/agent_client.py new file mode 100644 index 0000000..caa46d0 --- /dev/null +++ b/netbox_sync/core/agent_client.py @@ -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, + } diff --git a/netbox_sync/core/clients.py b/netbox_sync/core/clients.py index 08f2988..9e4c9cf 100644 --- a/netbox_sync/core/clients.py +++ b/netbox_sync/core/clients.py @@ -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): diff --git a/netbox_sync/core/config.py b/netbox_sync/core/config.py index 2defe65..7510936 100644 --- a/netbox_sync/core/config.py +++ b/netbox_sync/core/config.py @@ -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 ":" -> 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", [])], diff --git a/netbox_sync/ui/actions.py b/netbox_sync/ui/actions.py index 538786e..f423b29 100644 --- a/netbox_sync/ui/actions.py +++ b/netbox_sync/ui/actions.py @@ -9,7 +9,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completed from PySide6.QtCore import QTimer from PySide6.QtWidgets import QFileDialog -from netbox_sync.core import backups, exchange, lancom, netbox +from netbox_sync.core import agent_client, backups, exchange, lancom, netbox from netbox_sync.core.client_sync import ClientSyncEngine from netbox_sync.core.clients import ClientScanError, expand_targets, new_row, query_ad, scan_clients from netbox_sync.core.config import known_hosts_path @@ -645,9 +645,19 @@ class Actions: parallel = max(1, int(self.state.settings.get("parallel_wmi", 8))) mode = options.get("mode", "ad") hosts = [] - if rows is None and mode == "hosts": + agent = mode == "agent" + agent_key = (self.state.profile or {}).get("agent_key", "") + agent_port = int(options.get("agent_port") or agent_client.DEFAULT_PORT) + if agent and not agent_key: + widgets.message(self.window, "Agent-Schlüssel fehlt", + "Bitte zuerst einen Agent-Schlüssel erzeugen und mit der Agent-Konfiguration verteilen.", + "info") + return + if agent: + parallel = max(parallel, 32) + if rows is None and mode in ("hosts", "agent"): try: - hosts = expand_targets(options.get("hosts", "")) + hosts = expand_targets(options.get("agent_targets" if agent else "hosts", "")) except ClientScanError as error: widgets.error(self.window, "Ungültige Eingabe", str(error)) return @@ -684,11 +694,17 @@ class Actions: ctx.progress(done[0], len(targets), row["name"]) ctx.progress(0, len(targets), "") + extra = ({"query": lambda host: agent_client.query(host, agent_key, agent_port), "port": agent_port, + "service": "Agent"} if agent else {}) results = scan_clients(targets, credential, bool(options.get("use_ssl")), parallel, log=ctx.log, - on_result=on_result, cancelled=lambda: ctx.cancelled) + on_result=on_result, cancelled=lambda: ctx.cancelled, **extra) ctx.check_cancelled() by_host = {row["host"]: row for row in results} - return nb, engine, [by_host.get(row["host"], row) for row in targets] + scanned = [by_host.get(row["host"], row) for row in targets] + if agent and targets_given is None: + # A range scan: only hosts where an agent answered (or rejected us) are of interest. + scanned = [row for row in scanned if row["status"] != "offline"] + return nb, engine, scanned def success(result): nb, engine, scanned = result diff --git a/netbox_sync/ui/client_help.py b/netbox_sync/ui/client_help.py index ce2724e..bb646b4 100644 --- a/netbox_sync/ui/client_help.py +++ b/netbox_sync/ui/client_help.py @@ -119,6 +119,77 @@ winrm/config/listener. """ +AGENT_REPO = "https://git.mrblake.cc/MrBlake/Netbox-Client-Agent-for-Windows" + + +def _agent_html(): + accent = theme.color("accent") + code_bg = theme.color("log_bg") + return f""" + + +

NetBox-Agent statt WinRM

+

Der NetBox Windows Agent läuft unsichtbar als SYSTEM-Aufgabe auf den Clients und stellt sein +Inventar auf einem TCP-Port (Standard 8731) bereit. Dieser Rechner scannt IP-Bereiche und liest die Agenten +aus – ohne WinRM, ohne Administratorkonto und ohne NetBox-Zugang auf den Clients. Die Abfrage ist mit +dem Agent-Schlüssel signiert, die Antwort mit AES-256 verschlüsselt. Benutzer bemerken nichts: kein Fenster, +keine Firewall-Abfrage.

+ +

1. Schlüssel und Konfiguration

+
    +
  1. Modus NetBox-Agent (Netzwerk-Scan) wählen und Schlüssel erzeugen (einer pro Kunde, +verschlüsselt im Profil gespeichert).
  2. +
  3. Optional unter Freigegebene Netze das Admin-Netz eintragen – dann nehmen die Agenten nur von dort +Verbindungen an.
  4. +
  5. Agent-Konfiguration speichern … erzeugt die fertige config.json.
  6. +
+ +

2. Dateien zusammenstellen

+

agent.exe, install.ps1, +uninstall.ps1 und gpo-startup.ps1 kommen aus dem +Agent-Projekt ({AGENT_REPO}, Ordner dist bzw. scripts), +dazu die eben gespeicherte config.json.

+ +

3a. Verteilung per Intune

+ + + + + + +
Paketagent.exe, config.json, install.ps1, uninstall.ps1 als Win32-App (.intunewin)
Installationpowershell.exe -NoProfile -ExecutionPolicy Bypass -File .\\install.ps1 +-SourceDirectory .
Deinstallationpowershell.exe -NoProfile -ExecutionPolicy Bypass -File +.\\uninstall.ps1
VerhaltenSystem · als Erforderlich einer Gerätegruppe zuweisen
ErkennungDatei C:\\Program Files\\NetBox Windows Agent / +agent.exe, Methode „Zeichenfolge (Version)“, „Größer als oder gleich“, z. B. 0.2.0
+ +

3b. Verteilung per Gruppenrichtlinie

+
    +
  1. Alle fünf Dateien in eine Freigabe legen, die „Domänencomputer“ lesen dürfen, z. B. +\\\\fileserver\\NetBoxAgent$.
  2. +
  3. GPO für die OU der Clients: Computerkonfiguration › Richtlinien › Windows-Einstellungen › Skripts › +Starten › PowerShell-Skripts – \\\\fileserver\\NetBoxAgent$\\gpo-startup.ps1 +ohne Parameter.
  4. +
  5. Computerkonfiguration › Administrative Vorlagen › System › Anmelden › Beim Neustart des Computers und +bei der Anmeldung immer auf das Netzwerk warten = Aktiviert.
  6. +
+

Das Skript installiert beim Start nur, wenn sich agent.exe oder config.json auf der Freigabe geändert +haben – neue Versionen oder ein neuer Schlüssel werden so automatisch verteilt.

+ +

4. Scannen

+

IP-Bereiche als Ziele eintragen und Abfragen. Es erscheinen nur Rechner, auf denen ein Agent +antwortet; die Übertragung nach NetBox läuft wie beim WinRM-Scan mit Vorschau.

+

Findet der Scan keinen Agenten: Läuft die Aufgabe „NetBox Windows Agent Listener“? Ist Port 8731 +zwischen den Netzen offen (Test-NetConnection PC0815 -Port 8731)? Liegt dieser +Rechner in den freigegebenen Netzen? Die Firewall-Regel gilt für die Profile Domäne und Privat.

+""" + + class ClientHelpDialog(_Dialog): def __init__(self, parent, state, tab=0): super().__init__(parent, "Einrichtungshilfe: Windows-Clients", @@ -169,6 +240,11 @@ class ClientHelpDialog(_Dialog): layout.addStretch(1) self.tabs.addTab(test, "Verbindung testen") + agent = QTextBrowser() + agent.setOpenExternalLinks(True) + agent.setHtml(_agent_html()) + self.tabs.addTab(agent, "NetBox-Agent") + self.root.addWidget(self.tabs, 1) self.root.addWidget(button("Schließen", variant="primary", on_click=self.accept), 0, Qt.AlignRight) self.tabs.setCurrentIndex(tab) diff --git a/netbox_sync/ui/pages/clients.py b/netbox_sync/ui/pages/clients.py index 8ccbbfe..a18c384 100644 --- a/netbox_sync/ui/pages/clients.py +++ b/netbox_sync/ui/pages/clients.py @@ -1,9 +1,13 @@ +import ipaddress +import json import os import time from PySide6.QtCore import Qt +from PySide6.QtGui import QGuiApplication from PySide6.QtWidgets import ( QButtonGroup, + QFileDialog, QComboBox, QGridLayout, QHBoxLayout, @@ -15,6 +19,7 @@ from PySide6.QtWidgets import ( QWidget, ) +from netbox_sync.core import agent_client from netbox_sync.core.client_sync import clean_manufacturer from netbox_sync.core.clients import WINRM_HTTP_PORT, WINRM_HTTPS_PORT, os_label, os_version_label from netbox_sync.ui import widgets @@ -22,7 +27,18 @@ from netbox_sync.ui.client_help import ClientHelpDialog from netbox_sync.ui.credentials import ask_credentials from netbox_sync.ui.models import Column, FilterProxy, RowTableModel from netbox_sync.ui.pages import Page -from netbox_sync.ui.widgets import Badge, Banner, Card, EmptyState, SearchField, Table, button, checkbox, label +from netbox_sync.ui.widgets import ( + Badge, + Banner, + Card, + EmptyState, + PasswordField, + SearchField, + Table, + button, + checkbox, + label, +) STATUS = { "ok": ("OK", "success"), @@ -55,6 +71,9 @@ def _tooltip(row): ("RAM", f"{row['memory'] / 1024 ** 3:.0f} GB" if row.get("memory") else ""), ("Angemeldet", row.get("user")), ("Letzter Start", (row.get("last_boot") or "").replace("T", " ")), + ("Quelle", f"NetBox-Agent {row.get('agent_version', '')}".strip() if row.get("source") == "agent" else ""), + ("Software", f"{row['software_count']} Programme (laut Agent)" if row.get("software_count") else ""), + ("Datenträger", ", ".join(f"{disk['model']} ({disk['size'] / 1e9:.0f} GB)" for disk in row.get("disks") or [])), ("AD", (row.get("ad") or {}).get("dn")), ): if value: @@ -87,7 +106,8 @@ class ClientsPage(Page): mode_row.addWidget(label("Ziele", object_name="CardTitle")) self.mode_group = QButtonGroup(self) self.mode_buttons = {} - for key, text in (("ad", "Active Directory"), ("hosts", "Hostnamen / IP-Bereiche")): + for key, text in (("ad", "Active Directory"), ("hosts", "Hostnamen / IP-Bereiche"), + ("agent", "NetBox-Agent (Netzwerk-Scan)")): radio = QRadioButton(text) radio.setCursor(Qt.PointingHandCursor) self.mode_group.addButton(radio) @@ -136,12 +156,17 @@ class ClientsPage(Page): "PC0815.firma.local 10.0.10.0/24 10.0.20.10-50") self.hosts.setFixedHeight(76) self.mode_stack.addWidget(self.hosts) + self.mode_stack.addWidget(self._build_agent_panel()) # QPlainTextEdit reports a tall size hint even with a fixed height. - self.mode_stack.setFixedHeight(max(ad_panel.sizeHint().height(), self.hosts.height())) + self.mode_stack.setFixedHeight(max(ad_panel.sizeHint().height(), self.hosts.height(), + self.agent_panel.sizeHint().height())) targets.add(self.mode_stack) - targets.add(widgets.hline()) + self.separator = widgets.hline() + targets.add(self.separator) - logon = QHBoxLayout() + self.logon_widget = QWidget() + logon = QHBoxLayout(self.logon_widget) + logon.setContentsMargins(0, 0, 0, 0) logon.setSpacing(10) logon.addWidget(label("Anmeldung", object_name="CardTitle")) self.account_badge = Badge("", "neutral") @@ -161,7 +186,7 @@ class ClientsPage(Page): "verschlüsselt. HTTPS erfordert einen Zertifikats-Listener auf den Clients.") logon.addWidget(self.current_user) logon.addWidget(self.use_ssl) - targets.add(logon) + targets.add(self.logon_widget) self.body.addWidget(targets) self.help_banner = Banner("Die Clients müssen einmalig für WinRM vorbereitet werden (Gruppenrichtlinie, " @@ -250,6 +275,10 @@ class ClientsPage(Page): self.hosts.textChanged.connect(lambda: self._save(hosts=self.hosts.toPlainText())) self.current_user.toggled.connect(self._current_user_toggled) self.use_ssl.toggled.connect(lambda value: self._save(use_ssl=value)) + self.agent_targets.textChanged.connect(lambda: self._save(agent_targets=self.agent_targets.toPlainText())) + self.agent_port.valueChanged.connect(lambda value: self._save(agent_port=value)) + self.agent_networks.editingFinished.connect( + lambda: self._save(agent_networks=self.agent_networks.text().strip())) self.search.textChanged.connect(self.proxy.set_text) self.status_filter.currentIndexChanged.connect(self._apply_filters) self.netbox_filter.currentIndexChanged.connect(self._apply_filters) @@ -272,7 +301,8 @@ class ClientsPage(Page): def load_options(self): options = self.state.client_options controls = (self.ad_server, self.ad_base, self.only_enabled, self.include_servers, self.max_age, self.hosts, - self.current_user, self.use_ssl, *self.mode_buttons.values()) + self.current_user, self.use_ssl, self.agent_targets, self.agent_port, self.agent_networks, + *self.mode_buttons.values()) for widget in controls: widget.blockSignals(True) self.ad_server.setText(options.get("ad_server", "")) @@ -284,17 +314,125 @@ class ClientsPage(Page): self.hosts.setPlainText(options.get("hosts", "")) self.current_user.setChecked(bool(options.get("use_current_user"))) self.use_ssl.setChecked(bool(options.get("use_ssl"))) + if self.agent_targets.toPlainText() != options.get("agent_targets", ""): + self.agent_targets.setPlainText(options.get("agent_targets", "")) + self.agent_port.setValue(int(options.get("agent_port") or agent_client.DEFAULT_PORT)) + self.agent_networks.setText(options.get("agent_networks", "")) mode = options.get("mode", "ad") self.mode_buttons.get(mode, self.mode_buttons["ad"]).setChecked(True) - self.mode_stack.setCurrentIndex(0 if mode == "ad" else 1) for widget in controls: widget.blockSignals(False) + self._show_mode(mode) self._update_account() + self._update_agent_key() def _set_mode(self, mode): - self.mode_stack.setCurrentIndex(0 if mode == "ad" else 1) + self._show_mode(mode) self._save(mode=mode) + def _show_mode(self, mode): + self.mode_stack.setCurrentIndex({"ad": 0, "hosts": 1, "agent": 2}.get(mode, 0)) + agent = mode == "agent" + # The agent needs no Windows logon – its shared key replaces it. + self.logon_widget.setVisible(not agent) + self.separator.setVisible(not agent) + self.help_banner.set( + "Der NetBox-Agent wird per Intune oder GPO verteilt und stellt sein Inventar verschlüsselt bereit – " + "ohne WinRM und ohne NetBox-Zugang auf den Clients. Die Einrichtungshilfe zeigt die Verteilung." + if agent else + "Die Clients müssen einmalig für WinRM vorbereitet werden (Gruppenrichtlinie, Firewall). Die " + "Einrichtungshilfe zeigt alle Schritte.") + + # ------------------------------------------------------------------ + # NetBox Windows Agent + # ------------------------------------------------------------------ + + def _build_agent_panel(self): + self.agent_panel = QWidget() + grid = QGridLayout(self.agent_panel) + grid.setContentsMargins(0, 0, 0, 0) + grid.setHorizontalSpacing(12) + grid.setVerticalSpacing(8) + self.agent_targets = QPlainTextEdit() + self.agent_targets.setPlaceholderText("IP-Bereiche oder Hostnamen, z. B. 10.0.10.0/24, 10.0.20.10-50") + self.agent_targets.setFixedHeight(52) + grid.addWidget(label("Ziele"), 0, 0) + grid.addWidget(self.agent_targets, 0, 1, 1, 5) + self.agent_key = PasswordField("noch kein Schlüssel") + self.agent_key.setReadOnly(True) + grid.addWidget(label("Agent-Schlüssel"), 1, 0) + grid.addWidget(self.agent_key, 1, 1) + self.agent_key_new = button("Neu erzeugen", "refresh", on_click=self.new_agent_key, + tooltip="Neuen Schlüssel für die Agenten dieses Kunden erzeugen") + self.agent_key_copy = button("Kopieren", "copy", variant="ghost", on_click=self.copy_agent_key) + self.agent_config = button("Agent-Konfiguration speichern …", "download", on_click=self.save_agent_config, + tooltip="config.json für die Verteilung per Intune oder GPO erzeugen") + grid.addWidget(self.agent_key_new, 1, 2) + grid.addWidget(self.agent_key_copy, 1, 3) + grid.addWidget(self.agent_config, 1, 4, 1, 2) + self.agent_port = QSpinBox() + self.agent_port.setRange(1, 65535) + self.agent_port.setFixedWidth(100) + self.agent_networks = QLineEdit() + self.agent_networks.setPlaceholderText("leer = jede Adresse, z. B. 10.0.0.0/24 (Netz dieses Rechners)") + grid.addWidget(label("Port"), 2, 0) + grid.addWidget(self.agent_port, 2, 1, Qt.AlignLeft) + grid.addWidget(label("Freigegebene Netze"), 2, 2) + grid.addWidget(self.agent_networks, 2, 3, 1, 3) + grid.setColumnStretch(1, 1) + grid.setColumnStretch(3, 1) + return self.agent_panel + + def _update_agent_key(self): + key = (self.state.profile or {}).get("agent_key", "") + self.agent_key.setText(key) + self.agent_key_copy.setEnabled(bool(key)) + self.agent_config.setEnabled(bool(key)) + self.agent_key_new.setText("Neu erzeugen" if key else "Schlüssel erzeugen") + + def new_agent_key(self): + if self.state.profile is None: + return + if self.state.profile.get("agent_key") and not widgets.confirm( + self.window, "Neuen Schlüssel erzeugen?", + "Bereits verteilte Agenten lassen sich danach erst wieder abfragen, wenn sie die neue " + "Konfiguration erhalten haben.", "Neu erzeugen", destructive=True): + return + self.state.edit_profile(agent_key=agent_client.new_scan_key()) + self._update_agent_key() + self.window.toast("Neuer Agent-Schlüssel erzeugt – Konfiguration neu verteilen.", "info") + + def copy_agent_key(self): + QGuiApplication.clipboard().setText(self.agent_key.text()) + self.window.toast("Agent-Schlüssel kopiert.", "info") + + def save_agent_config(self): + key = (self.state.profile or {}).get("agent_key", "") + if not key: + return + networks = [part.strip() for part in self.agent_networks.text().replace(";", ",").split(",") if part.strip()] + for network in networks: + try: + ipaddress.ip_network(network, strict=False) + except ValueError: + widgets.message(self.window, "Freigegebene Netze prüfen", + f"„{network}“ ist kein Netz in CIDR-Schreibweise (z. B. 10.0.0.0/24).", "warning") + return + path, _filter = QFileDialog.getSaveFileName(self.window, "Agent-Konfiguration speichern", "config.json", + "JSON (*.json)") + if not path: + return + data = agent_client.agent_config(key, self.agent_port.value(), + [str(ipaddress.ip_network(n, strict=False)) for n in networks]) + try: + with open(path, "w", encoding="utf-8") as stream: + json.dump(data, stream, indent=2) + except OSError as error: + widgets.error(self.window, "Speichern fehlgeschlagen", str(error)) + return + self.window.toast("config.json gespeichert – zusammen mit agent.exe per Intune oder GPO verteilen.", + "success") + def _current_user_toggled(self, value): self._save(use_current_user=value) self._update_account() @@ -416,12 +554,14 @@ class ClientsPage(Page): return self.ad_server.editingFinished.emit() self.ad_base.editingFinished.emit() - if self._ensure_logon(): + if self.state.client_options.get("mode") == "agent": + self.actions.scan_clients() + elif self._ensure_logon(): self.actions.scan_clients() def rescan(self): rows = self.model.checked_rows() - if rows and self._ensure_logon(): + if rows and (self.state.client_options.get("mode") == "agent" or self._ensure_logon()): self.actions.scan_clients(rows) def load_file(self): @@ -436,5 +576,7 @@ class ClientsPage(Page): else: self.actions.sync_clients(rows) - def show_help(self, tab=0): - ClientHelpDialog(self.window, self.state, tab if isinstance(tab, int) else 0).exec() + def show_help(self, tab=None): + if tab is None or isinstance(tab, bool): # button signals pass "checked" + tab = 3 if self.state.client_options.get("mode") == "agent" else 0 + ClientHelpDialog(self.window, self.state, tab).exec() diff --git a/tests/test_agent_client.py b/tests/test_agent_client.py new file mode 100644 index 0000000..45dcd5a --- /dev/null +++ b/tests/test_agent_client.py @@ -0,0 +1,118 @@ +"""NetBox Windows Agent protocol v1 against a small in-process agent (same rules as the C# agent).""" + +import base64 +import hashlib +import hmac +import json +import os +import threading +import time +from http.server import BaseHTTPRequestHandler, HTTPServer +from urllib.parse import parse_qs, urlparse + +import pytest +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +from netbox_sync.core import agent_client +from netbox_sync.core.clients import apply_scan, new_row, scan_clients + +KEY = "test-key-0123456789abcdef" +INVENTORY = { + "ok": True, "source": "agent", "agent_version": "0.2.0", "name": "pc0815", "domain": "firma.local", + "part_of_domain": True, "manufacturer": "LENOVO", "model": "21MW", "product_name": "21MW", + "product_version": "ThinkBook 16 G7 ARP", "serial": "PW0K84A9", "bios_version": "N3BET", "chassis": [10], + "user": "FIRMA\\anna", "memory": 16 * 1024 ** 3, "cpu": "AMD Ryzen 5", "cores": 6, + "os": "Microsoft Windows 11 Pro", "os_version": "10.0.26100", "os_build": "26100", "os_display_version": "24H2", + "os_architecture": "64-Bit", "installed": "2025-01-01T10:00:00", "last_boot": "2026-11-18T08:00:00", + "nics": [{"name": "Ethernet", "description": "Realtek PCIe GbE", "mac": "84:BA:59:60:C8:B7", + "ips": ["192.168.65.43", "fe80::1"], "masks": ["255.255.255.0", "64"], "gateway": ["192.168.65.1"], + "dhcp": True, "physical": True, "speed": 1000000000}, + {"name": "", "description": "OpenVPN", "mac": "", "ips": ["10.8.0.2"], "masks": ["255.255.255.0"], + "gateway": [], "dhcp": False, "physical": False, "speed": 0}], + "disks": [{"device_id": "\\\\.\\PHYSICALDRIVE0", "model": "Samsung SSD", "serial": "S1", "size": 512110190592}], + "memory_modules": [], "software": [{"name": "7-Zip", "version": "24.08", "publisher": "Igor Pavlov"}], +} + + +class _Handler(BaseHTTPRequestHandler): + seen = set() + + def log_message(self, *_args): + pass + + def _send(self, status, data): + body = json.dumps(data).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): # noqa: N802 - http.server API + url = urlparse(self.path) + if url.path == "/v1/info": + return self._send(200, {"agent": "netbox-windows-agent", "version": "0.2.0", "protocol": 1}) + query = {key: values[0] for key, values in parse_qs(url.query).items()} + nonce, ts = query.get("nonce", ""), query.get("ts", "0") + if abs(time.time() - int(ts)) > 300: + return self._send(401, {"error": "clock skew too large"}) + expected = hmac.new(agent_client.derive_key(KEY, "netbox-agent auth v1"), + f"GET\n/v1/inventory\n{nonce}\n{ts}".encode(), hashlib.sha256).hexdigest() + if not hmac.compare_digest(expected, self.headers.get("X-Agent-Signature", "")): + return self._send(401, {"error": "wrong key"}) + if nonce in self.seen: + return self._send(401, {"error": "nonce reused"}) + self.seen.add(nonce) + iv = os.urandom(12) + data = AESGCM(agent_client.derive_key(KEY, "netbox-agent enc v1")).encrypt( + iv, json.dumps(INVENTORY).encode(), nonce.encode()) + self._send(200, {"protocol": 1, "iv": base64.b64encode(iv).decode(), "data": base64.b64encode(data).decode()}) + + +@pytest.fixture +def agent(): + server = HTTPServer(("127.0.0.1", 0), _Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield server.server_address[1] + server.shutdown() + + +def test_info_and_encrypted_inventory(agent): + assert agent_client.info("127.0.0.1", agent)["version"] == "0.2.0" + raw = agent_client.query("127.0.0.1", KEY, agent) + assert raw["ok"] and raw["host"] == "127.0.0.1" and raw["serial"] == "PW0K84A9" + + +def test_wrong_key_is_explained(agent): + raw = agent_client.query("127.0.0.1", "another-key-0123456789", agent) + assert raw == {"host": "127.0.0.1", "ok": False, "error": "Agent-Schlüssel stimmt nicht"} + + +def test_unreachable_agent_is_reported_not_raised(): + raw = agent_client.query("127.0.0.1", KEY, 1, timeout=1) + assert not raw["ok"] and raw["error"].startswith("Agent nicht erreichbar") + + +def test_agent_inventory_runs_through_the_client_scan(agent): + rows = scan_clients([new_row("127.0.0.1")], query=lambda host: agent_client.query(host, KEY, agent), + port=agent, service="Agent") + row = rows[0] + assert row["status"] == "ok" and row["name"] == "PC0815" and row["source"] == "agent" + # Lenovo: marketing name from the product version, VPN adapter (not physical) left out + assert row["model"] == "ThinkBook 16 G7 ARP" and row["machine_type"] == "21MW" + assert [(item["name"], item["ips"]) for item in row["interfaces"]] == [("Ethernet", ["192.168.65.43/24"])] + assert row["software_count"] == 1 and row["disks"][0]["model"] == "Samsung SSD" + + +def test_offline_host_names_the_agent_port(): + row = scan_clients([new_row("127.0.0.1")], query=lambda host: {}, port=1, service="Agent")[0] + assert row["status"] == "offline" and "Agent-Port 1" in row["message"] + + +def test_generated_configuration_is_valid_for_the_agent(): + key = agent_client.new_scan_key() + config = agent_client.agent_config(key, 8731, ["10.0.0.0/24"]) + assert len(key) >= 16 and config["mode"] == "listen" and config["scan_key"] == key + assert config["allowed_networks"] == ["10.0.0.0/24"] and config["listen_port"] == 8731 + assert apply_scan(new_row("x"), dict(INVENTORY, host="x"))["os_display_version"] == "24H2"