fix: query clients in-process via WSMan/ADSI COM instead of PowerShell

Endpoint protection (Sophos Application Lockdown) terminated the app when it spawned powershell.exe. WinRM and Active Directory are now accessed through Windows COM inside the process.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-10-21 13:41:52 +02:00
1 parent c42cedd655
commit d10190b7bc
6 files changed
+403 -266

No files matched your search

+61 -264
View File
@@ -1,21 +1,16 @@
"""Agentless inventory of Windows clients via WMI/CIM over WinRM.
Targets come from Active Directory (computer objects) or from a list of host
names, IP addresses and ranges. Each reachable client is queried with
``Get-CimInstance`` through Windows PowerShell, so authentication uses the
Windows stack (Kerberos/Negotiate) – either the signed-in user or credentials
from the Windows logon prompt. Passwords are handed to PowerShell via stdin and
never appear on a command line or on disk.
names, IP addresses and ranges. Each reachable client is queried in-process
through the Windows WSMan COM API (see :mod:`netbox_sync.core.wsman`), so
authentication uses Kerberos/Negotiate with either the signed-in user or
credentials from the Windows logon prompt. No helper processes are started.
"""
import base64
import ipaddress
import json
import os
import re
import shutil
import socket
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
@@ -134,193 +129,6 @@ def resolves(host):
return False
# --------------------------------------------------------------------------
# PowerShell
# --------------------------------------------------------------------------
def powershell_path():
root = os.environ.get("SystemRoot", r"C:\Windows")
candidate = os.path.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
return candidate if os.path.exists(candidate) else (shutil.which("powershell") or "powershell.exe")
def _start_powershell(script, payload):
if sys.platform != "win32":
raise ClientScanError("Die Abfrage von Windows-Clients ist nur unter Windows verfügbar.")
encoded = base64.b64encode(script.encode("utf-16-le")).decode("ascii")
process = subprocess.Popen( # noqa: S603 - fixed executable, script passed encoded
[powershell_path(), "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
"-EncodedCommand", encoded],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
process.stdin.write(json.dumps(payload).encode("utf-8"))
process.stdin.close()
return process
def _credential_payload(credential):
if credential is None:
return {"user": "", "password": ""}
return {"user": credential.username, "password": credential.password}
_PS_PROLOG = r"""
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false
$job = [Console]::In.ReadToEnd() | ConvertFrom-Json
$cred = $null
if ($job.user) {
$secure = ConvertTo-SecureString $job.password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($job.user, $secure)
}
function Emit($value) { [Console]::Out.WriteLine(($value | ConvertTo-Json -Compress -Depth 6)); [Console]::Out.Flush() }
function Text($value) { if ($null -eq $value) { '' } else { ([string]$value).Trim() } }
function Stamp($value) { if ($value -is [datetime]) { $value.ToString('s') } else { '' } }
"""
_SCAN_SCRIPT = _PS_PROLOG + r"""
if ($job.ssl) { $option = New-CimSessionOption -UseSsl } else { $option = New-CimSessionOption -Protocol Wsman }
foreach ($target in $job.hosts) {
$result = [ordered]@{ host = $target; ok = $false }
$session = $null
try {
$params = @{ ComputerName = $target; SessionOption = $option; OperationTimeoutSec = [int]$job.timeout }
if ($job.port) { $params.Port = [int]$job.port }
if ($cred) { $params.Credential = $cred; $params.Authentication = 'Negotiate' }
$session = New-CimSession @params
$cs = Get-CimInstance -CimSession $session -ClassName Win32_ComputerSystem
$os = Get-CimInstance -CimSession $session -ClassName Win32_OperatingSystem
$bios = Get-CimInstance -CimSession $session -ClassName Win32_BIOS
$product = Get-CimInstance -CimSession $session -ClassName Win32_ComputerSystemProduct
$enclosure = @(Get-CimInstance -CimSession $session -ClassName Win32_SystemEnclosure) | Select-Object -First 1
$cpu = @(Get-CimInstance -CimSession $session -ClassName Win32_Processor)
$adapters = @{}
foreach ($adapter in @(Get-CimInstance -CimSession $session -ClassName Win32_NetworkAdapter -Filter 'PhysicalAdapter = TRUE')) {
$adapters[[int]$adapter.InterfaceIndex] = $adapter
}
$nics = @()
foreach ($config in @(Get-CimInstance -CimSession $session -ClassName Win32_NetworkAdapterConfiguration -Filter 'IPEnabled = TRUE')) {
$adapter = $adapters[[int]$config.InterfaceIndex]
$nics += [ordered]@{
name = Text $adapter.NetConnectionID
description = Text $config.Description
mac = Text $config.MACAddress
ips = @($config.IPAddress | ForEach-Object { Text $_ })
masks = @($config.IPSubnet | ForEach-Object { Text $_ })
gateway = @($config.DefaultIPGateway | ForEach-Object { Text $_ })
dhcp = [bool]$config.DHCPEnabled
physical = [bool]($null -ne $adapter)
speed = [int64]$adapter.Speed
}
}
$displayVersion = ''
try {
$reg = Invoke-CimMethod -CimSession $session -Namespace root/default -ClassName StdRegProv -MethodName GetStringValue -Arguments @{ hDefKey = [uint32]2147483650; sSubKeyName = 'SOFTWARE\Microsoft\Windows NT\CurrentVersion'; sValueName = 'DisplayVersion' }
$displayVersion = Text $reg.sValue
} catch { }
$result.ok = $true
$result.name = Text $cs.Name
$result.domain = Text $cs.Domain
$result.part_of_domain = [bool]$cs.PartOfDomain
$result.manufacturer = Text $cs.Manufacturer
$result.model = Text $cs.Model
$result.product_name = Text $product.Name
$result.product_version = Text $product.Version
$result.serial = Text $bios.SerialNumber
$result.bios_version = Text $bios.SMBIOSBIOSVersion
$result.chassis = @($enclosure.ChassisTypes | ForEach-Object { [int]$_ })
$result.user = Text $cs.UserName
$result.memory = [int64]$cs.TotalPhysicalMemory
$result.cpu = Text ($cpu | Select-Object -First 1).Name
$result.cores = [int](($cpu | Measure-Object -Property NumberOfCores -Sum).Sum)
$result.os = Text $os.Caption
$result.os_version = Text $os.Version
$result.os_build = Text $os.BuildNumber
$result.os_display_version = $displayVersion
$result.os_architecture = Text $os.OSArchitecture
$result.installed = Stamp $os.InstallDate
$result.last_boot = Stamp $os.LastBootUpTime
$result.nics = $nics
} catch {
$result.error = Text $_.Exception.Message
} finally {
if ($session) { Remove-CimSession $session -ErrorAction SilentlyContinue }
}
Emit $result
}
"""
_AD_SCRIPT = _PS_PROLOG + r"""
try {
if ($cred) {
$plain = $cred.GetNetworkCredential()
$root = New-Object System.DirectoryServices.DirectoryEntry($job.path, $cred.UserName, $plain.Password)
} elseif ($job.path) {
$root = New-Object System.DirectoryServices.DirectoryEntry($job.path)
} else {
$root = New-Object System.DirectoryServices.DirectoryEntry
}
$searcher = New-Object System.DirectoryServices.DirectorySearcher($root)
$searcher.Filter = $job.filter
$searcher.PageSize = 1000
foreach ($name in 'name', 'dnshostname', 'operatingsystem', 'operatingsystemversion', 'lastlogontimestamp',
'distinguishedname', 'description', 'useraccountcontrol') {
[void]$searcher.PropertiesToLoad.Add($name)
}
foreach ($item in $searcher.FindAll()) {
$p = $item.Properties
Emit ([ordered]@{
name = Text ($p['name'] | Select-Object -First 1)
dns = Text ($p['dnshostname'] | Select-Object -First 1)
os = Text ($p['operatingsystem'] | Select-Object -First 1)
os_version = Text ($p['operatingsystemversion'] | Select-Object -First 1)
last_logon = [int64]($p['lastlogontimestamp'] | Select-Object -First 1)
dn = Text ($p['distinguishedname'] | Select-Object -First 1)
description = Text ($p['description'] | Select-Object -First 1)
disabled = [bool](([int]($p['useraccountcontrol'] | Select-Object -First 1)) -band 2)
})
}
} catch {
Emit ([ordered]@{ fatal = Text $_.Exception.Message })
}
"""
def _read_lines(process, cancelled):
"""Yield parsed JSON lines from a PowerShell process, killing it on cancel."""
try:
for raw in process.stdout:
if cancelled():
process.kill()
return
line = raw.decode("utf-8", errors="replace").strip()
if line.startswith("{"):
try:
yield json.loads(line)
except json.JSONDecodeError:
continue
finally:
if process.poll() is None:
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
def _stderr(process):
try:
text = process.stderr.read().decode("utf-8", errors="replace").strip()
except (OSError, ValueError):
return ""
if text.startswith("#< CLIXML"):
parts = re.findall(r'<S S="Error">(.*?)</S>', text, re.S)
text = "".join(parts).replace("_x000D__x000A_", "\n").replace("&lt;", "<").replace("&gt;", ">")
text = text.replace("&quot;", '"').replace("&amp;", "&")
return text.strip()
# --------------------------------------------------------------------------
# Active Directory
# --------------------------------------------------------------------------
@@ -334,17 +142,24 @@ def ad_filter(options):
return "(&" + "".join(parts) + ")"
def ad_path(options, credential):
def domain_base(domain):
return ",".join(f"DC={part}" for part in domain.strip(".").split(".") if part)
def ad_location(options):
"""``server/base`` for the LDAP query; defaults to the domain of the signed-in user."""
server = (options.get("ad_server") or "").strip().strip("/")
base = (options.get("ad_base") or "").strip()
if not server and not base and credential is None:
return ""
if not server and credential is not None:
server = os.environ.get("USERDNSDOMAIN", "")
if not server and not base:
raise ClientScanError("Dieser Rechner ist keiner Domäne beigetreten. Bitte unter „Domäne / DC“ die Domäne "
"angeben, z. B. firma.local.")
return "LDAP://" + "/".join(part for part in (server, base) if part)
if server and not base:
# LDAP://server binds to the default naming context of that domain or DC.
return server
if not base:
domain = os.environ.get("USERDNSDOMAIN", "")
if not domain:
raise ClientScanError("Dieser Rechner ist keiner Domäne beigetreten. Bitte unter „Domäne / DC“ die "
"Domäne angeben, z. B. firma.local.")
base = domain_base(domain)
return "/".join(part for part in (server, base) if part)
def filetime_to_unix(value):
@@ -355,15 +170,21 @@ def filetime_to_unix(value):
def query_ad(options, credential=None, log=lambda *_args: None, cancelled=lambda: False, now=None):
"""Return computer objects from Active Directory as client rows (not yet scanned)."""
payload = dict(_credential_payload(credential), path=ad_path(options, credential), filter=ad_filter(options))
log(f"Suche Computerkonten im Active Directory{' unter ' + payload['path'] if payload['path'] else ''} …")
process = _start_powershell(_AD_SCRIPT, payload)
from netbox_sync.core import wsman
location = ad_location(options)
log(f"Suche Computerkonten im Active Directory (LDAP://{location}) …")
try:
with wsman.com_thread():
items = wsman.search_ad(location, ad_filter(options), credential)
except wsman.WSManError as error:
raise ClientScanError(f"Active-Directory-Abfrage fehlgeschlagen: {friendly_error(str(error))}") from error
max_age = int(options.get("max_age_days") or 0)
limit = ((now or time.time()) - max_age * 86400) if max_age else None
rows, stale = [], 0
for item in _read_lines(process, cancelled):
if "fatal" in item:
raise ClientScanError(f"Active-Directory-Abfrage fehlgeschlagen: {friendly_error(item['fatal'])}")
for item in items:
if cancelled():
break
if not item.get("name"):
continue
last_logon = filetime_to_unix(item.get("last_logon"))
@@ -375,10 +196,6 @@ def query_ad(options, credential=None, log=lambda *_args: None, cancelled=lambda
"os_version": item.get("os_version", ""), "last_logon": last_logon, "dn": item.get("dn", ""),
"description": item.get("description", ""), "disabled": bool(item.get("disabled")),
}))
if process.returncode not in (0, None) and not rows:
problem = _stderr(process)
if problem:
raise ClientScanError(f"Active-Directory-Abfrage fehlgeschlagen: {problem}")
log(f"Active Directory: {len(rows)} Computer" + (f" ({stale} ohne Anmeldung seit {max_age} Tagen ausgelassen)"
if stale else ""), "success")
return rows
@@ -420,7 +237,7 @@ def chassis_name(types):
def apply_scan(row, raw, now=None):
"""Merge the raw PowerShell result into a result row."""
"""Merge the raw WinRM result into a result row."""
row = dict(row)
row["scanned_at"] = now or time.time()
if not raw.get("ok"):
@@ -540,65 +357,45 @@ def friendly_error(text):
# Scan
# --------------------------------------------------------------------------
def _chunks(items, count):
count = max(1, min(count, len(items)))
return [items[index::count] for index in range(count)]
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):
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)."""
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
by_host = {row["host"]: row for row in rows}
results = []
def reachable(row):
def scan(row):
if cancelled():
return None
host = row["host"]
if not is_ip(host) and not resolves(host):
return row, "Rechnername kann nicht aufgelöst werden (DNS)."
return dict(row, status="offline", message="Rechnername kann nicht aufgelöst werden (DNS).",
scanned_at=time.time())
if not port_open(host, port):
return row, f"Nicht erreichbar – ausgeschaltet oder WinRM-Port {port} geschlossen."
return row, None
return dict(row, status="offline", scanned_at=time.time(),
message=f"Nicht erreichbar – ausgeschaltet oder WinRM-Port {port} geschlossen.")
if cancelled():
return None
if query is not None:
raw = query(host)
else:
from netbox_sync.core import wsman
log(f"Prüfe Erreichbarkeit von {len(rows)} Client(s) auf Port {port} …")
online = []
with ThreadPoolExecutor(max_workers=min(64, max(1, len(rows)))) as pool:
for future in as_completed([pool.submit(reachable, row) for row in rows]):
if cancelled():
break
row, problem = future.result()
if problem:
finished = dict(row, status="offline", message=problem, scanned_at=time.time())
results.append(finished)
on_result(finished)
else:
online.append(row["host"])
if cancelled() or not online:
return results
log(f"{len(online)} Client(s) erreichbar, frage WMI ab …")
with wsman.com_thread():
raw = wsman.query_client(host, credential, use_ssl, port, timeout)
return apply_scan(row, raw)
def run_chunk(hosts):
payload = dict(_credential_payload(credential), hosts=hosts, ssl=use_ssl, port=port, timeout=timeout)
process = _start_powershell(_SCAN_SCRIPT, payload)
done = set()
for raw in _read_lines(process, cancelled):
row = by_host.get(raw.get("host"))
if row is None:
log(f"Frage {len(rows)} Client(s) über WinRM (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):
finished = future.result()
if finished is None:
continue
done.add(raw["host"])
finished = apply_scan(row, raw)
results.append(finished)
on_result(finished)
if not cancelled():
problem = _stderr(process) or "PowerShell wurde unerwartet beendet."
for host in hosts:
if host not in done:
finished = dict(by_host[host], status="error", message=friendly_error(problem),
scanned_at=time.time())
results.append(finished)
on_result(finished)
with ThreadPoolExecutor(max_workers=max(1, parallel)) as pool:
for future in as_completed([pool.submit(run_chunk, hosts) for hosts in _chunks(online, parallel)]):
future.result()
if cancelled():
for pending in futures:
pending.cancel()
return results