diff --git a/docs/muninn.md b/docs/muninn.md index 3b5dbf1..e2625ab 100644 --- a/docs/muninn.md +++ b/docs/muninn.md @@ -205,9 +205,9 @@ missing or the Quest is unavailable, Muninn publishes `muninn.quest_access` as Raven runs Muninn from `C:\Meta\Odin\Muninn`. `scripts/restart-muninn.ps1` recreates the `GameCult-Muninn` scheduled task with `wscript.exe` as the task action and `start-muninn-serve-hidden.vbs` as its argument. It also repairs -`GameCult-Muninn-Activate` and `GameCult-Muninn-VideoProof` to execute their -hidden VBS launchers directly when those compatibility commands exist on Raven. -The serve VBS launches `start-muninn-serve.ps1` with noninteractive hidden +`GameCult-Muninn-Activate` and `GameCult-Muninn-VideoProof` to execute hidden +VBS launchers whose bodies call PowerShell entrypoints directly, not `.cmd` +payloads. The serve VBS launches `start-muninn-serve.ps1` with noninteractive hidden PowerShell. The PowerShell launcher starts `muninn.exe` with `-WindowStyle Hidden`, passes `--idunn-rudp-health 10.77.0.2:17870`, `--idunn-daemon muninn`, and @@ -215,14 +215,16 @@ PowerShell. The PowerShell launcher starts `muninn.exe` with redirects logs under `C:\Meta\Odin\logs\muninn`. Raven is an operator-consented host: Muninn operations on Raven must be background-only and must not create visible terminal windows. `.cmd` files may -exist only as manual compatibility trampolines; Task Scheduler must execute -hidden launchers directly and must not flash an interactive console on Raven. +exist only as manual compatibility entrypoints that call the same hidden VBS +launchers; neither Task Scheduler nor the hidden VBS layer may route through a +`cmdPath` trampoline on Raven. The standalone repair actuator for live Raven task drift is `E:\Projects\Odin\scripts\repair-raven-muninn-task-actions.ps1`. It must register `GameCult-Muninn`, `GameCult-Muninn-Activate`, and `GameCult-Muninn-VideoProof` with `wscript.exe` as the task action and the -corresponding `*-hidden.vbs` launcher as arguments. If Raven is unreachable, the -repo is prepared but the live scheduler is not clean. +corresponding `*-hidden.vbs` launcher as arguments while also verifying that the +hidden VBS bodies reference `.ps1` launchers instead of `.cmd` payloads. If +Raven is unreachable, the repo is prepared but the live scheduler is not clean. Nightwing Muninn is kept alive by the single Idunn supervisor through the `nightwing-muninn` daemon target. Idunn learns that target through Odin's typed diff --git a/scripts/activate-muninn-raven-av-srt.ps1 b/scripts/activate-muninn-raven-av-srt.ps1 index 2eb9cea..2df02f4 100644 --- a/scripts/activate-muninn-raven-av-srt.ps1 +++ b/scripts/activate-muninn-raven-av-srt.ps1 @@ -15,80 +15,92 @@ param( $ErrorActionPreference = "Stop" -$remoteScript = @" -`$ErrorActionPreference = "Stop" -`$ProgressPreference = "SilentlyContinue" -if (-not (Test-Path -LiteralPath "$MuninnExe")) { - throw "Muninn executable not found at $MuninnExe" -} -if (-not (Test-Path -LiteralPath "$LoopbackScript")) { - throw "Muninn loopback script not found at $LoopbackScript" -} -New-Item -ItemType Directory -Force -Path "$LogRoot" | Out-Null -New-Item -ItemType Directory -Force -Path (Split-Path -Parent "$StorePath") | Out-Null -Get-CimInstance Win32_Process | - Where-Object { (`$_.Name -ieq "muninn.exe" -and `$_.CommandLine -like "*activate*") -or (`$_.Name -ieq "ffmpeg.exe" -and `$_.CommandLine -like "*srt://$TargetHost*") -or (`$_.Name -ieq "powershell.exe" -and `$_.CommandLine -like "*wasapi-loopback-capture.ps1*") } | - ForEach-Object { taskkill.exe /PID `$_.ProcessId /T /F | Out-Null } -`$muninnDir = Split-Path -Parent "$MuninnExe" -`$launcher = Join-Path `$muninnDir "activate-raven-av-srt.cmd" -`$psLauncher = Join-Path `$muninnDir "activate-raven-av-srt.ps1" -`$vbsLauncher = Join-Path `$muninnDir "activate-raven-av-srt-hidden.vbs" -`$pidPath = Join-Path "$LogRoot" "muninn-activate.pid" -`$obsArgs = "" -if (-not [bool]::Parse("$($NoObsTarget.IsPresent)") -and -not ("$TargetHost" -eq "$ObsTargetHost" -and $Port -eq $ObsPort)) { - `$obsArgs = " --obs-target-host ""$ObsTargetHost"" --obs-port $ObsPort" -} else { - `$obsArgs = " --no-obs-target" -} -`$arguments = @("activate", "--store", "$StorePath", "--host", "raven", "--stream", "muninn.raven.av.srt", "--target-host", "$TargetHost", "--port", "$Port") -if (`$obsArgs -like " --no-obs-target") { - `$arguments += "--no-obs-target" -} else { - `$arguments += @("--obs-target-host", "$ObsTargetHost", "--obs-port", "$ObsPort") -} -`$arguments += @("--audio-device", "$AudioDevice", "--ffmpeg", "$Ffmpeg", "--loopback-script", "$LoopbackScript", "--log-root", "$LogRoot") -`$encodedArguments = (`$arguments | ConvertTo-Json -Compress) -`$psLines = @( - '`$ErrorActionPreference = "Stop"', - '`$ProgressPreference = "SilentlyContinue"', - '`$arguments = ''$encodedArguments'' | ConvertFrom-Json', - '`$process = Start-Process -FilePath "$MuninnExe" -ArgumentList `$arguments -WindowStyle Hidden -PassThru -RedirectStandardOutput "$LogRoot\muninn-activate.out.log" -RedirectStandardError "$LogRoot\muninn-activate.err.log"', - '`$process.Id | Set-Content -Encoding ASCII -LiteralPath "$LogRoot\muninn-activate.pid"' -) -Set-Content -LiteralPath `$psLauncher -Value `$psLines -Encoding ASCII -`$vbsLines = @( - 'Set shell = CreateObject("WScript.Shell")', - 'psLauncher = "$psLauncher"', - 'shell.Run "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & psLauncher & """", 0, False' -) -Set-Content -LiteralPath `$vbsLauncher -Value `$vbsLines -Encoding ASCII -`$lines = @( - "@echo off", - "cd /d ""`$muninnDir""", - "wscript.exe //B //Nologo ""`$vbsLauncher""" -) -Set-Content -LiteralPath `$launcher -Value `$lines -Encoding ASCII -`$taskAction = New-ScheduledTaskAction -Execute "wscript.exe" -Argument "//B //Nologo ""`$vbsLauncher""" -`$taskTrigger = New-ScheduledTaskTrigger -Once -At ([DateTime]::Today.AddHours(23).AddMinutes(59)) -`$taskPrincipal = New-ScheduledTaskPrincipal -UserId ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name) -LogonType Interactive -RunLevel Limited -`$taskSettings = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -Register-ScheduledTask -TaskName "GameCult-Muninn-Activate" -Action `$taskAction -Trigger `$taskTrigger -Principal `$taskPrincipal -Settings `$taskSettings -Force | Out-Null -Start-ScheduledTask -TaskName "GameCult-Muninn-Activate" -"@ +function Set-AsciiFile { + param( + [Parameter(Mandatory = $true)] [string] $Path, + [Parameter(Mandatory = $true)] [string] $Content + ) -$uploadId = [guid]::NewGuid().ToString("N") -$localRemoteScript = Join-Path $env:TEMP "odin-raven-muninn-activate-$uploadId.ps1" -$localSftpBatch = Join-Path $env:TEMP "odin-raven-muninn-activate-$uploadId.sftp" -$remoteSftpPath = "C:/Windows/Temp/odin-raven-muninn-activate-$uploadId.ps1" -$remotePsPath = "C:\Windows\Temp\odin-raven-muninn-activate-$uploadId.ps1" -try { - Set-Content -LiteralPath $localRemoteScript -Encoding ASCII -Value $remoteScript - Set-Content -LiteralPath $localSftpBatch -Encoding ASCII -Value "put ""$localRemoteScript"" ""$remoteSftpPath""" - & sftp.exe -b $localSftpBatch $RavenHost - if ($LASTEXITCODE -ne 0) { - exit $LASTEXITCODE - } - $remoteRunner = @" + [System.IO.File]::WriteAllText($Path, ($Content -replace "`r?`n", "`r`n"), [System.Text.Encoding]::ASCII) +} + +function ConvertTo-PowerShellStringLiteral { + param( + [Parameter(Mandatory = $true)] [string] $Value + ) + + return "'" + $Value.Replace("'", "''") + "'" +} + +function ConvertTo-PowerShellArrayLiteral { + param( + [Parameter(Mandatory = $true)] [string[]] $Values + ) + + $lines = $Values | ForEach-Object { " {0}" -f (ConvertTo-PowerShellStringLiteral $_) } + return "@(`r`n{0}`r`n)" -f ($lines -join ",`r`n") +} + +function New-HiddenPowerShellVbsLauncherContent { + param( + [Parameter(Mandatory = $true)] [string] $PsPath + ) + + return (@' +Set fso = CreateObject("Scripting.FileSystemObject") +scriptDir = fso.GetParentFolderName(WScript.ScriptFullName) +psLauncher = "{0}" +Set shell = CreateObject("WScript.Shell") +shell.CurrentDirectory = scriptDir +shell.Run "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & psLauncher & """", 0, False +'@) -f $PsPath +} + +function New-WscriptCmdLauncherContent { + param( + [Parameter(Mandatory = $true)] [string] $WorkingDirectory, + [Parameter(Mandatory = $true)] [string] $VbsPath + ) + + return (@' +@echo off +cd /d "{0}" +wscript.exe //B //Nologo "{1}" +'@) -f $WorkingDirectory, $VbsPath +} + +function Invoke-RavenUploadedPowerShell { + param( + [Parameter(Mandatory = $true)] [string] $RavenHost, + [Parameter(Mandatory = $true)] [string] $RemoteScriptContent, + [Parameter(Mandatory = $true)] [object[]] $UploadSpecs, + [Parameter(Mandatory = $true)] [string] $TempPrefix + ) + + $uploadId = [guid]::NewGuid().ToString("N") + $localTempRoot = Join-Path $env:TEMP "$TempPrefix-$uploadId" + $localRemoteScript = Join-Path $localTempRoot "$TempPrefix-$uploadId.ps1" + $localSftpBatch = Join-Path $localTempRoot "$TempPrefix-$uploadId.sftp" + $remoteSftpPath = "C:/Windows/Temp/$TempPrefix-$uploadId.ps1" + $remotePsPath = "C:\Windows\Temp\$TempPrefix-$uploadId.ps1" + + try { + New-Item -ItemType Directory -Force -Path $localTempRoot | Out-Null + Set-AsciiFile -Path $localRemoteScript -Content $RemoteScriptContent + + $batchLines = @() + foreach ($spec in $UploadSpecs) { + $batchLines += 'put "{0}" "{1}"' -f $spec.LocalPath, $spec.RemotePath + } + $batchLines += 'put "{0}" "{1}"' -f $localRemoteScript, $remoteSftpPath + Set-AsciiFile -Path $localSftpBatch -Content ($batchLines -join "`r`n") + + & sftp.exe -b $localSftpBatch $RavenHost + if ($LASTEXITCODE -ne 0) { + exit $LASTEXITCODE + } + + $remoteRunner = @" `$ErrorActionPreference = "Stop" try { & "$remotePsPath" @@ -98,9 +110,139 @@ try { } exit `$code "@ - $encodedRunner = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($remoteRunner)) - & ssh.exe -o BatchMode=yes -o ConnectTimeout=10 $RavenHost "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand $encodedRunner" -} finally { - Remove-Item -LiteralPath $localRemoteScript, $localSftpBatch -Force -ErrorAction SilentlyContinue + $encodedRunner = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($remoteRunner)) + & ssh.exe -o BatchMode=yes -o ConnectTimeout=10 $RavenHost "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand $encodedRunner" + } finally { + Remove-Item -LiteralPath $localTempRoot -Recurse -Force -ErrorAction SilentlyContinue + } } + +$muninnDir = Split-Path -Parent $MuninnExe +$activateCmdPath = Join-Path $muninnDir "activate-raven-av-srt.cmd" +$activatePsPath = Join-Path $muninnDir "activate-raven-av-srt.ps1" +$activateVbsPath = Join-Path $muninnDir "activate-raven-av-srt-hidden.vbs" + +$activateArguments = @( + "activate", + "--store", $StorePath, + "--host", "raven", + "--stream", "muninn.raven.av.srt", + "--target-host", $TargetHost, + "--port", $Port.ToString() +) +if ($NoObsTarget.IsPresent -or ($TargetHost -eq $ObsTargetHost -and $Port -eq $ObsPort)) { + $activateArguments += "--no-obs-target" +} else { + $activateArguments += @("--obs-target-host", $ObsTargetHost, "--obs-port", $ObsPort.ToString()) +} +$activateArguments += @( + "--audio-device", $AudioDevice, + "--ffmpeg", $Ffmpeg, + "--loopback-script", $LoopbackScript, + "--log-root", $LogRoot +) + +$activatePsContent = (@' +$ErrorActionPreference = "Stop" +$ProgressPreference = "SilentlyContinue" +New-Item -ItemType Directory -Force -Path (Split-Path -Parent {0}) | Out-Null +New-Item -ItemType Directory -Force -Path {1} | Out-Null +$arguments = {2} +$process = Start-Process -FilePath {3} -ArgumentList $arguments -WindowStyle Hidden -PassThru -RedirectStandardOutput {4} -RedirectStandardError {5} +$process.Id | Set-Content -Encoding ASCII -LiteralPath {6} +'@) -f + (ConvertTo-PowerShellStringLiteral $StorePath), + (ConvertTo-PowerShellStringLiteral $LogRoot), + (ConvertTo-PowerShellArrayLiteral $activateArguments), + (ConvertTo-PowerShellStringLiteral $MuninnExe), + (ConvertTo-PowerShellStringLiteral (Join-Path $LogRoot "muninn-activate.out.log")), + (ConvertTo-PowerShellStringLiteral (Join-Path $LogRoot "muninn-activate.err.log")), + (ConvertTo-PowerShellStringLiteral (Join-Path $LogRoot "muninn-activate.pid")) + +$uploadRoot = Join-Path $env:TEMP ("odin-raven-muninn-activate-" + [guid]::NewGuid().ToString("N")) + +try { + New-Item -ItemType Directory -Force -Path $uploadRoot | Out-Null + + $localActivatePs = Join-Path $uploadRoot "activate-raven-av-srt.ps1" + $localActivateVbs = Join-Path $uploadRoot "activate-raven-av-srt-hidden.vbs" + $localActivateCmd = Join-Path $uploadRoot "activate-raven-av-srt.cmd" + + Set-AsciiFile -Path $localActivatePs -Content $activatePsContent + Set-AsciiFile -Path $localActivateVbs -Content (New-HiddenPowerShellVbsLauncherContent -PsPath $activatePsPath) + Set-AsciiFile -Path $localActivateCmd -Content (New-WscriptCmdLauncherContent -WorkingDirectory $muninnDir -VbsPath $activateVbsPath) + + $remoteScript = @" +`$ErrorActionPreference = "Stop" +`$ProgressPreference = "SilentlyContinue" +if (-not (Test-Path -LiteralPath "$MuninnExe")) { + throw "Muninn executable not found at $MuninnExe" +} +if (-not (Test-Path -LiteralPath "$LoopbackScript")) { + throw "Muninn loopback script not found at $LoopbackScript" +} +if (-not (Test-Path -LiteralPath "$Ffmpeg")) { + throw "FFmpeg executable not found at $Ffmpeg" +} +foreach (`$path in @( + "$activatePsPath", + "$activateVbsPath" +)) { + if (-not (Test-Path -LiteralPath `$path)) { + throw "Required launcher path not found at `$path" + } +} + +Get-CimInstance Win32_Process | + Where-Object { + (`$_.Name -ieq "muninn.exe" -and `$_.CommandLine -like "*activate*") -or + (`$_.Name -ieq "ffmpeg.exe" -and `$_.CommandLine -like "*srt://$TargetHost*") -or + (`$_.Name -ieq "powershell.exe" -and `$_.CommandLine -like "*wasapi-loopback-capture.ps1*") + } | + ForEach-Object { + & taskkill.exe /PID `$_.ProcessId /T /F | Out-Null + } + +New-Item -ItemType Directory -Force -Path "$LogRoot" | Out-Null +New-Item -ItemType Directory -Force -Path (Split-Path -Parent "$StorePath") | Out-Null + +`$taskAction = New-ScheduledTaskAction -Execute "wscript.exe" -Argument "//B //Nologo ""$activateVbsPath""" +`$taskTrigger = New-ScheduledTaskTrigger -Once -At ([DateTime]::Today.AddHours(23).AddMinutes(59)) +`$taskPrincipal = New-ScheduledTaskPrincipal -UserId ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name) -LogonType Interactive -RunLevel Limited +`$taskSettings = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew +Register-ScheduledTask -TaskName "GameCult-Muninn-Activate" -Action `$taskAction -Trigger `$taskTrigger -Principal `$taskPrincipal -Settings `$taskSettings -Force | Out-Null + +`$task = Get-ScheduledTask -TaskName "GameCult-Muninn-Activate" -ErrorAction Stop +`$action = @(`$task.Actions)[0] +if (`$action.Execute -notmatch '(^|\\)wscript\.exe$') { + throw "GameCult-Muninn-Activate action executes `$(`$action.Execute), expected wscript.exe" +} +if (`$action.Arguments -notlike "*$activateVbsPath*") { + throw "GameCult-Muninn-Activate action arguments `$(`$action.Arguments) do not reference $activateVbsPath" +} +if (`$action.Arguments -notlike "*//B*" -or `$action.Arguments -notlike "*//Nologo*") { + throw "GameCult-Muninn-Activate action arguments `$(`$action.Arguments) do not force background WScript execution" +} +`$vbs = Get-Content -LiteralPath "$activateVbsPath" -Raw +if (`$vbs -match 'cmdPath\s*=') { + throw "GameCult-Muninn-Activate hidden launcher at $activateVbsPath still routes through a cmdPath trampoline" +} +if (`$vbs -notmatch '\.ps1') { + throw "GameCult-Muninn-Activate hidden launcher at $activateVbsPath does not reference a PowerShell launcher" +} + +Start-ScheduledTask -TaskName "GameCult-Muninn-Activate" +"@ + + $uploadSpecs = @( + @{ LocalPath = $localActivatePs; RemotePath = ($activatePsPath -replace "\\", "/") }, + @{ LocalPath = $localActivateVbs; RemotePath = ($activateVbsPath -replace "\\", "/") }, + @{ LocalPath = $localActivateCmd; RemotePath = ($activateCmdPath -replace "\\", "/") } + ) + + Invoke-RavenUploadedPowerShell -RavenHost $RavenHost -RemoteScriptContent $remoteScript -UploadSpecs $uploadSpecs -TempPrefix "odin-raven-muninn-activate" +} finally { + Remove-Item -LiteralPath $uploadRoot -Recurse -Force -ErrorAction SilentlyContinue +} + exit $LASTEXITCODE diff --git a/scripts/health-muninn.ps1 b/scripts/health-muninn.ps1 index b83ff74..673a9a3 100644 --- a/scripts/health-muninn.ps1 +++ b/scripts/health-muninn.ps1 @@ -7,18 +7,126 @@ param( $ErrorActionPreference = "Stop" +function Set-AsciiFile { + param( + [Parameter(Mandatory = $true)] [string] $Path, + [Parameter(Mandatory = $true)] [string] $Content + ) + + [System.IO.File]::WriteAllText($Path, ($Content -replace "`r?`n", "`r`n"), [System.Text.Encoding]::ASCII) +} + +function Invoke-RavenUploadedPowerShell { + param( + [Parameter(Mandatory = $true)] [string] $RavenHost, + [Parameter(Mandatory = $true)] [string] $RemoteScriptContent, + [Parameter(Mandatory = $true)] [string] $TempPrefix + ) + + $uploadId = [guid]::NewGuid().ToString("N") + $localTempRoot = Join-Path $env:TEMP "$TempPrefix-$uploadId" + $localRemoteScript = Join-Path $localTempRoot "$TempPrefix-$uploadId.ps1" + $localSftpBatch = Join-Path $localTempRoot "$TempPrefix-$uploadId.sftp" + $remoteSftpPath = "C:/Windows/Temp/$TempPrefix-$uploadId.ps1" + $remotePsPath = "C:\Windows\Temp\$TempPrefix-$uploadId.ps1" + + try { + New-Item -ItemType Directory -Force -Path $localTempRoot | Out-Null + Set-AsciiFile -Path $localRemoteScript -Content $RemoteScriptContent + Set-AsciiFile -Path $localSftpBatch -Content ('put "{0}" "{1}"' -f $localRemoteScript, $remoteSftpPath) + + & sftp.exe -b $localSftpBatch $RavenHost + if ($LASTEXITCODE -ne 0) { + exit $LASTEXITCODE + } + + $remoteRunner = @" +`$ErrorActionPreference = "Stop" +try { + & "$remotePsPath" + `$code = `$LASTEXITCODE +} finally { + Remove-Item -LiteralPath "$remotePsPath" -Force -ErrorAction SilentlyContinue +} +exit `$code +"@ + $encodedRunner = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($remoteRunner)) + & ssh.exe -o BatchMode=yes -o ConnectTimeout=10 $RavenHost "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand $encodedRunner" + } finally { + Remove-Item -LiteralPath $localTempRoot -Recurse -Force -ErrorAction SilentlyContinue + } +} + $remoteScript = @" `$ErrorActionPreference = "Stop" `$ProgressPreference = "SilentlyContinue" if (-not (Test-Path -LiteralPath "$MuninnExe")) { throw "Muninn executable not found at $MuninnExe" } +`$muninnDir = Split-Path -Parent "$MuninnExe" +`$taskExpectations = @( + @{ Name = "GameCult-Muninn"; Vbs = Join-Path `$muninnDir "start-muninn-serve-hidden.vbs"; Ps = Join-Path `$muninnDir "start-muninn-serve.ps1" }, + @{ Name = "GameCult-Muninn-Activate"; Vbs = Join-Path `$muninnDir "activate-raven-av-srt-hidden.vbs"; Ps = Join-Path `$muninnDir "activate-raven-av-srt.ps1" }, + @{ Name = "GameCult-Muninn-VideoProof"; Vbs = Join-Path `$muninnDir "muninn-raven-video-to-starfire-obs-hidden.vbs"; Ps = Join-Path `$muninnDir "muninn-raven-video-to-starfire-obs.ps1" } +) +foreach (`$expectation in `$taskExpectations) { + `$task = Get-ScheduledTask -TaskName `$expectation.Name -ErrorAction Stop + `$action = @(`$task.Actions)[0] + if (`$action.Execute -notmatch '(^|\\)wscript\.exe$') { + throw "`$(`$expectation.Name) action executes `$(`$action.Execute), expected wscript.exe" + } + if (`$action.Arguments -notlike "*`$(`$expectation.Vbs)*") { + throw "`$(`$expectation.Name) action arguments `$(`$action.Arguments) do not reference `$(`$expectation.Vbs)" + } + if (`$action.Arguments -notlike "*//B*" -or `$action.Arguments -notlike "*//Nologo*") { + throw "`$(`$expectation.Name) action arguments `$(`$action.Arguments) do not force hidden WScript execution" + } + if (-not (Test-Path -LiteralPath `$expectation.Vbs)) { + throw "Missing hidden launcher for `$(`$expectation.Name) at `$(`$expectation.Vbs)" + } + if (-not (Test-Path -LiteralPath `$expectation.Ps)) { + throw "Missing PowerShell launcher for `$(`$expectation.Name) at `$(`$expectation.Ps)" + } + `$psContent = Get-Content -LiteralPath `$expectation.Ps -Raw + if (`$psContent -like "*'' | ConvertFrom-Json*") { + throw "`$(`$expectation.Ps) has an empty encoded-arguments payload" + } + if (`$psContent -notmatch 'Start-Process') { + throw "`$(`$expectation.Ps) does not launch a hidden process" + } + if (`$expectation.Name -eq "GameCult-Muninn-Activate" -and `$psContent -notmatch 'muninn\.exe') { + throw "`$(`$expectation.Ps) does not launch muninn.exe" + } + if (`$expectation.Name -eq "GameCult-Muninn-VideoProof" -and `$psContent -notmatch 'ffmpeg\.exe') { + throw "`$(`$expectation.Ps) does not launch ffmpeg.exe" + } + if (`$expectation.Name -eq "GameCult-Muninn-VideoProof" -and `$psContent -notmatch 'srt://.+:\d+\?mode=caller') { + throw "`$(`$expectation.Ps) does not carry the expected SRT caller target" + } + `$vbs = Get-Content -LiteralPath `$expectation.Vbs -Raw + if (`$vbs -match 'cmdPath\s*=') { + throw "`$(`$expectation.Vbs) still routes through a cmdPath trampoline" + } + if (`$vbs -notmatch '\.ps1') { + throw "`$(`$expectation.Vbs) does not reference a PowerShell launcher" + } +} `$process = Get-CimInstance Win32_Process | Where-Object { `$_.Name -ieq "muninn.exe" -and `$_.CommandLine -like "*serve*" } | Select-Object -First 1 if (`$null -eq `$process) { throw "Muninn serve process is not running" } +foreach (`$pattern in @( + "--host raven", + "--idunn-rudp-health $IdunnRudpHealth", + "--idunn-daemon muninn", + "--idunn-health-contract muninn.cultnet-rudp-remote-telemetry-health" +)) { + if (`$process.CommandLine -notlike "*`$pattern*") { + throw "Muninn serve process is missing expected command-line segment `${pattern}: `$(`$process.CommandLine)" + } +} `$healthArgs = @( "--health", "--store", "$StorePath", @@ -29,6 +137,5 @@ if (`$null -eq `$process) { & "$MuninnExe" @healthArgs "@ -$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($remoteScript)) -& ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $RavenHost "powershell.exe -NoProfile -NonInteractive -EncodedCommand $encoded" +Invoke-RavenUploadedPowerShell -RavenHost $RavenHost -RemoteScriptContent $remoteScript -TempPrefix "odin-raven-muninn-health" exit $LASTEXITCODE diff --git a/scripts/repair-raven-muninn-task-actions.ps1 b/scripts/repair-raven-muninn-task-actions.ps1 index 5ebdd1f..040631a 100644 --- a/scripts/repair-raven-muninn-task-actions.ps1 +++ b/scripts/repair-raven-muninn-task-actions.ps1 @@ -43,39 +43,70 @@ function Assert-HiddenVbsTask { if (`$action.Arguments -notlike "*//B*" -or `$action.Arguments -notlike "*//Nologo*") { throw "`$TaskName action arguments `$(`$action.Arguments) do not force background WScript execution" } + `$vbs = Get-Content -LiteralPath `$VbsPath -Raw + if (`$vbs -match 'cmdPath\s*=') { + throw "`$TaskName hidden launcher at `$VbsPath still routes through a cmdPath trampoline" + } + if (`$vbs -notmatch '\.ps1') { + throw "`$TaskName hidden launcher at `$VbsPath does not reference a PowerShell launcher" + } } `$serveVbs = Join-Path "$MuninnDir" "start-muninn-serve-hidden.vbs" `$activateCmd = Join-Path "$MuninnDir" "activate-raven-av-srt.cmd" +`$activatePs = Join-Path "$MuninnDir" "activate-raven-av-srt.ps1" `$activateVbs = Join-Path "$MuninnDir" "activate-raven-av-srt-hidden.vbs" `$videoProofCmd = Join-Path "$MuninnDir" "muninn-raven-video-to-starfire-obs.cmd" +`$videoProofPs = Join-Path "$MuninnDir" "muninn-raven-video-to-starfire-obs.ps1" `$videoProofVbs = Join-Path "$MuninnDir" "muninn-raven-video-to-starfire-obs-hidden.vbs" -function Write-HiddenCmdLauncher { +function Write-HiddenPowerShellVbsLauncher { param( - [Parameter(Mandatory = `$true)] [string] `$CmdPath, + [Parameter(Mandatory = `$true)] [string] `$PsPath, [Parameter(Mandatory = `$true)] [string] `$VbsPath ) - if (-not (Test-Path -LiteralPath `$CmdPath)) { - throw "Command launcher not found at `$CmdPath" + if (-not (Test-Path -LiteralPath `$PsPath)) { + throw "PowerShell launcher not found at `$PsPath" } `$lines = @( 'Set fso = CreateObject("Scripting.FileSystemObject")', + 'scriptDir = fso.GetParentFolderName(WScript.ScriptFullName)', 'Set shell = CreateObject("WScript.Shell")', - "cmdPath = ""`$CmdPath""", - 'shell.CurrentDirectory = fso.GetParentFolderName(cmdPath)', - 'shell.Run """" & cmdPath & """", 0, False' + "psLauncher = ""`$PsPath""", + 'shell.CurrentDirectory = scriptDir', + 'shell.Run "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & psLauncher & """", 0, False' ) Set-Content -LiteralPath `$VbsPath -Value `$lines -Encoding ASCII } -if (Test-Path -LiteralPath `$activateCmd) { - Write-HiddenCmdLauncher -CmdPath `$activateCmd -VbsPath `$activateVbs +function Write-WscriptCmdLauncher { + param( + [Parameter(Mandatory = `$true)] [string] `$CmdPath, + [Parameter(Mandatory = `$true)] [string] `$WorkingDirectory, + [Parameter(Mandatory = `$true)] [string] `$VbsPath + ) + + `$cmdLines = @( + '@echo off', + "cd /d ""`$WorkingDirectory""", + "wscript.exe //B //Nologo ""`$VbsPath""" + ) + Set-Content -LiteralPath `$CmdPath -Value `$cmdLines -Encoding ASCII } -if (Test-Path -LiteralPath `$videoProofCmd) { - Write-HiddenCmdLauncher -CmdPath `$videoProofCmd -VbsPath `$videoProofVbs + +if (Test-Path -LiteralPath `$activatePs) { + Write-HiddenPowerShellVbsLauncher -PsPath `$activatePs -VbsPath `$activateVbs + if (Test-Path -LiteralPath `$activateCmd) { + Write-WscriptCmdLauncher -CmdPath `$activateCmd -WorkingDirectory "$MuninnDir" -VbsPath `$activateVbs + } +} +if (Test-Path -LiteralPath `$videoProofPs) { + Write-HiddenPowerShellVbsLauncher -PsPath `$videoProofPs -VbsPath `$videoProofVbs + if (Test-Path -LiteralPath `$videoProofCmd) { + Write-WscriptCmdLauncher -CmdPath `$videoProofCmd -WorkingDirectory "$MuninnDir" -VbsPath `$videoProofVbs + } } Register-HiddenVbsTask -TaskName "GameCult-Muninn" -VbsPath `$serveVbs diff --git a/scripts/restart-muninn.ps1 b/scripts/restart-muninn.ps1 index 9108b2b..3b314ce 100644 --- a/scripts/restart-muninn.ps1 +++ b/scripts/restart-muninn.ps1 @@ -3,6 +3,13 @@ param( [string] $MuninnExe = "C:\Meta\Odin\Muninn\muninn.exe", [string] $StorePath = "C:\Meta\Odin\state\muninn.telemetry.cc", [string] $LogRoot = "C:\Meta\Odin\logs\muninn", + [string] $LoopbackScript = "C:\Meta\Odin\Muninn\scripts\wasapi-loopback-capture.ps1", + [string] $Ffmpeg = "C:\Users\Madman's Lullaby\AppData\Local\Microsoft\WinGet\Links\ffmpeg.exe", + [string] $TargetHost = "10.77.0.2", + [int] $Port = 5200, + [string] $ObsTargetHost = "10.77.0.2", + [int] $ObsPort = 5204, + [string] $AudioDevice = "Realtek", [string] $IdunnRudpHealth = "10.77.0.2:17870", [string] $IdunnDaemon = "muninn", [string] $IdunnHealthContract = "muninn.cultnet-rudp-remote-telemetry-health" @@ -10,69 +17,285 @@ param( $ErrorActionPreference = "Stop" -$remoteScript = @" +function Set-AsciiFile { + param( + [Parameter(Mandatory = $true)] [string] $Path, + [Parameter(Mandatory = $true)] [string] $Content + ) + + [System.IO.File]::WriteAllText($Path, ($Content -replace "`r?`n", "`r`n"), [System.Text.Encoding]::ASCII) +} + +function ConvertTo-PowerShellStringLiteral { + param( + [Parameter(Mandatory = $true)] [string] $Value + ) + + return "'" + $Value.Replace("'", "''") + "'" +} + +function ConvertTo-PowerShellArrayLiteral { + param( + [Parameter(Mandatory = $true)] [string[]] $Values + ) + + $lines = $Values | ForEach-Object { " {0}" -f (ConvertTo-PowerShellStringLiteral $_) } + return "@(`r`n{0}`r`n)" -f ($lines -join ",`r`n") +} + +function New-HiddenPowerShellVbsLauncherContent { + param( + [Parameter(Mandatory = $true)] [string] $PsPath + ) + + return (@' +Set fso = CreateObject("Scripting.FileSystemObject") +scriptDir = fso.GetParentFolderName(WScript.ScriptFullName) +psLauncher = "{0}" +Set shell = CreateObject("WScript.Shell") +shell.CurrentDirectory = scriptDir +shell.Run "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & psLauncher & """", 0, False +'@) -f $PsPath +} + +function New-WscriptCmdLauncherContent { + param( + [Parameter(Mandatory = $true)] [string] $WorkingDirectory, + [Parameter(Mandatory = $true)] [string] $VbsPath + ) + + return (@' +@echo off +cd /d "{0}" +wscript.exe //B //Nologo "{1}" +'@) -f $WorkingDirectory, $VbsPath +} + +function Invoke-RavenUploadedPowerShell { + param( + [Parameter(Mandatory = $true)] [string] $RavenHost, + [Parameter(Mandatory = $true)] [string] $RemoteScriptContent, + [Parameter(Mandatory = $true)] [object[]] $UploadSpecs, + [Parameter(Mandatory = $true)] [string] $TempPrefix + ) + + $uploadId = [guid]::NewGuid().ToString("N") + $localTempRoot = Join-Path $env:TEMP "$TempPrefix-$uploadId" + $localRemoteScript = Join-Path $localTempRoot "$TempPrefix-$uploadId.ps1" + $localSftpBatch = Join-Path $localTempRoot "$TempPrefix-$uploadId.sftp" + $remoteSftpPath = "C:/Windows/Temp/$TempPrefix-$uploadId.ps1" + $remotePsPath = "C:\Windows\Temp\$TempPrefix-$uploadId.ps1" + + try { + New-Item -ItemType Directory -Force -Path $localTempRoot | Out-Null + Set-AsciiFile -Path $localRemoteScript -Content $RemoteScriptContent + + $batchLines = @() + foreach ($spec in $UploadSpecs) { + $batchLines += 'put "{0}" "{1}"' -f $spec.LocalPath, $spec.RemotePath + } + $batchLines += 'put "{0}" "{1}"' -f $localRemoteScript, $remoteSftpPath + Set-AsciiFile -Path $localSftpBatch -Content ($batchLines -join "`r`n") + + & sftp.exe -b $localSftpBatch $RavenHost + if ($LASTEXITCODE -ne 0) { + exit $LASTEXITCODE + } + + $remoteRunner = @" +`$ErrorActionPreference = "Stop" +try { + & "$remotePsPath" + `$code = `$LASTEXITCODE +} finally { + Remove-Item -LiteralPath "$remotePsPath" -Force -ErrorAction SilentlyContinue +} +exit `$code +"@ + $encodedRunner = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($remoteRunner)) + & ssh.exe -o BatchMode=yes -o ConnectTimeout=10 $RavenHost "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand $encodedRunner" + } finally { + Remove-Item -LiteralPath $localTempRoot -Recurse -Force -ErrorAction SilentlyContinue + } +} + +$muninnDir = Split-Path -Parent $MuninnExe +$serveCmdPath = Join-Path $muninnDir "start-muninn-serve.cmd" +$servePsPath = Join-Path $muninnDir "start-muninn-serve.ps1" +$serveVbsPath = Join-Path $muninnDir "start-muninn-serve-hidden.vbs" +$activateCmdPath = Join-Path $muninnDir "activate-raven-av-srt.cmd" +$activatePsPath = Join-Path $muninnDir "activate-raven-av-srt.ps1" +$activateVbsPath = Join-Path $muninnDir "activate-raven-av-srt-hidden.vbs" +$videoProofCmdPath = Join-Path $muninnDir "muninn-raven-video-to-starfire-obs.cmd" +$videoProofPsPath = Join-Path $muninnDir "muninn-raven-video-to-starfire-obs.ps1" +$videoProofVbsPath = Join-Path $muninnDir "muninn-raven-video-to-starfire-obs-hidden.vbs" + +$serveArguments = @( + "serve", + "--store", $StorePath, + "--log-root", $LogRoot, + "--host", "raven", + "--interval-seconds", "15", + "--idunn-rudp-health", $IdunnRudpHealth, + "--idunn-daemon", $IdunnDaemon, + "--idunn-health-contract", $IdunnHealthContract +) + +$activateArguments = @( + "activate", + "--store", $StorePath, + "--host", "raven", + "--stream", "muninn.raven.av.srt", + "--target-host", $TargetHost, + "--port", $Port.ToString() +) +if ($TargetHost -eq $ObsTargetHost -and $Port -eq $ObsPort) { + $activateArguments += "--no-obs-target" +} else { + $activateArguments += @("--obs-target-host", $ObsTargetHost, "--obs-port", $ObsPort.ToString()) +} +$activateArguments += @( + "--audio-device", $AudioDevice, + "--ffmpeg", $Ffmpeg, + "--loopback-script", $LoopbackScript, + "--log-root", $LogRoot +) + +$videoProofArguments = @( + "-hide_banner", + "-loglevel", "info", + "-thread_queue_size", "1024", + "-f", "lavfi", + "-i", "ddagrab=framerate=30:output_idx=0:draw_mouse=1", + "-thread_queue_size", "1024", + "-f", "lavfi", + "-i", "anullsrc=channel_layout=stereo:sample_rate=48000", + "-map", "0:v:0", + "-map", "1:a:0", + "-c:v", "h264_nvenc", + "-preset", "p4", + "-tune", "ll", + "-b:v", "12000k", + "-maxrate", "12000k", + "-bufsize", "24000k", + "-g", "60", + "-c:a", "aac", + "-b:a", "192k", + "-ar", "48000", + "-ac", "2", + "-f", "mpegts", + ("srt://{0}:{1}?mode=caller&latency=120000&timeout=30000000" -f $ObsTargetHost, $ObsPort) +) + +$servePsContent = (@' +$ErrorActionPreference = "Stop" +$ProgressPreference = "SilentlyContinue" +New-Item -ItemType Directory -Force -Path (Split-Path -Parent {0}) | Out-Null +New-Item -ItemType Directory -Force -Path {1} | Out-Null +$arguments = {2} +$process = Start-Process -FilePath {3} -ArgumentList $arguments -WindowStyle Hidden -PassThru -RedirectStandardOutput {4} -RedirectStandardError {5} +$process.Id | Set-Content -Encoding ASCII -LiteralPath {6} +'@) -f + (ConvertTo-PowerShellStringLiteral $StorePath), + (ConvertTo-PowerShellStringLiteral $LogRoot), + (ConvertTo-PowerShellArrayLiteral $serveArguments), + (ConvertTo-PowerShellStringLiteral $MuninnExe), + (ConvertTo-PowerShellStringLiteral (Join-Path $LogRoot "muninn-serve.out.log")), + (ConvertTo-PowerShellStringLiteral (Join-Path $LogRoot "muninn-serve.err.log")), + (ConvertTo-PowerShellStringLiteral (Join-Path $LogRoot "muninn-serve.pid")) + +$activatePsContent = (@' +$ErrorActionPreference = "Stop" +$ProgressPreference = "SilentlyContinue" +New-Item -ItemType Directory -Force -Path (Split-Path -Parent {0}) | Out-Null +New-Item -ItemType Directory -Force -Path {1} | Out-Null +$arguments = {2} +$process = Start-Process -FilePath {3} -ArgumentList $arguments -WindowStyle Hidden -PassThru -RedirectStandardOutput {4} -RedirectStandardError {5} +$process.Id | Set-Content -Encoding ASCII -LiteralPath {6} +'@) -f + (ConvertTo-PowerShellStringLiteral $StorePath), + (ConvertTo-PowerShellStringLiteral $LogRoot), + (ConvertTo-PowerShellArrayLiteral $activateArguments), + (ConvertTo-PowerShellStringLiteral $MuninnExe), + (ConvertTo-PowerShellStringLiteral (Join-Path $LogRoot "muninn-activate.out.log")), + (ConvertTo-PowerShellStringLiteral (Join-Path $LogRoot "muninn-activate.err.log")), + (ConvertTo-PowerShellStringLiteral (Join-Path $LogRoot "muninn-activate.pid")) + +$videoProofPsContent = (@' +$ErrorActionPreference = "Stop" +$ProgressPreference = "SilentlyContinue" +New-Item -ItemType Directory -Force -Path {0} | Out-Null +$arguments = {1} +$process = Start-Process -FilePath {2} -ArgumentList $arguments -WorkingDirectory {3} -WindowStyle Hidden -PassThru -RedirectStandardOutput {4} -RedirectStandardError {5} +$process.Id | Set-Content -Encoding ASCII -LiteralPath {6} +'@) -f + (ConvertTo-PowerShellStringLiteral $LogRoot), + (ConvertTo-PowerShellArrayLiteral $videoProofArguments), + (ConvertTo-PowerShellStringLiteral $Ffmpeg), + (ConvertTo-PowerShellStringLiteral $muninnDir), + (ConvertTo-PowerShellStringLiteral (Join-Path $LogRoot "muninn-video-proof.out.log")), + (ConvertTo-PowerShellStringLiteral (Join-Path $LogRoot "muninn-video-proof.err.log")), + (ConvertTo-PowerShellStringLiteral (Join-Path $LogRoot "muninn-video-proof.pid")) + +$uploadRoot = Join-Path $env:TEMP ("odin-raven-muninn-launchers-" + [guid]::NewGuid().ToString("N")) + +try { + New-Item -ItemType Directory -Force -Path $uploadRoot | Out-Null + + $localServePs = Join-Path $uploadRoot "start-muninn-serve.ps1" + $localServeVbs = Join-Path $uploadRoot "start-muninn-serve-hidden.vbs" + $localServeCmd = Join-Path $uploadRoot "start-muninn-serve.cmd" + $localActivatePs = Join-Path $uploadRoot "activate-raven-av-srt.ps1" + $localActivateVbs = Join-Path $uploadRoot "activate-raven-av-srt-hidden.vbs" + $localActivateCmd = Join-Path $uploadRoot "activate-raven-av-srt.cmd" + $localVideoProofPs = Join-Path $uploadRoot "muninn-raven-video-to-starfire-obs.ps1" + $localVideoProofVbs = Join-Path $uploadRoot "muninn-raven-video-to-starfire-obs-hidden.vbs" + $localVideoProofCmd = Join-Path $uploadRoot "muninn-raven-video-to-starfire-obs.cmd" + + Set-AsciiFile -Path $localServePs -Content $servePsContent + Set-AsciiFile -Path $localServeVbs -Content (New-HiddenPowerShellVbsLauncherContent -PsPath $servePsPath) + Set-AsciiFile -Path $localServeCmd -Content (New-WscriptCmdLauncherContent -WorkingDirectory $muninnDir -VbsPath $serveVbsPath) + Set-AsciiFile -Path $localActivatePs -Content $activatePsContent + Set-AsciiFile -Path $localActivateVbs -Content (New-HiddenPowerShellVbsLauncherContent -PsPath $activatePsPath) + Set-AsciiFile -Path $localActivateCmd -Content (New-WscriptCmdLauncherContent -WorkingDirectory $muninnDir -VbsPath $activateVbsPath) + Set-AsciiFile -Path $localVideoProofPs -Content $videoProofPsContent + Set-AsciiFile -Path $localVideoProofVbs -Content (New-HiddenPowerShellVbsLauncherContent -PsPath $videoProofPsPath) + Set-AsciiFile -Path $localVideoProofCmd -Content (New-WscriptCmdLauncherContent -WorkingDirectory $muninnDir -VbsPath $videoProofVbsPath) + + $remoteScript = @" `$ErrorActionPreference = "Stop" `$ProgressPreference = "SilentlyContinue" + if (-not (Test-Path -LiteralPath "$MuninnExe")) { throw "Muninn executable not found at $MuninnExe" } +if (-not (Test-Path -LiteralPath "$LoopbackScript")) { + throw "Muninn loopback script not found at $LoopbackScript" +} +if (-not (Test-Path -LiteralPath "$Ffmpeg")) { + throw "FFmpeg executable not found at $Ffmpeg" +} +foreach (`$path in @( + "$servePsPath", + "$serveVbsPath", + "$activatePsPath", + "$activateVbsPath", + "$videoProofPsPath", + "$videoProofVbsPath" +)) { + if (-not (Test-Path -LiteralPath `$path)) { + throw "Required launcher path not found at `$path" + } +} + Get-CimInstance Win32_Process | Where-Object { `$_.Name -ieq "muninn.exe" -and `$_.CommandLine -like "*serve*" } | ForEach-Object { & taskkill.exe /PID `$_.ProcessId /T /F | Out-Null } + New-Item -ItemType Directory -Force -Path "$LogRoot" | Out-Null New-Item -ItemType Directory -Force -Path (Split-Path -Parent "$StorePath") | Out-Null -`$muninnDir = Split-Path -Parent "$MuninnExe" -`$launcher = Join-Path `$muninnDir "start-muninn-serve.cmd" -`$psLauncher = Join-Path `$muninnDir "start-muninn-serve.ps1" -`$vbsLauncher = Join-Path `$muninnDir "start-muninn-serve-hidden.vbs" -`$activateCmd = Join-Path `$muninnDir "activate-raven-av-srt.cmd" -`$activateVbs = Join-Path `$muninnDir "activate-raven-av-srt-hidden.vbs" -`$videoProofCmd = Join-Path `$muninnDir "muninn-raven-video-to-starfire-obs.cmd" -`$videoProofVbs = Join-Path `$muninnDir "muninn-raven-video-to-starfire-obs-hidden.vbs" -`$pidPath = Join-Path "$LogRoot" "muninn-serve.pid" -`$psLines = @( - '`$ErrorActionPreference = "Stop"', - '`$ProgressPreference = "SilentlyContinue"', - '`$process = Start-Process -FilePath "$MuninnExe" -ArgumentList @("serve", "--store", "$StorePath", "--log-root", "$LogRoot", "--host", "raven", "--interval-seconds", "15", "--idunn-rudp-health", "$IdunnRudpHealth", "--idunn-daemon", "$IdunnDaemon", "--idunn-health-contract", "$IdunnHealthContract") -WindowStyle Hidden -PassThru -RedirectStandardOutput "$LogRoot\muninn-serve.out.log" -RedirectStandardError "$LogRoot\muninn-serve.err.log"', - '`$process.Id | Set-Content -Encoding ASCII -LiteralPath "$LogRoot\muninn-serve.pid"' -) -Set-Content -LiteralPath `$psLauncher -Value `$psLines -Encoding ASCII -`$vbsLines = @( - 'Set fso = CreateObject("Scripting.FileSystemObject")', - 'scriptDir = fso.GetParentFolderName(WScript.ScriptFullName)', - 'psLauncher = fso.BuildPath(scriptDir, "start-muninn-serve.ps1")', - 'Set shell = CreateObject("WScript.Shell")', - 'shell.Run "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & psLauncher & """", 0, False' -) -Set-Content -LiteralPath `$vbsLauncher -Value `$vbsLines -Encoding ASCII -`$lines = @( - "@echo off", - "cd /d ""`$muninnDir""", - "wscript.exe //B //Nologo ""`$vbsLauncher""" -) -Set-Content -LiteralPath `$launcher -Value `$lines -Encoding ASCII - -function Write-HiddenCmdLauncher { - param( - [Parameter(Mandatory = `$true)] [string] `$CmdPath, - [Parameter(Mandatory = `$true)] [string] `$VbsPath - ) - - if (-not (Test-Path -LiteralPath `$CmdPath)) { - return - } - - `$launcherLines = @( - 'Set fso = CreateObject("Scripting.FileSystemObject")', - 'Set shell = CreateObject("WScript.Shell")', - "cmdPath = ""`$CmdPath""", - 'shell.CurrentDirectory = fso.GetParentFolderName(cmdPath)', - 'shell.Run """" & cmdPath & """", 0, False' - ) - Set-Content -LiteralPath `$VbsPath -Value `$launcherLines -Encoding ASCII -} function Register-HiddenVbsTask { param( @@ -80,10 +303,6 @@ function Register-HiddenVbsTask { [Parameter(Mandatory = `$true)] [string] `$VbsPath ) - if (-not (Test-Path -LiteralPath `$VbsPath)) { - return - } - `$taskAction = New-ScheduledTaskAction -Execute "wscript.exe" -Argument "//B //Nologo ""`$VbsPath""" `$taskTrigger = New-ScheduledTaskTrigger -Once -At ([DateTime]::Today.AddHours(23).AddMinutes(59)) `$taskPrincipal = New-ScheduledTaskPrincipal -UserId ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name) -LogonType Interactive -RunLevel Limited @@ -94,13 +313,10 @@ function Register-HiddenVbsTask { function Assert-HiddenVbsTask { param( [Parameter(Mandatory = `$true)] [string] `$TaskName, - [Parameter(Mandatory = `$true)] [string] `$VbsPath + [Parameter(Mandatory = `$true)] [string] `$VbsPath, + [Parameter(Mandatory = `$true)] [string] `$PsPath ) - if (-not (Test-Path -LiteralPath `$VbsPath)) { - return - } - `$task = Get-ScheduledTask -TaskName `$TaskName -ErrorAction Stop `$action = @(`$task.Actions)[0] if (`$action.Execute -notmatch '(^|\\)wscript\.exe$') { @@ -112,18 +328,29 @@ function Assert-HiddenVbsTask { if (`$action.Arguments -notlike "*//B*" -or `$action.Arguments -notlike "*//Nologo*") { throw "`$TaskName action arguments `$(`$action.Arguments) do not force background WScript execution" } + if (-not (Test-Path -LiteralPath `$PsPath)) { + throw "`$TaskName PowerShell launcher not found at `$PsPath" + } + `$vbs = Get-Content -LiteralPath `$VbsPath -Raw + if (`$vbs -match 'cmdPath\s*=') { + throw "`$TaskName hidden launcher at `$VbsPath still routes through a cmdPath trampoline" + } + if (`$vbs -notmatch '\.ps1') { + throw "`$TaskName hidden launcher at `$VbsPath does not reference a PowerShell launcher" + } } -Write-HiddenCmdLauncher -CmdPath `$activateCmd -VbsPath `$activateVbs -Write-HiddenCmdLauncher -CmdPath `$videoProofCmd -VbsPath `$videoProofVbs -Register-HiddenVbsTask -TaskName "GameCult-Muninn" -VbsPath `$vbsLauncher -Register-HiddenVbsTask -TaskName "GameCult-Muninn-Activate" -VbsPath `$activateVbs -Register-HiddenVbsTask -TaskName "GameCult-Muninn-VideoProof" -VbsPath `$videoProofVbs -Assert-HiddenVbsTask -TaskName "GameCult-Muninn" -VbsPath `$vbsLauncher -Assert-HiddenVbsTask -TaskName "GameCult-Muninn-Activate" -VbsPath `$activateVbs -Assert-HiddenVbsTask -TaskName "GameCult-Muninn-VideoProof" -VbsPath `$videoProofVbs +Register-HiddenVbsTask -TaskName "GameCult-Muninn" -VbsPath "$serveVbsPath" +Register-HiddenVbsTask -TaskName "GameCult-Muninn-Activate" -VbsPath "$activateVbsPath" +Register-HiddenVbsTask -TaskName "GameCult-Muninn-VideoProof" -VbsPath "$videoProofVbsPath" + +Assert-HiddenVbsTask -TaskName "GameCult-Muninn" -VbsPath "$serveVbsPath" -PsPath "$servePsPath" +Assert-HiddenVbsTask -TaskName "GameCult-Muninn-Activate" -VbsPath "$activateVbsPath" -PsPath "$activatePsPath" +Assert-HiddenVbsTask -TaskName "GameCult-Muninn-VideoProof" -VbsPath "$videoProofVbsPath" -PsPath "$videoProofPsPath" + Start-ScheduledTask -TaskName "GameCult-Muninn" Start-Sleep -Seconds 2 + `$process = Get-CimInstance Win32_Process | Where-Object { `$_.Name -ieq "muninn.exe" -and `$_.CommandLine -like "*serve*" -and `$_.CommandLine -like "*--host*raven*" } | Select-Object -First 1 @@ -144,33 +371,23 @@ foreach (`$pattern in @( } "@ -$uploadId = [guid]::NewGuid().ToString("N") -$localRemoteScript = Join-Path $env:TEMP "odin-raven-muninn-restart-$uploadId.ps1" -$localSftpBatch = Join-Path $env:TEMP "odin-raven-muninn-restart-$uploadId.sftp" -$remoteSftpPath = "C:/Windows/Temp/odin-raven-muninn-restart-$uploadId.ps1" -$remotePsPath = "C:\Windows\Temp\odin-raven-muninn-restart-$uploadId.ps1" -try { - Set-Content -LiteralPath $localRemoteScript -Encoding ASCII -Value $remoteScript - Set-Content -LiteralPath $localSftpBatch -Encoding ASCII -Value "put ""$localRemoteScript"" ""$remoteSftpPath""" - & sftp.exe -b $localSftpBatch $RavenHost - if ($LASTEXITCODE -ne 0) { - exit $LASTEXITCODE - } - $remoteRunner = @" -`$ErrorActionPreference = "Stop" -try { - & "$remotePsPath" - `$code = `$LASTEXITCODE + $uploadSpecs = @( + @{ LocalPath = $localServePs; RemotePath = ($servePsPath -replace "\\", "/") }, + @{ LocalPath = $localServeVbs; RemotePath = ($serveVbsPath -replace "\\", "/") }, + @{ LocalPath = $localServeCmd; RemotePath = ($serveCmdPath -replace "\\", "/") }, + @{ LocalPath = $localActivatePs; RemotePath = ($activatePsPath -replace "\\", "/") }, + @{ LocalPath = $localActivateVbs; RemotePath = ($activateVbsPath -replace "\\", "/") }, + @{ LocalPath = $localActivateCmd; RemotePath = ($activateCmdPath -replace "\\", "/") }, + @{ LocalPath = $localVideoProofPs; RemotePath = ($videoProofPsPath -replace "\\", "/") }, + @{ LocalPath = $localVideoProofVbs; RemotePath = ($videoProofVbsPath -replace "\\", "/") }, + @{ LocalPath = $localVideoProofCmd; RemotePath = ($videoProofCmdPath -replace "\\", "/") } + ) + + Invoke-RavenUploadedPowerShell -RavenHost $RavenHost -RemoteScriptContent $remoteScript -UploadSpecs $uploadSpecs -TempPrefix "odin-raven-muninn-restart" } finally { - Remove-Item -LiteralPath "$remotePsPath" -Force -ErrorAction SilentlyContinue -} -exit `$code -"@ - $encodedRunner = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($remoteRunner)) - & ssh.exe -o BatchMode=yes -o ConnectTimeout=10 $RavenHost "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand $encodedRunner" -} finally { - Remove-Item -LiteralPath $localRemoteScript, $localSftpBatch -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $uploadRoot -Recurse -Force -ErrorAction SilentlyContinue } + $restartExit = $LASTEXITCODE if ($restartExit -eq 0) { Start-Sleep -Seconds 2