Files
RDP-login-monitor/scripts/Sanitize-ForGitHub.ps1
T

170 lines
8.1 KiB
PowerShell
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Replace production-only values with public-safe placeholders (GitHub mirror).
# Usage: .\scripts\Sanitize-ForGitHub.ps1
# Reversible: production copies live on kalinamall/papatramp; restore via git reset --hard.
param(
[switch]$WhatIf
)
$ErrorActionPreference = 'Stop'
$Root = Split-Path -Parent $PSScriptRoot
Set-Location $Root
function Set-TrackedFileText {
param(
[Parameter(Mandatory = $true)][string]$RelativePath,
[Parameter(Mandatory = $true)][string]$Content
)
$path = Join-Path $Root $RelativePath
if ($WhatIf) {
Write-Output "WhatIf: would write $RelativePath"
return
}
$utf8Bom = New-Object System.Text.UTF8Encoding $true
[System.IO.File]::WriteAllText($path, $Content.TrimEnd() + "`r`n", $utf8Bom)
Write-Output "sanitized: $RelativePath"
}
$loginSettings = @'
<#
.SYNOPSIS
Локальные настройки Login_Monitor.ps1
.DESCRIPTION
Скопируйте в C:\ProgramData\RDP-login-monitor\login_monitor.settings.ps1
и при необходимости отредактируйте. Deploy-LoginMonitor.ps1 не перезаписывает settings,
если SAC уже настроен (UseSAC не off и задан SacApiKey). При первой установке или апгрейде
с версии без SAC (нет Sac-Client.ps1 / пустой ключ) example копируется поверх с резервной .bak.
#>
# --- Telegram (или DPAPI Base64 через Encrypt-DpapiForRdpMonitor.ps1) ---
$TelegramBotToken = 'YOUR_BOT_TOKEN'
$TelegramChatID = 'YOUR_CHAT_ID'
# $TelegramBotTokenProtectedB64 = ''
# $TelegramChatIDProtectedB64 = ''
# --- Email (опционально) ---
$NotifyOrder = 'tg'
# $MailSmtpHost = 'smtp.example.com'
# $MailSmtpPort = 587
# $MailSmtpUser = ''
# $MailSmtpPassword = ''
# $MailFrom = 'monitor@example.com'
# $MailTo = 'admin@example.com'
# $MailSmtpStartTls = $true
# $MailSmtpSsl = $false
# $MailSmtpPasswordProtectedB64 = ''
# --- Подпись сервера в Telegram и SAC (host.display_name); пусто = $env:COMPUTERNAME ---
# $ServerDisplayName = 'RDP-Server-01'
# --- Явный IPv4 хоста для SAC (опционально; иначе автоопределение) ---
# $ServerIPv4 = '192.168.1.10'
# --- Security Alert Center (SAC) ---
# off | exclusive | dual | fallback — см. security-alert-center/docs/agent-integration.md
$UseSAC = 'fallback'
$SacUrl = 'https://sac.example.com'
$SacApiKey = 'sac_CHANGE_ME'
$SacSpoolDir = 'C:\ProgramData\RDP-login-monitor\sac-spool'
$SacTimeoutSec = 45
$SacSpoolFlushMaxFiles = 50
$SacSpoolMaxAgeHours = 72
# $SacTlsSkipVerify = $false
# $SacFallbackFailures = 5
# $false = не слать report.daily.rdp с агента (суточный отчёт только из SAC)
# В settings.ps1 используйте 1/0 или $true/$false — не пишите голое false без $
$DailyReportEnabled = 1
# --- Heartbeat SAC (agent.heartbeat): интервал в секундах; 14400 = 4 ч ---
$HeartbeatInterval = 14400
# Оповещение, если last_heartbeat.txt не обновлялся > множитель × интервал (2 × 4 ч = 8 ч)
$HeartbeatStaleAlertMultiplier = 2
# Poll SAC на команды qwinsta/logoff (сек); см. security-alert-center/docs/agent-control-plane.md
# $SacCommandPollIntervalSec = 60
# Окно (мин): LastBootUpTime + System 41/1074/6005/6008/6009 → «старт после перезагрузки ОС»
$StartupRebootDetectMinutes = 5
# --- Инвентаризация железа/ПО для SAC (agent.inventory, раз в 12 ч) ---
$GetInventory = $true
# --- RDS Shadow Control + WinRM inbound (Enter-PSSession), severity warning ---
# $EnableRcm1149Monitoring = 1 # RCM Operational 1149 (RDP auth; workstation + RDS server)
# $EnableRcmShadowControlMonitoring = 1 # RCM Operational 20506/20507/20510
# $EnableWinRmInboundMonitoring = 1 # WinRM Operational 91 (+ correlate Security 4624)
# $EnableAdminShareMonitoring = 1 # Security 5140 C$/ADMIN$ (audit File Share)
# $WinRmIgnoreLocalSource = 1 # ::1, 127.0.0.1, fe80 (шум Exchange/локальный WinRM)
# $WinRmIgnoreMachineAccounts = 1 # учётки, оканчивающиеся на $
# $WinRmExchangeStrictMode = 1 # Exchange: user в Event 91 обязателен; 4624 только LogonProcess WinRM
# HealthMailbox* уже в ExcludedUserPatterns скрипта
# Проверка: powershell -File Login_Monitor.ps1 -CheckSac
# --- Узкое исключение шумовых сетевых логонов (LogonType=3, Advapi) ---
$IgnoreAdvapiNetworkLogonSourceIps = @(
'192.168.1.10'
)
# --- Exchange noise filter: 4624 + LogonType=3 + IP='-' (часто Outlook/почтовые клиенты) ---
# Включайте на почтовом сервере, если нужен только полезный интерактивный сигнал.
${Ignore4624-LT3-EmptyIP-Event} = $false
# --- Ротация login_monitor.log и хранение бэкапов (Logs\Backup\LoginLog_*.bak) ---
# $LogRotationHour = 0
# $LogRotationMinute = 0
$MaxBackupDays = 31
# --- Блокировка учётной записи AD (4740) + IP из IIS ActiveSync ---
# Мониторинг включается только на КД с именем $LockoutMonitorDomainController.
$LockoutMonitorDomainController = 'dc01.contoso.local'
$NetBiosDomainName = 'CONTOSO'
$ExchangeIisLogPath = '\\mail.contoso.local\c$\inetpub\logs\LogFiles\W3SVC1'
$ExchangeServerHostForIisExclude = ''
$ExchangeIisLogTailLines = 5000
$ExchangeIisLogMinutesBeforeLockout = 30
'@
Set-TrackedFileText -RelativePath 'login_monitor.settings.example.ps1' -Content $loginSettings
$exchangeSettingsPath = Join-Path $Root 'exchange_monitor.settings.example.ps1'
if (Test-Path -LiteralPath $exchangeSettingsPath) {
$ex = Get-Content -LiteralPath $exchangeSettingsPath -Raw
$ex = $ex -replace 'kalinamall\.ru', 'example.com'
$ex = $ex -replace 'fifth\.example\.com', 'mail.contoso.local'
$ex = $ex -replace 'k\.selezneva@example\.com', 'broken-mailbox@example.com'
Set-TrackedFileText -RelativePath 'exchange_monitor.settings.example.ps1' -Content $ex
}
$updatePath = Join-Path $Root 'update-rdp-monitor.ps1'
if (Test-Path -LiteralPath $updatePath) {
$upd = Get-Content -LiteralPath $updatePath -Raw
$upd = $upd -replace "Posle fetch: vsegda reset --hard na kalinamall/main \(bez merge\), zatem clean -fd\.",
'Posle fetch: reset --hard na upstream/main (bez merge), zatem clean -fd.'
$upd = $upd -replace "\\\\b26\\NETLOGON\\RDP-login-monitor", '\\dc.contoso.local\NETLOGON\RDP-login-monitor'
$upd = $upd -replace "https://git\.kalinamall\.ru/PapaTramp/RDP-login-monitor\.git",
'https://github.com/PTah/RDP-login-monitor.git'
Set-TrackedFileText -RelativePath 'update-rdp-monitor.ps1' -Content $upd
}
$netlogonDoc = Join-Path $Root 'Docs/deploy-netlogon-publish.md'
if (Test-Path -LiteralPath $netlogonDoc) {
$doc = Get-Content -LiteralPath $netlogonDoc -Raw
$doc = $doc -replace 'K6A-DC3', 'dc01.corp.example.com'
$doc = $doc -replace '\\\\b26\\', '\\dc.contoso.local\'
$doc = $doc -replace "https://git\.kalinamall\.ru/PapaTramp/RDP-login-monitor\.git",
'https://git.example.com/org/RDP-login-monitor.git'
Set-TrackedFileText -RelativePath 'Docs/deploy-netlogon-publish.md' -Content $doc
}
$mdFiles = @(git ls-files '*.md' 2>$null | Where-Object { $_ -and (Test-Path $_) })
foreach ($rel in $mdFiles) {
$path = Join-Path $Root $rel
$md = Get-Content -LiteralPath $path -Raw
$orig = $md
$md = $md -replace 'https://git\.kalinamall\.ru/PapaTramp/([^)/\s]+)/src/branch/main/', 'https://github.com/PTah/$1/blob/main/'
$md = $md -replace 'https://git\.papatramp\.ru/PapaTramp/([^)/\s]+)/src/branch/main/', 'https://github.com/PTah/$1/blob/main/'
$md = $md -replace 'https://git\.kalinamall\.ru/PapaTramp/', 'https://github.com/PTah/'
$md = $md -replace 'https://git\.papatramp\.ru/PapaTramp/', 'https://github.com/PTah/'
if ($md -ne $orig) {
Set-TrackedFileText -RelativePath $rel -Content $md
}
}
Write-Output 'Sanitize-ForGitHub: done'