Files
USB_installer/tests/who-holds-flash.ps1

151 lines
6.6 KiB
PowerShell

# Кто держит флешку (диск 2): дескрипторы на томах F:/G:/H: и проверка монопольного доступа к диску.
# Только чтение, без сети. Результат: who-holds-flash.txt рядом со скриптом.
$ErrorActionPreference = 'Stop'
$outFile = 'C:\PF\USBInstaller\test\who-holds-flash.txt'
$log = New-Object System.Collections.Generic.List[string]
function Add-Line([string]$s) { $script:log.Add($s) }
$cs = @'
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class H {
[DllImport("ntdll.dll")] public static extern int NtQuerySystemInformation(int cls, IntPtr buf, int len, out int ret);
[DllImport("ntdll.dll")] public static extern int NtQueryObject(IntPtr h, int cls, IntPtr buf, int len, out int ret);
[DllImport("kernel32.dll", SetLastError=true)] public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
[DllImport("kernel32.dll", SetLastError=true)] public static extern bool DuplicateHandle(IntPtr sp, IntPtr sh, IntPtr tp, out IntPtr th, int access, bool inherit, int opt);
[DllImport("kernel32.dll")] public static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", SetLastError=true)] public static extern bool CloseHandle(IntPtr h);
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] public static extern IntPtr CreateFileW(string n, uint acc, uint sh, IntPtr sec, uint disp, uint fl, IntPtr t);
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] public static extern uint GetFinalPathNameByHandleW(IntPtr h, StringBuilder sb, uint len, uint flags);
public static string QueryObjectName(IntPtr h) {
int ret = 0;
IntPtr buf = Marshal.AllocHGlobal(8192);
try {
int st = NtQueryObject(h, 1, buf, 8192, out ret);
if (st != 0) return null;
int len = (int)Marshal.ReadInt16(buf, 0);
IntPtr ptr = Marshal.ReadIntPtr(buf, 8);
if (len <= 0 || ptr == IntPtr.Zero) return null;
return Marshal.PtrToStringUni(ptr, len / 2);
} finally { Marshal.FreeHGlobal(buf); }
}
public static string NtPathOf(string dosPath) {
IntPtr h = CreateFileW(dosPath, 0x80000000u, 3u, IntPtr.Zero, 3u, 0u, IntPtr.Zero);
if (h == IntPtr.Zero || h == (IntPtr)(-1)) return null;
try {
StringBuilder sb = new StringBuilder(512);
uint n = GetFinalPathNameByHandleW(h, sb, 512u, 2u);
if (n == 0) return null;
return sb.ToString();
} finally { CloseHandle(h); }
}
public static string TryExclusive(string path, uint access) {
IntPtr h = CreateFileW(path, access, 0u, IntPtr.Zero, 3u, 0u, IntPtr.Zero);
if (h == IntPtr.Zero || h == (IntPtr)(-1)) {
int e = Marshal.GetLastWin32Error();
return "FAIL " + e + " (" + new System.ComponentModel.Win32Exception(e).Message + ")";
}
CloseHandle(h);
return "OK (никто не держит)";
}
}
'@
Add-Type -TypeDefinition $cs -ErrorAction Stop
Add-Line ("scan " + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'))
# 1) Монопольный доступ к самому диску
Add-Line "--- exclusive open \\\\.\\PhysicalDrive2 ---"
Add-Line (" read : " + [H]::TryExclusive('\\.\PhysicalDrive2', 0x80000000))
Add-Line (" read+write : " + [H]::TryExclusive('\\.\PhysicalDrive2', 0x80000000 -bor 0x40000000))
# 2) NT-имена томов флешки
$devs = @{}
foreach ($dl in @('F','G','H')) {
$nt = [H]::NtPathOf('\\.\' + $dl + ':')
Add-Line (" volume " + $dl + ": -> " + $nt)
if ($nt) { $devs[$nt.ToLower()] = $dl }
}
# 3) Тип объекта "File" для этой сборки Windows
$mine = [H]::CreateFileW('C:\PF\USBInstaller\test\.h', 0x80000000u, 3u, [IntPtr]::Zero, 4u, 0x80u, [IntPtr]::Zero)
$myH = $mine.ToInt64()
$myPid = $PID
$len = 4MB
$buf = [Runtime.InteropServices.Marshal]::AllocHGlobal($len)
$ret = 0
while ($true) {
$st = [H]::NtQuerySystemInformation(64, $buf, $len, [ref]$ret)
if ($st -eq 0) { break }
if ($st -ne -1073741820) { throw ("NtQuerySystemInformation: 0x{0:X8}" -f $st) }
[Runtime.InteropServices.Marshal]::FreeHGlobal($buf)
$len *= 2
$buf = [Runtime.InteropServices.Marshal]::AllocHGlobal($len)
}
$count = [Runtime.InteropServices.Marshal]::ReadInt64($buf, 0)
Add-Line (" system handles: " + $count)
$fileType = -1
for ($i = 0; $i -lt $count; $i++) {
$e = 16 + 40 * $i
if ([Runtime.InteropServices.Marshal]::ReadInt64($buf, $e + 8) -eq $myPid) {
if ([Runtime.InteropServices.Marshal]::ReadInt64($buf, $e + 16) -eq $myH) {
$fileType = [int][Runtime.InteropServices.Marshal]::ReadInt16($buf, $e + 30)
break
}
}
}
if ($mine -ne [IntPtr]::Zero -and $mine -ne [IntPtr](-1)) { [void][H]::CloseHandle($mine) }
Add-Line (" File type index: " + $fileType)
# 4) Обход дескрипторов
$hits = @{}
$cur = [H]::GetCurrentProcess()
for ($i = 0; $i -lt $count; $i++) {
$e = 16 + 40 * $i
$opid = [Runtime.InteropServices.Marshal]::ReadInt64($buf, $e + 8)
$hval = [Runtime.InteropServices.Marshal]::ReadInt64($buf, $e + 16)
$tidx = [int][Runtime.InteropServices.Marshal]::ReadInt16($buf, $e + 30)
if ($tidx -ne $fileType) { continue }
$hp = [H]::OpenProcess(0x0040, $false, [int]$opid)
if ($hp -eq [IntPtr]::Zero) { continue }
$dup = [IntPtr]::Zero
$okDup = [H]::DuplicateHandle($hp, [IntPtr]$hval, $cur, [ref]$dup, 0, $false, 2)
if ($okDup) {
try {
$nm = [H]::QueryObjectName($dup)
if ($nm -and $nm.StartsWith('\Device\HarddiskVolume')) {
$low = $nm.ToLower()
foreach ($k in $devs.Keys) {
if ($low -eq $k -or $low.StartsWith($k + '\')) {
if (-not $hits.ContainsKey($opid)) { $hits[$opid] = New-Object System.Collections.Generic.List[string] }
if ($hits[$opid].Count -lt 4) { $hits[$opid].Add($nm) }
break
}
}
}
} catch { }
[void][H]::CloseHandle($dup)
}
[void][H]::CloseHandle($hp)
}
[Runtime.InteropServices.Marshal]::FreeHGlobal($buf)
Add-Line "--- processes holding volumes of disk 2 ---"
if ($hits.Count -eq 0) { Add-Line " none" }
foreach ($k in $hits.Keys) {
$p = Get-Process -Id $k -ErrorAction SilentlyContinue
Add-Line (" PID " + $k + " " + $p.ProcessName + " (" + $hits[$k].Count + " handles)")
foreach ($s in $hits[$k]) { Add-Line (" " + $s) }
}
Add-Line "--- volumes / disk ---"
Get-Volume | Where-Object DriveLetter -in 'F','G','H' | ForEach-Object { Add-Line (" " + $_.DriveLetter + ": " + $_.FileSystemLabel) }
$d = Get-Disk 2
Add-Line (" disk2 offline=" + $d.IsOffline + " readonly=" + $d.IsReadOnly)
[System.IO.File]::WriteAllLines($outFile, $log, (New-Object System.Text.UTF8Encoding($true)))
Write-Host ("written " + $outFile)