Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
975eecf0cc |
No files matched your search
+14
-9
@@ -7,15 +7,20 @@ All notable changes to this driver. The format follows
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- The security posture as napalm-device-types' hardening reading (NetOrk/netork#2893):
|
||||
`get_hardening()` reads, in one script, whether Secure Boot is on (or unsupported on a
|
||||
BIOS boot), the TPM, BitLocker's protection per volume, Microsoft Defender (real-time
|
||||
protection, its running mode, the signatures' age), whether each firewall profile is on,
|
||||
and virtualization-based security. Each part is read on its own: a part that fails, or a
|
||||
cmdlet the host does not have, is reported as not read, and a server without the
|
||||
BitLocker feature as not installed. BitLocker is read through `Win32_EncryptableVolume`,
|
||||
never `Get-BitLockerVolume`, so no recovery password or key protector is read. Nothing on
|
||||
the host is changed.
|
||||
- The host firewall (NetOrk/netork#2894): `get_host_firewall` returns the Windows
|
||||
Firewall under `windows` (napalm-device-types' `WindowsFirewallDict`), with `sources`
|
||||
`["windows-firewall"]` and no netfilter chains. It reads the three profiles as the
|
||||
firewall applies them (on or off, default inbound and outbound action, "block all
|
||||
incoming connections", whether local rules apply), every enabled rule of the active
|
||||
policy with its ports, addresses, program, service, interfaces and where it comes from
|
||||
(group policy included), and the profile each connected interface is in. The filters
|
||||
are read in bulk, one cmdlet per kind, so a host with hundreds of rules answers in one
|
||||
script rather than one query per rule. Nothing is written.
|
||||
- Windows features (NetOrk/netork#2898): `get_windows_features` lists every optional
|
||||
feature of the host's image with its state (enabled, disabled, absent, unknown) from
|
||||
`Win32_OptionalFeature`, under the names Windows uses on clients and servers alike
|
||||
(`SMB1Protocol`, `MSMQ-Server`, `IIS-WebServerRole`, `Microsoft-Hyper-V`). It is what
|
||||
a CVE that needs a role or feature is held against.
|
||||
- Restarting and shutting the host down (NetOrk/netork#2841): `reboot_host()` and
|
||||
`shutdown_host()` from napalm-device-types' `HostRebootMixin` and `HostShutdownMixin`
|
||||
run `Restart-Computer` and `Stop-Computer` over the PSRP connection, neither with
|
||||
|
||||
@@ -42,8 +42,9 @@ handshake once.
|
||||
| `get_scheduled_jobs` | `Get-ScheduledTask` + `Get-ScheduledTaskInfo`, one script; `\Microsoft\*` is `platform`, other tasks `admin`, the root task an application wrote `application`; time zone mapped to IANA for the common zones |
|
||||
| `manage_scheduled_job` | `Enable-`/`Disable-ScheduledTask`, `Start-ScheduledTask` (returns once started; the result shows in the next reading) |
|
||||
| `put_scheduled_job` / `delete_scheduled_job` | `Register-ScheduledTask -Xml -Force` in the root folder, `Unregister-ScheduledTask`; an application's tasks only |
|
||||
| `get_hardening` | The security posture: `Confirm-SecureBootUEFI`, `Win32_Tpm`, `Win32_EncryptableVolume` (BitLocker, never `Get-BitLockerVolume`), `Get-MpComputerStatus`, `Get-NetFirewallProfile -PolicyStore ActiveStore`, `Win32_DeviceGuard`. See *Security posture* |
|
||||
| `get_time_sync` / `configure_time_sync` | w32time's registry values (group policy first), `w32tm /query /status`, the registry's `TimeZoneInformation`; writes `NtpServer`/`Type` + `w32tm /config /update`, `Set-TimeZone`. See *Time sync* |
|
||||
| `get_host_firewall` | The Windows Firewall under `windows` (no netfilter chains): the profiles' settings in force from `HNetCfg.FwPolicy2`, `AllowLocalFirewallRules` from `Get-NetFirewallProfile`, the enabled rules of `Get-NetFirewallRule -PolicyStore ActiveStore` with every filter read in bulk and joined on `InstanceID`, and `Get-NetConnectionProfile`. See *Host firewall* |
|
||||
| `get_windows_features` | `Win32_OptionalFeature`: every optional feature of the image with its state, under DISM's names (`SMB1Protocol`, `MSMQ-Server`), a server's roles included |
|
||||
|
||||
`running_kernel` carries the full build including the update revision
|
||||
(`10.0.20348.2340`): Windows ships fixes as UBR bumps, which is what CVE
|
||||
@@ -98,35 +99,25 @@ napalm-device-types' `TimeSyncMixin`; both the servers and the zone are written.
|
||||
zone with summer time switched off reads as `None`; writing the zone switches it
|
||||
back on.
|
||||
|
||||
### Security posture
|
||||
### Host firewall
|
||||
|
||||
`get_hardening` fills the posture keys of napalm-device-types' `HardeningDict`
|
||||
(NetOrk/netork#2893); what only a Linux kernel reports (security modules, crypto policy,
|
||||
CPU vulnerabilities, command line) is `None`. One read-only script; each part is caught on
|
||||
its own, and a part that failed, or a cmdlet the host lacks (probed with `Get-Command`),
|
||||
is `None`: not read, never off. Most parts need an administrator.
|
||||
What the exposure chain holds a listening socket against (netork#2894). Read only: no
|
||||
rule is ever written.
|
||||
|
||||
* **Secure Boot:** `Confirm-SecureBootUEFI`; on a BIOS boot it throws
|
||||
`PlatformNotSupportedException`, which reads `unsupported`, not `off`.
|
||||
* **TPM:** `Win32_Tpm` (`root\cimv2\Security\MicrosoftTpm`): present, enabled, activated,
|
||||
owned, the specification's version and the manufacturer's ID.
|
||||
* **BitLocker:** `Win32_EncryptableVolume` (`root\cimv2\Security\MicrosoftVolumeEncryption`)
|
||||
for each volume with a drive letter: protection (`on`, `off` -- also while suspended --
|
||||
or `unknown`), conversion status and cipher; the OS volume is `system`. Never
|
||||
`Get-BitLockerVolume`, whose objects carry the key protectors and recovery passwords:
|
||||
the class's properties hold no secret. Where the class is missing the BitLocker feature
|
||||
is not installed (Windows Server's default), reported as `installed: false`.
|
||||
* **Defender:** `Get-MpComputerStatus`: engine and service, real-time protection, the
|
||||
running mode (`Passive Mode`, `EDR Block Mode`: another product protects the host), the
|
||||
signatures' date, age and version, tamper protection. Missing on Server Core without
|
||||
the feature, and throwing where Defender is switched off for another product: `None`,
|
||||
since no other product is judged.
|
||||
* **Firewall profiles:** `Get-NetFirewallProfile -PolicyStore ActiveStore`, each profile on
|
||||
or off after group policy. The rules are the host firewall reading's.
|
||||
* **VBS:** `Win32_DeviceGuard` (`root\Microsoft\Windows\DeviceGuard`): off, configured or
|
||||
running, and the services it runs (`credential_guard`, `hvci`, ...).
|
||||
|
||||
Nothing is changed on the host: no signature update, no scan, no setting.
|
||||
* **Profiles:** on or off, the default inbound and outbound action and "block all
|
||||
incoming connections" as the firewall applies them (`HNetCfg.FwPolicy2`, group
|
||||
policy over local), and whether group policy lets local rules apply.
|
||||
* **Rules:** every enabled rule of the active policy (`ActiveStore`, local and group
|
||||
policy merged), inbound and outbound, each with where it comes from (`local`,
|
||||
`group_policy`, `dynamic`, ...). Its filters -- ports, addresses, program, service,
|
||||
app package, interfaces, interface types, IPsec -- are read with one cmdlet per
|
||||
filter kind (`Get-NetFirewallPortFilter -All`, ...) and joined on the rule's
|
||||
`InstanceID`: one filter query per rule takes minutes on a few hundred rules.
|
||||
Addresses become CIDRs (a mask as its prefix, a range as the networks covering it);
|
||||
Windows' keywords (`LocalSubnet`, `RPC`) are kept in lower case. A block rule whose
|
||||
filters did not all come back is left out rather than read as blocking everything.
|
||||
* **Connections:** the profile of each connected interface, from its network's category
|
||||
(`DomainAuthenticated` is the domain profile); None where that could not be read.
|
||||
|
||||
Not yet: packages, Windows Update, health metrics, Hyper-V.
|
||||
See netork#300 for the plan.
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
"""The Windows Firewall: profiles, rules and the profile of each connection (NetOrk/netork#2894).
|
||||
|
||||
:class:`WindowsHostFirewallMixin` gives the driver ``get_host_firewall``, the getter a
|
||||
Linux driver answers with netfilter chains. A Windows host answers with napalm-device-types'
|
||||
``WindowsFirewallDict`` under ``windows``, ``sources`` ``["windows-firewall"]`` and no
|
||||
chains: its rules belong to profiles, and match a program and a service as well as ports
|
||||
and addresses, which chains have no place for. Whether a socket is reachable is the
|
||||
consumer's call; nothing here judges it, and nothing here writes a rule.
|
||||
|
||||
**One script, no per-rule queries.** ``Get-NetFirewallRule | Get-NetFirewallPortFilter``
|
||||
asks the firewall once per rule and takes minutes for a few hundred rules. So every filter
|
||||
kind is read in bulk (``Get-Net*Filter -All -PolicyStore ActiveStore``), only the enabled
|
||||
rules' filters leave the host, and the join on the rule's ``InstanceID`` is done here.
|
||||
|
||||
- **The active policy** (``ActiveStore``): what the host applies, local rules and group
|
||||
policy's merged. Each rule says where it comes from (``PolicyStoreSourceType``: local,
|
||||
group policy, a service's dynamic rule, ...). Only enabled rules are read.
|
||||
- **The profiles' settings in force** come from the firewall's COM object
|
||||
(``HNetCfg.FwPolicy2``), which answers with the effective value where
|
||||
``Get-NetFirewallProfile`` would say ``NotConfigured``: on or off, the default inbound and
|
||||
outbound action, "block all incoming connections". Whether group policy lets local rules
|
||||
apply (``AllowLocalFirewallRules``) only ``Get-NetFirewallProfile`` says;
|
||||
``NotConfigured`` there is the default, which lets them.
|
||||
- **The profile of each connected interface** is its network's category
|
||||
(``Get-NetConnectionProfile``): ``DomainAuthenticated`` is the domain profile. Where that
|
||||
cannot be read, ``connections`` is None -- not "no interface is connected".
|
||||
|
||||
**A filter that was not read never widens a block.** Every rule has every filter, so one
|
||||
missing from the bulk read is a reading that went wrong. An allow rule keeps "any" for it,
|
||||
which can only make more reachable; a block rule without one is left out, since "any"
|
||||
would have it block everything.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import json
|
||||
import re
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import WINDOWS_FIREWALL_PROFILES
|
||||
from napalm_device_types.host_firewall_models import (
|
||||
WindowsFirewallConnectionDict,
|
||||
WindowsFirewallProfileDict,
|
||||
WindowsFirewallRuleDict,
|
||||
)
|
||||
from napalm_device_types.models import HostFirewallDict
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
|
||||
SOURCE = "windows-firewall"
|
||||
|
||||
# The COM object's profile types (NET_FW_PROFILE_TYPE2) and actions (NET_FW_ACTION).
|
||||
_PS_HOST_FIREWALL = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$store = 'ActiveStore'
|
||||
$fw = New-Object -ComObject HNetCfg.FwPolicy2
|
||||
$local = @{}
|
||||
try {
|
||||
foreach ($p in @(Get-NetFirewallProfile -PolicyStore $store)) {
|
||||
$local[([string]$p.Name).ToLower()] = [string]$p.AllowLocalFirewallRules
|
||||
}
|
||||
} catch { }
|
||||
$types = @{ domain = 1; private = 2; public = 4 }
|
||||
$profiles = @(foreach ($name in @('domain', 'private', 'public')) {
|
||||
$t = $types[$name]
|
||||
[pscustomobject]@{
|
||||
name = $name
|
||||
enabled = [bool]$fw.FirewallEnabled($t)
|
||||
default_inbound = [int]$fw.DefaultInboundAction($t)
|
||||
default_outbound = [int]$fw.DefaultOutboundAction($t)
|
||||
block_all_inbound = [bool]$fw.BlockAllInboundTraffic($t)
|
||||
local_rules = $local[$name]
|
||||
}
|
||||
})
|
||||
$rules = @(Get-NetFirewallRule -PolicyStore ActiveStore -Enabled True)
|
||||
$ids = @{}
|
||||
foreach ($r in $rules) { $ids[[string]$r.InstanceID] = $true }
|
||||
function Of($items) { @($items | Where-Object { $ids.ContainsKey([string]$_.InstanceID) }) }
|
||||
function AsStrings($values) { @($values | ForEach-Object { [string]$_ }) }
|
||||
$pf = Of (Get-NetFirewallPortFilter -All -PolicyStore ActiveStore)
|
||||
$af = Of (Get-NetFirewallAddressFilter -All -PolicyStore ActiveStore)
|
||||
$apf = Of (Get-NetFirewallApplicationFilter -All -PolicyStore ActiveStore)
|
||||
$sf = Of (Get-NetFirewallServiceFilter -All -PolicyStore ActiveStore)
|
||||
$if_ = Of (Get-NetFirewallInterfaceFilter -All -PolicyStore ActiveStore)
|
||||
$itf = Of (Get-NetFirewallInterfaceTypeFilter -All -PolicyStore ActiveStore)
|
||||
$sec = Of (Get-NetFirewallSecurityFilter -All -PolicyStore ActiveStore)
|
||||
$connections = $null
|
||||
try {
|
||||
$connections = @(Get-NetConnectionProfile | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
interface = [string]$_.InterfaceAlias
|
||||
category = [string]$_.NetworkCategory
|
||||
}
|
||||
})
|
||||
} catch { $connections = $null }
|
||||
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
|
||||
profiles = $profiles
|
||||
rules = @($rules | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
id = [string]$_.InstanceID
|
||||
name = [string]$_.DisplayName
|
||||
group = [string]$_.DisplayGroup
|
||||
direction = [string]$_.Direction
|
||||
action = [string]$_.Action
|
||||
profile = [string]$_.Profile
|
||||
source = [string]$_.PolicyStoreSourceType
|
||||
}
|
||||
})
|
||||
ports = @($pf | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
id = [string]$_.InstanceID; protocol = [string]$_.Protocol
|
||||
local = @(AsStrings $_.LocalPort); remote = @(AsStrings $_.RemotePort)
|
||||
}
|
||||
})
|
||||
addresses = @($af | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
id = [string]$_.InstanceID
|
||||
local = @(AsStrings $_.LocalAddress); remote = @(AsStrings $_.RemoteAddress)
|
||||
}
|
||||
})
|
||||
applications = @($apf | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
id = [string]$_.InstanceID; program = [string]$_.Program; package = [string]$_.Package
|
||||
}
|
||||
})
|
||||
services = @($sf | ForEach-Object {
|
||||
[pscustomobject]@{ id = [string]$_.InstanceID; service = [string]$_.Service }
|
||||
})
|
||||
interfaces = @($if_ | ForEach-Object {
|
||||
[pscustomobject]@{ id = [string]$_.InstanceID; aliases = @(AsStrings $_.InterfaceAlias) }
|
||||
})
|
||||
interface_types = @($itf | ForEach-Object {
|
||||
[pscustomobject]@{ id = [string]$_.InstanceID; types = [string]$_.InterfaceType }
|
||||
})
|
||||
security = @($sec | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
id = [string]$_.InstanceID; authentication = [string]$_.Authentication
|
||||
override_block = [bool]$_.OverrideBlockRules
|
||||
}
|
||||
})
|
||||
connections = $connections
|
||||
})
|
||||
"""
|
||||
|
||||
#: NET_FW_ACTION: what the COM object answers for a default action.
|
||||
_ACTIONS = {0: "block", 1: "allow"}
|
||||
_CATEGORIES = {"domainauthenticated": "domain", "private": "private", "public": "public"}
|
||||
_PROTOCOLS = {"6": "tcp", "17": "udp", "1": "icmpv4", "58": "icmpv6"}
|
||||
_ANY = "any"
|
||||
_CAMEL = re.compile(r"(?<=[a-z])(?=[A-Z])")
|
||||
|
||||
#: The filter kinds a rule's matching depends on: a block rule without one is left out.
|
||||
_REQUIRED = ("ports", "addresses", "applications", "services")
|
||||
|
||||
|
||||
def _snake(value: str) -> str:
|
||||
"""``GroupPolicy`` -> ``group_policy``, ``RemoteAccess`` -> ``remote_access``."""
|
||||
return _CAMEL.sub("_", value.strip()).lower()
|
||||
|
||||
|
||||
def _flags(value: Any) -> list[str] | None:
|
||||
"""An enum of flags as PowerShell prints it (``Domain, Private``); None for ``Any``."""
|
||||
names = [_snake(v) for v in str(value or "").split(",") if v.strip()]
|
||||
if not names or _ANY in names:
|
||||
return None
|
||||
return names
|
||||
|
||||
|
||||
def _profiles(value: Any) -> list[str] | None:
|
||||
names = _flags(value)
|
||||
if names is None:
|
||||
return None
|
||||
known: list[str] = [n for n in WINDOWS_FIREWALL_PROFILES if n in names]
|
||||
return known or None
|
||||
|
||||
|
||||
def _protocol(value: Any) -> str | None:
|
||||
text = str(value or "").strip().lower()
|
||||
if not text or text == _ANY:
|
||||
return None
|
||||
return _PROTOCOLS.get(text, text)
|
||||
|
||||
|
||||
def _values(value: Any) -> list[str] | None:
|
||||
"""A filter's list as Windows prints it; None for ``Any`` (or nothing)."""
|
||||
values = [str(v).strip() for v in _as_list(value) if str(v).strip()]
|
||||
if not values or any(v.lower() == _ANY for v in values):
|
||||
return None
|
||||
return values
|
||||
|
||||
|
||||
def _ports(value: Any) -> list[str] | None:
|
||||
values = _values(value)
|
||||
return None if values is None else [v.lower() for v in values]
|
||||
|
||||
|
||||
def _address(text: str) -> list[str]:
|
||||
"""One address entry as CIDRs: a mask (``10.0.0.0/255.0.0.0``) as its prefix, a range
|
||||
as the networks that cover it, a single address as a host route; a keyword lowered."""
|
||||
low, sep, high = text.partition("-")
|
||||
try:
|
||||
if sep:
|
||||
first, last = ipaddress.ip_address(low.strip()), ipaddress.ip_address(high.strip())
|
||||
return [str(n) for n in ipaddress.summarize_address_range(first, last)]
|
||||
return [str(ipaddress.ip_network(text, strict=False))]
|
||||
except (TypeError, ValueError):
|
||||
return [text.lower()]
|
||||
|
||||
|
||||
def _addresses(value: Any) -> list[str] | None:
|
||||
values = _values(value)
|
||||
if values is None:
|
||||
return None
|
||||
return [cidr for v in values for cidr in _address(v)]
|
||||
|
||||
|
||||
def _named(value: Any) -> str | None:
|
||||
"""A program, package or service as named; None for ``Any`` or nothing."""
|
||||
text = str(value or "").strip()
|
||||
return None if not text or text.lower() == _ANY else text
|
||||
|
||||
|
||||
def _by_id(raw: dict[str, Any], kind: str) -> dict[str, dict[str, Any]]:
|
||||
return {str(f.get("id")): f for f in _as_list(raw.get(kind)) if isinstance(f, dict)}
|
||||
|
||||
|
||||
class _Filters:
|
||||
"""The bulk-read filters of every kind, by rule id."""
|
||||
|
||||
def __init__(self, raw: dict[str, Any]) -> None:
|
||||
self.kinds = {
|
||||
kind: _by_id(raw, kind)
|
||||
for kind in (*_REQUIRED, "interfaces", "interface_types", "security")
|
||||
}
|
||||
|
||||
def complete(self, rule_id: str) -> bool:
|
||||
return all(rule_id in self.kinds[kind] for kind in _REQUIRED)
|
||||
|
||||
def of(self, rule_id: str, kind: str) -> dict[str, Any]:
|
||||
return self.kinds[kind].get(rule_id) or {}
|
||||
|
||||
|
||||
def _rule(rule: dict[str, Any], filters: _Filters) -> WindowsFirewallRuleDict:
|
||||
rule_id = str(rule.get("id") or "")
|
||||
ports, addresses = filters.of(rule_id, "ports"), filters.of(rule_id, "addresses")
|
||||
application, security = filters.of(rule_id, "applications"), filters.of(rule_id, "security")
|
||||
source = _snake(str(rule.get("source") or ""))
|
||||
return {
|
||||
"id": rule_id,
|
||||
"name": str(rule.get("name") or rule_id),
|
||||
"group": str(rule.get("group") or "") or None,
|
||||
"direction": str(rule.get("direction") or "").lower(),
|
||||
"action": str(rule.get("action") or "").lower(),
|
||||
"profiles": _profiles(rule.get("profile")),
|
||||
"protocol": _protocol(ports.get("protocol")),
|
||||
"local_ports": _ports(ports.get("local")),
|
||||
"remote_ports": _ports(ports.get("remote")),
|
||||
"local_addresses": _addresses(addresses.get("local")),
|
||||
"remote_addresses": _addresses(addresses.get("remote")),
|
||||
"program": _named(application.get("program")),
|
||||
"service": _named(filters.of(rule_id, "services").get("service")),
|
||||
"package": _named(application.get("package")),
|
||||
"interfaces": _values(filters.of(rule_id, "interfaces").get("aliases")),
|
||||
"interface_types": _flags(filters.of(rule_id, "interface_types").get("types")),
|
||||
"authenticated": str(security.get("authentication") or "notrequired").lower()
|
||||
!= "notrequired",
|
||||
"override_block": bool(security.get("override_block")),
|
||||
"source": source or None,
|
||||
}
|
||||
|
||||
|
||||
def _rules(raw: dict[str, Any]) -> list[WindowsFirewallRuleDict]:
|
||||
filters = _Filters(raw)
|
||||
rules: list[WindowsFirewallRuleDict] = []
|
||||
for rule in _as_list(raw.get("rules")):
|
||||
if not isinstance(rule, dict):
|
||||
continue
|
||||
read = _rule(rule, filters)
|
||||
if read["action"] == "block" and not filters.complete(read["id"]):
|
||||
continue
|
||||
rules.append(read)
|
||||
return rules
|
||||
|
||||
|
||||
def _setting(value: Any) -> bool | None:
|
||||
"""``AllowLocalFirewallRules``: ``False`` only where group policy says so."""
|
||||
text = str(value or "").strip().lower()
|
||||
if text in ("true", "notconfigured"):
|
||||
return True
|
||||
return False if text == "false" else None
|
||||
|
||||
|
||||
def _bool(value: Any) -> bool | None:
|
||||
return value if isinstance(value, bool) else None
|
||||
|
||||
|
||||
def _profile(raw: dict[str, Any]) -> WindowsFirewallProfileDict:
|
||||
return {
|
||||
"name": str(raw.get("name") or ""),
|
||||
"enabled": _bool(raw.get("enabled")),
|
||||
"default_inbound": _ACTIONS.get(raw.get("default_inbound")), # type: ignore[arg-type]
|
||||
"default_outbound": _ACTIONS.get(raw.get("default_outbound")), # type: ignore[arg-type]
|
||||
"block_all_inbound": _bool(raw.get("block_all_inbound")),
|
||||
"local_rules": _setting(raw.get("local_rules")),
|
||||
}
|
||||
|
||||
|
||||
def _connections(value: Any) -> list[WindowsFirewallConnectionDict] | None:
|
||||
if value is None:
|
||||
return None
|
||||
found: list[WindowsFirewallConnectionDict] = []
|
||||
for entry in _as_list(value):
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
profile = _CATEGORIES.get(str(entry.get("category") or "").lower())
|
||||
if profile and entry.get("interface"):
|
||||
found.append({"interface": str(entry["interface"]), "profile": profile})
|
||||
return found
|
||||
|
||||
|
||||
def parse_host_firewall(raw: Any) -> HostFirewallDict:
|
||||
"""What ``_PS_HOST_FIREWALL`` emitted, joined and normalised.
|
||||
|
||||
:raises ValueError: when the reading came back empty or without the profiles.
|
||||
"""
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError("the firewall reading came back empty")
|
||||
profiles = [_profile(p) for p in _as_list(raw.get("profiles")) if isinstance(p, dict)]
|
||||
if not profiles:
|
||||
raise ValueError("the firewall reading has no profiles")
|
||||
return {
|
||||
"sources": [SOURCE],
|
||||
"chains": [],
|
||||
"windows": {
|
||||
"profiles": profiles,
|
||||
"rules": _rules(raw),
|
||||
"connections": _connections(raw.get("connections")),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class WindowsHostFirewallMixin:
|
||||
"""``get_host_firewall`` for a Windows host; the driver carries the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_raw(self, script: str) -> str: ...
|
||||
|
||||
def get_host_firewall(self) -> HostFirewallDict:
|
||||
"""The Windows Firewall's profiles, enabled rules and the profile of each
|
||||
connected interface, under ``windows``; see the module.
|
||||
|
||||
:raises ValueError: when the reading came back empty or without the profiles.
|
||||
"""
|
||||
out = self._run_raw(_PS_HOST_FIREWALL).strip()
|
||||
return parse_host_firewall(json.loads(out) if out else None)
|
||||
@@ -1,353 +0,0 @@
|
||||
"""A Windows host's security posture as the hardening reading (NetOrk/netork#2893).
|
||||
|
||||
:class:`WindowsPostureMixin` gives the driver napalm-device-types' ``get_hardening``,
|
||||
filled with the posture keys of ``HardeningDict``; what only a Linux kernel has (the
|
||||
security modules, the crypto policy, the CPU vulnerabilities, the command line) is
|
||||
``None``. One script, read-only, six parts, each caught on its own so one that fails
|
||||
leaves the others standing; a part that failed, or a cmdlet the host lacks, is ``None``:
|
||||
not read, never "off".
|
||||
|
||||
- **Secure Boot:** ``Confirm-SecureBootUEFI``. On a BIOS boot it throws
|
||||
``PlatformNotSupportedException``, which is ``unsupported``, not off.
|
||||
- **TPM:** ``Win32_Tpm`` in ``root\\cimv2\\Security\\MicrosoftTpm``; no instance is no TPM.
|
||||
- **BitLocker:** ``Win32_EncryptableVolume`` in
|
||||
``root\\cimv2\\Security\\MicrosoftVolumeEncryption``: protection, conversion status,
|
||||
cipher and volume type, per volume with a drive letter. Never ``Get-BitLockerVolume``,
|
||||
whose objects carry the key protectors with their recovery passwords: the CIM class's
|
||||
properties carry no secret. Where the class is missing, the BitLocker feature is not
|
||||
installed (Windows Server's default): ``installed`` False, not an error.
|
||||
- **Defender:** ``Get-MpComputerStatus``: the service and the engine, real-time
|
||||
protection, the running mode (``Passive Mode`` and ``EDR Block Mode`` when another
|
||||
product protects the host), the signatures' date, age and version, tamper protection.
|
||||
Missing on Server Core without the Defender feature; it throws where Defender is
|
||||
switched off for another product. Both are ``None``: no product is judged here.
|
||||
- **Firewall profiles:** ``Get-NetFirewallProfile -PolicyStore ActiveStore``, the
|
||||
effective state of each profile after group policy. On or off only: the rules are
|
||||
the host firewall reading's.
|
||||
- **VBS:** ``Win32_DeviceGuard`` in ``root\\Microsoft\\Windows\\DeviceGuard``: whether
|
||||
virtualization-based security runs, and which of its services.
|
||||
|
||||
The cmdlets are probed with ``Get-Command`` first, so a missing one is not read rather
|
||||
than an error. Most parts need an administrator; as another user they fail on their own.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.hardening import (
|
||||
AntimalwareDict,
|
||||
AntimalwareMode,
|
||||
DiskEncryptionDict,
|
||||
EncryptedVolumeDict,
|
||||
FirewallProfileDict,
|
||||
HardeningDict,
|
||||
SecureBootState,
|
||||
TpmDict,
|
||||
VbsDict,
|
||||
VbsStatus,
|
||||
VolumeProtection,
|
||||
)
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_PS_POSTURE = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function Has([string]$name) { [bool](Get-Command -Name $name -ErrorAction SilentlyContinue) }
|
||||
function Unix($when) {
|
||||
if ($when) { [int64]([datetimeoffset]$when).ToUnixTimeSeconds() } else { $null }
|
||||
}
|
||||
$errors = [ordered]@{}
|
||||
$secureBoot = $null
|
||||
if (Has 'Confirm-SecureBootUEFI') {
|
||||
try { $secureBoot = [string][bool](Confirm-SecureBootUEFI) }
|
||||
catch {
|
||||
if ($_.Exception -is [System.PlatformNotSupportedException] -or
|
||||
[string]$_.FullyQualifiedErrorId -like '*PlatformNotSupported*') {
|
||||
$secureBoot = 'unsupported'
|
||||
} else { $errors.secure_boot = [string]$_.Exception.Message }
|
||||
}
|
||||
}
|
||||
$tpm = $null
|
||||
try {
|
||||
$t = Get-CimInstance -Namespace 'root\cimv2\Security\MicrosoftTpm' -ClassName Win32_Tpm |
|
||||
Select-Object -First 1
|
||||
if ($t) {
|
||||
$tpm = [pscustomobject]@{
|
||||
present = $true
|
||||
enabled = $t.IsEnabled_InitialValue
|
||||
activated = $t.IsActivated_InitialValue
|
||||
owned = $t.IsOwned_InitialValue
|
||||
spec_version = [string]$t.SpecVersion
|
||||
manufacturer = [string]$t.ManufacturerIdTxt
|
||||
}
|
||||
} else { $tpm = [pscustomobject]@{ present = $false } }
|
||||
} catch { $errors.tpm = [string]$_.Exception.Message }
|
||||
$bitlocker = $null
|
||||
$bde = 'root\cimv2\Security\MicrosoftVolumeEncryption'
|
||||
$probe = @{
|
||||
Namespace = $bde; ClassName = 'Win32_EncryptableVolume'; ErrorAction = 'SilentlyContinue'
|
||||
}
|
||||
try {
|
||||
if (Get-CimClass @probe) {
|
||||
$bitlocker = [pscustomobject]@{
|
||||
installed = $true
|
||||
volumes = @(Get-CimInstance -Namespace $bde -ClassName Win32_EncryptableVolume |
|
||||
ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
drive = $_.DriveLetter
|
||||
volume_type = [string]$_.VolumeType
|
||||
protection = [string]$_.ProtectionStatus
|
||||
conversion = [string]$_.ConversionStatus
|
||||
method = [string]$_.EncryptionMethod
|
||||
}
|
||||
})
|
||||
}
|
||||
} else { $bitlocker = [pscustomobject]@{ installed = $false; volumes = @() } }
|
||||
} catch { $errors.bitlocker = [string]$_.Exception.Message }
|
||||
$defender = $null
|
||||
if (Has 'Get-MpComputerStatus') {
|
||||
try {
|
||||
$mp = Get-MpComputerStatus
|
||||
$defender = [pscustomobject]@{
|
||||
am_service = $mp.AMServiceEnabled
|
||||
antivirus = $mp.AntivirusEnabled
|
||||
real_time = $mp.RealTimeProtectionEnabled
|
||||
running_mode = [string]$mp.AMRunningMode
|
||||
signature_updated = Unix $mp.AntivirusSignatureLastUpdated
|
||||
signature_age = $mp.AntivirusSignatureAge
|
||||
signature_version = [string]$mp.AntivirusSignatureVersion
|
||||
tamper_protected = $mp.IsTamperProtected
|
||||
}
|
||||
} catch { $errors.defender = [string]$_.Exception.Message }
|
||||
}
|
||||
$firewall = $null
|
||||
if (Has 'Get-NetFirewallProfile') {
|
||||
try {
|
||||
$firewall = @(Get-NetFirewallProfile -PolicyStore ActiveStore | ForEach-Object {
|
||||
[pscustomobject]@{ name = [string]$_.Name; enabled = [string]$_.Enabled }
|
||||
})
|
||||
} catch { $errors.firewall = [string]$_.Exception.Message }
|
||||
}
|
||||
$vbs = $null
|
||||
try {
|
||||
$dg = Get-CimInstance -Namespace 'root\Microsoft\Windows\DeviceGuard' `
|
||||
-ClassName Win32_DeviceGuard | Select-Object -First 1
|
||||
if ($dg) {
|
||||
$vbs = [pscustomobject]@{
|
||||
status = [string]$dg.VirtualizationBasedSecurityStatus
|
||||
running = @($dg.SecurityServicesRunning | ForEach-Object { [string]$_ })
|
||||
}
|
||||
}
|
||||
} catch { $errors.vbs = [string]$_.Exception.Message }
|
||||
[pscustomobject]@{
|
||||
system_drive = $env:SystemDrive
|
||||
secure_boot = $secureBoot
|
||||
tpm = $tpm
|
||||
bitlocker = $bitlocker
|
||||
defender = $defender
|
||||
firewall = $firewall
|
||||
vbs = $vbs
|
||||
errors = $errors
|
||||
} | ConvertTo-Json -Compress -Depth 5
|
||||
"""
|
||||
|
||||
_SECURE_BOOT: dict[str, SecureBootState] = {
|
||||
"true": "on",
|
||||
"false": "off",
|
||||
"unsupported": "unsupported",
|
||||
}
|
||||
#: Win32_EncryptableVolume.ProtectionStatus
|
||||
_PROTECTION: dict[str, VolumeProtection] = {"0": "off", "1": "on", "2": "unknown"}
|
||||
#: Win32_EncryptableVolume.ConversionStatus
|
||||
_CONVERSION = {
|
||||
"0": "fully_decrypted",
|
||||
"1": "fully_encrypted",
|
||||
"2": "encrypting",
|
||||
"3": "decrypting",
|
||||
"4": "encryption_paused",
|
||||
"5": "decryption_paused",
|
||||
}
|
||||
#: Win32_EncryptableVolume.EncryptionMethod; 0 is none.
|
||||
_CIPHER = {
|
||||
"1": "aes_128_diffuser",
|
||||
"2": "aes_256_diffuser",
|
||||
"3": "aes_128",
|
||||
"4": "aes_256",
|
||||
"5": "hardware",
|
||||
"6": "xts_aes_128",
|
||||
"7": "xts_aes_256",
|
||||
}
|
||||
#: Win32_EncryptableVolume.VolumeType: the volume the OS runs from.
|
||||
_OS_VOLUME = "0"
|
||||
#: MSFT_MpComputerStatus.AMRunningMode
|
||||
_MODES: dict[str, AntimalwareMode] = {
|
||||
"normal": "active",
|
||||
"passive mode": "passive",
|
||||
"passive": "passive",
|
||||
"edr block mode": "edr_block",
|
||||
"sxs passive mode": "sxs_passive",
|
||||
}
|
||||
#: Win32_DeviceGuard.VirtualizationBasedSecurityStatus
|
||||
_VBS_STATUS: dict[str, VbsStatus] = {"0": "off", "1": "configured", "2": "running"}
|
||||
#: Win32_DeviceGuard.SecurityServicesRunning; 0 is none.
|
||||
_VBS_SERVICES = {
|
||||
"1": "credential_guard",
|
||||
"2": "hvci",
|
||||
"3": "system_guard",
|
||||
"4": "smm_firmware_measurement",
|
||||
"5": "kernel_shadow_stacks",
|
||||
"6": "kernel_shadow_stacks_audit",
|
||||
"7": "hypervisor_paging_translation",
|
||||
}
|
||||
_GPO_BOOLEAN = {"true": True, "false": False}
|
||||
|
||||
|
||||
def _text(value: Any) -> str | None:
|
||||
text = str(value).strip() if value is not None else ""
|
||||
return text or None
|
||||
|
||||
|
||||
def _flag(value: Any) -> bool | None:
|
||||
return value if isinstance(value, bool) else None
|
||||
|
||||
|
||||
def _number(value: Any) -> int | None:
|
||||
return int(value) if isinstance(value, int | float) and not isinstance(value, bool) else None
|
||||
|
||||
|
||||
def _secure_boot(value: Any) -> SecureBootState | None:
|
||||
return _SECURE_BOOT.get(str(value).lower()) if value is not None else None
|
||||
|
||||
|
||||
def _tpm_version(spec: Any) -> str | None:
|
||||
"""``SpecVersion`` is ``"2.0, 0, 1.59"``: the specification's version comes first."""
|
||||
return _text(str(spec or "").split(",", 1)[0])
|
||||
|
||||
|
||||
def _tpm(raw: Any) -> TpmDict | None:
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
return {
|
||||
"present": bool(raw.get("present")),
|
||||
"enabled": _flag(raw.get("enabled")),
|
||||
"activated": _flag(raw.get("activated")),
|
||||
"owned": _flag(raw.get("owned")),
|
||||
"version": _tpm_version(raw.get("spec_version")),
|
||||
"manufacturer": _text(raw.get("manufacturer")),
|
||||
}
|
||||
|
||||
|
||||
def _volume(raw: dict[str, Any], system_drive: str) -> EncryptedVolumeDict | None:
|
||||
drive = _text(raw.get("drive"))
|
||||
if drive is None:
|
||||
return None # a recovery or boot partition: nothing is stored on it
|
||||
return {
|
||||
"volume": drive,
|
||||
"system": str(raw.get("volume_type")) == _OS_VOLUME or drive.upper() == system_drive,
|
||||
"protection": _PROTECTION.get(str(raw.get("protection")), "unknown"),
|
||||
"status": _CONVERSION.get(str(raw.get("conversion"))),
|
||||
"method": _CIPHER.get(str(raw.get("method"))),
|
||||
}
|
||||
|
||||
|
||||
def _disk_encryption(raw: Any, system_drive: str) -> DiskEncryptionDict | None:
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
volumes = [
|
||||
volume
|
||||
for item in _as_list(raw.get("volumes"))
|
||||
if isinstance(item, dict) and (volume := _volume(item, system_drive)) is not None
|
||||
]
|
||||
return {"provider": "bitlocker", "installed": bool(raw.get("installed")), "volumes": volumes}
|
||||
|
||||
|
||||
def _antimalware(raw: Any) -> AntimalwareDict | None:
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
service, engine = _flag(raw.get("am_service")), _flag(raw.get("antivirus"))
|
||||
return {
|
||||
"product": "Microsoft Defender Antivirus",
|
||||
"enabled": False if service is False else engine,
|
||||
"real_time": _flag(raw.get("real_time")),
|
||||
"mode": _MODES.get(str(raw.get("running_mode") or "").strip().lower()),
|
||||
"signatures_updated": _number(raw.get("signature_updated")),
|
||||
"signature_age_days": _number(raw.get("signature_age")),
|
||||
"signature_version": _text(raw.get("signature_version")),
|
||||
"tamper_protected": _flag(raw.get("tamper_protected")),
|
||||
}
|
||||
|
||||
|
||||
def _firewall_profiles(raw: Any) -> list[FirewallProfileDict] | None:
|
||||
if raw is None:
|
||||
return None
|
||||
return [
|
||||
{
|
||||
"name": str(item.get("name") or "").lower(),
|
||||
"enabled": _GPO_BOOLEAN.get(str(item.get("enabled")).lower()),
|
||||
}
|
||||
for item in _as_list(raw)
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
|
||||
|
||||
def _vbs(raw: Any) -> VbsDict | None:
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
running = [str(code) for code in _as_list(raw.get("running")) if str(code) != "0"]
|
||||
return {
|
||||
"status": _VBS_STATUS.get(str(raw.get("status"))),
|
||||
"running": [_VBS_SERVICES.get(code, f"service_{code}") for code in running],
|
||||
}
|
||||
|
||||
|
||||
def parse_posture(raw: dict[str, Any]) -> HardeningDict:
|
||||
"""The hardening reading from what :data:`_PS_POSTURE` emitted."""
|
||||
for part, error in (raw.get("errors") or {}).items():
|
||||
logger.info("posture: %s not read: %s", part, error)
|
||||
system_drive = str(raw.get("system_drive") or "C:").upper()
|
||||
reading: HardeningDict = {
|
||||
"lsm": None,
|
||||
"selinux": None,
|
||||
"apparmor": None,
|
||||
"crypto_policy": None,
|
||||
"fips": None,
|
||||
"cpu_vulnerabilities": None,
|
||||
"cmdline": None,
|
||||
"mitigations": None,
|
||||
"nosmt": None,
|
||||
"os_ids": None,
|
||||
"virtualization": None,
|
||||
"cpu_vendor": None,
|
||||
"secure_boot": _secure_boot(raw.get("secure_boot")),
|
||||
"tpm": _tpm(raw.get("tpm")),
|
||||
"disk_encryption": _disk_encryption(raw.get("bitlocker"), system_drive),
|
||||
"antimalware": _antimalware(raw.get("defender")),
|
||||
"firewall_profiles": _firewall_profiles(raw.get("firewall")),
|
||||
"vbs": _vbs(raw.get("vbs")),
|
||||
}
|
||||
return reading
|
||||
|
||||
|
||||
class WindowsPostureMixin:
|
||||
"""``get_hardening`` for a Windows host: its security posture; the driver carries the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_raw(self, script: str) -> str: ...
|
||||
|
||||
def get_hardening(self) -> HardeningDict:
|
||||
"""Secure Boot, the TPM, BitLocker per volume, Defender, the firewall's profiles and
|
||||
virtualization-based security, in one round trip; see the module.
|
||||
|
||||
:raises ValueError: when the reading came back empty.
|
||||
"""
|
||||
out = self._run_raw(_PS_POSTURE).strip()
|
||||
raw = json.loads(out) if out else None
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError("the posture reading came back empty")
|
||||
return parse_posture(raw)
|
||||
@@ -27,10 +27,11 @@ from napalm_device_types import FingerprintRule, OSDriver, PortSpec
|
||||
from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict, ServiceDict
|
||||
|
||||
from napalm_windows._powershell import _as_list, _ps_quote
|
||||
from napalm_windows.posture import WindowsPostureMixin
|
||||
from napalm_windows.host_firewall import WindowsHostFirewallMixin
|
||||
from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin
|
||||
from napalm_windows.time_sync import WindowsTimeSyncMixin
|
||||
from napalm_windows.transport import PowerShellError, PsrpTransport
|
||||
from napalm_windows.windows_features import WindowsFeaturesMixin
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -262,7 +263,13 @@ def _is_noise_route(destination: str) -> bool:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, WindowsPostureMixin, OSDriver):
|
||||
class WindowsDriver(
|
||||
WindowsHostFirewallMixin,
|
||||
WindowsFeaturesMixin,
|
||||
WindowsScheduledJobsMixin,
|
||||
WindowsTimeSyncMixin,
|
||||
OSDriver,
|
||||
):
|
||||
"""NAPALM driver for Windows Server 2016+ and Windows 10/11.
|
||||
|
||||
``optional_args``:
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Windows optional features: which roles and features a host has on (NetOrk/netork#2898).
|
||||
|
||||
:class:`WindowsFeaturesMixin` implements napalm-device-types'
|
||||
:class:`~napalm_device_types.windows_features.WindowsFeaturesMixin`: the facts a CVE that
|
||||
needs a role or feature -- the DNS Server, Hyper-V, IIS, SMB 1.0, Message Queuing --
|
||||
is held against.
|
||||
|
||||
**One CIM query** (``Win32_OptionalFeature``), not ``Get-WindowsOptionalFeature -Online``,
|
||||
which loads the DISM module and takes far longer, and not Server Manager's
|
||||
``Get-WindowsFeature``, which a client has not. The class lists every feature the image
|
||||
knows, on a client and a server, under the names DISM gives them (``SMB1Protocol``,
|
||||
``MSMQ-Server``, ``IIS-WebServerRole``); a server's roles are among them under those
|
||||
names. ``InstallState`` is 1 enabled, 2 disabled, 3 absent (the payload removed),
|
||||
4 unknown. A pending change shows as the state the feature has now.
|
||||
|
||||
No feature at all is a reading that went wrong -- every image has features -- and raises
|
||||
rather than reading as a host with none.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import WindowsFeaturesMixin as _Contract
|
||||
from napalm_device_types.windows_features import WindowsFeatureDict, WindowsFeaturesDict
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
|
||||
_PS_WINDOWS_FEATURES = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
ConvertTo-Json -Compress -Depth 3 -InputObject @(
|
||||
Get-CimInstance -ClassName Win32_OptionalFeature | ForEach-Object {
|
||||
[pscustomobject]@{ name = [string]$_.Name; state = [int]$_.InstallState }
|
||||
}
|
||||
)
|
||||
"""
|
||||
|
||||
#: Win32_OptionalFeature's InstallState.
|
||||
_STATES = {1: "enabled", 2: "disabled", 3: "absent", 4: "unknown"}
|
||||
|
||||
|
||||
def parse_windows_features(raw: Any) -> WindowsFeaturesDict:
|
||||
"""What ``_PS_WINDOWS_FEATURES`` emitted, as names and states.
|
||||
|
||||
:raises ValueError: when no feature came back.
|
||||
"""
|
||||
features: list[WindowsFeatureDict] = []
|
||||
for entry in _as_list(raw):
|
||||
name = str(entry.get("name") or "").strip() if isinstance(entry, dict) else ""
|
||||
if name:
|
||||
features.append({"name": name, "state": _STATES.get(entry.get("state"), "unknown")})
|
||||
if not features:
|
||||
raise ValueError("the Windows features reading came back without features")
|
||||
return {"features": features}
|
||||
|
||||
|
||||
class WindowsFeaturesMixin(_Contract):
|
||||
"""``get_windows_features`` for a Windows host; the driver carries the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_raw(self, script: str) -> str: ...
|
||||
|
||||
def get_windows_features(self) -> WindowsFeaturesDict:
|
||||
"""Every optional feature of the host's image with its state; see the module.
|
||||
|
||||
:raises ValueError: when no feature came back.
|
||||
"""
|
||||
out = self._run_raw(_PS_WINDOWS_FEATURES).strip()
|
||||
return parse_windows_features(json.loads(out) if out else None)
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"profiles": [
|
||||
{"name": "domain", "enabled": true, "default_inbound": 0, "default_outbound": 1, "block_all_inbound": false, "local_rules": "NotConfigured"},
|
||||
{"name": "private", "enabled": true, "default_inbound": 0, "default_outbound": 1, "block_all_inbound": false, "local_rules": "True"},
|
||||
{"name": "public", "enabled": true, "default_inbound": 0, "default_outbound": 1, "block_all_inbound": false, "local_rules": "False"}
|
||||
],
|
||||
"rules": [
|
||||
{"id": "RemoteDesktop-UserMode-In-TCP", "name": "Remote Desktop - User Mode (TCP-In)", "group": "Remote Desktop", "direction": "Inbound", "action": "Allow", "profile": "Any", "source": "Local"},
|
||||
{"id": "FPS-SMB-In-TCP", "name": "File and Printer Sharing (SMB-In)", "group": "File and Printer Sharing", "direction": "Inbound", "action": "Allow", "profile": "Domain, Private", "source": "Local"},
|
||||
{"id": "WINRM-HTTP-In-TCP-PUBLIC", "name": "Windows Remote Management (HTTP-In)", "group": "Windows Remote Management", "direction": "Inbound", "action": "Allow", "profile": "Public", "source": "Local"},
|
||||
{"id": "{7A1D3F2E-0B4C-4C8E-9F61-2D5A8B3C1E90}", "name": "Line of business app", "group": "", "direction": "Inbound", "action": "Allow", "profile": "Public", "source": "Local"},
|
||||
{"id": "{0C4E2B7A-51D3-4E8F-A6B9-3F7D1C2E8A45}", "name": "Block SQL Server from the internet", "group": "", "direction": "Inbound", "action": "Block", "profile": "Public", "source": "GroupPolicy"},
|
||||
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "name": "Management subnets", "group": "", "direction": "Inbound", "action": "Allow", "profile": "Domain", "source": "GroupPolicy"},
|
||||
{"id": "{5B8D2F4A-1E3C-4A7B-9C6D-8E0F2A4B6C81}", "name": "Block an unread filter", "group": "", "direction": "Inbound", "action": "Block", "profile": "Any", "source": "Local"},
|
||||
{"id": "CoreNet-DNS-Out-UDP", "name": "Core Networking - DNS (UDP-Out)", "group": "Core Networking", "direction": "Outbound", "action": "Allow", "profile": "Any", "source": "Local"}
|
||||
],
|
||||
"ports": [
|
||||
{"id": "RemoteDesktop-UserMode-In-TCP", "protocol": "TCP", "local": ["3389"], "remote": ["Any"]},
|
||||
{"id": "FPS-SMB-In-TCP", "protocol": "TCP", "local": ["445"], "remote": ["Any"]},
|
||||
{"id": "WINRM-HTTP-In-TCP-PUBLIC", "protocol": "TCP", "local": ["5985"], "remote": ["Any"]},
|
||||
{"id": "{7A1D3F2E-0B4C-4C8E-9F61-2D5A8B3C1E90}", "protocol": "Any", "local": ["Any"], "remote": ["Any"]},
|
||||
{"id": "{0C4E2B7A-51D3-4E8F-A6B9-3F7D1C2E8A45}", "protocol": "6", "local": ["1433", "1434"], "remote": ["Any"]},
|
||||
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "protocol": "TCP", "local": ["RPC", "49152-65535"], "remote": ["Any"]},
|
||||
{"id": "{5B8D2F4A-1E3C-4A7B-9C6D-8E0F2A4B6C81}", "protocol": "TCP", "local": ["8080"], "remote": ["Any"]},
|
||||
{"id": "CoreNet-DNS-Out-UDP", "protocol": "UDP", "local": ["Any"], "remote": ["53"]}
|
||||
],
|
||||
"addresses": [
|
||||
{"id": "RemoteDesktop-UserMode-In-TCP", "local": ["Any"], "remote": ["Any"]},
|
||||
{"id": "FPS-SMB-In-TCP", "local": ["Any"], "remote": ["LocalSubnet"]},
|
||||
{"id": "WINRM-HTTP-In-TCP-PUBLIC", "local": ["Any"], "remote": ["LocalSubnet"]},
|
||||
{"id": "{7A1D3F2E-0B4C-4C8E-9F61-2D5A8B3C1E90}", "local": ["Any"], "remote": ["Any"]},
|
||||
{"id": "{0C4E2B7A-51D3-4E8F-A6B9-3F7D1C2E8A45}", "local": ["Any"], "remote": ["Any"]},
|
||||
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "local": ["Any"], "remote": ["10.0.0.0/255.0.0.0", "192.0.2.1-192.0.2.6", "2001:db8::/48", "198.51.100.7"]},
|
||||
{"id": "CoreNet-DNS-Out-UDP", "local": ["Any"], "remote": ["DNS"]}
|
||||
],
|
||||
"applications": [
|
||||
{"id": "RemoteDesktop-UserMode-In-TCP", "program": "%SystemRoot%\\system32\\svchost.exe", "package": ""},
|
||||
{"id": "FPS-SMB-In-TCP", "program": "System", "package": ""},
|
||||
{"id": "WINRM-HTTP-In-TCP-PUBLIC", "program": "System", "package": ""},
|
||||
{"id": "{7A1D3F2E-0B4C-4C8E-9F61-2D5A8B3C1E90}", "program": "C:\\Program Files\\Contoso\\lob.exe", "package": ""},
|
||||
{"id": "{0C4E2B7A-51D3-4E8F-A6B9-3F7D1C2E8A45}", "program": "Any", "package": ""},
|
||||
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "program": "Any", "package": "S-1-15-2-1"},
|
||||
{"id": "{5B8D2F4A-1E3C-4A7B-9C6D-8E0F2A4B6C81}", "program": "Any", "package": ""},
|
||||
{"id": "CoreNet-DNS-Out-UDP", "program": "%SystemRoot%\\system32\\svchost.exe", "package": ""}
|
||||
],
|
||||
"services": [
|
||||
{"id": "RemoteDesktop-UserMode-In-TCP", "service": "TermService"},
|
||||
{"id": "FPS-SMB-In-TCP", "service": "Any"},
|
||||
{"id": "WINRM-HTTP-In-TCP-PUBLIC", "service": "Any"},
|
||||
{"id": "{7A1D3F2E-0B4C-4C8E-9F61-2D5A8B3C1E90}", "service": "Any"},
|
||||
{"id": "{0C4E2B7A-51D3-4E8F-A6B9-3F7D1C2E8A45}", "service": "Any"},
|
||||
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "service": "*"},
|
||||
{"id": "{5B8D2F4A-1E3C-4A7B-9C6D-8E0F2A4B6C81}", "service": "Any"},
|
||||
{"id": "CoreNet-DNS-Out-UDP", "service": "dnscache"}
|
||||
],
|
||||
"interfaces": [
|
||||
{"id": "RemoteDesktop-UserMode-In-TCP", "aliases": ["Any"]},
|
||||
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "aliases": ["Ethernet0"]}
|
||||
],
|
||||
"interface_types": [
|
||||
{"id": "RemoteDesktop-UserMode-In-TCP", "types": "Any"},
|
||||
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "types": "Wired, RemoteAccess"}
|
||||
],
|
||||
"security": [
|
||||
{"id": "RemoteDesktop-UserMode-In-TCP", "authentication": "NotRequired", "override_block": false},
|
||||
{"id": "{9E3B5D1F-7C2A-4B6E-8D4F-1A2C3E5B7D90}", "authentication": "Required", "override_block": true}
|
||||
],
|
||||
"connections": [
|
||||
{"interface": "Ethernet0", "category": "DomainAuthenticated"},
|
||||
{"interface": "Ethernet1", "category": "Public"}
|
||||
]
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
{"system_drive":"C:","secure_boot":"True","tpm":{"present":true,"enabled":true,"activated":true,"owned":true,"spec_version":"2.0, 0, 1.59","manufacturer":"INTC"},"bitlocker":{"installed":true,"volumes":[{"drive":"C:","volume_type":"0","protection":"1","conversion":"1","method":"6"},{"drive":"D:","volume_type":"1","protection":"0","conversion":"0","method":"0"}]},"defender":{"am_service":true,"antivirus":true,"real_time":true,"running_mode":"Normal","signature_updated":1764547200,"signature_age":0,"signature_version":"1.443.512.0","tamper_protected":true},"firewall":[{"name":"Domain","enabled":"True"},{"name":"Private","enabled":"True"},{"name":"Public","enabled":"True"}],"vbs":{"status":"2","running":["1","2"]},"errors":{}}
|
||||
@@ -1 +0,0 @@
|
||||
{"system_drive":"C:","secure_boot":"unsupported","tpm":{"present":false},"bitlocker":{"installed":false,"volumes":[]},"defender":{"am_service":true,"antivirus":true,"real_time":false,"running_mode":"Passive Mode","signature_updated":1763942400,"signature_age":7,"signature_version":"1.443.300.0","tamper_protected":false},"firewall":[{"name":"Domain","enabled":"True"},{"name":"Private","enabled":"False"},{"name":"Public","enabled":"True"}],"vbs":{"status":"0","running":["0"]},"errors":{}}
|
||||
@@ -0,0 +1,8 @@
|
||||
[
|
||||
{"name": "SMB1Protocol", "state": 2},
|
||||
{"name": "MSMQ-Server", "state": 1},
|
||||
{"name": "IIS-WebServerRole", "state": 1},
|
||||
{"name": "Microsoft-Hyper-V", "state": 3},
|
||||
{"name": "DNS-Server-Full-Role", "state": 4},
|
||||
{"name": "Printing-PrintToPDFServices-Features", "state": 1}
|
||||
]
|
||||
@@ -0,0 +1,222 @@
|
||||
"""The Windows Firewall as the exposure chain reads it (NetOrk/netork#2894).
|
||||
|
||||
The script reads the profiles from the firewall's own COM object (the settings in
|
||||
force, group policy over local), the enabled rules of the active policy, and every
|
||||
filter in bulk -- one cmdlet per filter kind, never one per rule -- and the profile
|
||||
of each connected interface. The rules and their filters are joined here, on the
|
||||
rule's InstanceID. The fixture is what the script emits on a Windows Server.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import WINDOWS_FIREWALL_PROFILES
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import host_firewall as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "host_firewall.json"
|
||||
|
||||
|
||||
class FakeHost:
|
||||
def __init__(self, answer: Any) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer if isinstance(self.answer, str) else json.dumps(self.answer)
|
||||
|
||||
def close(self) -> None:
|
||||
self.is_open = False
|
||||
|
||||
|
||||
def _read(answer: Any = None) -> dict[str, Any]:
|
||||
driver = WindowsDriver("win", "u", "p")
|
||||
host = FakeHost(json.loads(FIXTURE.read_text()) if answer is None else answer)
|
||||
driver._transport = host # type: ignore[assignment]
|
||||
reading = driver.get_host_firewall()
|
||||
assert host.sent == [mod._PS_HOST_FIREWALL]
|
||||
return dict(reading)
|
||||
|
||||
|
||||
def _rule(reading: dict[str, Any], name: str) -> dict[str, Any]:
|
||||
return next(r for r in reading["windows"]["rules"] if r["name"] == name)
|
||||
|
||||
|
||||
def test_a_windows_reading_has_no_chains_and_names_its_source():
|
||||
reading = _read()
|
||||
assert reading["sources"] == ["windows-firewall"]
|
||||
assert reading["chains"] == []
|
||||
|
||||
|
||||
def test_the_profiles_are_the_settings_in_force():
|
||||
profiles = _read()["windows"]["profiles"]
|
||||
assert [p["name"] for p in profiles] == list(WINDOWS_FIREWALL_PROFILES)
|
||||
assert profiles[0] == {
|
||||
"name": "domain",
|
||||
"enabled": True,
|
||||
"default_inbound": "block",
|
||||
"default_outbound": "allow",
|
||||
"block_all_inbound": False,
|
||||
# NotConfigured: the default, which lets local rules apply.
|
||||
"local_rules": True,
|
||||
}
|
||||
assert profiles[2]["local_rules"] is False
|
||||
|
||||
|
||||
def test_a_rule_carries_its_filters_joined_on_its_instance_id():
|
||||
rdp = _rule(_read(), "Remote Desktop - User Mode (TCP-In)")
|
||||
assert rdp == {
|
||||
"id": "RemoteDesktop-UserMode-In-TCP",
|
||||
"name": "Remote Desktop - User Mode (TCP-In)",
|
||||
"group": "Remote Desktop",
|
||||
"direction": "inbound",
|
||||
"action": "allow",
|
||||
"profiles": None,
|
||||
"protocol": "tcp",
|
||||
"local_ports": ["3389"],
|
||||
"remote_ports": None,
|
||||
"local_addresses": None,
|
||||
"remote_addresses": None,
|
||||
"program": "%SystemRoot%\\system32\\svchost.exe",
|
||||
"service": "TermService",
|
||||
"package": None,
|
||||
"interfaces": None,
|
||||
"interface_types": None,
|
||||
"authenticated": False,
|
||||
"override_block": False,
|
||||
"source": "local",
|
||||
}
|
||||
|
||||
|
||||
def test_profiles_protocol_numbers_and_port_keywords_are_normalised():
|
||||
reading = _read()
|
||||
smb = _rule(reading, "File and Printer Sharing (SMB-In)")
|
||||
assert smb["profiles"] == ["domain", "private"]
|
||||
assert smb["remote_addresses"] == ["localsubnet"]
|
||||
assert smb["program"] == "System"
|
||||
sql = _rule(reading, "Block SQL Server from the internet")
|
||||
assert (sql["action"], sql["protocol"], sql["local_ports"]) == (
|
||||
"block",
|
||||
"tcp",
|
||||
["1433", "1434"],
|
||||
)
|
||||
assert sql["source"] == "group_policy"
|
||||
mgmt = _rule(reading, "Management subnets")
|
||||
assert mgmt["local_ports"] == ["rpc", "49152-65535"]
|
||||
|
||||
|
||||
def test_addresses_become_cidrs_masks_and_ranges_included():
|
||||
mgmt = _rule(_read(), "Management subnets")
|
||||
assert mgmt["remote_addresses"] == [
|
||||
"10.0.0.0/8",
|
||||
"192.0.2.1/32",
|
||||
"192.0.2.2/31",
|
||||
"192.0.2.4/31",
|
||||
"192.0.2.6/32",
|
||||
"2001:db8::/48",
|
||||
"198.51.100.7/32",
|
||||
]
|
||||
|
||||
|
||||
def test_a_range_across_families_is_kept_as_written():
|
||||
raw = json.loads(FIXTURE.read_text())
|
||||
raw["addresses"][0]["remote"] = ["10.0.0.1-::1"]
|
||||
rdp = _rule(_read(raw), "Remote Desktop - User Mode (TCP-In)")
|
||||
assert rdp["remote_addresses"] == ["10.0.0.1-::1"]
|
||||
|
||||
|
||||
def test_the_rarer_filters_are_kept():
|
||||
mgmt = _rule(_read(), "Management subnets")
|
||||
assert mgmt["interfaces"] == ["Ethernet0"]
|
||||
assert mgmt["interface_types"] == ["wired", "remote_access"]
|
||||
assert mgmt["package"] == "S-1-15-2-1"
|
||||
assert mgmt["service"] == "*"
|
||||
assert (mgmt["authenticated"], mgmt["override_block"]) == (True, True)
|
||||
|
||||
|
||||
def test_a_block_rule_whose_filter_was_not_read_is_left_out():
|
||||
# A filter left unread would read as "any" and make the rule block everything.
|
||||
names = [r["name"] for r in _read()["windows"]["rules"]]
|
||||
assert "Block an unread filter" not in names
|
||||
assert "Core Networking - DNS (UDP-Out)" in names
|
||||
|
||||
|
||||
def test_an_allow_rule_whose_filter_was_not_read_matches_more_not_less():
|
||||
raw = json.loads(FIXTURE.read_text())
|
||||
raw["addresses"] = [a for a in raw["addresses"] if a["id"] != "FPS-SMB-In-TCP"]
|
||||
smb = _rule(_read(raw), "File and Printer Sharing (SMB-In)")
|
||||
assert smb["remote_addresses"] is None
|
||||
|
||||
|
||||
def test_each_connection_names_its_profile():
|
||||
connections = _read()["windows"]["connections"]
|
||||
assert connections == [
|
||||
{"interface": "Ethernet0", "profile": "domain"},
|
||||
{"interface": "Ethernet1", "profile": "public"},
|
||||
]
|
||||
|
||||
|
||||
def test_connections_that_could_not_be_read_are_none_not_empty():
|
||||
raw = json.loads(FIXTURE.read_text())
|
||||
raw["connections"] = None
|
||||
assert _read(raw)["windows"]["connections"] is None
|
||||
|
||||
|
||||
def test_an_unknown_category_and_setting_say_nothing():
|
||||
raw = json.loads(FIXTURE.read_text())
|
||||
raw["connections"] = [{"interface": "Wi-Fi", "category": "Something"}, "junk"]
|
||||
raw["rules"].append("junk")
|
||||
raw["profiles"][0].update(default_inbound=7, local_rules=None, enabled=None)
|
||||
windows = _read(raw)["windows"]
|
||||
assert windows["connections"] == []
|
||||
domain = windows["profiles"][0]
|
||||
assert (domain["default_inbound"], domain["local_rules"], domain["enabled"]) == (
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def test_one_element_lists_arrive_bare_and_are_still_lists():
|
||||
raw = json.loads(FIXTURE.read_text())
|
||||
raw["rules"] = raw["rules"][0]
|
||||
raw["ports"] = {**raw["ports"][0], "local": "3389"}
|
||||
raw["addresses"] = raw["addresses"][0]
|
||||
raw["applications"] = raw["applications"][0]
|
||||
raw["services"] = raw["services"][0]
|
||||
(rule,) = _read(raw)["windows"]["rules"]
|
||||
assert rule["local_ports"] == ["3389"]
|
||||
|
||||
|
||||
def test_a_reading_without_profiles_is_refused():
|
||||
with pytest.raises(ValueError, match="firewall"):
|
||||
_read("")
|
||||
raw = json.loads(FIXTURE.read_text())
|
||||
raw["profiles"] = []
|
||||
with pytest.raises(ValueError, match="profiles"):
|
||||
_read(raw)
|
||||
|
||||
|
||||
def test_the_script_reads_every_filter_in_bulk():
|
||||
script = mod._PS_HOST_FIREWALL
|
||||
for cmdlet in (
|
||||
"Get-NetFirewallPortFilter",
|
||||
"Get-NetFirewallAddressFilter",
|
||||
"Get-NetFirewallApplicationFilter",
|
||||
"Get-NetFirewallServiceFilter",
|
||||
"Get-NetFirewallInterfaceFilter",
|
||||
"Get-NetFirewallInterfaceTypeFilter",
|
||||
"Get-NetFirewallSecurityFilter",
|
||||
):
|
||||
assert f"{cmdlet} -All -PolicyStore ActiveStore" in script
|
||||
assert "Get-NetFirewallRule -PolicyStore ActiveStore -Enabled True" in script
|
||||
# Never a filter per rule: no pipeline from the rules into a filter cmdlet.
|
||||
assert "| Get-NetFirewall" not in script
|
||||
assert "$ErrorActionPreference = 'Stop'" in script
|
||||
@@ -1,330 +0,0 @@
|
||||
"""A Windows host's security posture as napalm-device-types' hardening reading (NetOrk/netork#2893).
|
||||
|
||||
The reading is one script whose JSON a fake host answers, from
|
||||
tests/fixtures/synthetic/posture_client.json (a Windows 11 client with everything on) and
|
||||
posture_server.json (a Windows Server VM booted from BIOS, without the BitLocker feature,
|
||||
Defender passive beside another product, the Private profile off).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import posture as mod
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
|
||||
LINUX_KEYS = (
|
||||
"lsm",
|
||||
"selinux",
|
||||
"apparmor",
|
||||
"crypto_policy",
|
||||
"fips",
|
||||
"cpu_vulnerabilities",
|
||||
"cmdline",
|
||||
"mitigations",
|
||||
"nosmt",
|
||||
"os_ids",
|
||||
"virtualization",
|
||||
"cpu_vendor",
|
||||
)
|
||||
|
||||
|
||||
def _fixture(name: str) -> dict[str, Any]:
|
||||
data: dict[str, Any] = json.loads((FIXTURES / f"posture_{name}.json").read_text())
|
||||
return data
|
||||
|
||||
|
||||
class FakeHost:
|
||||
is_open = True
|
||||
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer
|
||||
|
||||
def close(self) -> None:
|
||||
self.is_open = False
|
||||
|
||||
|
||||
def _read(raw: dict[str, Any] | str) -> dict[str, Any]:
|
||||
host = FakeHost(raw if isinstance(raw, str) else json.dumps(raw))
|
||||
driver = WindowsDriver("win01", "admin", "secret")
|
||||
driver._transport = host # type: ignore[assignment]
|
||||
reading: dict[str, Any] = dict(driver.get_hardening())
|
||||
assert host.sent == [mod._PS_POSTURE]
|
||||
return reading
|
||||
|
||||
|
||||
def _with(name: str, **changes: Any) -> dict[str, Any]:
|
||||
return {**_fixture(name), **changes}
|
||||
|
||||
|
||||
class TestClient:
|
||||
def test_everything_on(self):
|
||||
reading = _read(_fixture("client"))
|
||||
|
||||
assert reading["secure_boot"] == "on"
|
||||
assert reading["tpm"] == {
|
||||
"present": True,
|
||||
"enabled": True,
|
||||
"activated": True,
|
||||
"owned": True,
|
||||
"version": "2.0",
|
||||
"manufacturer": "INTC",
|
||||
}
|
||||
assert reading["disk_encryption"] == {
|
||||
"provider": "bitlocker",
|
||||
"installed": True,
|
||||
"volumes": [
|
||||
{
|
||||
"volume": "C:",
|
||||
"system": True,
|
||||
"protection": "on",
|
||||
"status": "fully_encrypted",
|
||||
"method": "xts_aes_128",
|
||||
},
|
||||
{
|
||||
"volume": "D:",
|
||||
"system": False,
|
||||
"protection": "off",
|
||||
"status": "fully_decrypted",
|
||||
"method": None,
|
||||
},
|
||||
],
|
||||
}
|
||||
assert reading["antimalware"] == {
|
||||
"product": "Microsoft Defender Antivirus",
|
||||
"enabled": True,
|
||||
"real_time": True,
|
||||
"mode": "active",
|
||||
"signatures_updated": 1764547200,
|
||||
"signature_age_days": 0,
|
||||
"signature_version": "1.443.512.0",
|
||||
"tamper_protected": True,
|
||||
}
|
||||
assert reading["firewall_profiles"] == [
|
||||
{"name": "domain", "enabled": True},
|
||||
{"name": "private", "enabled": True},
|
||||
{"name": "public", "enabled": True},
|
||||
]
|
||||
assert reading["vbs"] == {"status": "running", "running": ["credential_guard", "hvci"]}
|
||||
|
||||
def test_what_only_linux_has_is_not_read(self):
|
||||
reading = _read(_fixture("client"))
|
||||
|
||||
assert all(reading[key] is None for key in LINUX_KEYS)
|
||||
|
||||
|
||||
class TestServer:
|
||||
def test_a_bios_boot_has_no_secure_boot_to_switch_on(self):
|
||||
assert _read(_fixture("server"))["secure_boot"] == "unsupported"
|
||||
|
||||
def test_no_tpm(self):
|
||||
assert _read(_fixture("server"))["tpm"] == {
|
||||
"present": False,
|
||||
"enabled": None,
|
||||
"activated": None,
|
||||
"owned": None,
|
||||
"version": None,
|
||||
"manufacturer": None,
|
||||
}
|
||||
|
||||
def test_bitlocker_not_installed_is_said_so_not_an_error(self):
|
||||
assert _read(_fixture("server"))["disk_encryption"] == {
|
||||
"provider": "bitlocker",
|
||||
"installed": False,
|
||||
"volumes": [],
|
||||
}
|
||||
|
||||
def test_defender_passive_beside_another_product(self):
|
||||
antimalware = _read(_fixture("server"))["antimalware"]
|
||||
|
||||
assert antimalware["mode"] == "passive"
|
||||
assert antimalware["real_time"] is False
|
||||
assert antimalware["signature_age_days"] == 7
|
||||
|
||||
def test_a_profile_switched_off(self):
|
||||
profiles = _read(_fixture("server"))["firewall_profiles"]
|
||||
|
||||
assert {"name": "private", "enabled": False} in profiles
|
||||
|
||||
def test_vbs_off_runs_nothing(self):
|
||||
assert _read(_fixture("server"))["vbs"] == {"status": "off", "running": []}
|
||||
|
||||
|
||||
class TestEachPartOnItsOwn:
|
||||
@pytest.mark.parametrize(
|
||||
("part", "key"),
|
||||
[
|
||||
("secure_boot", "secure_boot"),
|
||||
("tpm", "tpm"),
|
||||
("bitlocker", "disk_encryption"),
|
||||
("defender", "antimalware"),
|
||||
("firewall", "firewall_profiles"),
|
||||
("vbs", "vbs"),
|
||||
],
|
||||
)
|
||||
def test_a_part_that_failed_is_not_read_and_the_rest_is(self, part, key):
|
||||
raw = _with("client", **{part: None, "errors": {part: "Access denied"}})
|
||||
|
||||
reading = _read(raw)
|
||||
|
||||
assert reading[key] is None
|
||||
others = {"secure_boot", "tpm", "disk_encryption", "antimalware", "firewall_profiles"}
|
||||
assert all(reading[k] is not None for k in others - {key})
|
||||
|
||||
def test_a_cmdlet_the_host_lacks_is_not_read(self):
|
||||
"""Server Core without Defender, a build without the firewall module."""
|
||||
reading = _read(_with("client", defender=None, firewall=None, secure_boot=None))
|
||||
|
||||
assert reading["antimalware"] is None
|
||||
assert reading["firewall_profiles"] is None
|
||||
assert reading["secure_boot"] is None
|
||||
|
||||
def test_secure_boot_off(self):
|
||||
assert _read(_with("client", secure_boot="False"))["secure_boot"] == "off"
|
||||
|
||||
def test_a_secure_boot_answer_it_does_not_know_is_not_read(self):
|
||||
assert _read(_with("client", secure_boot="maybe"))["secure_boot"] is None
|
||||
|
||||
|
||||
class TestValues:
|
||||
def test_one_element_lists_arrive_bare(self):
|
||||
"""ConvertTo-Json unwraps a one-element array into its element."""
|
||||
raw = _fixture("client")
|
||||
raw["bitlocker"]["volumes"] = raw["bitlocker"]["volumes"][0]
|
||||
raw["firewall"] = raw["firewall"][0]
|
||||
raw["vbs"]["running"] = "2"
|
||||
|
||||
reading = _read(raw)
|
||||
|
||||
assert [v["volume"] for v in reading["disk_encryption"]["volumes"]] == ["C:"]
|
||||
assert reading["firewall_profiles"] == [{"name": "domain", "enabled": True}]
|
||||
assert reading["vbs"]["running"] == ["hvci"]
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("mode", "word"),
|
||||
[
|
||||
("Normal", "active"),
|
||||
("Passive Mode", "passive"),
|
||||
("Passive", "passive"),
|
||||
("EDR Block Mode", "edr_block"),
|
||||
("SxS Passive Mode", "sxs_passive"),
|
||||
("Not running", None),
|
||||
(None, None),
|
||||
],
|
||||
)
|
||||
def test_defenders_running_mode(self, mode, word):
|
||||
raw = _fixture("client")
|
||||
raw["defender"]["running_mode"] = mode
|
||||
|
||||
assert _read(raw)["antimalware"]["mode"] == word
|
||||
|
||||
def test_defender_with_its_service_off_scans_nothing(self):
|
||||
raw = _fixture("client")
|
||||
raw["defender"].update(am_service=False)
|
||||
|
||||
antimalware = _read(raw)["antimalware"]
|
||||
|
||||
assert antimalware["enabled"] is False
|
||||
|
||||
def test_defender_without_signatures_yet(self):
|
||||
raw = _fixture("client")
|
||||
raw["defender"].update(signature_updated=None, signature_age=None, signature_version="")
|
||||
|
||||
antimalware = _read(raw)["antimalware"]
|
||||
|
||||
assert antimalware["signatures_updated"] is None
|
||||
assert antimalware["signature_age_days"] is None
|
||||
assert antimalware["signature_version"] is None
|
||||
|
||||
def test_the_os_volume_is_the_system_volume_by_its_type_or_its_letter(self):
|
||||
raw = _fixture("client")
|
||||
raw["bitlocker"]["volumes"] = [
|
||||
{
|
||||
"drive": "C:",
|
||||
"volume_type": "1",
|
||||
"protection": "2",
|
||||
"conversion": "4",
|
||||
"method": "7",
|
||||
},
|
||||
{
|
||||
"drive": "E:",
|
||||
"volume_type": "0",
|
||||
"protection": "0",
|
||||
"conversion": "2",
|
||||
"method": "4",
|
||||
},
|
||||
{
|
||||
"drive": None,
|
||||
"volume_type": "1",
|
||||
"protection": "0",
|
||||
"conversion": "0",
|
||||
"method": "0",
|
||||
},
|
||||
]
|
||||
|
||||
volumes = _read(raw)["disk_encryption"]["volumes"]
|
||||
|
||||
assert [(v["volume"], v["system"]) for v in volumes] == [("C:", True), ("E:", True)]
|
||||
assert volumes[0]["protection"] == "unknown"
|
||||
assert volumes[0]["status"] == "encryption_paused"
|
||||
assert volumes[0]["method"] == "xts_aes_256"
|
||||
assert volumes[1]["status"] == "encrypting"
|
||||
assert volumes[1]["method"] == "aes_256"
|
||||
|
||||
def test_numbers_it_does_not_know_are_not_guessed(self):
|
||||
raw = _fixture("client")
|
||||
raw["bitlocker"]["volumes"] = [
|
||||
{"drive": "C:", "volume_type": "0", "protection": "9", "conversion": "9", "method": "x"}
|
||||
]
|
||||
raw["vbs"] = {"status": "7", "running": ["9"]}
|
||||
raw["tpm"]["spec_version"] = ""
|
||||
|
||||
reading = _read(raw)
|
||||
|
||||
volume = reading["disk_encryption"]["volumes"][0]
|
||||
assert (volume["protection"], volume["status"], volume["method"]) == ("unknown", None, None)
|
||||
assert reading["vbs"] == {"status": None, "running": ["service_9"]}
|
||||
assert reading["tpm"]["version"] is None
|
||||
|
||||
def test_a_firewall_profile_not_configured_is_not_read(self):
|
||||
raw = _with("client", firewall=[{"name": "Public", "enabled": "NotConfigured"}])
|
||||
|
||||
assert _read(raw)["firewall_profiles"] == [{"name": "public", "enabled": None}]
|
||||
|
||||
def test_an_empty_answer_raises(self):
|
||||
with pytest.raises(ValueError, match="came back empty"):
|
||||
_read("")
|
||||
|
||||
|
||||
class TestTheScript:
|
||||
def test_it_never_touches_a_key(self):
|
||||
"""Get-BitLockerVolume returns the key protectors, recovery passwords among them;
|
||||
the CIM class's properties carry none."""
|
||||
for word in ("Get-BitLockerVolume", "KeyProtector", "RecoveryPassword", "manage-bde"):
|
||||
assert word not in mod._PS_POSTURE
|
||||
|
||||
def test_it_changes_nothing(self):
|
||||
for verb in ("Set-", "Enable-", "Disable-", "Update-MpSignature", "Start-MpScan"):
|
||||
assert verb not in mod._PS_POSTURE
|
||||
|
||||
def test_it_probes_the_cmdlets_first(self):
|
||||
for cmdlet in ("Confirm-SecureBootUEFI", "Get-MpComputerStatus", "Get-NetFirewallProfile"):
|
||||
assert f"Has '{cmdlet}'" in mod._PS_POSTURE
|
||||
|
||||
def test_it_stops_on_errors_and_catches_each_part(self):
|
||||
assert "$ErrorActionPreference = 'Stop'" in mod._PS_POSTURE
|
||||
assert mod._PS_POSTURE.count("catch") >= 6
|
||||
|
||||
|
||||
def test_the_driver_reads_the_hardening():
|
||||
assert callable(getattr(WindowsDriver, "get_hardening", None))
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Windows optional features, the facts a role's CVE precondition is held against (NetOrk/netork#2898).
|
||||
|
||||
``Win32_OptionalFeature`` lists every feature of the image, on a client and a server,
|
||||
under the names ``Get-WindowsOptionalFeature`` uses; its ``InstallState`` is 1 enabled,
|
||||
2 disabled, 3 absent, 4 unknown. The fixture is what the script emits.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import WindowsFeaturesMixin
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import windows_features as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "windows_features.json"
|
||||
|
||||
|
||||
class FakeHost:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer
|
||||
|
||||
def close(self) -> None:
|
||||
self.is_open = False
|
||||
|
||||
|
||||
def _read(answer: Any = None) -> dict[str, Any]:
|
||||
driver = WindowsDriver("win", "u", "p")
|
||||
text = FIXTURE.read_text() if answer is None else answer
|
||||
host = FakeHost(text if isinstance(text, str) else json.dumps(text))
|
||||
driver._transport = host # type: ignore[assignment]
|
||||
reading = driver.get_windows_features()
|
||||
assert host.sent == [mod._PS_WINDOWS_FEATURES]
|
||||
return dict(reading)
|
||||
|
||||
|
||||
def test_the_driver_declares_the_contract():
|
||||
assert issubclass(WindowsDriver, WindowsFeaturesMixin)
|
||||
|
||||
|
||||
def test_every_feature_comes_with_its_state():
|
||||
assert _read()["features"] == [
|
||||
{"name": "SMB1Protocol", "state": "disabled"},
|
||||
{"name": "MSMQ-Server", "state": "enabled"},
|
||||
{"name": "IIS-WebServerRole", "state": "enabled"},
|
||||
{"name": "Microsoft-Hyper-V", "state": "absent"},
|
||||
{"name": "DNS-Server-Full-Role", "state": "unknown"},
|
||||
{"name": "Printing-PrintToPDFServices-Features", "state": "enabled"},
|
||||
]
|
||||
|
||||
|
||||
def test_a_state_outside_the_four_is_unknown_and_a_nameless_entry_is_dropped():
|
||||
raw = [
|
||||
{"name": "X", "state": 9},
|
||||
{"name": "", "state": 1},
|
||||
"junk",
|
||||
{"name": "Y", "state": None},
|
||||
]
|
||||
assert _read(raw)["features"] == [
|
||||
{"name": "X", "state": "unknown"},
|
||||
{"name": "Y", "state": "unknown"},
|
||||
]
|
||||
|
||||
|
||||
def test_one_feature_arrives_bare_and_is_still_a_list():
|
||||
assert _read({"name": "SMB1Protocol", "state": 1})["features"] == [
|
||||
{"name": "SMB1Protocol", "state": "enabled"}
|
||||
]
|
||||
|
||||
|
||||
def test_no_feature_at_all_is_a_reading_that_went_wrong():
|
||||
# Every image has features; none read is not "none switched on".
|
||||
with pytest.raises(ValueError, match="features"):
|
||||
_read("")
|
||||
with pytest.raises(ValueError, match="features"):
|
||||
_read([])
|
||||
|
||||
|
||||
def test_the_script_asks_cim_not_dism():
|
||||
script = mod._PS_WINDOWS_FEATURES
|
||||
assert "Win32_OptionalFeature" in script
|
||||
assert "$ErrorActionPreference = 'Stop'" in script
|
||||
assert "-InputObject @(" in script
|
||||
+9
-2
@@ -14,7 +14,13 @@ import argparse
|
||||
import getpass
|
||||
import pathlib
|
||||
|
||||
from napalm_windows import WindowsDriver, posture, scheduled_tasks, time_sync
|
||||
from napalm_windows import (
|
||||
WindowsDriver,
|
||||
host_firewall,
|
||||
scheduled_tasks,
|
||||
time_sync,
|
||||
windows_features,
|
||||
)
|
||||
from napalm_windows import windows as mod
|
||||
|
||||
SCRIPTS = {
|
||||
@@ -27,7 +33,8 @@ SCRIPTS = {
|
||||
"listening": mod._PS_LISTENING,
|
||||
"scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS,
|
||||
"time_sync": time_sync._PS_TIME_SYNC,
|
||||
"posture": posture._PS_POSTURE,
|
||||
"host_firewall": host_firewall._PS_HOST_FIREWALL,
|
||||
"windows_features": windows_features._PS_WINDOWS_FEATURES,
|
||||
}
|
||||
|
||||
OUT = pathlib.Path(__file__).parent / "harvest-out"
|
||||
|
||||
Reference in new issue
Block a user