Friday, September 25, 2009

PERL: Check dlls used in a process

Problem Statement:
Find whether named dll’s are injected into certain processes

Solution:
Perl script (CheckDllInjection.pl) would:
Read a configuration xml
Start monitoring the processes (added in the process tags) and
Check if the dlls (added in dll tags) are getting injected in these processes or not.
Report the results in a desired format.

Pre-requisites:
You need to have Perl installed on your system and XML::Simple module should be present.

Input:
DllConfig.xml would contain the processes (Process tag) to be monitored and the dll’s (Dll tags) that need to be checked for injection. (sample Dllconfig.xml attached). Perl script to be run from a location where dll file is present.

Output:
Output is a Results.csv file that would give out the results telling if the dlls were really injected in the processes with the values as YES/NO and results as PASS/FAIL.

Contents of DllConfig.xml file:

<configuration>
<test>
<test1>
<process>process1.exe</process>
<dll>abc.dll</dll>
<dll>xyz.dll</dll>
</test1>

<test2>
<process>process2.exe</process>
<dll>pqr.dll</dll>
<dll>lmnop.dll</dll>
<dll>cjg.dll</dll>
</test2>
</test>
</configuration>

Perl Script that works on Windows Platform:

#!/usr/bin/perl
use XML::Simple;
if(-e "Results.csv")
{
system "del Results.csv";
}
open(FP, "> Results.csv");
print FP "Process,DLL,Injected?,Result \n";

$xml = new XML::Simple;
$dllconfig = $xml->XMLin("DllConfig.xml"); #reached the Configuration tag
$test = $dllconfig->{Test}; #reached the Test tag
%tests = %$test;

#got all the processes and dlls
$count=0;
foreach my $k (keys %tests) {
$process = $test->{$k}->{Process};
$dll = $test->{$k}->{Dll};
if(ref($dll) eq 'ARRAY')
{
foreach $mydll (@$dll) #reading DLL files one by one
{
system "tasklist /M $mydll > C:\\$mydll.txt";

open(FH, "C:\\$mydll.txt");

$size = -s FH;
if(!$size) { print FP "$process,$mydll,NO,FAIL\n";}

while()
{
if($_ =~ m/.*$process.*/i)
{
print FP "$process,$mydll,YES,PASS\n";
$flag=1;
last;
}
else
{
$flag=0;
}
}
if(!$flag) {print FP "$process,$mydll,NO,FAIL\n";}
close FH;
system "del c:\\$mydll.txt";
}

}
else
{
system "tasklist /M $dll > C:\\$dll.txt";

open(FH, "C:\\$dll.txt");

$size = -s FH;
if(!$size) { print FP "$process,$dll,NO,FAIL\n";}

while()
{
if($_ =~ m/.*$process.*/i)
{
print FP "$process,$dll,YES,PASS\n";
$flag=1;last;
}
else
{
$flag=0;
}

}if(!$flag) {print FP "$process,$dll,NO,FAIL\n";}
close FH;
system "del c:\\$dll.txt";
}
}

close FP;

No comments: