533 lines
43 KiB
PowerShell
533 lines
43 KiB
PowerShell
Set-StrictMode -Version 2.0
|
|
$script:OtcheVersion = '1.1.0'
|
|
$script:OtcheRoot = 'C:\ProgramData\Otche'
|
|
|
|
function Read-OtcheJson([string]$Path, [int]$MaxBytes = 1048576) {
|
|
$stream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, ([IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete))
|
|
try {
|
|
if ($stream.Length -gt $MaxBytes) { throw 'JSON exceeds bounded control limit' }
|
|
$reader = New-Object IO.StreamReader($stream, [Text.Encoding]::UTF8, $true)
|
|
try { return ($reader.ReadToEnd() | ConvertFrom-Json -ErrorAction Stop) } finally { $reader.Dispose() }
|
|
} finally { $stream.Dispose() }
|
|
}
|
|
function Write-OtcheJson([string]$Path, $Value, [switch]$CreateNew) {
|
|
$bytes = [Text.UTF8Encoding]::new($false).GetBytes((ConvertTo-Json -InputObject $Value -Depth 18 -Compress))
|
|
if ($bytes.Length -gt 2097152) { throw 'JSON exceeds output limit' }
|
|
if ($CreateNew) {
|
|
$file = [IO.File]::Open($Path, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::Read)
|
|
try { $file.Write($bytes, 0, $bytes.Length); $file.Flush($true) } finally { $file.Dispose() }
|
|
return
|
|
}
|
|
$temp = $Path + '.' + [guid]::NewGuid().ToString('N') + '.tmp'
|
|
try {
|
|
$file = [IO.File]::Open($temp, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None)
|
|
try { $file.Write($bytes, 0, $bytes.Length); $file.Flush($true) } finally { $file.Dispose() }
|
|
if ([IO.File]::Exists($Path)) {
|
|
$replaceTimer = [Diagnostics.Stopwatch]::StartNew()
|
|
while ($true) {
|
|
try {
|
|
[IO.File]::Replace($temp, $Path, [System.Management.Automation.Language.NullString]::Value)
|
|
break
|
|
} catch {
|
|
$cause = $_.Exception.GetBaseException()
|
|
$code = $cause.HResult -band 0xffff
|
|
# Readers or AV may briefly deny delete sharing. Keep the
|
|
# flushed temp intact and never retry unrelated I/O errors.
|
|
$remaining = 2000 - $replaceTimer.ElapsedMilliseconds
|
|
if ($cause -isnot [IO.IOException] -or $code -notin @(32,33) -or $remaining -le 0) { throw }
|
|
Start-Sleep -Milliseconds ([Math]::Min(20, $remaining))
|
|
if ($replaceTimer.ElapsedMilliseconds -ge 2000) { throw }
|
|
}
|
|
}
|
|
} else { [IO.File]::Move($temp, $Path) }
|
|
} finally { if ([IO.File]::Exists($temp)) { [IO.File]::Delete($temp) } }
|
|
}
|
|
function Get-OtcheHash([string]$Path) {
|
|
$file = [IO.File]::OpenRead($Path); $hash = [Security.Cryptography.SHA256]::Create()
|
|
try { return ([BitConverter]::ToString($hash.ComputeHash($file))).Replace('-', '').ToLowerInvariant() }
|
|
finally { $file.Dispose(); $hash.Dispose() }
|
|
}
|
|
function Get-OtcheTextHash([string]$Text) {
|
|
$hash = [Security.Cryptography.SHA256]::Create()
|
|
try { return ([BitConverter]::ToString($hash.ComputeHash([Text.Encoding]::UTF8.GetBytes($Text)))).Replace('-', '').ToLowerInvariant() }
|
|
finally { $hash.Dispose() }
|
|
}
|
|
function Get-OtcheUtc { return [DateTime]::UtcNow.ToString('o') }
|
|
function Get-OtcheProperty($Object, [string]$Name, $Default = $null) {
|
|
if ($null -ne $Object -and $null -ne $Object.PSObject.Properties[$Name]) { return $Object.$Name }
|
|
return $Default
|
|
}
|
|
function Confirm-OtcheManifest($Manifest) {
|
|
foreach ($key in @('command_id','attempt_id','job_id')) {
|
|
$v = [string](Get-OtcheProperty $Manifest $key)
|
|
if ($v -notmatch '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$') { throw "Invalid $key" }
|
|
}
|
|
if ([string]$Manifest.iso_label -cnotmatch '^OT[0-9A-F]{14}$') { throw 'Invalid ISO label' }
|
|
if ([string]$Manifest.sha256 -notmatch '^[0-9a-f]{64}$') { throw 'Invalid SHA256' }
|
|
$name = [string]$Manifest.filename
|
|
if (!$name -or $name.Length -gt 180 -or $name -ne [IO.Path]::GetFileName($name) -or $name.IndexOfAny([IO.Path]::GetInvalidFileNameChars()) -ge 0 -or $name -match '[\. ]$' -or $name -match '^(?i:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)') { throw 'Unsafe execution filename' }
|
|
$s = $Manifest.settings
|
|
foreach ($rule in @(@('privilege','user','admin'),@('architecture','auto','x86','x64'),@('wsh_host','cscript','wscript'),@('msi_ui','full','quiet','passive'),@('internet','offline','online'),@('args_mode','none','custom'),@('filename','original','random'),@('dll_mode','regsvr32','rundll32'))) {
|
|
if ([string](Get-OtcheProperty $s $rule[0]) -notin $rule[1..($rule.Length-1)]) { throw ('Invalid setting ' + $rule[0]) }
|
|
}
|
|
# Whole seconds 1..1800, matching backend internal/duration. Fractions, strings and booleans are rejected, never coerced.
|
|
$duration = Get-OtcheProperty $s 'duration_seconds'
|
|
if (($duration -isnot [int] -and $duration -isnot [long]) -or $duration -lt 1 -or $duration -gt 1800) { throw 'Invalid duration' }
|
|
if ($s.set_zoneid -isnot [bool]) { throw 'set_zoneid must be boolean' }
|
|
if ($null -eq $s.args -or $s.args -isnot [array] -or $s.args.Count -gt 64) { throw 'args must be an explicit bounded array' }
|
|
foreach ($arg in $s.args) { if ($arg -isnot [string] -or $arg.Length -gt 4096 -or $arg.Contains([string][char]0)) { throw 'Invalid argument' } }
|
|
$grub=@(Get-OtcheProperty $s 'grub_paths' @())
|
|
if ($grub.Count -gt 32 -or ($null -ne $s.PSObject.Properties['grub_paths'] -and $s.grub_paths -isnot [array])) {throw 'Invalid Grub path array'}
|
|
if ($grub.Count -gt 0) {
|
|
Initialize-OtcheGrub;$bytes=0
|
|
foreach ($p in $grub) {
|
|
if ($p -isnot [string]) {throw 'Grub paths must be strings'}
|
|
$length=[Text.Encoding]::UTF8.GetByteCount($p);$bytes+=$length
|
|
if ($length -gt 1024 -or $bytes -gt 8192) {throw 'Grub paths exceed byte bound'}
|
|
[Otche.Grub]::Validate($p)
|
|
}
|
|
}
|
|
$q = [string](Get-OtcheProperty $Manifest 'qualification' '')
|
|
if ($q -notin @('','benign','eicar')) { throw 'Invalid qualification control' }
|
|
}
|
|
function ConvertTo-OtcheNativeArgument([AllowEmptyString()][string]$Value) {
|
|
# CommandLineToArgvW / CRT convention, including trailing backslashes.
|
|
$b = New-Object Text.StringBuilder
|
|
[void]$b.Append('"'); $slashes = 0
|
|
foreach ($c in $Value.ToCharArray()) {
|
|
if ($c -eq '\') { $slashes++; continue }
|
|
if ($c -eq '"') { [void]$b.Append(('\' * ($slashes * 2 + 1))); [void]$b.Append('"') }
|
|
else { [void]$b.Append(('\' * $slashes)); [void]$b.Append($c) }
|
|
$slashes = 0
|
|
}
|
|
[void]$b.Append(('\' * ($slashes * 2))); [void]$b.Append('"')
|
|
return $b.ToString()
|
|
}
|
|
function Join-OtcheNativeArguments([string[]]$Values) { return (($Values | ForEach-Object { ConvertTo-OtcheNativeArgument $_ }) -join ' ') }
|
|
function Initialize-OtcheNative {
|
|
if ('Otche.Native' -as [type]) { return }
|
|
Add-Type -TypeDefinition @'
|
|
using System;
|
|
using System.IO;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Runtime.InteropServices;
|
|
namespace Otche {
|
|
public static class Native {
|
|
[DllImport("kernel32.dll")] public static extern uint WTSGetActiveConsoleSessionId();
|
|
[DllImport("wtsapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool WTSQuerySessionInformation(IntPtr server, int session, int info, out IntPtr buffer, out int bytes);
|
|
[DllImport("wtsapi32.dll")] static extern void WTSFreeMemory(IntPtr memory);
|
|
[DllImport("advapi32.dll", SetLastError=true)] public static extern bool GetTokenInformation(IntPtr token, int type, out int value, int size, out int length);
|
|
[DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr handle);
|
|
[DllImport("user32.dll")] public static extern IntPtr GetShellWindow();
|
|
[DllImport("user32.dll",CharSet=CharSet.Unicode)] public static extern IntPtr FindWindow(string className,string title);
|
|
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
|
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window,out uint process);
|
|
[DllImport("user32.dll",SetLastError=true)] static extern IntPtr OpenInputDesktop(uint flags,bool inherit,uint access);
|
|
[DllImport("user32.dll")] static extern bool CloseDesktop(IntPtr desktop);
|
|
[DllImport("user32.dll",CharSet=CharSet.Unicode,SetLastError=true)] static extern bool GetUserObjectInformation(IntPtr handle,int index,StringBuilder text,int length,out int needed);
|
|
public delegate bool WindowCallback(IntPtr window,IntPtr state);
|
|
[DllImport("user32.dll")] public static extern bool EnumWindows(WindowCallback callback,IntPtr state);
|
|
public static string InputDesktop() {var h=OpenInputDesktop(0,false,1);if(h==IntPtr.Zero)throw new System.ComponentModel.Win32Exception();try{var b=new StringBuilder(256);int n;if(!GetUserObjectInformation(h,2,b,512,out n))throw new System.ComponentModel.Win32Exception();return b.ToString();}finally{CloseDesktop(h);}}
|
|
public static string SessionValue(int session,int type) { IntPtr p; int n; if(!WTSQuerySessionInformation(IntPtr.Zero,session,type,out p,out n)) throw new System.ComponentModel.Win32Exception(); try{return Marshal.PtrToStringUni(p) ?? "";}finally{WTSFreeMemory(p);} }
|
|
public static bool IsActive(int session) { IntPtr p; int n; if(!WTSQuerySessionInformation(IntPtr.Zero,session,8,out p,out n)) return false; try{return Marshal.ReadInt32(p)==0;}finally{WTSFreeMemory(p);} }
|
|
public static Task<long> Capture(StreamReader reader,string path,int limit) {
|
|
return Task.Run(async delegate { long total=0; using(var f=new FileStream(path,FileMode.CreateNew,FileAccess.Write,FileShare.Read)){var chars=new char[2048]; int written=0,n; while((n=await reader.ReadAsync(chars,0,chars.Length))!=0){var b=Encoding.UTF8.GetBytes(chars,0,n); total+=b.Length; int keep=Math.Min(b.Length,Math.Max(0,limit-written)); if(keep>0){await f.WriteAsync(b,0,keep); await f.FlushAsync(); written+=keep;}} f.Flush(true);} return total; });
|
|
}
|
|
}
|
|
}
|
|
'@ -ErrorAction Stop
|
|
}
|
|
function Get-OtcheSession([string]$Privilege, [switch]$Current) {
|
|
Initialize-OtcheNative
|
|
$config = Read-OtcheJson "$script:OtcheRoot\source.json"
|
|
$sid = [int][Otche.Native]::WTSGetActiveConsoleSessionId()
|
|
if ($sid -lt 1 -or ![Otche.Native]::IsActive($sid)) { throw 'No active interactive console session' }
|
|
$account = [Otche.Native]::SessionValue($sid,7) + '\' + [Otche.Native]::SessionValue($sid,5)
|
|
$accountSid = ([Security.Principal.NTAccount]::new($account)).Translate([Security.Principal.SecurityIdentifier]).Value
|
|
if ($accountSid -ne $config.account_sid) { throw 'Active console account differs from prepared account' }
|
|
if ($Current) {
|
|
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
|
|
$process = [Diagnostics.Process]::GetCurrentProcess()
|
|
if ($identity.User.Value -ne $config.account_sid -or $process.SessionId -ne $sid -or ![Environment]::UserInteractive) { throw 'Runner is not using the prepared interactive token/session' }
|
|
$elevated = 0; $size = 0
|
|
if (![Otche.Native]::GetTokenInformation($identity.Token,20,[ref]$elevated,4,[ref]$size)) { throw 'Cannot inspect actual elevation token' }
|
|
if (($Privilege -eq 'admin') -ne ($elevated -ne 0)) { throw 'Actual token privilege does not match request' }
|
|
Assert-OtcheDesktop $sid
|
|
}
|
|
return [ordered]@{ session_id=$sid; user=$account; privilege=$Privilege }
|
|
}
|
|
function Assert-OtcheDesktop([int]$SessionId) {
|
|
if ([Otche.Native]::InputDesktop() -cne 'Default') {throw 'Interactive input desktop is locked or secure'}
|
|
$shell=[Otche.Native]::GetShellWindow();$taskbar=[Otche.Native]::FindWindow('Shell_TrayWnd',$null)
|
|
if ($shell -eq [IntPtr]::Zero -or $taskbar -eq [IntPtr]::Zero -or ![Otche.Native]::IsWindowVisible($taskbar)) {throw 'Explorer desktop/taskbar is not ready; complete first-login setup'}
|
|
foreach ($window in @($shell,$taskbar)) {
|
|
[uint32]$owner=0;[void][Otche.Native]::GetWindowThreadProcessId($window,[ref]$owner)
|
|
$process=Get-Process -Id $owner -ErrorAction Stop
|
|
if ($process.ProcessName -ine 'explorer' -or $process.SessionId -ne $SessionId) {throw 'Desktop shell does not belong to the prepared Explorer session'}
|
|
}
|
|
$blocked=New-Object 'Collections.Generic.List[string]'
|
|
$callback=[Otche.Native+WindowCallback]{param($window,$state)
|
|
if ([Otche.Native]::IsWindowVisible($window)) {
|
|
[uint32]$owner=0;[void][Otche.Native]::GetWindowThreadProcessId($window,[ref]$owner)
|
|
$process=Get-Process -Id $owner -ErrorAction SilentlyContinue
|
|
if ($process -and $process.ProcessName -in @('CloudExperienceHost','oobe','msoobe','LogonUI')) {$blocked.Add($process.ProcessName)}
|
|
}
|
|
return $true
|
|
}
|
|
[void][Otche.Native]::EnumWindows($callback,[IntPtr]::Zero)
|
|
if ($blocked.Count) {throw ('Visible setup/sign-in host prevents desktop readiness: '+($blocked -join ', '))}
|
|
}
|
|
function Get-OtcheRegistryValue([string]$Path, [string]$Name) {
|
|
$key=[Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($Path)
|
|
if ($null -eq $key) {return $null}
|
|
try {return $key.GetValue($Name,$null)} finally {$key.Dispose()}
|
|
}
|
|
function Get-OtcheEnvironment {
|
|
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SOFTWARE\Microsoft\Windows NT\CurrentVersion')
|
|
try { $build = '{0}.{1}.{2}' -f $key.GetValue('CurrentBuildNumber'),$key.GetValue('UBR'),$key.GetValue('BuildLabEx') } finally { $key.Dispose() }
|
|
# Registry-backed state is identical for Limited, Highest and SYSTEM tokens.
|
|
$uac=[ordered]@{}
|
|
foreach ($name in @('EnableLUA','ConsentPromptBehaviorAdmin','PromptOnSecureDesktop','FilterAdministratorToken')) {$uac[$name]=Get-OtcheRegistryValue 'SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' $name}
|
|
$security=[ordered]@{uac=$uac;smart_app_control=(Get-OtcheRegistryValue 'SYSTEM\CurrentControlSet\Control\CI\Policy' 'VerifiedAndReputablePolicyState');secure_boot=(Get-OtcheRegistryValue 'SYSTEM\CurrentControlSet\Control\SecureBoot\State' 'UEFISecureBootEnabled');device_guard=[ordered]@{EnableVirtualizationBasedSecurity=(Get-OtcheRegistryValue 'SYSTEM\CurrentControlSet\Control\DeviceGuard' 'EnableVirtualizationBasedSecurity');RequirePlatformSecurityFeatures=(Get-OtcheRegistryValue 'SYSTEM\CurrentControlSet\Control\DeviceGuard' 'RequirePlatformSecurityFeatures');HVCIEnabled=(Get-OtcheRegistryValue 'SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity' 'Enabled')}}
|
|
return [ordered]@{ os_build=$build; architecture=$(if ([Environment]::Is64BitOperatingSystem) {'x64'} else {'x86'}); powershell_version=$PSVersionTable.PSVersion.ToString(); execution_policy=[string](Get-ExecutionPolicy); runner_version=$script:OtcheVersion; security=$security }
|
|
}
|
|
function Get-OtcheDeviceGuard {
|
|
# CIM availability can depend on token rights; never hash this diagnostic snapshot.
|
|
try {
|
|
$state=Get-CimInstance -Namespace root\Microsoft\Windows\DeviceGuard -ClassName Win32_DeviceGuard -ErrorAction Stop
|
|
if ($null -eq $state) {return $null}
|
|
return [ordered]@{VirtualizationBasedSecurityStatus=(Get-OtcheProperty $state 'VirtualizationBasedSecurityStatus');SecurityServicesConfigured=@(Get-OtcheProperty $state 'SecurityServicesConfigured' @());SecurityServicesRunning=@(Get-OtcheProperty $state 'SecurityServicesRunning' @());CodeIntegrityPolicyEnforcementStatus=(Get-OtcheProperty $state 'CodeIntegrityPolicyEnforcementStatus');UsermodeCodeIntegrityPolicyEnforcementStatus=(Get-OtcheProperty $state 'UsermodeCodeIntegrityPolicyEnforcementStatus')}
|
|
} catch {return $null}
|
|
}
|
|
function Get-OtcheDefender {
|
|
$status = Get-MpComputerStatus -ErrorAction Stop
|
|
$prefs = Get-MpPreference -ErrorAction Stop
|
|
$selected = [ordered]@{}
|
|
foreach ($name in @('DisableRealtimeMonitoring','DisableBehaviorMonitoring','DisableIOAVProtection','DisableScriptScanning','DisableArchiveScanning','DisableBlockAtFirstSeen','MAPSReporting','SubmitSamplesConsent','PUAProtection','CloudBlockLevel','CloudExtendedTimeout','EnableControlledFolderAccess','AttackSurfaceReductionRules_Ids','AttackSurfaceReductionRules_Actions','ExclusionPath','ExclusionProcess','ExclusionExtension','ExclusionIpAddress')) {
|
|
if ($null -eq $prefs.PSObject.Properties[$name]) { throw "Required Defender preference unreadable: $name" }
|
|
$selected[$name] = $prefs.$name
|
|
}
|
|
$updated = $status.AntivirusSignatureLastUpdated
|
|
if ($null -eq $updated) { throw 'Defender intelligence timestamp unavailable' }
|
|
$state = [ordered]@{ active=([bool]$status.AMServiceEnabled -and [bool]$status.AntivirusEnabled -and [bool]$status.RealTimeProtectionEnabled -and !$prefs.DisableRealtimeMonitoring); platform=[string]$status.AMProductVersion; engine=[string]$status.AMEngineVersion; intelligence=[string]$status.AntivirusSignatureVersion; intelligence_updated_at=$updated.ToUniversalTime().ToString('o'); fingerprint=''; preferences=$selected }
|
|
$state.fingerprint = Get-OtcheTextHash ($state | ConvertTo-Json -Depth 8 -Compress)
|
|
return $state
|
|
}
|
|
function Get-OtcheBaseline {
|
|
$errors = New-Object 'Collections.Generic.List[string]'; $defender=$null; $environment=$null
|
|
try { $environment=Get-OtcheEnvironment } catch { $errors.Add($_.Exception.Message) }
|
|
if ($null -ne $environment -and $environment.security.uac.EnableLUA -ne 1) {$errors.Add('UAC EnableLUA must be 1')}
|
|
try { $defender=Get-OtcheDefender; if (!$defender.active) { $errors.Add('Defender is not active') } } catch { $errors.Add($_.Exception.Message) }
|
|
try {
|
|
$null=Get-MpThreatDetection -ErrorAction Stop
|
|
$null=Get-MpThreat -ErrorAction Stop
|
|
foreach ($channel in @('Microsoft-Windows-Windows Defender/Operational','Microsoft-Windows-AppLocker/EXE and DLL','Microsoft-Windows-AppLocker/MSI and Script','Microsoft-Windows-CodeIntegrity/Operational')) {$null=Get-WinEvent -ListLog $channel -ErrorAction Stop}
|
|
} catch {$errors.Add('Required telemetry source unreadable: '+$_.Exception.Message)}
|
|
$scripts=[ordered]@{}
|
|
foreach ($name in @('Otche.Common.psm1','Invoke-Otche.ps1','Invoke-OtcheDispatch.ps1','Start-OtcheCommand.ps1','Collect-Otche.ps1','Test-OtcheReady.ps1')) {
|
|
try {
|
|
$path="$script:OtcheRoot\runner\$name"
|
|
$signature=Get-AuthenticodeSignature -LiteralPath $path -ErrorAction Stop
|
|
$scripts[$name]=[ordered]@{sha256=(Get-OtcheHash $path); signature=[string]$signature.Status; signer=$(if ($signature.SignerCertificate) {$signature.SignerCertificate.Thumbprint} else {''})}
|
|
if ((Get-ExecutionPolicy) -eq 'AllSigned' -and $signature.Status -ne 'Valid') {$errors.Add("Required signature invalid: $name")}
|
|
} catch { $errors.Add("Runner fingerprint $name unreadable: " + $_.Exception.Message) }
|
|
}
|
|
$policy=@(Get-ExecutionPolicy -List | ForEach-Object { [ordered]@{scope=[string]$_.Scope; policy=[string]$_.ExecutionPolicy} })
|
|
if ((Get-ExecutionPolicy) -eq 'Restricted') { $errors.Add('Restricted blocks all script files, including signed runners') }
|
|
$fingerprint=Get-OtcheTextHash ([ordered]@{environment=$environment; defender=$defender; scripts=$scripts; policies=$policy} | ConvertTo-Json -Depth 12 -Compress)
|
|
return [ordered]@{fingerprint=$fingerprint; qualified=($errors.Count -eq 0); errors=@($errors.ToArray()); defender=$defender; environment=$environment; scripts=$scripts; policies=$policy; device_guard_runtime=(Get-OtcheDeviceGuard)}
|
|
}
|
|
function Get-OtcheBootId { return (Get-CimInstance Win32_OperatingSystem -ErrorAction Stop).LastBootUpTime.ToUniversalTime().ToString('o') }
|
|
function Get-OtchePE([string]$Path) {
|
|
$stream=[IO.File]::OpenRead($Path); $r=[IO.BinaryReader]::new($stream)
|
|
try {
|
|
if ($stream.Length -lt 64 -or $r.ReadUInt16() -ne 0x5a4d) { return $null }
|
|
$stream.Position=60; $offset=$r.ReadUInt32()
|
|
if ($offset -gt $stream.Length-24) { return $null }
|
|
$stream.Position=$offset
|
|
if ($r.ReadUInt32() -ne 0x4550) { return $null }
|
|
$machine=$r.ReadUInt16(); $count=$r.ReadUInt16(); $stream.Position+=12; $optionalSize=$r.ReadUInt16(); $flags=$r.ReadUInt16()
|
|
if ($count -gt 96 -or $optionalSize -lt 112 -or $offset+24+$optionalSize+$count*40 -gt $stream.Length) { throw 'Malformed PE header' }
|
|
$optional=$stream.Position; $magic=$r.ReadUInt16()
|
|
if ($magic -eq 0x10b) {$stream.Position=$optional+96} elseif ($magic -eq 0x20b) {$stream.Position=$optional+112} else {throw 'Unsupported PE optional header'}
|
|
$exportRva=$r.ReadUInt32(); $exportSize=$r.ReadUInt32(); $sections=@()
|
|
$stream.Position=$optional+$optionalSize
|
|
for ($i=0;$i -lt $count;$i++) { $stream.Position+=8; $virtualSize=$r.ReadUInt32(); $rva=$r.ReadUInt32(); $rawSize=$r.ReadUInt32(); $raw=$r.ReadUInt32(); $stream.Position+=16; $sections+=@{rva=$rva; size=[Math]::Max($virtualSize,$rawSize); raw=$raw; raw_size=$rawSize} }
|
|
$exports=New-Object 'Collections.Generic.List[string]'
|
|
if ($exportRva -ne 0) {
|
|
$location=Convert-OtcheRva $exportRva $sections $stream.Length; $stream.Position=$location+16
|
|
$ordinalBase=$r.ReadUInt32(); $functionCount=$r.ReadUInt32(); $nameCount=$r.ReadUInt32(); $functions=$r.ReadUInt32(); $names=$r.ReadUInt32(); $ordinals=$r.ReadUInt32()
|
|
if ($functionCount -gt 65536 -or $nameCount -gt 65536) {throw 'PE export table exceeds bound'}
|
|
$functionOffset=Convert-OtcheRva $functions $sections $stream.Length
|
|
for ($i=0;$i -lt $functionCount;$i++) { $stream.Position=$functionOffset+4*$i; if ($r.ReadUInt32() -ne 0) {$exports.Add('#'+($ordinalBase+$i))} }
|
|
if ($nameCount -gt 0) {
|
|
$namesOffset=Convert-OtcheRva $names $sections $stream.Length
|
|
for ($i=0;$i -lt $nameCount;$i++) {
|
|
$stream.Position=$namesOffset+4*$i; $nameRva=$r.ReadUInt32(); $stream.Position=Convert-OtcheRva $nameRva $sections $stream.Length
|
|
$bytes=New-Object 'Collections.Generic.List[byte]'
|
|
for ($j=0;$j -lt 256;$j++) {$v=$r.ReadByte(); if ($v -eq 0) {break}; $bytes.Add($v)}
|
|
if ($j -eq 256) {throw 'PE export name exceeds bound'}
|
|
$exports.Add([Text.Encoding]::ASCII.GetString($bytes.ToArray()))
|
|
}
|
|
}
|
|
}
|
|
return @{architecture=$(if ($machine -eq 0x14c) {'x86'} elseif ($machine -eq 0x8664) {'x64'} else {'unsupported'}); dll=(($flags -band 0x2000) -ne 0); exports=$exports.ToArray()}
|
|
} finally {$r.Dispose(); $stream.Dispose()}
|
|
}
|
|
function Convert-OtcheRva([long]$Rva,$Sections,[long]$Length) {
|
|
foreach ($s in $Sections) { if ($Rva -ge $s.rva -and $Rva-$s.rva -lt $s.raw_size) { $p=$s.raw+$Rva-$s.rva; if ($p -ge 0 -and $p -lt $Length) {return $p} } }
|
|
throw 'PE RVA is outside file-backed sections'
|
|
}
|
|
function ConvertTo-OtcheBatchArgument([AllowEmptyString()][string]$Value, [switch]$Last) {
|
|
# cmd's batch parameter parser is not CommandLineToArgvW. Preserve data with
|
|
# one outer quote pair; escape only cmd operators exposed by inner quote pairs.
|
|
$encoded=[Text.StringBuilder]::new(); [void]$encoded.Append('"'); $quoted=$true
|
|
foreach ($c in $Value.ToCharArray()) {
|
|
if ($c -eq '"') {$quoted=!$quoted;[void]$encoded.Append($c);continue}
|
|
if ($c -eq [char]0 -or $c -eq "`r" -or $c -eq "`n") {throw 'INCOMPATIBLE: Batch parameters cannot contain NUL or line breaks'}
|
|
if (!$quoted -and $c -in @(' ', "`t", ',', ';', '=')) {throw 'INCOMPATIBLE: Embedded quotes expose a batch argument separator; exact literal value is not representable'}
|
|
if (!$quoted -and $c -in @('^','&','|','<','>','(',')')) {[void]$encoded.Append('^')}
|
|
[void]$encoded.Append($c)
|
|
}
|
|
if (!$quoted -and !$Last) {throw 'INCOMPATIBLE: An unmatched literal quote would consume subsequent batch parameters'}
|
|
[void]$encoded.Append('"');return $encoded.ToString()
|
|
}
|
|
function ConvertTo-OtcheMsiProperty([string]$Value) {
|
|
$equal=$Value.IndexOf('=')
|
|
return $Value.Substring(0,$equal)+'="'+$Value.Substring($equal+1).Replace('"','""')+'"'
|
|
}
|
|
function Get-OtcheLaunch([string]$Path,$Settings,[string]$Directory) {
|
|
$ext=[IO.Path]::GetExtension($Path).ToLowerInvariant(); $arch=[string]$Settings.architecture
|
|
$values=New-Object 'Collections.Generic.List[string]'
|
|
if ($Settings.args_mode -eq 'custom') { foreach ($arg in $Settings.args) {$values.Add($arg.Replace('{sample.path}',$Path).Replace('{sample.name}',[IO.Path]::GetFileName($Path)))} }
|
|
if ($ext -in @('.exe','.dll','.scr','.com')) {
|
|
$pe=Get-OtchePE $Path
|
|
if ($null -eq $pe) {throw 'INCOMPATIBLE: Non-PE/DOS16 executable is unsupported'}
|
|
if ($pe.architecture -eq 'unsupported' -or ($pe.architecture -eq 'x64' -and ![Environment]::Is64BitOperatingSystem)) {throw 'INCOMPATIBLE: Unsupported PE architecture'}
|
|
if ($arch -ne 'auto' -and $arch -ne $pe.architecture) {throw 'INCOMPATIBLE: Requested architecture disagrees with PE'}
|
|
$arch=$pe.architecture
|
|
}
|
|
if ($arch -eq 'auto') {$arch=$(if ([Environment]::Is64BitOperatingSystem) {'x64'} else {'x86'})}
|
|
if ($arch -eq 'x64' -and ![Environment]::Is64BitOperatingSystem) {throw 'INCOMPATIBLE: x64 handler unavailable'}
|
|
$system=Join-Path $env:WINDIR 'System32'
|
|
if ($arch -eq 'x86' -and [Environment]::Is64BitOperatingSystem) {$system=Join-Path $env:WINDIR 'SysWOW64'}
|
|
$file=''; $arguments=@(); $handler=''; $raw=$null; $environment=@{}
|
|
switch ($ext) {
|
|
{$_ -in @('.exe','.scr','.com')} {if ($pe.dll) {throw 'INCOMPATIBLE: Executable has DLL characteristics'}; $file=$Path; $arguments=$values.ToArray(); $handler='direct'}
|
|
'.dll' {
|
|
if (!$pe.dll) {throw 'INCOMPATIBLE: File is not a PE DLL'}
|
|
if ($Settings.dll_mode -eq 'regsvr32') {
|
|
if ($pe.exports -cnotcontains 'DllRegisterServer') {throw 'INCOMPATIBLE: regsvr32 requires actual DllRegisterServer export'}
|
|
if ($values.Count -ne 0) {throw 'INCOMPATIBLE: regsvr32 does not accept generic sample arguments'}
|
|
$file=Join-Path $system 'regsvr32.exe'; $arguments=@($Path); $handler='regsvr32'
|
|
} else {
|
|
$export=[string]$Settings.dll_export
|
|
if ($export -notmatch '^(?:[A-Za-z_?][A-Za-z0-9_?@$]*|#[0-9]+)$' -or $pe.exports -cnotcontains $export) {throw 'INCOMPATIBLE: Explicit DLL export is absent or invalid'}
|
|
if ($Path.Contains(',')) {throw 'INCOMPATIBLE: rundll32 cannot safely address a comma in the DLL path'}
|
|
$file=Join-Path $system 'rundll32.exe'; $arguments=@($Path+','+$export)+$values.ToArray(); $handler='rundll32'
|
|
$raw='"'+$Path+'",'+$export
|
|
if ($values.Count -gt 0) {$raw+=' '+(Join-OtcheNativeArguments $values.ToArray())}
|
|
}
|
|
}
|
|
'.ps1' {$file=Join-Path $system 'WindowsPowerShell\v1.0\powershell.exe'; $arguments=@('-NoProfile','-File',$Path)+$values.ToArray(); $handler='powershell-file'}
|
|
{$_ -in @('.vbs','.js')} {$file=Join-Path $system ($Settings.wsh_host+'.exe'); $arguments=@('//Nologo',$Path)+$values.ToArray(); $handler=$Settings.wsh_host}
|
|
{$_ -in @('.bat','.cmd')} {
|
|
$parts=@($Path)+$values.ToArray();$references=New-Object 'Collections.Generic.List[string]';$expandedLength=0
|
|
for ($i=0;$i -lt $parts.Count;$i++) {
|
|
$key='OTCHE_BATCH_ARG_'+$i
|
|
$environment[$key]=ConvertTo-OtcheBatchArgument $parts[$i] -Last:($i -eq $parts.Count-1)
|
|
$expandedLength+=$environment[$key].Length+1
|
|
$references.Add('%'+$key+'%')
|
|
}
|
|
# Environment substitution is a single nonrecursive expansion: literal
|
|
# percent expressions in values are not reparsed. Delayed expansion stays off.
|
|
if ($expandedLength -gt 8000) {throw 'INCOMPATIBLE: Expanded batch command exceeds cmd.exe 8191-character limit'}
|
|
$file=Join-Path $system 'cmd.exe'; $handler='cmd'; $arguments=$values.ToArray()
|
|
$raw='/d /s /v:off /c "'+($references.ToArray() -join ' ')+'"'
|
|
}
|
|
'.msi' {
|
|
$file=Join-Path $system 'msiexec.exe'; $handler='msiexec'
|
|
$arguments=@('/i',$Path,'/L*V',(Join-Path $Directory 'msi.log'))
|
|
$msiTokens=New-Object 'Collections.Generic.List[string]'
|
|
$msiTokens.Add('/i');$msiTokens.Add('"'+$Path+'"');$msiTokens.Add('/L*V');$msiTokens.Add('"'+(Join-Path $Directory 'msi.log')+'"')
|
|
$ui=$(if ($Settings.msi_ui -eq 'quiet') {'/qn'} elseif ($Settings.msi_ui -eq 'passive') {'/passive'} else {'/qf'})
|
|
$arguments+=$ui;$msiTokens.Add($ui)
|
|
for ($i=0;$i -lt $values.Count;$i++) {
|
|
$arg=$values[$i]
|
|
if ($arg -match '^[A-Za-z_][A-Za-z0-9_]*=') {
|
|
$property=$arg.Substring(0,$arg.IndexOf('='))
|
|
if ($property -in @('ACTION','UILEVEL')) {throw 'INCOMPATIBLE: MSI operation/UI is controlled by the selected sample/settings, not custom properties'}
|
|
$arguments+=$arg;$msiTokens.Add((ConvertTo-OtcheMsiProperty $arg));continue
|
|
}
|
|
$option=$arg.ToLowerInvariant()
|
|
if ($option -in @('/norestart','-norestart','/promptrestart','-promptrestart','/forcerestart','-forcerestart')) {
|
|
if ($option -match 'promptrestart$' -and $Settings.msi_ui -eq 'quiet') {throw 'INCOMPATIBLE: msiexec does not support /promptrestart with quiet UI'}
|
|
$arguments+=$arg;$msiTokens.Add($arg);continue
|
|
}
|
|
if ($option -in @('/m','-m','/n','-n')) {
|
|
$i++;if ($i -ge $values.Count) {throw 'INCOMPATIBLE: MSI modifier requires an operand'}
|
|
$operand=$values[$i]
|
|
if ($option -in @('/m','-m') -and (!$operand -or $operand.Length -gt 8 -or $operand.IndexOfAny([IO.Path]::GetInvalidFileNameChars()) -ge 0 -or $operand -match '[. ]$')) {throw 'INCOMPATIBLE: MSI /m requires a valid SMS MIF basename of at most eight characters'}
|
|
if ($option -in @('/n','-n') -and $operand -notmatch '^\{[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\}$') {throw 'INCOMPATIBLE: MSI /n requires an instance ProductCode GUID'}
|
|
$arguments+=@($arg,$operand);$msiTokens.Add($arg);$msiTokens.Add('"'+$operand+'"');continue
|
|
}
|
|
throw 'INCOMPATIBLE: MSI option is not an install modifier, or would replace the required sample, operation, log or selected UI'
|
|
}
|
|
$raw=$msiTokens.ToArray() -join ' '
|
|
}
|
|
default {throw 'INCOMPATIBLE: Unsupported sample extension'}
|
|
}
|
|
if (!$raw) {$raw=Join-OtcheNativeArguments $arguments}
|
|
if ($raw.Length -gt 30000) {throw 'INCOMPATIBLE: Windows command line exceeds safe bound'}
|
|
return @{file=$file; arguments=@($arguments); command_line=$raw; handler=$handler; architecture=$arch; environment=$environment}
|
|
}
|
|
function Initialize-OtcheGrub {
|
|
if ('Otche.Grub' -as [type]) {return}
|
|
Add-Type -TypeDefinition @'
|
|
using System;
|
|
using System.IO;
|
|
using System.Text;
|
|
using System.Collections.Generic;
|
|
using System.ComponentModel;
|
|
using System.Runtime.InteropServices;
|
|
using Microsoft.Win32.SafeHandles;
|
|
namespace Otche {
|
|
public static class Grub {
|
|
public sealed class Capture {public long Size,OpenSize;public bool Changed;}
|
|
[StructLayout(LayoutKind.Sequential)] struct Info {public uint Attributes; public System.Runtime.InteropServices.ComTypes.FILETIME Creation,Access,Write; public uint Volume,SizeHigh,SizeLow,Links,IndexHigh,IndexLow;}
|
|
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] static extern SafeFileHandle CreateFile(string p,uint access,uint share,IntPtr security,uint disposition,uint flags,IntPtr template);
|
|
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetFileInformationByHandle(SafeFileHandle h,out Info info);
|
|
[DllImport("kernel32.dll")] static extern uint GetFileType(SafeFileHandle h);
|
|
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] static extern uint GetFinalPathNameByHandle(SafeFileHandle h,StringBuilder path,uint length,uint flags);
|
|
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] static extern bool GetVolumeInformationByHandleW(SafeFileHandle h,StringBuilder volume,uint volumeLength,out uint serial,out uint maxComponent,out uint flags,StringBuilder fs,uint fsLength);
|
|
static void CheckLocalHandle(SafeFileHandle h,string expectedDevice,bool root) {
|
|
var path=new StringBuilder(32768);uint count=GetFinalPathNameByHandle(h,path,(uint)path.Capacity,2);
|
|
if(count==0 || count>=path.Capacity || !path.ToString().StartsWith(expectedDevice+"\\",StringComparison.OrdinalIgnoreCase))throw new ArgumentException("Opened handle is not on the verified local volume");
|
|
if(root){uint serial,component,flags;var fs=new StringBuilder(64);if(!GetVolumeInformationByHandleW(h,null,0,out serial,out component,out flags,fs,(uint)fs.Capacity) || fs.ToString()!="NTFS")throw new ArgumentException("Opened volume is not NTFS");}
|
|
}
|
|
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] static extern uint QueryDosDevice(string name,StringBuilder target,int size);
|
|
public static void Validate(string p) {
|
|
if(p==null || p.Length<4 || p.Length>1024 || !System.Text.RegularExpressions.Regex.IsMatch(p,@"^[A-Za-z]:\\") || p.Substring(3).IndexOfAny("/:*?\"<>|".ToCharArray())>=0) throw new ArgumentException("Exact literal local absolute file path required; no devices, streams or wildcards");
|
|
foreach(char c in p) if(c<32 || c==127)throw new ArgumentException("Control character in path");
|
|
foreach(string part in p.Substring(3).Split('\\')) if(part.Length==0 || part=="." || part==".." || part.EndsWith(".") || part.EndsWith(" ") || System.Text.RegularExpressions.Regex.IsMatch(part,@"^(CON|PRN|AUX|NUL|COM[1-9\u00b9\u00b2\u00b3]|LPT[1-9\u00b9\u00b2\u00b3])(?:\.|$)",System.Text.RegularExpressions.RegexOptions.IgnoreCase)) throw new ArgumentException("Unsafe device, traversal or directory path");
|
|
}
|
|
// Pin every ancestor without FILE_SHARE_DELETE; no path component may be
|
|
// replaced between validation and opening the file. OPEN_REPARSE_POINT never
|
|
// follows the final component. Only an actual local fixed NTFS volume is used.
|
|
public static Capture Copy(string source,string destination,long limit,DateTime deadline) {
|
|
Validate(source);
|
|
var drive=new DriveInfo(source.Substring(0,3));
|
|
var target=new StringBuilder(1024);
|
|
if(QueryDosDevice(source.Substring(0,2),target,target.Capacity)==0 || !System.Text.RegularExpressions.Regex.IsMatch(target.ToString(),@"^\\Device\\HarddiskVolume[0-9]+$") || drive.DriveType!=DriveType.Fixed || drive.DriveFormat!="NTFS") throw new ArgumentException("Only local fixed NTFS volumes are allowed");
|
|
var handles=new List<SafeFileHandle>();
|
|
try {
|
|
Validate(destination);
|
|
var destinationDrive=new DriveInfo(destination.Substring(0,3));var destinationTarget=new StringBuilder(1024);
|
|
if(QueryDosDevice(destination.Substring(0,2),destinationTarget,destinationTarget.Capacity)==0 || !System.Text.RegularExpressions.Regex.IsMatch(destinationTarget.ToString(),@"^\\Device\\HarddiskVolume[0-9]+$") || destinationDrive.DriveType!=DriveType.Fixed || destinationDrive.DriveFormat!="NTFS")throw new ArgumentException("Export destination must be local NTFS");
|
|
string parent=destination.Substring(0,3);string[] destinations=destination.Substring(3).Split('\\');
|
|
for(int j=-1;j<destinations.Length-1;j++) {
|
|
if(j>=0)parent=Path.Combine(parent,destinations[j]);
|
|
var h=CreateFile(parent,0x80u,3u,IntPtr.Zero,3,0x00200000u|0x02000000u,IntPtr.Zero);
|
|
if(h.IsInvalid){int error=Marshal.GetLastWin32Error();h.Dispose();throw new Win32Exception(error);}
|
|
handles.Add(h);Info info;
|
|
if(!GetFileInformationByHandle(h,out info) || (info.Attributes&0x400)!=0 || (info.Attributes&0x10)==0)throw new ArgumentException("Unsafe export directory/reparse point");
|
|
CheckLocalHandle(h,destinationTarget.ToString(),j==-1);
|
|
}
|
|
string current=source.Substring(0,3); string[] parts=source.Substring(3).Split('\\');
|
|
for(int i=-1;i<parts.Length;i++) {
|
|
if(i>=0)current=Path.Combine(current,parts[i]); bool last=i==parts.Length-1;
|
|
var h=CreateFile(current,last?0x80000000u:0x80u,3u,IntPtr.Zero,3,0x00200000u|0x02000000u,IntPtr.Zero);
|
|
if(h.IsInvalid){int error=Marshal.GetLastWin32Error();h.Dispose();throw new Win32Exception(error);}
|
|
handles.Add(h); Info info;
|
|
if(GetFileType(h)!=1 || !GetFileInformationByHandle(h,out info))throw new IOException("Not an ordinary disk file");
|
|
if((info.Attributes&0x400)!=0)throw new ArgumentException("Reparse points are not allowed");
|
|
CheckLocalHandle(h,target.ToString(),i==-1);
|
|
if(!last && (info.Attributes&0x10)==0)throw new ArgumentException("Non-directory ancestor");
|
|
if(last) {
|
|
if((info.Attributes&0x10)!=0)throw new ArgumentException("Directories are not supported");
|
|
if(info.Links!=1)throw new ArgumentException("Hard-linked files are not supported");
|
|
long length=((long)info.SizeHigh<<32)|info.SizeLow;
|
|
if(length>limit)throw new OverflowException("File exceeds per-file or remaining total byte limit");
|
|
// Capture at most the open length; concurrent writers are permitted, never chased.
|
|
using(var input=new FileStream(h,FileAccess.Read,65536))
|
|
using(var output=new FileStream(destination,FileMode.CreateNew,FileAccess.Write,FileShare.Read))
|
|
using(var first=System.Security.Cryptography.SHA256.Create())
|
|
using(var second=System.Security.Cryptography.SHA256.Create()) {
|
|
var buffer=new byte[65536];long copied=0;int n;
|
|
while(copied<length && (n=input.Read(buffer,0,(int)Math.Min(buffer.Length,length-copied)))!=0){if(DateTime.UtcNow>deadline)throw new TimeoutException("Grub collection deadline expired");copied+=n;output.Write(buffer,0,n);first.TransformBlock(buffer,0,n,buffer,0);}
|
|
first.TransformFinalBlock(new byte[0],0,0);
|
|
input.Position=0;long checkedBytes=0;
|
|
while(checkedBytes<copied && (n=input.Read(buffer,0,(int)Math.Min(buffer.Length,copied-checkedBytes)))!=0){if(DateTime.UtcNow>deadline)throw new TimeoutException("Grub snapshot verification deadline expired");checkedBytes+=n;second.TransformBlock(buffer,0,n,buffer,0);}
|
|
second.TransformFinalBlock(new byte[0],0,0);Info after=new Info();
|
|
bool changed=copied!=length || input.Length!=length || checkedBytes!=copied || Convert.ToBase64String(first.Hash)!=Convert.ToBase64String(second.Hash) || !GetFileInformationByHandle(h,out after);
|
|
if(!changed)changed=info.Write.dwHighDateTime!=after.Write.dwHighDateTime || info.Write.dwLowDateTime!=after.Write.dwLowDateTime;
|
|
output.Flush(true);return new Capture{Size=copied,OpenSize=length,Changed=changed};
|
|
}
|
|
}
|
|
}
|
|
throw new IOException("File was not opened");
|
|
} finally {foreach(var h in handles)h.Dispose();}
|
|
}
|
|
}
|
|
}
|
|
'@ -ErrorAction Stop
|
|
}
|
|
function Get-OtcheGrubSnapshot($Manifest,[string]$Directory) {
|
|
Initialize-OtcheGrub
|
|
$paths=@(Get-OtcheProperty $Manifest.settings 'grub_paths' @())
|
|
$limits=$Manifest.grub_limits
|
|
if ($paths.Count -gt 32 -or $limits.total_bytes -lt 0 -or $limits.total_bytes -gt 33554432 -or $limits.file_bytes -lt 0 -or $limits.file_bytes -gt 8388608 -or $limits.seconds -lt 1 -or $limits.seconds -gt 150) {throw 'Invalid Grub bounds'}
|
|
$deadline=[DateTime]::UtcNow.AddSeconds([int]$limits.seconds)
|
|
$files=New-Object 'Collections.Generic.List[object]';[long]$total=0
|
|
for ($i=0;$i -lt $paths.Count;$i++) {
|
|
$requested=[string]$paths[$i];$destination=Join-Path $Directory ('grub-{0:000}.bin' -f ($i+1))
|
|
$entry=[ordered]@{requested_path=$requested;resolved_path=$null;member=$null;status='error';error='';size=$null;sha256=$null;snapshot=$null}
|
|
try {
|
|
if ([DateTime]::UtcNow -gt $deadline) {throw [TimeoutException]::new('Grub collection deadline expired')}
|
|
$captured=[Otche.Grub]::Copy($requested,$destination,[Math]::Min([long]$limits.file_bytes,[long]$limits.total_bytes-$total),$deadline)
|
|
$entry.sha256=Get-OtcheHash $destination;$entry.size=$captured.Size;$entry.resolved_path=$requested;$entry.status='collected';$total+=$captured.Size
|
|
$entry.snapshot=@{open_size=$captured.OpenSize;changed=$captured.Changed;consistency='best_effort'}
|
|
if ($captured.Changed) {$entry.status='changed';$entry.error='File changed during bounded open-length snapshot; archived bytes are not an atomic snapshot'}
|
|
} catch {
|
|
$exception=$_.Exception.GetBaseException();$entry.error=$exception.Message
|
|
if ($entry.error.Length -gt 1024) {$entry.error=$entry.error.Substring(0,1024)}
|
|
if ($exception -is [ArgumentException]) {$entry.status='invalid_path'}
|
|
elseif ($exception -is [OverflowException]) {$entry.status='oversize'}
|
|
elseif ($exception -is [ComponentModel.Win32Exception]) {
|
|
if ($exception.NativeErrorCode -in @(2,3)) {$entry.status='missing'}
|
|
elseif ($exception.NativeErrorCode -eq 5) {$entry.status='access_denied'}
|
|
elseif ($exception.NativeErrorCode -in @(32,33)) {$entry.status='changed'}
|
|
} elseif ($exception -is [IO.IOException]) {$entry.status='changed'}
|
|
if ([IO.File]::Exists($destination)) {[IO.File]::Delete($destination)}
|
|
}
|
|
$files.Add($entry)
|
|
}
|
|
$collected=@($files | Where-Object {$null -ne $_.size}).Count
|
|
$complete=@($files | Where-Object {$_.status -eq 'collected'}).Count -eq $paths.Count
|
|
return [ordered]@{status=$(if ($complete) {'complete'} elseif ($collected -eq 0) {'empty'} else {'partial'});requested=$paths.Count;collected=$collected;files=@($files.ToArray())}
|
|
}
|
|
function Export-OtcheGrub($Manifest,[string]$Directory) {
|
|
Initialize-OtcheGrub
|
|
$paths=@(Get-OtcheProperty $Manifest.settings 'grub_paths' @())
|
|
if ($paths.Count -eq 0) {return}
|
|
$result=Read-OtcheJson "$Directory\result.json"
|
|
$prefix="$script:OtcheRoot\control\grub-$($Manifest.command_id)"
|
|
try {
|
|
if ($result.report.grub.files.Count -ne $paths.Count) {throw 'Grub export mapping is incomplete'}
|
|
$total=0L;$deadline=[DateTime]::UtcNow.AddSeconds([int]$Manifest.grub_limits.seconds)
|
|
for ($i=0;$i -lt $paths.Count;$i++) {
|
|
$entry=$result.report.grub.files[$i]
|
|
if ($entry.requested_path -cne $paths[$i]) {throw 'Grub export mapping mismatch'}
|
|
if ($null -eq $entry.size) {continue}
|
|
$source=Join-Path $Directory ('grub-{0:000}.bin' -f ($i+1))
|
|
$destination=('{0}-{1:000}.bin' -f $prefix,($i+1))
|
|
$captured=[Otche.Grub]::Copy($source,$destination,[Math]::Min([long]$Manifest.grub_limits.file_bytes,[long]$Manifest.grub_limits.total_bytes-$total),$deadline)
|
|
if ($captured.Changed -or $captured.Size -ne $entry.size -or (Get-OtcheHash $destination) -cne $entry.sha256) {throw 'Grub staged file changed before export'}
|
|
$total+=$captured.Size
|
|
}
|
|
Write-OtcheJson "$prefix.json" @{command_id=$Manifest.command_id;ready=$true;error=''} -CreateNew
|
|
} catch {Write-OtcheJson "$prefix.json" @{command_id=$Manifest.command_id;ready=$false;error=$_.Exception.GetBaseException().Message} -CreateNew}
|
|
}
|
|
Export-ModuleMember -Function *-Otche*
|