perl basics for pentesters

46
Minimal Perl Basics for Pentesters Sanjeev Jaiswal (Jassi) Perl Programmer and Security Enthusiast #nullhyd

Upload: alien-coders

Post on 15-Jul-2015

635 views

Category:

Technology


4 download

TRANSCRIPT

Minimal Perl Basics for Pentesters

Sanjeev Jaiswal (Jassi)

Perl Programmer and Security Enthusiast

#nullhyd

Agenda

http://www.aliencoders.org/

•Minimal Perl fundamentals

•CPAN modules a Pentester should know

•Known Perl scripts for Pentesting

•Sample scripts (Demo)

http://www.aliencoders.org/

This is just the beginning…

Perl Fundamentals

http://www.aliencoders.org/

• When you refer a programming language say it Perl• When you refer a script , let’s say perl• But never ever say PERL, use perl or Perl

Perl mongers and Larry Wall don’t like it ;-)

Perl has some backronyms though Practical Extraction and Report Language, or

Pathologically Eclectic Rubbish Lister.

And its Perl not Pearl

http://www.aliencoders.org/

Perl or perl or PERL?

• Try perl -v to check if it’s installed or not

Unix/Linux

• Run curl -L http://xrl.us/installperlnix | bash in terminal

OSX

• Install command line toll Xcode

• Run curl -L http://xrl.us/installperlnix | bash in terminal

Windows

• install strawberry perl or activestate perl

Then install cpan App::cpanminus to install perl modules easily in future

http://www.aliencoders.org/

Installing perl

• perl <perl_program>

• chmod 755 and execute ./<perl_program>

Let’s try something more on CLI• perl –d <perl_program> #Diagonise more

• perl –c <perl_program> #check if syntax is ok

• perl -e 'print "perl one-liner\n";'

• perl one-liner examples (palindrome, inplace-editing)

http://www.aliencoders.org/

Executing perl program

• shebang i.e #!

•print, say

•#comment

•$calar, @rray, %ash

•Comparison operators (> or gt <= or le)

•Reference in Perl

•%INC and @INC

http://www.aliencoders.org/

Who’s who in Perl ;)

#!/usr/bin/perl #Shebang starts with #!

use strict;

use warnings;

# It's a comment and its just the basic

my $name = "Sanjeev Jaiswal"; #scalar

my $id = 10; # scalar

my $sal = 100.98; #scalar

my @name = ("Sanjeev", "Jaiswal"); #array

my %hash = ('fname'=>'Sanjeev', 'lname', 'Jaiswal'); #hash

print "$id, $name[0], $hash{'lname}\n";

print "$name\n" if ( $id < 100 );

http://www.aliencoders.org/

Basic Example in Perl ;)

Loop Control

http://www.aliencoders.org/

•if, if else, if elsif else

•for, foreach

•while, do while

•next, unless, last

•return, exit

http://www.aliencoders.org/

Loop and control structures

while(<>){

next if /^\d+/;

last if /^\W/;

print $_;

}

print $_ foreach(1 .. 100);

print if(10 <= 10.0);

if($name eq 'sanjeev'){

print "$name\n";

} elsif ($id >70){

print "$id\n";

} else {

print "not matched\n";

}

http://www.aliencoders.org/

Loop and control structures

Functions to memorize

http://www.aliencoders.org/

•shift , push and chomp

•sort and reverse

•exec, system and eval

•warn, die

• join and split

•keys, values, each

•exists, defined, delete, unlink

http://www.aliencoders.org/

Minimal functions you should know

• chomp (my $u_input = <STDIN>); #chomps the user input

• my $f_elem = shift @array; # assign first element of an array

• push @arr, $elem; # Adding $elem at the last of @arr

• @sorted_num = sort {$a <=> $b} @unsorted_num; #sort integer array

• @reverse_sort = sort {$b <=> $a} @unsorted_num; #reverse sort

• @reverse_sort = reverse sort @unsorted_arr # reverse sort of string array or

• @reverse_sort = sort {$b cmp $a} @unsorted_arr

• warn "Very high\n" if($num > 10);

• die "Very low\n" if($num < 2);

• system("ls -la", "dir" )

• exec("/bin/cat", "/home.txt");

• `ls -la`; #avoid backtick if possible

• join(/\s/ , @array);

• split(/\s/, $string);

http://www.aliencoders.org/

Minimal examples ;)

Perl File Handlers

http://www.aliencoders.org/

•open(), close()

•>, >>, <

•+>, +>>, +<

•File testing -e, -f, -d, -s, -m etc.

•opendir, closedir, readdir

http://www.aliencoders.org/

Manipulate file handling

open(FH, "<", "filename") or die "can't open: $!\n"; # > for write and >> for append

while ( defined(my $line = <FH>) ) { do something .. }

close(FH);

open(LS, "<", "ls -la|"); # use instead of ``

open(FIND, "find . -type f -name dns_info.pl |-"); #better than previous command

do something if -e $file; # -e means exists, -f is for file and -d for directory

do something if -s >0; #-s is for size and -m means modified

$dir = "/home/sanjeev/";

opendir ( DIR, $dir ) || die "Error in opening directory $dir\n";

while( ($file = readdir(DIR))){

next if $file =~ m/\.{1,2}/;

print("$file\n") if -f $file;

}

closedir(DIR);

http://www.aliencoders.org/

File Handling examples

Perl Special Variables

• $0 – name of perl script being executed

• $^O – O.S.

• $! – current value of errno in scalar and string in list context

• $@ - error message from the last eval, do-FILE, or require command

• $_ - default input and search pattern space

• @_ - arguments passed to the given subroutine

• $$ - process number of the running program

• $? – status returned by the last pipe close, back tick or system command

http://www.aliencoders.org/

Most used special variables

Regular Expression

http://www.aliencoders.org/

•Regex operators: m, s, tr

•Metacharacters: ^, $, ., \, |, (, ), [, ], *, +, ?, {, }

•Quantifiers (iterators): *, +, ?, {m}, {m,n}, {m,}

•Characters classes: [], ^(negation), - (ranges)

•Character class abbr: \d, \D, \s, \S, \w, \W,

•Anchors: ^, $, \b ,\B, \A,\Z, \z

•Modifiers: m,s,i,g,e,x etc.

http://www.aliencoders.org/

Real Power of Perl

next if $file =~ m/\.{1,2}/; #skip if its . or ..

if($ARGV[0] =~/^(\d+\.){3}\d+$/) { .. } # IPv4

$word =~ s/^\s+|\s+$//; #trim a word

return int( (split /\./, $string)[0] ); #string to int conversion

my $email =~ /^([a-zA-Z][\w\_\.]{6,15})\@([a-zA-Z0-9-]+)\.([a-zA-Z]{2,4})$/;

#email validation

my ($matched) = $content =~ /$phone_code(.*?)\d+/sg ? $1 : 'No Result.';

my ($alexa_rank) = $content =~ m#globe-sm\.jpg(?:.*?)">(.*?)</strong>?#gis

($version) = $content =~ /version\s+(\d+\.\d+(?:\.\d+)?)/mig; } # wp-version

m#wp-(?:admin|content|includes)/(?!plugins|js).*?ver=(\d+\.\d+(?:\.\d+)?(?:[-

\w\.]+)?)#mig; }

$dob =~ #^((?:19|20)\d\d)[-/.](0[1-9]|1[012])[-/.](0[1-9]|[12][0-9]|3[01])$#;

#yyyy-mm-dd format

http://www.aliencoders.org/

Real Power of Perl

Perl Modules to learn

http://www.aliencoders.org/

• CGI – Handles CGI request and responses

• DBI – for any database related stuffs

• Net::IP – manipulate IPv4/IPv6 address

• Net::RawIP - manipulate raw IP packets with interface to libpcap

• Net::DNS – DNS resolver implemented in Perl

• Net::SNMP - Object oriented interface to SNMP

• IO::Socket - Object interface to socket communications

• WWW::Mechanize - Automating web browsing

• LWP::UserAgent – web user agent class

• http://search.cpan.org/~jabra/ for all scan parsers

http://www.aliencoders.org/

Modules useful for Pentesters

Perl Helpers

http://www.aliencoders.org/

• perldoc perlmodlib – modules with Perl distribution

• perldoc perllocal – Locally installed modules

• perldoc perlfunc – list of perl functions

• perldoc perlop – list of perl operators

• perldoc perl – overview of perl

• perldoc -m Net::Ping – see the code behind it ;)

• perldoc -f map – help for a specific function

• perldoc IO::Socket – documentation for the given module

• man IO::Socket – same as above

• perl -MData::Dumper -e 'print 1 ' -module installed or not

• perl -MCGI -e 'print "$CGI::VERSION \n" ' -module version

http://www.aliencoders.org/

Scripts for Pentesting

http://www.aliencoders.org/

• dnsenum, dnswalk, fierce

• nikto - web server scanner

• sqlninja - SQL Server injection and takeover tool

• snmpenum, snmpwalk, snmpcheck

• arp-fingerprint – Fingerpring a system using ARP

• cisco-torch.pl, CAT

• WeBaCoo - Web Backdoor Cookie Script kit

• uniscan - RFI, LFI and RCE, XSS, SQLi vulnerability scanner

• Slowlowris - HTTP DoS Tool

http://www.aliencoders.org/

Perl scripts in Kali/Others

Demo

http://www.aliencoders.org/

•DNS Info•Header Response Info•Website Details•Get WordPress Version•Simple Port scan•IP from ifconfig•Get GHDB list in a file•Windows OS Version details

http://www.aliencoders.org/

Kickstart with simple scripts

#!/usr/bin/perl

use strict;use warnings;use IO::Socket::INET;

my $socket;my $host = $ARGV[0] || die "Usage: perl $0 <hostname>\n";my @ports = qw(21 22 23 25 53 69 80 110 137 139 143 150 162 443 445);

for(@ports){ my $success = eval { $socket = IO::Socket::INET->new(

PeerAddr => $host, PeerPort => $_, Proto => 'tcp‘ )

};

#If the port was opened, say it was and close it. if ($success) {print "Port $_: Open\n"; shutdown($socket, 2); }};

http://www.aliencoders.org/

Simple Port Scan

use WWW::Mechanize;

use LWP::UserAgent;

my $url = $ARGV[0] || die "Should pass site name $0 <sitename>\n";

$url = "http://".$url unless($url =~ m/^http/);

print "# Checking Response Header for generator tag\n";

my $meta_version = check_response_header( $url );

print_version( $url, $meta_version) if $meta_version;

print "# Checking readme.html source for the version\n";

my $readme_version = get_site_content( "$url/readme.html" );

print_version( $url, $readme_version ) if $readme_version;

print "# Checking wp-login.php source page for ?ver= instances \n";

my $login_ver = get_site_content( "$url/wp-login.php" );

print_version( $url, $login_ver ) if ( $login_ver );

http://www.aliencoders.org/

Find WordPress Version

use LWP::UserAgent; # for web requests

use WWW::Mechanize; # My favourite web scrapper module

$url = "http://".$url unless($url =~ m/^http/);

# Using LWP::UserAgent method 1

my $ua = LWP::UserAgent->new();

$ua->agent('Mozilla/5.0');

# connect and get

my $response = $ua->get($url);

print $response->headers()->as_string;

# Using WWW::Mechanize method 2

my $mech = WWW::Mechanize->new();

my $resp = $mech->get($url);

print $resp->headers->as_string;

http://www.aliencoders.org/

Get Header Response

use WWW::Mechanize;

my $mech = WWW::Mechanize->new();

my $url = "http://www.exploit-db.com/google-dorks/";

$mech->get( $url );

my $link = $mech->find_link( url_regex => qr/ghdb/ );

my ($ghdb_count) = $link->[0] =~ m|ghdb/(\d+)/|;

my $exploit_url = "http://www.exploit-db.com/ghdb/";

open FH, "+<", "ghdb.txt" or die "Can\'t open ghdb.txt: $!\n";

chomp( my @ghdb_content = <FH> );

my $present_count = 0;

($present_count) = split(/\./, $ghdb_content[$#ghdb_content]) if(scalar @ghdb_content > 1);

binmode(FH, ":utf8");

for( ($present_count + 1) .. $ghdb_count ){

my $final_url = $exploit_url."$_";

my $mc = WWW::Mechanize->new();

$mc->get( $final_url );

my $dork = $mc->content();

my $link = $mc->find_link( url_regex => qr/search|image.*?q=/);

$link->[1] =~ s/[^[:ascii:]]+//g if($link->[1]);

print FH "$_. $link->[1]\n" if($link->[1]);

}

close(FH);

http://www.aliencoders.org/

Save GHDB in text file

use Net::DNS;

use Net::IP;

die "Usage: perl $0 [site_name|IP Address]\n" unless(scalar $ARGV[0]);

if($ARGV[0] =~/^(\d+\.){3}\d+$/){

$ip_address = new Net::IP($ARGV[0],4);

} else {

$site = $ARGV[0];

$site =~ s#http[s]?://##;

$site =~ s/www\.//;

}

my $res = Net::DNS::Resolver->new;

if($site){ show_ip(); show_ns(); show_mx(); show_soa(); }

show_ip_lookup() if($ip_address);

http://www.aliencoders.org/

Get DNS Info of a site

open my $in, "/sbin/ifconfig |";

my (@addrs);

while (my $line = <$in>)

{

if ($line =~ /inet addr:((\d+\.){3}\d+)/)

{

push @addrs, $1;

}

}

close($in);

print "You have the following addresses: \n", join("\n",@addrs), "\n";

http://www.aliencoders.org/

Get IP from ifconfig

Future Scope

http://www.aliencoders.org/

•Can write DoS exploits•Buffer overflow test•MITM exploits•Fuzzying•Nmap scripts•RFI,RCE exploits•Network Pentesting•Web Attacks automations• Integrate with RE Tools•Data Scrapping and many more

http://www.aliencoders.org/

We can do almost everything

Resources

http://www.aliencoders.org/

•http://www.cpan.org/•http://perldoc.perl.org/•https://twitter.com/jabra•http://www.sans.org/•https://www.kali.org/•https://www.blackhat.com/•https://www.owasp.org/index.php/Perl•http://www.aliencoders.org/forum/Forum-perl•http://www.iconsdb.com for icons used

http://www.aliencoders.org/

Links you can follow

•Learning Perl by Brian D foy

•Programming Perl by Larry Wall

•Penetration Testing with Perl Douglas Berdeaux

•Network Programming with Perl Lincon D. Stein

•Perl for System Administration David Edelman

http://www.aliencoders.org/

Books you can read

• https://twitter.com/jabra Joshua Abraham

• https://twitter.com/weaknetlabs Douglas Berdeaux

• https://twitter.com/briandfoy_perl Brian D Foy

• https://twitter.com/davorg Dave Cross

• https://twitter.com/timtoady Larry Wall

• https://twitter.com/merlyn Randal L. Schwartz

• https://twitter.com/szabgab Gabor Szabo

http://www.aliencoders.org/

People you can follow

Support and share

http://www.aliencoders.org/

Website: http://www.aliencoders.org/

Facebook: https://www.facebook.com/aliencoders

Slideshare: http://slideshare.net/jassics

Twitter: https://twitter.com/aliencoders

G+: https://plus.google.com/+Aliencoders/

LinkedIn: https://www.linkedin.com/groups/Alien-Coders-4642371

YouTube: http://www.youtube.com/user/jassics

Learning through sharing

Questions

http://www.aliencoders.org/