64 lines
7.0 KiB
PowerShell
64 lines
7.0 KiB
PowerShell
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
|
if((($p.PSObject.Properties.Name|Sort-Object)-join',')-cne'agent_sha256,helper_sha256,id'-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.agent_sha256-cnotmatch'^[0-9a-f]{64}$'-or$p.helper_sha256-cnotmatch'^[0-9a-f]{64}$'){throw 'Fixed public sample read'}
|
|
$state='C:\ProgramData\RustDiscovery\state';$agent='RmmDiscoveryWindows';$helper='RmmDiscoverySystemHelper'
|
|
$agentSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$agent)).Translate([Security.Principal.SecurityIdentifier]).Value
|
|
$allowed=@('S-1-5-18','S-1-5-32-544',$agentSid)
|
|
function Check($path,[bool]$directory){
|
|
$i=Get-Item -LiteralPath $path -Force
|
|
if($i.PSIsContainer-ne$directory-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Regular public report path'}
|
|
$ancestor=$i.Directory;if($directory){$ancestor=$i.Parent};while($null-ne$ancestor){if($ancestor.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Public report reparse ancestry'};$ancestor=$ancestor.Parent}
|
|
$acl=Get-Acl -LiteralPath $path;$owner=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value
|
|
if($owner-cnotin$allowed-and!(!$directory-and$owner-ceq'S-1-5-19')){throw 'Public report owner'}
|
|
$rules=@($acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Public report empty DACL'}
|
|
foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-cnotin$allowed){throw 'Public report broad DACL'}}
|
|
if($directory-and!$acl.AreAccessRulesProtected){throw 'Protected public report directory'}
|
|
return @{owner_sid=$owner;sddl=$acl.Sddl;dacl_checked=$true}
|
|
}
|
|
Add-Type -TypeDefinition @'
|
|
using System; using System.Text; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles;
|
|
public static class RmmPassiveTimeRead {
|
|
[StructLayout(LayoutKind.Sequential)] public struct Info {public uint Attr,CL,CH,AL,AH,WL,WH,Volume,SizeH,SizeL,Links,IndexH,IndexL;}
|
|
[DllImport("kernel32.dll",SetLastError=true)] public static extern bool GetFileInformationByHandle(SafeFileHandle h,out Info i);
|
|
[DllImport("kernel32.dll",SetLastError=true)] static extern IntPtr OpenProcess(uint access,bool inherit,int pid);
|
|
[DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern bool QueryFullProcessImageName(IntPtr h,uint flags,StringBuilder text,ref uint size);
|
|
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetProcessTimes(IntPtr h,out long creation,out long exit,out long kernel,out long user);
|
|
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr h,out uint code);
|
|
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
|
|
public static string[] Process(int pid){IntPtr h=OpenProcess(0x1000,false,pid);if(h==IntPtr.Zero)throw new InvalidOperationException("QUERY_PROCESS");try{long c,e,k,u;uint code,size=32768;StringBuilder image=new StringBuilder((int)size);if(!GetProcessTimes(h,out c,out e,out k,out u)||!QueryFullProcessImageName(h,0,image,ref size)||!GetExitCodeProcess(h,out code)||code!=259)throw new InvalidOperationException("LIVE_PROCESS");return new string[]{c.ToString(System.Globalization.CultureInfo.InvariantCulture),image.ToString()};}finally{CloseHandle(h);}}
|
|
}
|
|
'@
|
|
function Hash([byte[]]$bytes){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
|
|
function Runtime($role){
|
|
$name=$agent;$image='C:\Program Files\RustDiscovery\rmm-agent-windows.exe';$owner='NT AUTHORITY\LocalService';$mode='Auto';$sha=$p.agent_sha256
|
|
if($role-ceq'helper'){$name=$helper;$image='C:\Program Files\RustDiscovery\rmm-helper-windows.exe';$owner='LocalSystem';$mode='Manual';$sha=$p.helper_sha256}
|
|
$s=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -OperationTimeoutSec 5
|
|
if(!$s-or$s.State-cne'Running'-or$s.StartName-cne$owner-or$s.StartMode-cne$mode-or$s.ProcessId-le0-or$s.ServiceType-cne'Own Process'){throw 'Current fixed service role'}
|
|
$expected='"'+$image+'" --service';if($role-ceq'agent'){$expected+=' --config "C:\ProgramData\RustDiscovery\config.json"'}
|
|
if($s.PathName-cne$expected){throw 'Current fixed service command'}
|
|
$native=[RmmPassiveTimeRead]::Process([int]$s.ProcessId)
|
|
if($native[1]-cne$image-or(Get-FileHash -LiteralPath $image -Algorithm SHA256).Hash.ToLowerInvariant()-cne$sha){throw 'Current fixed service image'}
|
|
return [ordered]@{pid=[uint32]$s.ProcessId;birth_filetime=$native[0];image=$native[1];sha256=$sha;start_name=$s.StartName;start_mode=$s.StartMode;command=$s.PathName}
|
|
}
|
|
function Boot{return (Get-CimInstance Win32_OperatingSystem -Property LastBootUpTime -OperationTimeoutSec 5).LastBootUpTime.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture)}
|
|
$null=Check 'C:\ProgramData\RustDiscovery' $true;$directory=Check $state $true
|
|
$boot=Boot;$before=[ordered]@{agent=(Runtime 'agent');helper=(Runtime 'helper')};$reports=[ordered]@{}
|
|
foreach($name in @('agent-time-sample.json','helper-time-sample.json')){
|
|
$path=Join-Path $state $name
|
|
if(!(Test-Path -LiteralPath $path)){$reports[$name]=$null;continue}
|
|
$stream=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read)
|
|
try{
|
|
$meta=Check $path $false;$info=New-Object RmmPassiveTimeRead+Info
|
|
if(![RmmPassiveTimeRead]::GetFileInformationByHandle($stream.SafeFileHandle,[ref]$info)-or$info.Links-ne1-or($info.Attr-band0x410)-ne0-or$info.SizeH-ne0-or$info.SizeL-lt1-or$info.SizeL-gt8192-or$stream.Length-ne$info.SizeL){throw 'Single-link bounded public report'}
|
|
$raw=New-Object byte[] $info.SizeL;$offset=0;while($offset-lt$raw.Length){$count=$stream.Read($raw,$offset,$raw.Length-$offset);if($count-le0){throw 'Complete held public report'};$offset+=$count}
|
|
$after=New-Object RmmPassiveTimeRead+Info
|
|
if(![RmmPassiveTimeRead]::GetFileInformationByHandle($stream.SafeFileHandle,[ref]$after)-or$after.IndexH-ne$info.IndexH-or$after.IndexL-ne$info.IndexL-or$after.WH-ne$info.WH-or$after.WL-ne$info.WL-or$after.SizeL-ne$info.SizeL-or$after.Links-ne1){throw 'Stable held public report'}
|
|
$again=Check $path $false;if($again.sddl-cne$meta.sddl-or$again.owner_sid-cne$meta.owner_sid){throw 'Stable public report security'}
|
|
$meta['volume']=$info.Volume;$meta['index_high']=$info.IndexH;$meta['index_low']=$info.IndexL;$meta['last_write_filetime']=(([uint64]$info.WH-shl32)-bor$info.WL).ToString([Globalization.CultureInfo]::InvariantCulture)
|
|
$reports[$name]=@{raw_base64=[Convert]::ToBase64String($raw);sha256=(Hash $raw);metadata=$meta}
|
|
}finally{$stream.Dispose()}
|
|
}
|
|
$after=[ordered]@{agent=(Runtime 'agent');helper=(Runtime 'helper')}
|
|
$directoryAfter=Check $state $true
|
|
if(($before|ConvertTo-Json -Depth 8 -Compress)-cne($after|ConvertTo-Json -Depth 8 -Compress)-or(Boot)-cne$boot-or$directory.sddl-cne$directoryAfter.sddl){throw 'Stable process, directory and boot during public read'}
|
|
@{id=$p.id;read_only=$true;boot_ticks=$boot;runtime=$after;state_metadata=$directory;reports=$reports;observed_at=[DateTime]::UtcNow.ToString('o')}|ConvertTo-Json -Depth 12 -Compress
|