fix: recheck process absence after an owner observation exit race

This commit is contained in:
Agent Workbench Dev
2026-11-01 13:53:04 +08:00
parent 0efc3450d2
commit 52d9b86ae1
3 changed files with 55 additions and 5 deletions
+13 -5
View File
@@ -22,17 +22,25 @@ export function protectUserDirectory(directory) {
catch { throw hostError('无法为本机秘密目录设置当前Windows用户权限。', 'HOST_DIRECTORY_UNPROTECTED'); }
}
export function observeWindowsProcess(pid) {
if (process.platform !== 'win32') throw hostError('此桌面宿主核验需要Windows。', 'HOST_PLATFORM_UNSUPPORTED');
export function windowsProcessObservationScript(pid) {
if (!Number.isInteger(pid) || pid < 1 || pid > 2147483647) throw hostError('宿主PID无效。');
const script = "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';[Console]::OutputEncoding=New-Object System.Text.UTF8Encoding($false);"
+ '$awbProcess=Get-CimInstance Win32_Process -Filter "ProcessId=' + pid + '";'
const query = 'Get-CimInstance Win32_Process -Filter "ProcessId=' + pid + '"';
return "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';[Console]::OutputEncoding=New-Object System.Text.UTF8Encoding($false);"
+ '$awbProcess=' + query + ';'
+ 'if($null -eq $awbProcess){Write-Output "null";exit 0};'
+ '$awbOwner=Invoke-CimMethod -InputObject $awbProcess -MethodName GetOwnerSid;'
+ 'try{$awbOwner=Invoke-CimMethod -InputObject $awbProcess -MethodName GetOwnerSid;'
+ 'if($awbOwner.ReturnValue -ne 0 -or -not $awbOwner.Sid){throw "Owner identity unavailable"};'
// A process can exit after the snapshot and before its owner is queried.
// Only a fresh successful absence query can establish that it has gone.
+ '}catch{$awbRemaining=' + query + ';if($null -eq $awbRemaining){Write-Output "null";exit 0};throw};'
+ '[pscustomobject]@{pid=[int]$awbProcess.ProcessId;parentPid=[int]$awbProcess.ParentProcessId;'
+ 'createdAt=$awbProcess.CreationDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ");'
+ 'executable=$awbProcess.ExecutablePath;userSid=$awbOwner.Sid}|ConvertTo-Json -Compress';
}
export function observeWindowsProcess(pid) {
if (process.platform !== 'win32') throw hostError('此桌面宿主核验需要Windows。', 'HOST_PLATFORM_UNSUPPORTED');
const script = windowsProcessObservationScript(pid);
try {
const shell = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32/WindowsPowerShell/v1.0/powershell.exe');
const output = execFileSync(shell, ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],