get_login_accounts reads the host's own accounts (Get-LocalUser), their last login and failed attempts from the account database, expiry and lock, and whether each is an administrator (S-1-5-32-544, by SID) or may log in over Remote Desktop (the logon right and its denial from secedit, the host's fDenyTSConnections). groups lists the groups that grant either, with every member, a domain's included. uid is the RID, sid the SID. A domain controller's accounts are not read. get_login_sessions reads logon events 4624 of type 2, 10 and 11 of the last seven days from the Security log, ended by 4634/4647, an administrator's two linked logons as one session. own_address is the reading's own WinRM logon's address; records_since the log's oldest event. A log without any logon raises LoginSessionsUnavailable. Both scripts are in tools/harvest.py.
389 lines
14 KiB
Python
389 lines
14 KiB
Python
"""Who can log in to a Windows host: local accounts, administrators, Remote Desktop
|
|
(NetOrk/netork#2895).
|
|
|
|
The reading is one script whose JSON a fake transport answers, from
|
|
tests/fixtures/synthetic/login_accounts_server_de.json (a German-language domain
|
|
member: "Administratoren", "Remotedesktopbenutzer", a domain group among the
|
|
administrators, Remote Desktop on, Guests denied it) and login_accounts_client.json (a
|
|
Windows 11 workgroup client, Remote Desktop off). What a real host emits the fixtures
|
|
cannot prove -- see the README there.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import copy
|
|
import json
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
import pytest
|
|
|
|
from napalm_windows import WindowsDriver
|
|
from napalm_windows import login_accounts as mod
|
|
|
|
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
|
|
MACHINE = "S-1-5-21-1004336348-1177238915-682003330"
|
|
DOMAIN = "S-1-5-21-3623811015-3361044348-30300820"
|
|
|
|
|
|
def _raw(name: str) -> dict[str, Any]:
|
|
return json.loads((FIXTURES / f"login_accounts_{name}.json").read_text())
|
|
|
|
|
|
class FakeTransport:
|
|
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(raw: Any) -> tuple[dict[str, Any], FakeTransport]:
|
|
d = WindowsDriver("win01", "admin", "secret")
|
|
host = FakeTransport(raw)
|
|
d._transport = host # type: ignore[assignment]
|
|
return dict(d.get_login_accounts()), host
|
|
|
|
|
|
def _by_name(reading: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
|
return {a["name"]: a for a in reading["accounts"]}
|
|
|
|
|
|
class TestGermanMemberServer:
|
|
def test_the_accounts_without_the_systems_own(self):
|
|
reading, _ = _read(_raw("server_de"))
|
|
|
|
assert [a["name"] for a in reading["accounts"]] == [
|
|
"Administrator",
|
|
"Gast",
|
|
"helpdesk",
|
|
"svc-backup",
|
|
]
|
|
|
|
def test_uid_is_the_rid_and_sid_the_whole_sid(self):
|
|
admin = _by_name(_read(_raw("server_de"))[0])["Administrator"]
|
|
|
|
assert admin["uid"] == 500
|
|
assert admin["sid"] == f"{MACHINE}-500"
|
|
assert admin["home"] == "C:\\Users\\Administrator"
|
|
assert admin["shell"] == ""
|
|
|
|
def test_the_last_login_is_the_account_databases(self):
|
|
reading, _ = _read(_raw("server_de"))
|
|
admin = _by_name(reading)["Administrator"]
|
|
|
|
assert admin["last_login"] == "2025-11-29T00:00:00+00:00"
|
|
assert admin["last_login_source"] == "sam"
|
|
assert admin["last_login_from"] is None
|
|
assert admin["last_login_port"] is None
|
|
assert reading["login_sources"] == ["sam"]
|
|
assert _by_name(reading)["Gast"]["last_login"] is None
|
|
assert _by_name(reading)["Gast"]["last_login_source"] is None
|
|
|
|
def test_administrators_are_found_by_sid_not_by_name(self):
|
|
"""The group is "Administratoren" here; S-1-5-32-544 finds it all the same."""
|
|
accounts = _by_name(_read(_raw("server_de"))[0])
|
|
|
|
assert accounts["Administrator"]["administrator"] is True
|
|
assert accounts["helpdesk"]["administrator"] is False
|
|
|
|
def test_remote_desktop_by_the_right_and_its_holders(self):
|
|
accounts = _by_name(_read(_raw("server_de"))[0])
|
|
|
|
assert accounts["Administrator"]["remote_desktop"] is True
|
|
assert accounts["helpdesk"]["remote_desktop"] is True # Remotedesktopbenutzer
|
|
assert accounts["svc-backup"]["remote_desktop"] is False # no group holds it
|
|
|
|
def test_a_denied_group_wins_over_the_right(self):
|
|
raw = _raw("server_de")
|
|
raw["groups"][2]["members"].append(
|
|
{"path": "WinNT://CONTOSO/SRV01/helpdesk", "class": "User", "sid": f"{MACHINE}-1001"}
|
|
)
|
|
|
|
assert _by_name(_read(raw)[0])["helpdesk"]["remote_desktop"] is False
|
|
|
|
def test_denying_every_local_account_denies_them_all(self):
|
|
"""``Local account`` (S-1-5-113), as Microsoft's security baseline denies it."""
|
|
raw = _raw("server_de")
|
|
raw["rights"]["deny"].append("*S-1-5-113")
|
|
|
|
accounts = _by_name(_read(raw)[0])
|
|
|
|
assert not any(a["remote_desktop"] for a in accounts.values())
|
|
|
|
def test_a_right_given_to_everyone_reaches_every_account(self):
|
|
raw = _raw("server_de")
|
|
raw["rights"]["allow"].append("*S-1-1-0")
|
|
|
|
assert _by_name(_read(raw)[0])["svc-backup"]["remote_desktop"] is True
|
|
|
|
def test_a_right_given_by_name_counts(self):
|
|
raw = _raw("server_de")
|
|
raw["rights"]["allow"].append("svc-backup")
|
|
|
|
assert _by_name(_read(raw)[0])["svc-backup"]["remote_desktop"] is True
|
|
|
|
def test_locked_disabled_expired_or_locked_out(self):
|
|
accounts = _by_name(_read(_raw("server_de"))[0])
|
|
|
|
assert accounts["Gast"]["locked"] is True # disabled
|
|
assert accounts["helpdesk"]["locked"] is True # locked out
|
|
assert accounts["svc-backup"]["locked"] is True # expired
|
|
assert accounts["Administrator"]["locked"] is False
|
|
|
|
def test_the_lock_out_not_read_is_none(self):
|
|
raw = _raw("server_de")
|
|
raw["users"][5]["account_expires"] = None
|
|
|
|
assert _by_name(_read(raw)[0])["svc-backup"]["locked"] is None
|
|
|
|
def test_password_and_account_expiry(self):
|
|
accounts = _by_name(_read(_raw("server_de"))[0])
|
|
|
|
assert accounts["Administrator"]["password"] == "set"
|
|
assert accounts["Administrator"]["password_changed"] == "2025-05-15"
|
|
assert accounts["Administrator"]["password_expires"] == "never"
|
|
assert accounts["Administrator"]["account_expires"] == "never"
|
|
assert accounts["helpdesk"]["password_expires"] == "2025-10-22"
|
|
assert accounts["svc-backup"]["account_expires"] == "2025-11-26"
|
|
assert accounts["Gast"]["password"] is None
|
|
assert accounts["Gast"]["password_expires"] is None
|
|
|
|
def test_failed_attempts_since_the_last_login(self):
|
|
reading, _ = _read(_raw("server_de"))
|
|
accounts = _by_name(reading)
|
|
|
|
assert accounts["helpdesk"]["failed_logins"] == 7
|
|
assert accounts["svc-backup"]["failed_logins"] is None
|
|
assert accounts["helpdesk"]["failed_logins_capped"] is False
|
|
assert reading["failed_logins_source"] == "sam"
|
|
|
|
def test_read_as_an_administrator(self):
|
|
assert _read(_raw("server_de"))[0]["privileged"] is True
|
|
|
|
|
|
class TestTheGroups:
|
|
def test_the_groups_that_grant_administration_or_remote_desktop(self):
|
|
groups = _read(_raw("server_de"))[0]["groups"]
|
|
|
|
assert [(g["name"], g["sid"], g["grants"]) for g in groups] == [
|
|
("Administratoren", "S-1-5-32-544", ["administrator", "remote_desktop"]),
|
|
("Remotedesktopbenutzer", "S-1-5-32-555", ["remote_desktop"]),
|
|
]
|
|
|
|
def test_a_domain_group_among_the_administrators_by_name(self):
|
|
admins = _read(_raw("server_de"))[0]["groups"][0]["members"]
|
|
|
|
assert admins == [
|
|
{
|
|
"name": "SRV01\\Administrator",
|
|
"sid": f"{MACHINE}-500",
|
|
"local": True,
|
|
"group": False,
|
|
},
|
|
{
|
|
"name": "CONTOSO\\Domänen-Admins",
|
|
"sid": f"{DOMAIN}-512",
|
|
"local": False,
|
|
"group": True,
|
|
},
|
|
{"name": "CONTOSO\\jdoe", "sid": f"{DOMAIN}-1107", "local": False, "group": False},
|
|
{"name": f"{DOMAIN}-1290", "sid": f"{DOMAIN}-1290", "local": False, "group": False},
|
|
]
|
|
|
|
def test_a_principal_of_the_host_itself_is_local(self):
|
|
raw = _raw("server_de")
|
|
raw["groups"][1]["members"] = [
|
|
{"path": "WinNT://NT-AUTORITÄT/INTERAKTIV", "class": "Group", "sid": "S-1-5-4"}
|
|
]
|
|
|
|
member = _read(raw)[0]["groups"][1]["members"][0]
|
|
|
|
assert member == {
|
|
"name": "NT-AUTORITÄT\\INTERAKTIV",
|
|
"sid": "S-1-5-4",
|
|
"local": True,
|
|
"group": True,
|
|
}
|
|
|
|
def test_without_a_sid_the_path_tells(self):
|
|
raw = _raw("server_de")
|
|
raw["groups"][1]["members"] = [
|
|
{"path": "WinNT://CONTOSO/SRV01/old", "class": "", "sid": None},
|
|
{"path": "WinNT://CONTOSO/someone", "class": "User", "sid": None},
|
|
{"path": "", "class": "", "sid": None},
|
|
]
|
|
raw["users"] = []
|
|
|
|
members = _read(raw)[0]["groups"][1]["members"]
|
|
|
|
assert [(m["name"], m["local"], m["group"]) for m in members] == [
|
|
("SRV01\\old", True, None),
|
|
("CONTOSO\\someone", False, False),
|
|
("", None, None),
|
|
]
|
|
|
|
def test_a_domain_sid_without_the_hosts_own_is_told_by_its_path(self):
|
|
raw = _raw("server_de")
|
|
raw["users"] = []
|
|
|
|
admins = _read(raw)[0]["groups"][0]["members"]
|
|
|
|
assert [m["local"] for m in admins] == [True, False, False, None]
|
|
|
|
|
|
class TestWindows11Client:
|
|
def test_remote_desktop_off_lets_no_one_in(self):
|
|
reading, _ = _read(_raw("client"))
|
|
accounts = _by_name(reading)
|
|
|
|
assert {a["remote_desktop"] for a in accounts.values()} == {False}
|
|
assert [g["sid"] for g in reading["groups"]] == ["S-1-5-32-544"]
|
|
assert reading["groups"][0]["grants"] == ["administrator"]
|
|
|
|
def test_the_owner_is_an_administrator_the_other_user_is_not(self):
|
|
accounts = _by_name(_read(_raw("client"))[0])
|
|
|
|
assert accounts["alice"]["administrator"] is True
|
|
assert accounts["bob"]["administrator"] is False
|
|
|
|
def test_group_policy_wins_over_the_local_setting(self):
|
|
raw = _raw("client")
|
|
raw["rdp_deny_policy"] = "0"
|
|
|
|
accounts = _by_name(_read(raw)[0])
|
|
|
|
assert accounts["alice"]["remote_desktop"] is True
|
|
assert accounts["bob"]["remote_desktop"] is False
|
|
|
|
|
|
class TestNotRead:
|
|
def test_rights_not_read_leave_remote_desktop_unknown(self):
|
|
raw = _raw("server_de")
|
|
raw["rights"] = None
|
|
raw["admin"] = False
|
|
|
|
reading, _ = _read(raw)
|
|
|
|
assert {a["remote_desktop"] for a in reading["accounts"]} == {None}
|
|
assert [g["grants"] for g in reading["groups"]] == [["administrator"]]
|
|
assert reading["privileged"] is False
|
|
|
|
def test_the_remote_desktop_setting_not_read_is_unknown(self):
|
|
raw = _raw("server_de")
|
|
raw["rdp_deny"] = None
|
|
|
|
assert {a["remote_desktop"] for a in _read(raw)[0]["accounts"]} == {None}
|
|
|
|
def test_administrators_not_read_is_unknown(self, caplog):
|
|
raw = _raw("server_de")
|
|
raw["groups"] = [g for g in raw["groups"] if g["sid"] != "S-1-5-32-544"]
|
|
raw["errors"] = ["group S-1-5-32-544: Zugriff verweigert"]
|
|
|
|
with caplog.at_level("INFO"):
|
|
reading, _ = _read(raw)
|
|
|
|
assert {a["administrator"] for a in reading["accounts"]} == {None}
|
|
assert "Zugriff verweigert" in caplog.text
|
|
|
|
def test_no_failed_attempts_read_has_no_source(self):
|
|
raw = _raw("server_de")
|
|
for user in raw["users"]:
|
|
user["bad_passwords"] = None
|
|
|
|
assert _read(raw)[0]["failed_logins_source"] is None
|
|
|
|
def test_one_group_member_arrives_as_an_object(self):
|
|
"""ConvertTo-Json writes a one-element array as its element."""
|
|
raw = _raw("server_de")
|
|
raw["groups"][1]["members"] = raw["groups"][1]["members"][0]
|
|
raw["users"] = raw["users"][0]
|
|
|
|
reading, _ = _read(raw)
|
|
|
|
assert [a["name"] for a in reading["accounts"]] == ["Administrator"]
|
|
assert len(reading["groups"][1]["members"]) == 1
|
|
|
|
def test_without_get_localuser_the_reading_is_not_supported(self):
|
|
raw = _raw("server_de")
|
|
raw["users"] = None
|
|
|
|
with pytest.raises(NotImplementedError, match="Get-LocalUser"):
|
|
_read(raw)
|
|
|
|
@pytest.mark.parametrize("answer", ["", "[]", "null"])
|
|
def test_an_empty_answer_raises(self, answer):
|
|
with pytest.raises(ValueError, match="empty"):
|
|
_read(answer)
|
|
|
|
def test_an_account_without_a_sid_is_left_out(self):
|
|
raw = _raw("server_de")
|
|
raw["users"].append({"name": "odd", "sid": None})
|
|
raw["users"].append("garbage")
|
|
|
|
assert "odd" not in _by_name(_read(raw)[0])
|
|
|
|
|
|
class TestDomainController:
|
|
def test_its_accounts_are_the_directorys_its_groups_are_read(self):
|
|
raw = copy.deepcopy(_raw("server_de"))
|
|
raw.update(domain_role=5, users=[])
|
|
|
|
reading, _ = _read(raw)
|
|
|
|
assert reading["accounts"] == []
|
|
assert reading["login_sources"] == []
|
|
assert reading["failed_logins_source"] is None
|
|
assert reading["groups"][0]["sid"] == "S-1-5-32-544"
|
|
|
|
def test_a_domain_controller_without_get_localuser_is_read_all_the_same(self):
|
|
raw = _raw("server_de")
|
|
raw.update(domain_role=4, users=None)
|
|
|
|
assert _read(raw)[0]["accounts"] == []
|
|
|
|
|
|
class TestTheScript:
|
|
def test_it_is_one_round_trip(self):
|
|
_, host = _read(_raw("server_de"))
|
|
|
|
assert host.sent == [mod._PS_LOGIN_ACCOUNTS]
|
|
|
|
def test_the_conventions(self):
|
|
script = mod._PS_LOGIN_ACCOUNTS
|
|
assert "$ErrorActionPreference = 'Stop'" in script
|
|
assert "Get-Command -Name Get-LocalUser" in script
|
|
assert "ToUnixTimeMilliseconds" in script
|
|
assert "ConvertTo-Json -Compress -Depth 6" in script
|
|
|
|
def test_groups_are_named_by_sid_never_by_their_english_name(self):
|
|
script = mod._PS_LOGIN_ACCOUNTS
|
|
assert "'S-1-5-32-544'" in script and "'S-1-5-32-555'" in script
|
|
assert "Translate([Security.Principal.NTAccount])" in script
|
|
assert "WinNT://' + $env:COMPUTERNAME + '/Administrators" not in script
|
|
|
|
def test_it_reads_no_secret_and_leaves_nothing_behind(self):
|
|
"""The only file is secedit's export of the user rights, removed in ``finally``."""
|
|
script = mod._PS_LOGIN_ACCOUNTS
|
|
assert "/areas USER_RIGHTS" in script
|
|
assert "finally { Remove-Item -LiteralPath $cfg" in script
|
|
for verb in (
|
|
"Set-LocalUser",
|
|
"Add-LocalGroupMember",
|
|
"net user",
|
|
"SetPassword",
|
|
"/configure",
|
|
):
|
|
assert verb not in script
|
|
|
|
def test_a_native_command_runs_inside_cmd_with_stderr_merged(self):
|
|
"""A line on stderr would be an error record in a remote session (time_sync.py)."""
|
|
assert "cmd.exe /c ('secedit " in mod._PS_LOGIN_ACCOUNTS
|
|
assert "' 2>&1')" in mod._PS_LOGIN_ACCOUNTS
|