Friday, November 18, 2011

How do you convert a chunk of obfuscated or just plain messy and hard to read Perl code into readable format?

We can take advantage of the "Deparse" module. It compiles, then decompiles the program it is given, expanding it out and formatting it nicely.

To run it at the command line, type "perl -MO=Deparse prog.pl". Here is an example
of its usage, showing the input program (red) and the output of Deparse (blue).

$ cat messy.pl
for(74,117,115,116){$::a.=chr};(($_.='qwertyui')&&
(tr/yuiqwert/her anot/))for($::b);for($::c){$_.=$^X;
/(p.{2}l)/;$_=$1}$::b=~/(..)$/;print("$::a$::b $::c hack$1.");


$ perl -MO=Deparse messy.pl
foreach $_ (74, 117, 115, 116) {
    $a .= chr $_;
}
;
$_ .= 'qwertyui' and tr/eiqrtuwy/nr oteah/ foreach ($b);
foreach $_ ($c) {
    $_ .= $^X;
    /(p.{2}l)/;
    $_ = $1;
}
$b =~ /(..)$/;
print "$a$b $c hack$1.";

Tuesday, November 8, 2011

How can we access environmenttal variables in Perl?

Perl provides access to environment variables via the global %ENV hash. However, if using the Env module, it will create global scalars for all the environment variables.

use Env; print "$USER uses $SHELL";
If required to get only a few selected variables then it can be done like:
 
use Env qw[@PATH $USER]; print "$USER's path is @PATH";

How can we call another program without invokation of shell in Perl?

The system function is Perl's simplest method for accomplishing this. However, one point that should be noted here is: both this program and the Perl program from where we will be running it, will be sharing the same STDIN and STDOUT.

The syntax is like:

$status = system("myprog arg1 arg2");

This particular syntax will invoke the shell, to interpret the command line. In order to avoid the shell's involvement, the arguments for the program being executed should be passed as a list, like:
$status = system("myprog", "arg1", "arg2);

The system function does not return the program's STDOUT, rather its return value is either the program's exit status or the signal number that the process might have died from.

How can we dynamic activate the debugger in Perl?

while (<INPUT>)
   {
   $DB::trace = 1, next if /debug/;
   $DB::trace = 0, next if /nodebug/;
   # more codes
   }
When run under the debugger, this enables tracing when the loop encounters an input line containing "debug" and ceases tracing upon reading one containing "nodebug". We can even force the debugger to breakpoint by setting the variable $DB::single to 1, which also happens to provide a way you can debug code in BEGIN blocks (which otherwise are executed before control is given to the debugger).