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;

Monday, August 3, 2009

PERL: Testing a Web Service

Problem Statement: Testing a Web Service

Here's a small script that you can use for testing a Web Service.

#!/usr/bin/perl


use LWP::UserAgent;
use HTTP::Request;


TestWS();

sub TestWS
{

my $message = "Your Request Message";

my $userAgent = LWP::UserAgent->new();
my $request = HTTP::Request->new(POST => "Link of the WebService");
$request->header(SOAPAction => '"Soap Header that is being used"');
$request->content($message);
$request->content_type("text/xml; charset=utf-8");
my $response = $userAgent->request($request);

if($response->code == 200)
{
print "Web Service works fine";
}

else
{
print "Looks like there is a bug in the web service";
}
}


By posting the request message and getting the HTTP response back with the help of useragent would help us test the Web Service.


Getting performance of Web Service:

This can be done by keeping the method TestWS() in a for loop and logging the response in a log file along with the date.

So, keeping everything same as above, we create a file C:\WSlog.log file and run a while loop for TestWS method. Also we log the time every time we get a response as depicted in the change script below.


open (FP, ">C:\\WSlog.log");

while(1)
{
&TestWS();
}

Change in the script:
if($response->code == 200)
{
$x = gmtime();
print FP "$x";
print FP $response->as_string;

}

Analyzing the log file:
Finding the no. of requests and responses taht we have received, we can get the time frame in which a response is made from the Web Service.

Also while running this script, after sometime we would observe 500 Internal Server Error. That is the point we say teh Web Service has run out of sockets for communication. Hence we get a limit on teh no. of continous requests that can be made to a Web Service.

Monday, June 29, 2009

PowerShell: MD5/SHA1 hashes of files

Problem Statement: I need to get Signatures (MD5 and SHA1) of all the files present at a certain location on the hard disk.
Utility: This could be for checking the signature of the files present in the downloaded build for correctness or if need be for whitelisting of files.
Here's a small PowerShell script

function Get-Md5{
param ($file)
$input = get-content -encoding byte -readcount -1 $file$md5 = [System.Security.Cryptography.MD5]::Create()
$output = $md5.ComputeHash($input)$sb = new-object Text.StringBuilder
foreach ($b in $output) {
[void] $sb.Append($b.ToString("X2"));
}
$sb.ToString()
}function Get-SHA1{param ($file)
$input = get-content -encoding byte -readcount -1 $file$sha1 = [System.Security.Cryptography.SHA1]::Create()
$output = $sha1.ComputeHash($input)
$sb = new-object Text.StringBuilder
foreach ($b in $output) {
[void] $sb.Append($b.ToString("X2"));
}
$sb.ToString()
}
"MD5`tSHA1`tFilePath" out-file C:\Hashes.xls -append$files = get-childitem $args -recurse -include *.*
foreach ($i in $files) {
$md5 = get-md5 $i $sha1 = get-sha1 $i "$md5`t$sha1`t$i" out-file C:\Hashes.xls -append
}
Hope this helps.

Tuesday, May 26, 2009

Batch: '-' issues

Today, I encountered something unusual at work.

~ I had an application (say app.exe) that accepted parameters; for e.g., if "App.exe -i" command is executed, the application would get installed on the system.
~ Also, I had a BATCH script that would call App.exe with options for further processing.
But somehow the script didn't run effectively. I had to use the command, "App.exe -i" in the script and when I ran the script, to my surprise, I could see the command being executed as "App.exe ϋi" instead of "App.exe -i". That is, instaed of "-" it ran as "ϋ" on the command prompt.
Where did this "ϋ" come from??

After struggling for an hour or so I could gauge that the "ϋ" sign was because of the space between App.exe and -i in the command.

The simple solution was to use a ESCAPE sequence before the space. Hence I scripted the command as "App.exe^ -i". where ^ is the escape sequence in DOS and then space was no more an issue.

Interesting isn't it!! :-)

Wednesday, April 1, 2009

Powershell-GUI: EventLog Manager

Problem Statement: Recently. there was a requirement for me to clear or save event logs of different systems on the network. The number of systems in the network were at least 10 and the requirement demanded that I had to Save Event logs or Clear Event Logs on all/selected servers (separated by commas), in one go!



Now here's what I came up with:






Script:
Function Main{
[reflection.assembly]::LoadWithPartialName( "System.Windows.Forms")
$form = New-Object Windows.Forms.Form $form.text = "Event Log Manager"
$form.height = 400
$label_logname = New-Object Windows.Forms.Label
$label_logname.Location = New-Object Drawing.Point 50,30
$label_logname.Size = New-Object Drawing.Point 200,30
$label_logname.text = "Enter the EventLog Name"
$combo = new-object System.Windows.Forms.ComboBox
$combo.Location = new-object System.Drawing.Size(50,60)
$combo.Size = new-object System.Drawing.Size(200,15)
$combo.Items.Add("Enter EventLog") $combo.Items.Add("Application")
$combo.Items.Add("System")
$label_server = New-Object Windows.Forms.Label
$label_server.Location = New-Object Drawing.Point 50,110
$label_server.Size = New-Object Drawing.Point 200,30
$label_server.text = "Enter the Server Names separated by commas"
$combo1 = new-object System.Windows.Forms.ComboBox
$combo1.Location = new-object System.Drawing.Size(50,150)
$combo1.Size = new-object System.Drawing.Size(200,15)
$combo1.Items.Add("10.2.2.3")
$button = New-Object Windows.Forms.Button
$button.text = "Save EventLog"
$button.Location = New-Object Drawing.Point 50,200
$button.Size = New-Object Drawing.Point 200,25
$button1 = New-Object Windows.Forms.Button
$button1.text = "Clear EventLog"
$button1.Location = New-Object Drawing.Point 50,250
$button1.Size = New-Object Drawing.Point 200,25
$button2 = New-Object Windows.Forms.Button
$button2.text = "Quit..."
$button2.Location = New-Object Drawing.Point 50,300
$button2.Size = New-Object Drawing.Point 200,25
$button.add_click({ $form.hide()
SaveEvtLog $combo1.text $combo.text })
$button1.add_click({ $form.hide()
ClearEvtLog $combo1.text $combo.text })
$button2.add_click({ $form.dispose() })
$form.controls.add($button)
$form.controls.add($label_logname)
$form.controls.add($label_server)
$form.controls.add($button1)
$form.controls.add($button2)
$form.controls.add($combo)
$form.controls.add($combo1)
$form.ShowDialog()
}

Function SaveEvtLog {
param ($computer,$evtlog)
$servers = $computer.split(',')
foreach ($server in $servers) {
[reflection.assembly]::LoadWithPartialName( "System.Windows.Forms")
$form1 = New-Object Windows.Forms.Form $form1.height = 300 $form1.width = 300 $label2 = New-Object Windows.Forms.Label
$label2.Location = New-Object Drawing.Point 50,30
$label2.Size = New-Object Drawing.Point 200,90
$ALive=get-wmiobject win32_pingstatus -Filter "Address='$server'" Select-Object statuscode
if($ALive.statuscode -ne 0)
{ "Host $server is Unreachable...`n" out-file log.txt -append }
else { $filename = "Log_" + $evtlog + "_" + $server + ".evt"
if((Test-Path -path c:\$filename) -ne $False) { remove-item C:\$filename } wmic /node:"$server" nteventlog where "logfilename='$evtlog'" call backupeventlog "C:\$filename" out-file null
remove-item null
copy-item file://$server/c$/$filename C:\
remove-item file://$server/c$/$filename
$lbl_text = "EventLog copied at c:\$filename" out-file log.txt -append } }
$lbl = get-content log.txt
$label2.text = $lbl
$button4 = New-Object Windows.Forms.Button
$button4.text = "Back to Main..."
$button4.Location = New-Object Drawing.Point 50,180
$button4.Size = New-Object Drawing.Point 200,25 remove-item log.txt
$button4.add_click({ $form1.hide()
Main })
$form1.controls.add($label2)
$form1.controls.add($button4)
$form1.ShowDialog() }

Function ClearEvtLog {
param ($computer,$evtlog)
$servers = $computer.split(',')
foreach ($server in $servers) {
[reflection.assembly]::LoadWithPartialName( "System.Windows.Forms")
$form1 = New-Object Windows.Forms.Form
$form1.height = 300 $form1.width = 300
$label2 = New-Object Windows.Forms.Label
$label2.Location = New-Object Drawing.Point 50,30
$label2.Size = New-Object Drawing.Point 200,90
$ALive=get-wmiobject win32_pingstatus -Filter "Address='$server'" Select-Object statuscode
if($ALive.statuscode -ne 0)
{ "Host $server is Unreachable...`n" out-file evt.txt -append }
else { $logs = [System.Diagnostics.Eventlog]::GetEventLogs("$server")
$Applogs = $logswhere-object {$_.logdisplayname -eq "$evtlog" }
if($Applogs -ne $null)
{$Applogs.clear()
"$evtlog Event Log Cleared at $server `n" out-file evt.txt -append}
else {"Event log is already cleared or it doesnt exist `n" out-file evt.txt -append} } } $lbl = get-content evt.txt
$label2.text = $lbl
$button4 = New-Object Windows.Forms.Button
$button4.text = "Back to Main..."
$button4.Location = New-Object Drawing.Point 50,180
$button4.Size = New-Object Drawing.Point 200,25 remove-item evt.txt
$button4.add_click({ $form1.hide()
Main })
$form1.controls.add($label2)
$form1.controls.add($button4)
$form1.ShowDialog() }

Main



Hope this helps!! Let me know your comments...

PERL: Base64 Encoding

What is Base64: Base64 is MIME character tranafer encoding...Its like any other encoding that uses a-zA-Z0-9/+ (64 characters and = for padding) for converting the string...An important encoding format....Between, have you wondered if we could use a Base64 encoded string as a filename?? Think??

Here's a small PERL script that would help you in encoding and decoding the input string:

C0de:
#! /usr/bin/perl
use MIME::Base64;
print "Enter the Choice\n";
print "1. Encode to Base 64\n";
print "2. Decode from Base64\n";print "Enter the choice::";
my $choice=<STDIN>;
if($choice==1)
{ print "Please enter a string that is to be encoded:"; my $str=; my $encode=encode_base64($str); print "String ENCODED as:$encode"; }
if($choice==2)
{ print "Please enter a Base 64 string that is to be decoded:"; my $str=; my $decode=decode_base64($str); print "String DECODED as:$decode"; }

Hope this helps!!!

PowerShell: Script for getting the inventory details....

Hya!! After a long gap, I am here again...
This time I have come up with an utility that takes the details of your inventory.

Problem Statement: I have a lot of servers on my network and my manager comes and tell me, "Can you get me details like the total RAM, HDD, Manufacturer, Serial Number and ServerName of all these servers?? I need to report this to Infrastructure team! Please get this in 2 hours time!!" Sounds laborious..Isn't it??

Here's the script:

"IP`tHardDisk`tRAM`tSystemName`tManufacturer`tSerialNumber" out-file C:\Results.csv -append

Function HDDInfo { param($ip) $alldrives = get-wmiobject win32_logicaldisk -filter "DriveType=3" -computername $ip $HDD = 0 foreach ($i in $alldrives) { $HDD = $HDD + ($i.size)/(1gb) } $HDD }

Function RAMInfo { param($ip) $ram = get-wmiobject win32_ComputerSystem -computername $ip $RAM = ($ram.TotalPhysicalMemory)/(1gb) $RAM }

Function SystemName { param($ip) $bios = get-wmiobject win32_bios -computer $ip $bios.name }

Function Manufacturer { param($ip) $bios = get-wmiobject win32_bios -computer $ip $bios.manufacturer } Function SerialNumber { param($ip) $bios = get-wmiobject win32_bios -computer $ip $bios.SerialNumber }

$address = "10.2.2."
2..254 foreach-object { $ip = $address + $_
$ping = get-wmiobject win32_pingstatus -filter "Address = '$ip'" select-object statuscode
if($ping.statuscode -eq 0) { $HDD = HDDInfo $ip sleep 1 $RAM = RAMInfo $ip sleep 1 $SystemName = SystemName $ip $Manufacturer = Manufacturer $ip $SerialNumber = SerialNumber $ip
"$ip`t$HDD`t$RAM`t$SystemName`t$Manufacturer`t$SerialNumber" out-file C:\Results.csv -append } else { "$ip is Offline or Not Reachable.." out-file C:\Results.csv -append }
}


In this script, I assume all your systems on the network are in the IP range of 10.2.2.x and I am collecting the details of IPs: 10.2.2.2 - 10.2.2.254

Run the script, wait for 4-5 minutes and get the results in Results.csv file. :-)

Hope this helps!!