fix: tolerate missing ServerDisplayName and send host.ipv4 (1.2.17-SAC)

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-05-28 13:33:26 +10:00
parent 611d9c68ca
commit 49359c07a6
5 changed files with 49 additions and 7 deletions
+7 -3
View File
@@ -80,7 +80,7 @@ $script:MonitorLoopInitialized = $false
# строки ниже, если правки «мелкие» и вы не хотите менять отображаемую версию в логах).
# Рекомендация: при значимых релизах меняйте и $ScriptVersion, и version.txt одинаково; при только
# исправлениях на шаре — достаточно поднять patch в version.txt (например 1.3.0.1).
$ScriptVersion = "1.2.16-SAC"
$ScriptVersion = "1.2.17-SAC"
# Логи (все под InstallRoot)
$LogFile = Join-Path $script:InstallRoot "Logs\login_monitor.log"
@@ -1244,8 +1244,12 @@ function Format-Rcm1149Event {
}
function Get-MonitorServerLabel {
if ($null -ne $ServerDisplayName -and -not [string]::IsNullOrWhiteSpace([string]$ServerDisplayName)) {
return [string]$ServerDisplayName.Trim()
$label = $null
if (Get-Variable -Name ServerDisplayName -ErrorAction SilentlyContinue) {
$label = (Get-Variable -Name ServerDisplayName -ValueOnly)
}
if ($null -ne $label -and -not [string]::IsNullOrWhiteSpace([string]$label)) {
return [string]$label.Trim()
}
return [string]$env:COMPUTERNAME
}
+2 -1
View File
@@ -13,7 +13,7 @@ PowerShell-набор для мониторинга входов в Windows с
- Документация по развёртыванию: **[Docs/README.md](Docs/README.md)** (RDP-монитор, Exchange, NETLOGON).
- **`Encrypt-DpapiForRdpMonitor.ps1`** — опционально для подготовки DPAPI-строк токена/chat id и пароля SMTP (`$MailSmtpPasswordProtectedB64` в файле настроек).
- **Локальные настройки RDP-монитора:** **`login_monitor.settings.ps1`** в каталоге установки (образец **`login_monitor.settings.example.ps1`**). При автообновлении **`Login_Monitor.ps1`** с шары файл настроек **не перезаписывается** (как **`exchange_monitor.settings.ps1`** для Exchange).
- **Security Alert Center (SAC):** модуль **`Sac-Client.ps1`** (копируется вместе с `Login_Monitor.ps1`). Режимы **`$UseSAC`**: `off` | `exclusive` | `dual` | `fallback` — контракт в репозитории **security-alert-center** (`docs/agent-integration.md`). Версия релиза: **`$ScriptVersion`** и **`version.txt`** (сейчас **1.2.16-SAC**); **`Sac-Client.ps1`** передаёт ту же версию в SAC (`product_version`).
- **Security Alert Center (SAC):** модуль **`Sac-Client.ps1`** (копируется вместе с `Login_Monitor.ps1`). Режимы **`$UseSAC`**: `off` | `exclusive` | `dual` | `fallback` — контракт в репозитории **security-alert-center** (`docs/agent-integration.md`). Версия релиза: **`$ScriptVersion`** и **`version.txt`** (сейчас **1.2.17-SAC**); **`Sac-Client.ps1`** передаёт ту же версию в SAC (`product_version`).
## Что изменилось (важное)
@@ -39,6 +39,7 @@ PowerShell-набор для мониторинга входов в Windows с
- **Email (SMTP):** `$MailSmtpHost`, `$MailFrom`, `$MailTo`, `$MailSmtpPort` (по умолчанию 587), при необходимости `$MailSmtpUser` / `$MailSmtpPassword` (или `$MailSmtpPasswordProtectedB64` через DPAPI), `$MailSmtpStartTls` / `$MailSmtpSsl`
- **Порядок:** `$NotifyOrder` — пусто = авто (Telegram → Email, только настроенные); иначе `telegram,email` или `email` и т.п. (допускаются `tg`, `mail`)
- **SAC (опционально):** `$UseSAC`, `$SacUrl`, `$SacApiKey` — см. блок в **`login_monitor.settings.example.ps1`**. Проверка: `Login_Monitor.ps1 -CheckSac`
- **IP хоста для SAC (опционально):** `$ServerIPv4` — явный IPv4 для `host.ipv4`; если не задан, берётся автоопределение
- **Exchange-шум 4624 (опционально):** `${Ignore4624-LT3-EmptyIP-Event} = $true` — подавляет `4624` c `LogonType=3` и `IP='-'` (часто Outlook/SMTP-клиенты на почтовом сервере)
- Пошаговое обновление по домену: **[Docs/deploy-rdp-login-monitor.md](Docs/deploy-rdp-login-monitor.md)** (раздел «Обновление на любой Windows-машине»)
4. Запускайте с правами администратора (чтение `Security` журнала и регистрация задач).
+37 -2
View File
@@ -4,7 +4,7 @@
.DESCRIPTION
Dot-source после login_monitor.settings.ps1 и функции Write-Log.
Ожидает: $UseSAC, $SacUrl, $SacApiKey, $ScriptVersion, $script:InstallRoot.
Release: 1.2.15-SAC (host.display_name from $ServerDisplayName).
Release: same as Login_Monitor.ps1 $ScriptVersion / version.txt (host.display_name via $ServerDisplayName).
#>
function Test-SacIngestAcceptedStatus {
@@ -254,14 +254,49 @@ function Get-SacHostBlock {
os_family = 'windows'
}
if (Get-Variable -Name ServerDisplayName -ErrorAction SilentlyContinue) {
$label = $ServerDisplayName
$label = (Get-Variable -Name ServerDisplayName -ValueOnly)
if (-not [string]::IsNullOrWhiteSpace([string]$label)) {
$hostBlock.display_name = [string]$label.Trim()
}
}
$ipv4 = Get-SacHostIPv4
if (-not [string]::IsNullOrWhiteSpace($ipv4)) {
$hostBlock.ipv4 = $ipv4
}
return $hostBlock
}
function Get-SacHostIPv4 {
# Явный override в login_monitor.settings.ps1 (опционально).
if (Get-Variable -Name ServerIPv4 -ErrorAction SilentlyContinue) {
$manual = [string](Get-Variable -Name ServerIPv4 -ValueOnly)
if (-not [string]::IsNullOrWhiteSpace($manual)) {
$m = $manual.Trim()
if ($m -match '^(?:\d{1,3}\.){3}\d{1,3}$') { return $m }
Write-SacLog "WARN: ServerIPv4='$m' не похож на IPv4, игнорирую override"
}
}
try {
$ips = @(Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object {
$_.IPAddress -and
$_.IPAddress -notmatch '^(127\.|169\.254\.)' -and
$_.PrefixOrigin -ne 'WellKnown'
} | Select-Object -ExpandProperty IPAddress)
if ($ips.Count -gt 0) { return [string]$ips[0] }
} catch {}
try {
$sock = New-Object System.Net.Sockets.Socket ([System.Net.Sockets.AddressFamily]::InterNetwork), ([System.Net.Sockets.SocketType]::Dgram), ([System.Net.Sockets.ProtocolType]::Udp)
$sock.Connect('1.1.1.1', 53)
$ip = [string]$sock.LocalEndPoint.Address
$sock.Dispose()
if ($ip -match '^(?:\d{1,3}\.){3}\d{1,3}$' -and $ip -notmatch '^(127\.|169\.254\.)') { return $ip }
} catch {}
return ''
}
function New-SacEventPayload {
param(
[Parameter(Mandatory = $true)][string]$EventType,
+2
View File
@@ -29,6 +29,8 @@ $NotifyOrder = 'tg'
# --- Подпись сервера в Telegram и SAC (host.display_name); пусто = $env:COMPUTERNAME ---
# $ServerDisplayName = 'UNMS Kalina'
# --- Явный IPv4 хоста для SAC (опционально; иначе автоопределение) ---
# $ServerIPv4 = '192.168.160.57'
# --- Security Alert Center (SAC) ---
# off | exclusive | dual | fallback — см. security-alert-center/docs/agent-integration.md
+1 -1
View File
@@ -1 +1 @@
1.2.16-SAC
1.2.17-SAC