Files
napalm-windows/napalm_windows/transport.py
T
Christian Manivong 0bbeebb7a7 feat(repairs): SFC, DISM and Defender runs through HostRepairMixin (NetOrk/netork#2899)
verify_system_files (sfc /verifyonly), check_component_store (DISM
/ScanHealth /English), update_antimalware_signatures (Update-MpSignature)
and scan_antimalware (Start-MpScan, quick or full), each one bounded PSRP
call streamed line by line through PsrpTransport.run_streaming. Native
tools run as a process read in their own encoding (sfc: UTF-16), and NULs
of UTF-16 read byte by byte are dropped. The exit code decides; a missing
tool or Defender says it is not available. sfc /scannow and DISM
/RestoreHealth stay undefined until a real host was tested.

tools/harvest.py --runs records the runs' output.
2026-12-01 12:49:37 +01:00

189 lines
7.1 KiB
Python

"""PowerShell Remoting (PSRP) over WinRM — the driver's only path to the host.
One runspace pool stays open for the lifetime of the connection, so a poll
that sends a dozen scripts pays the WinRM handshake once. Everything the
driver knows about pypsrp lives in this module; the driver itself sees a
``run(script) -> str`` seam, which is what its tests replace and what an SSH
transport (Windows OpenSSH) would implement later.
"""
from __future__ import annotations
import logging
import time
from collections.abc import Callable
import requests
from napalm.base.exceptions import ConnectionClosedException, ConnectionException
from pypsrp.complex_objects import PSInvocationState
from pypsrp.exceptions import AuthenticationError, WinRMError, WinRMTransportError
from pypsrp.powershell import PowerShell, RunspacePool
from pypsrp.wsman import WSMan
logger = logging.getLogger(__name__)
#: The longest one poll of a streaming script waits for output, so its limit is
#: checked at least this often.
_POLL_SECONDS = 20
class PowerShellError(Exception):
"""A script ran but wrote to PowerShell's error stream."""
class PsrpTransport:
def __init__(
self,
host: str,
username: str,
password: str,
*,
port: int,
ssl: bool,
cert_validation: bool,
auth: str,
timeout: int,
) -> None:
self.host = host
self.username = username
self._password = password
self.port = port
self.ssl = ssl
self.cert_validation = cert_validation
self.auth = auth
self.timeout = timeout
self._wsman: WSMan | None = None
self._pool: RunspacePool | None = None
def __repr__(self) -> str:
scheme = "https" if self.ssl else "http"
return f"<PsrpTransport {self.username}@{scheme}://{self.host}:{self.port}>"
@property
def is_open(self) -> bool:
return self._pool is not None
def open(self) -> None:
# encryption="auto" gives message-level encryption on plain HTTP when
# the auth protocol supports it (NTLM/Kerberos), so 5985 does not mean
# credentials or output travel in the clear.
self._wsman = WSMan(
self.host,
port=self.port,
username=self.username,
password=self._password,
ssl=self.ssl,
auth=self.auth,
cert_validation=self.cert_validation,
connection_timeout=self.timeout,
read_timeout=self.timeout,
operation_timeout=max(self.timeout - 10, 20),
encryption="auto",
)
pool = RunspacePool(self._wsman)
try:
pool.open()
except AuthenticationError as exc:
self._drop()
raise ConnectionException(f"Authentication failed for {self.username}: {exc}") from exc
except WinRMTransportError as exc:
self._drop()
if exc.code == 401:
raise ConnectionException(
f"Authentication failed for {self.username}: HTTP 401"
) from exc
raise ConnectionException(f"WinRM error from {self.host}:{self.port}: {exc}") from exc
except (requests.RequestException, WinRMError, OSError) as exc:
self._drop()
raise ConnectionException(
f"Cannot reach WinRM on {self.host}:{self.port}: {exc}"
) from exc
self._pool = pool
def run(self, script: str) -> str:
if self._pool is None:
raise ConnectionClosedException("WinRM connection is not open")
ps = PowerShell(self._pool)
ps.add_script(script)
output = ps.invoke()
if ps.had_errors:
message = "; ".join(str(e) for e in ps.streams.error).strip()
raise PowerShellError(message or "PowerShell reported an error")
return "\n".join(str(o) for o in output if o is not None)
def run_streaming(
self, script: str, on_output: Callable[[str], None], *, limit: float
) -> list[str]:
"""Run a long script, handing each output object to *on_output* as it arrives.
For a run that takes minutes: the pipeline is started and polled, each poll
waiting at most ``_POLL_SECONDS`` (and less than a read of the connection), so
output reaches the caller while the host still works. A script still running
after *limit* seconds is stopped (Ctrl+C to the pipeline) and raises
:class:`TimeoutError`. An error the script wrote raises :class:`PowerShellError`
once it ended, after its output was passed on.
:returns: Every output object, as text, in order.
"""
if self._pool is None:
raise ConnectionClosedException("WinRM connection is not open")
ps = PowerShell(self._pool)
ps.add_script(script)
poll = min(_POLL_SECONDS, max(self.timeout // 2, 1))
deadline = time.monotonic() + limit
taken, out = 0, []
ps.begin_invoke()
while ps.state == PSInvocationState.RUNNING:
if time.monotonic() > deadline:
self._stop(ps)
raise TimeoutError(f"The script did not end within {int(limit)} seconds")
ps.poll_invoke(timeout=poll)
arrived, taken = ps.output[taken:], len(ps.output)
for item in arrived:
if item is not None:
out.append(str(item))
on_output(out[-1])
if ps.had_errors:
message = "; ".join(str(e) for e in ps.streams.error).strip()
raise PowerShellError(message or "PowerShell reported an error")
return out
def _stop(self, ps: PowerShell) -> None:
try:
ps.stop()
except Exception: # a pipeline that ended meanwhile has nothing to stop
logger.debug("Stopping a pipeline on %s failed", self.host, exc_info=True)
def run_last(self, script: str) -> bool:
"""Run a script after which the host may stop answering: a restart, a shutdown.
True when the script finished. False when the connection broke before the
answer came, which for such a script means the host went down first; the
transport is closed then. An error the script wrote still raises
:class:`PowerShellError`: the host answered, and refused.
"""
try:
self.run(script)
except (requests.RequestException, WinRMError, OSError) as exc:
logger.debug("Connection to %s broke during its last script: %s", self.host, exc)
self._drop()
return False
return True
def close(self) -> None:
if self._pool is not None:
try:
self._pool.close()
except Exception: # a dead connection is closed enough
logger.debug("Closing runspace pool on %s failed", self.host, exc_info=True)
self._drop()
def _drop(self) -> None:
if self._wsman is not None:
try:
self._wsman.close()
except Exception:
logger.debug("Closing WSMan session on %s failed", self.host, exc_info=True)
self._wsman = None
self._pool = None