fix: invoke auditpol by full path when System32 is missing from PATH (v1.5.6)

This commit is contained in:
PTah
2026-05-22 10:41:59 +10:00
parent eccffe927a
commit ab98eab49c
4 changed files with 23 additions and 10 deletions
+20 -7
View File
@@ -71,7 +71,7 @@ $script:MonitorSingletonLockStream = $null
# строки ниже, если правки «мелкие» и вы не хотите менять отображаемую версию в логах).
# Рекомендация: при значимых релизах меняйте и $ScriptVersion, и version.txt одинаково; при только
# исправлениях на шаре — достаточно поднять patch в version.txt (например 1.3.0.1).
$ScriptVersion = "1.5.5"
$ScriptVersion = "1.5.6"
# Логи (все под InstallRoot)
$LogFile = Join-Path $script:InstallRoot "Logs\login_monitor.log"
@@ -806,15 +806,28 @@ $script:HeartbeatStaleAlertActive = $false
function Enable-SecurityAudit {
Write-Log "Checking security audit (auditpol) settings..."
# auditpol writes to stderr; do not throw under $ErrorActionPreference = Stop.
# auditpol: full path (PATH on some hosts omits System32). Merge stdout+stderr via ProcessStartInfo.
function Invoke-AuditPol {
param([Parameter(Mandatory = $true)][string]$Arguments)
$cmd = "auditpol $Arguments 2>&1"
$text = cmd.exe /c $cmd
$code = $LASTEXITCODE
$auditpolExe = Join-Path $env:SystemRoot 'System32\auditpol.exe'
if (-not (Test-Path -LiteralPath $auditpolExe)) {
throw "auditpol.exe not found: $auditpolExe"
}
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $auditpolExe
$psi.Arguments = $Arguments
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $true
$proc = [System.Diagnostics.Process]::Start($psi)
$stdout = $proc.StandardOutput.ReadToEnd()
$stderr = $proc.StandardError.ReadToEnd()
$proc.WaitForExit()
$text = ($stdout + $stderr).Trim()
return [pscustomobject]@{
ExitCode = $code
Text = ($text | Out-String).Trim()
ExitCode = $proc.ExitCode
Text = $text
}
}
+1 -1
View File
@@ -18,7 +18,7 @@ PowerShell-набор для мониторинга входов в Windows с
- **Кодировка `.ps1`**: в репозитории добавлены `.editorconfig` и `.gitattributes`, чтобы `*.ps1` по умолчанию сохранялись как **UTF-8 with BOM** и с **CRLF** (это сильно снижает “кракозябры” и ошибки парсинга PowerShell).
- **Кодировка логов**: `login_monitor.log` / `watchdog.log` пишутся как **UTF-8 с BOM** (и при необходимости BOM добавляется к уже существующему файлу), чтобы в **FAR/старых просмотрщиках** не было ситуации “в консоли нормально, а в файле РЈРІРµ…” из‑за неверной авто-кодировки.
- **`auditpol` на русской Windows**: настройка/проверка аудита опирается на категорию **`Вход/выход`** и подкатегории **`Вход в систему` / `Выход из системы`** (ожидается строка **`Успех и сбой`**). Это устраняет ошибки вида `0x00000057` из‑за несуществующего на RU ОС имени `Logon`.
- **Стабильность**: `auditpol` запускается через `cmd.exe` с перехватом `stdout+stderr`, чтобы не ломать выполнение при `$ErrorActionPreference = "Stop"`.
- **Стабильность**: `auditpol` вызывается по полному пути `%SystemRoot%\System32\auditpol.exe` (без зависимости от PATH), stdout+stderr объединяются через `ProcessStartInfo`.
## 1) Подготовка
+1 -1
View File
@@ -18,7 +18,7 @@ PowerShell toolkit for monitoring Windows logons with Telegram and/or Email (SMT
- **`.ps1` encoding**: `.editorconfig` and `.gitattributes` encourage **`*.ps1`** as **UTF-8 with BOM** and **CRLF**, reducing mojibake and PowerShell parse issues.
- **Log encoding**: `login_monitor.log` / `watchdog.log` are written as **UTF-8 with BOM** (BOM is applied to existing files if missing) so viewers like **FAR Manager** do not mis-detect encoding.
- **`auditpol` on Russian Windows**: auditing checks use the **`Вход/выход`** category and **`Вход в систему` / `Выход из системы`** subcategories (expect **`Успех и сбой`**), avoiding errors such as `0x00000057` when English names like `Logon` are absent on a localized OS.
- **Stability**: `auditpol` is invoked via `cmd.exe` with merged stdout/stderr so `$ErrorActionPreference = 'Stop'` does not abort on stderr-only output.
- **Stability**: `auditpol` is invoked via full path `%SystemRoot%\System32\auditpol.exe` (no PATH dependency); stdout and stderr are merged via `ProcessStartInfo`.
## 1) Preparation
+1 -1
View File
@@ -1 +1 @@
1.5.5
1.5.6