Baseline comparison code

Last month I talked a bit about establishing a baseline and performing regular checks against it to ensure that the system was not compromised in some way.

I’ve finally gotten around to putting some code together to show how something like this can be automated.

Plus I got to learn more about using Microsoft’s PowerShell, which I had been wanting to do for a while.

The following bit of PowerShell code compares the current list of running processes and services to an existing baseline (saved as “baseline.txt” in the same directory)

(Warning: I’m not a very accomplished coder.  There are probably much more efficient ways of doing this)

$base = Get-Content("./baseline.txt");
$a = tasklist /svc /fo csv;
$current = New-Object System.Collections.ArrayList;
$baseline = New-Object System.Collections.ArrayList;
$results = [System.IO.StreamWriter] "results.txt";
$date = Get-Date;

foreach ($b in $a){

$b = $b.Replace("`",`"","#");
$b = $b.Replace("`"","");
$c = $b.Split("#");
$current.Add($c[0] + ":" + $c[2]);

foreach ($x in $base){
$x = $x.Replace("`",`"","#");
$x = $x.Replace("`"","");
$j = $x.Split("#");
$baseline.Add($j[0] + ":" + $j[2]);


$results.WriteLine("Entries in current tasklist not matching baseline:");

foreach($k in $current){
  if($baseline -notcontains $k){
$results.WriteLine("Entries in baseline not found in current tasklist:");
foreach($l in $baseline){
  if($current -notcontains $l){

The code formats the current tasklist output as CSV (comma separated value) to make text parsing easier.  I run a few replace commands to clean up the data, and split each row into an array of substrings.  I take the first column (process name) and third column  (attached services) and write them together into an ArrayList structure.

This is repeated for the baseline.  Then the two lists can be compared, and any anomalous results are written to the results.txt file.

To make administration and monitoring even easier, this can be followed up with some code to email the data (Powershell has a handy Send-MailMessage cmdlet).  Save the whole thing into a *.ps1 file and schedule it to run however often you need.

Your servers should have PowerShell configured to disable running unsigned code (Set-ExecutionPolicy AllSigned), so you’ll have to self-sign the script and trust yourself as a root authority.


4 responses

  1. Pingback: What do you do with a hacker who’s already in jail? | Arboreal Security

  2. Pingback: Posting again with a new focus | Arboreal Security

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s