Friday, January 2, 2009

Searching for malware with Powershell



hmmm.....
This gives me output like:
1/3/2009 11:09 AM,19:9:16:859,100,csrss,1124,16388096,40923136,104357888,15458304,39809024,87851008
which covers WorkingSet, PrivateMemorySize, VirtualMemorySize, and their deltas between measurement interval.
## Use ps to measure Application Memory Deltas
## Run '.\ws_diff [Interval in Seconds] [Process Name] or
## to log all processes continually every 10 seconds -- 'while (1) {.\WS_diff.ps1 10 cmd >> ps_out.txt }'

# Create args as Variables or Objects
$sleep_time = $args[0]

# Create or define PS_Array. Default is ps is called without args. 
# Then take measurements $now, $then, $count
if ($args[1] -eq $NULL )
    {
    $then = ps | %{$_ | Select Name,ID,WorkingSet,PrivateMemorySize,VirtualMemorySize}
    sleep -seconds $sleep_time
    $now  = ps | %{$_ | Select Name,ID,WorkingSet,PrivateMemorySize,VirtualMemorySize}
    $count = ($now | Select Name).count
    }
else
    {
    $ps_array = ( ps $args[1] )
    $then = ps -inputobject $ps_array | %{$_ | Select Name,ID,WorkingSet,PrivateMemorySize,VirtualMemorySize}
    sleep -seconds $sleep_time
    $now  = ps -inputobject $ps_array | %{$_ | Select Name,ID,WorkingSet,PrivateMemorySize,VirtualMemorySize}
    $count = ($now | Select Name).count
    }

# Declare Time Measurements 
$date = (get-date -format g)
$hour = [DateTime]::UtcNow.TimeOfDay.Hours
$minutes = [DateTime]::UtcNow.TimeOfDay.Minutes
$seconds = [DateTime]::UtcNow.TimeOfDay.Seconds
$ms = [DateTime]::UtcNow.TimeOfDay.Milliseconds

# Write output and find diffs. Check if process has multiple instances first
if ( $count -gt 1 ) 
{
    $array_out = 0..$count |
    %{ 
    $date + "," +
    $hour + ":" + $minutes + ":" + $seconds + ":"  + $ms + "," +
    $sleep_time + "," + $now[$_].Name + "," + $now[$_].ID + "," +
    $now[$_].WorkingSet + "," +
    $now[$_].PrivateMemorySize + "," +
    $now[$_].VirtualMemorySize + "," +
    ( ($now[$_].WorkingSet) - ($then[$_].WorkingSet) ) + "," +
    ( ($now[$_].PrivateMemorySize) - ($then[$_].PrivateMemorySize) ) + "," +
    ( ($now[$_].VirtualMemorySize) - ($then[$_].VirtualMemorySize) )
    }
}

else  
{
    $array_out =
    $date + "," +
    $hour + ":" + $minutes + ":" + $seconds + ":"  + $ms + "," +
    $sleep_time + "," + $now.Name + "," + $now.ID + "," +
    $now.WorkingSet + "," +
    $now.PrivateMemorySize + "," +
    $now.VirtualMemorySize + "," +
    ( ($now.WorkingSet) - ($then.WorkingSet) ) + "," +
    ( ($now.PrivateMemorySize) - ($then.PrivateMemorySize) ) + "," +
    ( ($now.VirtualMemorySize) - ($then.VirtualMemorySize) )
}

write $array_out

No comments: