_member hands its name and kind to _member_name and _is_group; parse_login_sessions hands the audit check to _audited_logons and the sessions to _sessions. No change in behaviour.
266 lines
11 KiB
Python
266 lines
11 KiB
Python
"""The logins a Windows host recorded, at its console and over Remote Desktop
|
|
(NetOrk/netork#2895).
|
|
|
|
:class:`WindowsLoginSessionsMixin` fills napalm-device-types' ``get_login_sessions``
|
|
reading (``LoginSessionsDict``) from the Security event log, in one script, read-only:
|
|
|
|
- **The logons** are event 4624 of the last :data:`SESSION_WINDOW_DAYS` days, bounded on
|
|
the host (``timediff``), the newest :data:`SESSIONS_READ`: logon type 2 (at the
|
|
console), 10 (Remote Desktop) and 11 (at the console with cached credentials), as
|
|
``tty`` ``console`` or ``rdp``. Not type 3 (network): every SMB access and every WinRM
|
|
connection is one, this reading's own included; nor 7, an unlock of a session already
|
|
read. Only a person's account counts -- a SID of the host, a domain (``S-1-5-21-``) or
|
|
Entra ID (``S-1-12-``) -- not the window manager's or the font driver's (``DWM-1``,
|
|
``UMFD-0``). An administrator's logon is two events, a full and a filtered token
|
|
linked to each other (``TargetLinkedLogonId``): one session.
|
|
- **The end** is the logoff of the logon (4634, or 4647 when the user logged off). The
|
|
account is ``DOMAIN\\name``, the host's own accounts by name alone. The address is the
|
|
event's ``IpAddress``; a console logon's loopback is none.
|
|
- **The reading's own address** is that of its own WinRM logon: the session's logon ID
|
|
(``Win32_SessionProcess``, else the logon SID ``S-1-5-5-X-Y`` of its token) names its
|
|
4624 event. Where that event has no address, the one client connected to WinRM's ports
|
|
(``Get-NetTCPConnection``); several, none. Remote Desktop sessions from it are left out,
|
|
as on Linux the reading's own SSH sessions are.
|
|
- **Coverage:** the Security log rotates by size, often within days. ``records_since`` is
|
|
its oldest event, so a login before it is unknown rather than absent. A host that holds
|
|
not even this reading's own logon and no other in the window does not audit logons:
|
|
:class:`LoginSessionsUnavailable`, never "nobody logged in".
|
|
|
|
``Get-WinEvent`` answers no match with an error (``NoMatchingEventsFound``); the script
|
|
takes that for none. Reading the Security log takes an administrator.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import ipaddress
|
|
import json
|
|
from collections.abc import Iterable
|
|
from datetime import UTC, datetime
|
|
from typing import TYPE_CHECKING, Any
|
|
|
|
from napalm_device_types.login_sessions import (
|
|
SESSION_WINDOW_DAYS,
|
|
SESSIONS_READ,
|
|
LoginSessionsUnavailable,
|
|
session_address,
|
|
)
|
|
|
|
from napalm_windows._powershell import _as_list
|
|
|
|
if TYPE_CHECKING: # pragma: no cover - the contract's newer keys, for type checkers only
|
|
from napalm_device_types.login_sessions import LoginSessionDict, LoginSessionsDict
|
|
|
|
#: Logon type → terminal: at the console, Remote Desktop, at the console with cached
|
|
#: credentials.
|
|
LOGON_TYPES = {"2": "console", "10": "rdp", "11": "console"}
|
|
#: The SIDs of a person's account: the host's or a domain's, and Entra ID's.
|
|
_PERSON_SIDS = ("S-1-5-21-", "S-1-12-")
|
|
_DAY_MS = 86_400_000
|
|
|
|
_PS_SESSIONS_TEMPLATE = r"""
|
|
$ErrorActionPreference = 'Stop'
|
|
function Ms($t) { if ($null -ne $t) { ([DateTimeOffset]$t).ToUnixTimeMilliseconds() } }
|
|
function Events($filter, $max, [switch]$Oldest) {
|
|
try { Get-WinEvent -LogName Security -FilterXPath $filter -MaxEvents $max -Oldest:$Oldest }
|
|
catch { if ($_.FullyQualifiedErrorId -notlike 'NoMatchingEventsFound*') { throw } }
|
|
}
|
|
function P($e, $i) { if ($e.Properties.Count -gt $i) { [string]$e.Properties[$i].Value } }
|
|
function Logon($t) { "Data[@Name='LogonType']='" + $t + "'" }
|
|
function Query($id, $data) {
|
|
$within = 'TimeCreated[timediff(@SystemTime) <= __WINDOW_MS__]'
|
|
$system = "*[System[EventID=" + $id + " and " + $within + "]"
|
|
if ($data) { $system + " and EventData[" + $data + "]]" } else { $system + "]" }
|
|
}
|
|
$types = (Logon 2) + ' or ' + (Logon 10) + ' or ' + (Logon 11)
|
|
$ownId = $null
|
|
try {
|
|
$query = "ASSOCIATORS OF {Win32_Process.Handle='" + $PID + "'}" +
|
|
" WHERE AssocClass=Win32_SessionProcess"
|
|
$session = @(Get-CimInstance -Query $query)
|
|
if ($session.Count -gt 0) { $ownId = [uint64]$session[0].LogonId }
|
|
} catch { }
|
|
if ($null -eq $ownId) {
|
|
$groups = [Security.Principal.WindowsIdentity]::GetCurrent().Groups
|
|
$logonSid = @($groups | Where-Object { $_.Value -like 'S-1-5-5-*' })
|
|
if ($logonSid.Count -gt 0) {
|
|
$parts = $logonSid[0].Value.Split('-')
|
|
$ownId = ([uint64]$parts[4] -shl 32) + [uint64]$parts[5]
|
|
}
|
|
}
|
|
$canary = $null; $ownIp = $null
|
|
if ($null -ne $ownId) {
|
|
$mine = "Data[@Name='TargetLogonId']='" + ('0x{0:x}' -f $ownId) + "'"
|
|
$within = 'TimeCreated[timediff(@SystemTime) <= __DAY_MS__]'
|
|
$own = @(Events ("*[System[EventID=4624 and " + $within + "] and EventData[" + $mine + "]]") 1)
|
|
$canary = $own.Count -gt 0
|
|
if ($canary) { $ownIp = P $own[0] 18 }
|
|
}
|
|
$peers = @()
|
|
try {
|
|
$winrm = Get-NetTCPConnection -State Established -LocalPort 5985, 5986 `
|
|
-ErrorAction SilentlyContinue
|
|
$peers = @($winrm | ForEach-Object { [string]$_.RemoteAddress } | Sort-Object -Unique)
|
|
} catch { }
|
|
$logons = @(Events (Query 4624 $types) __READ__ | ForEach-Object {
|
|
[pscustomobject]@{
|
|
t = Ms $_.TimeCreated; sid = P $_ 4; user = P $_ 5; domain = P $_ 6
|
|
id = P $_ 7; type = P $_ 8; ip = P $_ 18; linked = P $_ 25
|
|
}
|
|
})
|
|
$ended = @(Events (Query 4634 $types) __ENDS__) + @(Events (Query 4647 $null) __READ__)
|
|
$ends = @($ended | ForEach-Object { [pscustomobject]@{ t = Ms $_.TimeCreated; id = P $_ 3 } })
|
|
$first = @(Events '*' 1 -Oldest)
|
|
[pscustomobject]@{
|
|
computer = $env:COMPUTERNAME
|
|
canary = $canary
|
|
own_ip = $ownIp
|
|
winrm_peers = $peers
|
|
oldest = if ($first.Count -gt 0) { Ms $first[0].TimeCreated } else { $null }
|
|
logons = $logons
|
|
ends = $ends
|
|
} | ConvertTo-Json -Compress -Depth 4
|
|
"""
|
|
#: The script: the window, a day for its own logon, and the events read, filled in.
|
|
_PS_LOGIN_SESSIONS = (
|
|
_PS_SESSIONS_TEMPLATE.replace("__WINDOW_MS__", str(SESSION_WINDOW_DAYS * _DAY_MS))
|
|
.replace("__DAY_MS__", str(_DAY_MS))
|
|
.replace("__READ__", str(SESSIONS_READ))
|
|
.replace("__ENDS__", str(2 * SESSIONS_READ))
|
|
)
|
|
|
|
|
|
def _iso(ms: Any) -> str | None:
|
|
if not isinstance(ms, int | float) or isinstance(ms, bool):
|
|
return None
|
|
return datetime.fromtimestamp(ms / 1000, UTC).isoformat()
|
|
|
|
|
|
def _id(value: Any) -> int | None:
|
|
"""A logon ID as the event gives it, decimal; None for none or 0 (no linked logon)."""
|
|
try:
|
|
number = int(str(value))
|
|
except ValueError:
|
|
return None
|
|
return number or None
|
|
|
|
|
|
def _own_address(raw: dict[str, Any]) -> str | None:
|
|
"""Where this reading's own WinRM logon came from: its 4624 event's address, else the
|
|
one client connected to WinRM."""
|
|
own = session_address(raw.get("own_ip")) if raw.get("canary") else None
|
|
if own is not None:
|
|
return own
|
|
peers = {session_address(str(p)) for p in _as_list(raw.get("winrm_peers"))} - {None}
|
|
return peers.pop() if len(peers) == 1 else None
|
|
|
|
|
|
def _user(event: dict[str, Any], computer: str) -> str:
|
|
user, domain = str(event.get("user") or ""), str(event.get("domain") or "")
|
|
return user if not domain or domain.upper() == computer.upper() else f"{domain}\\{user}"
|
|
|
|
|
|
def _address(event: dict[str, Any], tty: str) -> str | None:
|
|
address = session_address(event.get("ip"))
|
|
if tty == "console" and address is not None:
|
|
try:
|
|
if ipaddress.ip_address(address).is_loopback:
|
|
return None
|
|
except ValueError:
|
|
return address
|
|
return address
|
|
|
|
|
|
def _ends(raw: dict[str, Any]) -> dict[int, list[int]]:
|
|
"""Each logon ID's logoffs, in milliseconds: an ID is used again after a restart."""
|
|
ends: dict[int, list[int]] = {}
|
|
for end in _as_list(raw.get("ends")):
|
|
logon, at = _id(end.get("id")), end.get("t")
|
|
if logon is not None and isinstance(at, int):
|
|
ends.setdefault(logon, []).append(at)
|
|
return ends
|
|
|
|
|
|
def _logons(events: list[dict[str, Any]]) -> Iterable[dict[str, Any]]:
|
|
"""The 4624 events of a person's interactive logon, one per linked pair."""
|
|
seen: set[int] = set()
|
|
for event in sorted(events, key=lambda e: int(e["t"])):
|
|
logon, linked = _id(event.get("id")), _id(event.get("linked"))
|
|
if logon is None or str(event.get("type")) not in LOGON_TYPES:
|
|
continue
|
|
if not str(event.get("sid") or "").upper().startswith(_PERSON_SIDS):
|
|
continue
|
|
key = min(logon, linked) if linked else logon
|
|
if key not in seen:
|
|
seen.add(key)
|
|
yield event
|
|
|
|
|
|
def _session(event: dict[str, Any], computer: str, ends: dict[int, list[int]]) -> LoginSessionDict:
|
|
tty = LOGON_TYPES[str(event.get("type"))]
|
|
started = int(event["t"])
|
|
ids = [i for i in (_id(event.get("id")), _id(event.get("linked"))) if i is not None]
|
|
ended = [at for i in ids for at in ends.get(i, ()) if at >= started]
|
|
return {
|
|
"user": _user(event, computer),
|
|
"tty": tty,
|
|
"address": _address(event, tty),
|
|
"started": _iso(started) or "",
|
|
"ended": _iso(min(ended)) if ended else None,
|
|
}
|
|
|
|
|
|
def _audited_logons(raw: dict[str, Any]) -> list[dict[str, Any]]:
|
|
"""The logon events read; raises when the log holds none, not even this reading's own."""
|
|
logons = [e for e in _as_list(raw.get("logons")) if isinstance(e, dict)]
|
|
if raw.get("canary") is False and not logons:
|
|
raise LoginSessionsUnavailable(
|
|
"the Security log holds no logon, not even this reading's own: logons are not audited"
|
|
)
|
|
return [e for e in logons if isinstance(e.get("t"), int)]
|
|
|
|
|
|
def _sessions(
|
|
logons: list[dict[str, Any]], raw: dict[str, Any], own: str | None
|
|
) -> list[LoginSessionDict]:
|
|
"""The sessions newest first, those from *own* left out, at most SESSIONS_READ."""
|
|
computer, ends = str(raw.get("computer") or ""), _ends(raw)
|
|
sessions = [_session(e, computer, ends) for e in _logons(logons)]
|
|
sessions = [s for s in sessions if own is None or s["address"] != own]
|
|
sessions.sort(key=lambda s: s["started"], reverse=True)
|
|
return sessions[:SESSIONS_READ]
|
|
|
|
|
|
def parse_login_sessions(raw: dict[str, Any]) -> LoginSessionsDict:
|
|
"""What :data:`_PS_LOGIN_SESSIONS` emitted, as napalm-device-types' reading.
|
|
|
|
:raises LoginSessionsUnavailable: when the host does not audit logons.
|
|
"""
|
|
logons = _audited_logons(raw)
|
|
own = _own_address(raw)
|
|
return {
|
|
"own_address": own,
|
|
"sessions": _sessions(logons, raw, own),
|
|
"records_since": _iso(raw.get("oldest")),
|
|
}
|
|
|
|
|
|
class WindowsLoginSessionsMixin:
|
|
"""``get_login_sessions`` for the driver, which carries the script."""
|
|
|
|
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
|
|
|
def _run_raw(self, script: str) -> str: ...
|
|
|
|
def get_login_sessions(self) -> LoginSessionsDict:
|
|
"""The console and Remote Desktop logins of the last seven days, newest first, in
|
|
napalm-device-types' ``LoginSessionsDict``; see the module.
|
|
|
|
:raises LoginSessionsUnavailable: when the host does not audit logons.
|
|
:raises ValueError: when the reading came back empty.
|
|
"""
|
|
out = self._run_raw(_PS_LOGIN_SESSIONS).strip()
|
|
raw = json.loads(out) if out else None
|
|
if not isinstance(raw, dict):
|
|
raise ValueError("the login session reading came back empty")
|
|
return parse_login_sessions(raw)
|