Tuesday, December 29, 2009

Perl - Notes

I have decided to learn perl as i began to encouter many perl scripts used for forensics and pentesting. I believe it would help me learn more if i write my own tools and understand the entire process a little bit better. This blog would house my notes and cheat sheets from day one.

Perl is a case sensitive language.

Starting line of every perl program

Printing text:
print 'hello world';

When printing from a variable use double quotes instead of single quotes. Information within the single quotes are interpreted as is.
print "$var1";

Declare and assign a variable. This variable is known as a scalar variable. Scalar variables are simple variables containing only one element--a string, a number, or a reference. Strings may contain any symbol, letter, or number. Numbers may contain exponents, integers, or decimal values.
$var1 = 1;
$var1 = 'hello world';

Declare an Array:
@food = ("rice", "eggs", "orange");

Accessing a portion of an array
print "$food[1]"; //this here would print eggs with reference to the above example

Finding length of array just involves redifing the array as a scalar variable. For instance
@food = ("rice", "eggs", "orange");
print "$3"; // This would output '3'

Add and Remove elements from an array
  • push() - adds an element to the end of an array.
  • unshift() - adds an element to the beginning of an array.
  • pop() - removes the last element of an array.
  • shift() - removes the first element of an array.

Concatanate two string variables;
print $string.$linebreak;

Opening a file and printing its contents like the unix program 'cat'
$file_path = '/root/myfile.txt';
open (file1, "$file_path");
@mydata = ;
print @mydata;

Formating Characters

Regular Expression Cheat Cheets

Using substrings.
To use substr() to grab a substring, you need to give it both a string variable to pick something out of and an offset (which starts at 0). The first argument of substr() is the string we want to take something from and the second argument is the offset, or where we want to start at. Substr function can take a third and forth argument, third being the length and forth being a replacement string value.

$mystr = "hello world";

$mystr1 = substr($mystr, 2);
$mystr2 = substr($mystr, 2, 3);
$mystr3 = substr($mystr, 6, 5, "there");

print "$mystr1";
// this would print 'llo world'
print "$mystr2"; // this would print 'llo'
print "$mystr"; // this would print 'hello there'. Note we are printing $mystr and not mystr3 here

Transforming strings into arrays with split function
$mystr = 'the/boy/walked/fast';
@myarr = split('/', $mystr);
print "@myarr"; // this prints 'the boy walked fast'

Likewise we can join elements of an array into a scalar string.
@array = ("David","Larry","Roger","Ken","Michael","Tom");
@array2 = qw(Pizza Steak Chicken Burgers);

@array = ("a") x 10;
print "@array"; //would print the character 'a' 10 times

$firststring = join(", ",@array);
$secondstring = join(" ",@array2);

Sorting arrays
@myarr = ("chicken" , "eggs", "apples");
@myarr = sort(@myarr);

Conditions and loops are Similar in syntax to C.
[While loop]
$a = ; //Read input from keyboard
while ($a ne "kill")
print "wrong";
$a = ; //Read input from keyboard

print "Correct";

[For loop]
" for ($x = 0; $x < style="color: rgb(255, 0, 0);">{
print "$x\n";

[until statement]
$a = 1;

print $a;
while ($a <>

[If statement]
" $a = "hello" ; "
if (length ($a) > 3)
print "more than 3 characters";

[RE expression] using =~ or !~
$word = "Hello my good friend";
if ($word =~ /my/)
print "found the word: my"
print "Not found";

The opposite of the above would be to use '!~' instead of '=~'.

$word = "canada states";
$word =~ s/canada/United/ //replaces only the first occurance of the string canada with United
$word =~ s/canada/United/g //the addition of the g in the end would replace all occurances of the string. It represents global change.
$word =~ s/[Hh][Oo][Pp][Ee]/Hope/g //This pretty much ignores the case. The next example is a better way to do this
$word =~ s/CanADa/Canada/gi // The 'i' in the end ignores case

$search = "the";

will replace every occurrence of the with xxx. If you want to replace every occurence of there then you cannot do s/$searchre/xxx/ because this will be interpolated as the variable $searchre. Instead you should put the variable name in curly braces so that the code becomes $search = "the";


Character Translation
$a = "abc";
$a =~ tr/abc/boy/; // will trnaslate a to a b, b to an o and c to a y
print $a; // will print boy

$count = ($a =~ tr/*/*/); //the statement here counts the number of asterisks in the $sentence variable and stores that in the $count variable.

However, the dash is still used to mean "between". This statement converts $_ to upper case. tr/a-z/A-Z/;

Sorting Arrays of words
@array1 = ("orange","yellow","Red","green,","blue");
@sorted = sort(@array1); //Sorts in alphabetical order
@sorted_reversed = sort {$b cmp $a} (array1); //sorts in reverse order

Sorting arrays of numbers
@array1 = (5,7,2,4,1,8,6);
@sorted = sort (@array1); //sorts in alphabetical order
@sorted_reversed = sort {$b <=> $a} (@array1); //sorts in reverse order

Key Functions to remember
my $position = index($longString, $shortstring); //returns the position of a character or substring in a string
splice (@myarr, 2 , 3); // If you have an array of 7 elements, this function reads all the 5 elements and starting from with position two(which is actually the third position, as the first element starts with a 0) cuts the next three elements.

Monday, December 21, 2009

pcapcat, dumping the contents of a tcp stream

Pcapcat is a simple perl script that can dump the contents of a tcp stream. The script gives an index of the tcp streams that it identifies (by default shows only new tcp connection streams, those initialize by syn packets but you have the option to show all already established connections as well) and you would use this index to indentify which stream you would like to dump.

# perl pcapcat -r pcap_file // displays new connection streams. Already established connections would be ignored

# perl pcapcat -r pcap_file -a // '-a' displays already established connections. Useful in many cases where the initial communication had already commenced like a conversation.

# perl pcapcat -h // gives you a listing of all the options used with pcapcat

Resources/Good reading:

smtpcat, Parseing emails from a pcap file

I learned of the tool from a forensic contest blog i've been following for awhile now. This tool came about when a challenge was posed to determine the contents of an email from a pcap file. I've posted the solutions to this contest in an early blog entry (still have to update the part on getting the password) but my methods were not very automated and as easy as one might want things to be. A perl script, Smtpcat, came about to resolve this issue. From the author, Amar Yousif,
"I wrote smtpcat which will loop through a pcap file and identify all of the smtp conversations in it. Smtpcat dive deep into the payload and identifies the sender, receiver, date, subject, and optionally the AuthSMTP decoded password. The tool also has the ability to dump the payload of any smtp message as an eml file that can be further opened via outlook express for example. "

This tool definitly would make my life easier when pasrsing through network captures for email messages and its contents. Im happy i did things using a more manual procedure, just goes to show that i understood what i was doing.

# perl smtpcat -r pcap_file -p // '-r' reads the pcap and '-p' tells smtpcat to decode the smtp password

[1] ->
[1] sneakyg33k@aol.com -> sec558@gmail.com Sat, 10 Oct 2009 07:35:30 -0600
[1] SUBJ: lunch next week
[1] PASS:558r00lz

[2] ->
[2] sneakyg33k@aol.com -> mistersecretx@aol.com Sat, 10 Oct 2009 07:38:10 -0600
[2] SUBJ: rendezvous
[2] PASS:558r00lz

The above shows two email conversations being sent. Smtpcat identifies the sender and recipient as well as the smtp password.

# perl smtpcat -r pcap_file -p -d 2 -w message.eml // '-d 2' dumps the content of the smtp message from index 2 (index 2 was identified with the first command output above). '-w' writes the contents of the smtp message to a file

You can then open the message.eml file in outlook express to get the email body and possible attachments.

For more commands type: # perl smtpcat -h

Resources/Good reading:

Wednesday, December 16, 2009

Replaying captured web traffic using ncat

If you are not familiar with the whole idea of replaying a packet then you should get to googling. The basic idea behind this methodology is to sniff and capture interesting information from either the client or server then replay them. By doing this you can mimic a certain client's request or a server's response and vice versa. In the my demo, i will demonstrate how i was able to capture a users 'GET' request for a website (in my demo, www.ask.com) and the server's response and use the captured response to replay the same data that www.ask.com responds with to client request. This has the effect of mimicing a site and in some ways tricking a user to believe they are at the website of www.ask.com when they are basically connected to your machine. Not as fun as gaining a shell but with your imagination, you can come up with ideas for interesting packets to replay that can form the basis for some more fun stuff.

  1. Use wireshark to capture packets of a user making a request for www.ask.com on their web browser
  2. Use a display filter for that stream and filter the stream to show only the servers response. Save the data of the servers response to a file.
  3. Start up ncat to replay the saved response(data)
    "# ncat --send-only -l 80 < response"
  4. Use a web browser to connect to your ncat 'fake' webserver.
If you were to practice this on a few websites you're gonna notice that not all of the contents of the page might be displayed. If you've written html code before, you should already know why this is so. If you wanna get crafty and do some editing of the packets to change some directory paths, that should get things up and running, but to me its not worth the effort since im no criminal. YES, if you actually took the time to modify the response in such a way that you will get all the original's website content to show, then you more than likely have some evil intentions in mind.

Video demonstration...

Untitled from aerokid240 on Vimeo.

Thursday, December 10, 2009

SSH public and private key authentication

If anyone has played with ssh before, you should be quite familiar with login in with your password/passphrase to the ssh server. There is nothing wrong with this method of authentication at all as long as you have a complex password thats extremely hard to guess. However there is a more advanced method of authentication used by many professional organizations and businesses and the internet as well, known and Public key authentication. This system utilizes two keys, a public key known to everyone and is used for encryption and a private or secret key known only to the recipient of the message. In ssh, the use of the private keys are only for authentication purposes but then all of the communications are done using a negotiated symmetric key, which is a key common to both the sender and reciever of the message that is used to decrypt and encrypt the message.

SSh is commonly used for remote administering of machines, but is very common in the unix environment. As an administrator, we want to be able automate most of our tasks remotely over ssh, but the problem that arises is the password prompt screen. How can we automate a remote task if the machine we are login into is gonna ask for a password everytime we try to log on? The answer is to utilize the public and private key authentication method. You specify a private key to be used to authenticate on to the remote machine. The remote machine should have a matching public key under the logging in user account. Wants the pair of the public and private key is made, access is granted automatically withouth the use for a password/passphrase.

sshd [linux]
Putty [windows]
Puttygen [windows]

Step 1. Using puttygen, generate a 1024 bit rsa keys and save the public and private key portion to a USB key (mykey.pub and mykey.ppk ).

Step 2. Copy the puiblic key (mykey.pub) to the unix machine into the "/root/.ssh/" folder

Step 3. Convert the puttygen public key to an openssh format.
# ssh-keygen -i -f /root/.ssh/mykey.pub > mykey2.pub

Step 4. Paste the contents of the public key into a file called authorized_keys or
# touch authorized_keys
# cat mykey2.pub >> authorized_keys

Step 5. Using putty, enter in root@, assuming is the remote hosts ip address.

Step 6. Under the 'Connections' section in putty, goto the 'SSH' sub section then 'Auth'. Browse
for your private key (mykey.ppk) then click on open

If all went well you should be granted access to the root account without having to enter a password. If you were using a linux client, this could have been automated using bash scripts and all that is required is for you to place your private key in your local home directory in the .ssh folder, i.e, /home/user1/.ssh/

Resources/Good reading:

Wednesday, December 9, 2009

Video Demo of me exploiting Internet explorer 6 on XP SP2

It cannot be stressed enough why you should always try to keep your software patched and up to date. Alot of individuals understand that updates can add new features and fix some bugs but don't have a clue about the security aspects of it. You may have come around the term 'exploit' before but don't really quite grasp the concept of it. An exploit is special code that attempts to capitalize on what is known as software vulnerabilities, and in capitalize i mean do something that is of the benefit to the attacker. In the hacker culture, most of the time we would want to exploit software in hopes of gaining "shell" access which is basically a command prompt environment of the exploited machine. Picture being at a Windows machine at the command line and the amount of power you have at your arsenal. You can create user accounts, kill process, create and delete files, etc. This is what the hacker hopes to gain from his exploit, such an environment where he can command your machine via a shell, i.e. command prompt from his own attacking machine.

In my video demonstration, im gonna exploit a vulnerability in IE 6 on a XP SP2 machine. The attacker sets up his machine as a special type of web server awaiting a user to connect to his machine using internet explorer(you can force a user to connect to your machine via dns spoofing on a LAN, see my earlier post on dnspoof). When the victim browses to the attackers web page(of was forced onto the page by the attacker) an exploit is run on the victims browser and on the attacking machine if the exploit was successful you would get a command prompt/shell of the victims machine. From here the attacker can take command of the victim's computer and is only limited by his imagination.

[Tools used]

Internet Explorer 6 exploit from aerokid240 on Vimeo.

Tuesday, December 8, 2009

New Video demos

[Breaking into facebook and gmail without a username and password]
***** http://aerokid240.blogspot.com/2009/11/ferret-and-hamster-20-sidejacking.html

[Eaves dropping on your neighbours msn conversations]

[Exploiting IE6 on XP SP2 machine to gain shell access]

Monday, December 7, 2009

Video illustrations on the way...

I know some of the demo's my leave you a bit puzzled at times but some of the concepts cant be adopted overnight. And as you would have noticed, most of the demo's use linux quite heavily adding to the frustration to most windows users. The good news today is i just got an account with www.vimeo.com so now i can add video illustrations to some of my blogs. I'm gonna go back to some of my previous post and add some video illustrations to them. If there is any request for any visual illustration on any previous post, just leave a comment or shoot me an email.

Saturday, December 5, 2009

How you can steal log-on credentials from forum based websites using Paros and ngrep

As you can imagine, ngrep would be our sniffer that would parse out the necessary information that we would be looking for. But what is Paros and what is it gonna be used for? Paros is a proxy, but unlike traditional proxies, it allows you to modify certain parameters in http request and reply packets. How we are gonna use it in our demo is to modify the password field of a http POST to input the appropriate password. Confused? Well just follow my demo and hopefully all will be clear.

First we use ngrep (look back at my earlier post for info on using ngrep) to sniff out the important information when the user logs in. Note that sometimes the passwords may be in cleartext or in a md5hash. If the password is in MD5 hash form, we can use online resources to crack them or dont even bother cracking them. Why not just use the hash to login? Is it possible? Yes.. and thats what ill be showing you.

[Note, you would be required to perform some form of man in the middle attack in order to be able to sniff the packets]

Setting up ngrep to sniff:
# ngrep -W byline -d eth0 -q "POST" port 80 //we are sniffing of port 80 for the string 'POST', i.e when a user hits the login button a post would be send to the logon server. '-W byline' makes the output to standard out more readable.

On some other machine [victim machine], login to your favorite forum website and pay attention to ngrep's output. It should have captured the post packet with your username and password. Like i said earlier, sometimes the password is not in plain-text. Sometimes it would be and MD5 hash. Lets see how we can use this hash with Paros proxy.

Lets fire up Paros on the attacking machine.
# java -jar paros.jar

On the attacking machine, open up your web browser and change its network settings to use the proxy on port 8080. Trying browseing to a website to confirm the proxy works. Paros should now have captured traffic.

In the "Trap" tab select "trap request". Now navigate to the same forum website that you've captured info from. On the login form, put in the username that you would have captured and some bogus password and hit the submit button. Notice that the web page is stuck loading and paros is blinking. Lets investigate. Paros has captured the request and is awaiting on some sort of feedback from you. At this point you can see that paros has captured the login request. The username is the right one u typed in and the password is in some encrypted md5 form. Its actually the md5sum to the bogus password you inputed. What we wanna do is take the md5 hash that we captured from the ngrep output, and input it in the paros parameter screen (easier to view it in tabular view). Note you gon need to enter it in two places, the "vb_login_md5password" and "vb_login_md5password_utf". After you've done this, deselct the trap request option and hit the continue button. Guess what has happend............... You've now logged into your victims account.

To help in my above illustration, here's a video illustrating the simplicity of the attack. Note that the user uses a different sniffer to sniff on the wire.

[video]: http://www.securitytube.net/How-Secure-is-your-Forum-Login-video.aspx

Resources/Good reading:

Using netcat to stream music with mpg123

Like my previos post, i used netcat as a simple one page webserver, basically having netcat listen on port 80 and anything that connects to port 80, send them an html file. Simple enough. This post shows how we can use the same concept and listen on a port and send an mp3 over the network to connecting clients. Mpg123 is a command line utility that basically play music on the command line. You can see how netcat and mpg123 is used together to stream music accross the network.


[server] # cat music_file.mp3 | nc -l -p 4444 //listens on port 4444 and cats the contents of the mp3 file accross the network

[client] # nc 4444 | mpg123 - // connects to the server on port 4444 and plays what ever data comes through its connection

Resources/Good reading:

Thursday, December 3, 2009

Using netcat and ncat as simple webservers

Nothing too fancy here, but just an illustration of how versatile the netcat tool is/can be. We all know netcat to be a simple backdoor utility that can be used for simple chats and file transfers. Well to add to its long list of possibilities and features, i am going to set up a one page webserver. Useful if you got to set up a notification about your page being down for maintenance. In its basic form, we set up a netcat listener on port 80 then pipe or push a file into the connection when clients connect.

[for netcat] "# while true; do nc -l -p 80 -q 1 < index.html" ; done
[for ncat]
"# while true; d0 ncat -l 80 --send-only < index.html ; done"

Note: we set up a while loop to keep the connection open to accept other requests. Using "-k" in ncat would not work in this instance as using the "--send-only" terminates the connection when all data has been sent to the client.

References/Good reading:

Another example where physical access always gets you in (using chntpw)

Chnypw is a small linux utilty that is used to (re)set the password of any valid local account on a windowsNT, 2000 and XP machine (have not tried on vista and 7). Knowledge of the old password for an account is not needed to set a new one. The tool works by modifying crypted data in the registry's SAM file. This utilty works with syskey and includes the option to turn it off.

The target Windows machine needs to be in offline mode which means that the installed OS should not be loaded. You're gonna need a bootable linux distrobution (CD or bootable usb works) with chntpw package installed.

  1. Mount the NTFS drive. Needs to be mounted for read/write and not read-only.
    # mount -t ntfs-3g /dev/sda1 /mnt/disk1 or # ntfsmount /dev/sda1 /mnt/disk1 -o default_permissions
  2. Navigate to the location of the SAM file, typically located at \windows\system32\config
    # cd /mnt/disk1/WINDOWS/System32/Config
  3. Make a back up of the SAM, security and system files.
    # cp SAM SAM.bak && cp security security.bak && cp system system.bak
  4. Run chntpw in interactive mode with the SAM, system and security file as arguments.
    # chntpw -i SAM security system
  5. You should be presented with an interactive screen where you can list the local users and change or reset their passwords.
    NOTE: It is known that changing the user's passwords here are less reliable to work than actually just resetting/blanking their passwords. I would suggest to just blank the passwords if applicable then when you get into windows, change the passwords their. Use an "*" to Blank passwords in the interactive screens in chntpw.
  6. Remember to save your changes before you exit.
  7. Reebot computer and login to windows to see if your hack worked (more than likely it did)
For more chntpw options (although you probably wont need nothing else), type:
# chntpw -h

#chntpw help and usage

chntpw version 0.99.3 040818, (c) Petter N Hagen
chntpw: change password of a user in a NT SAM file, or invoke registry editor.
chntpw [OPTIONS] [systemfile] [securityfile] [otherreghive] [...]
-h This message
-u Username to change, Administrator is default
-l list all users in SAM file
-i Interactive. List users (as -l) then ask for username to change
-e Registry editor. Now with full write support!
-d Enter buffer debugger instead (hex editor),
-t Trace. Show hexdump of structs/segments. (deprecated debug function)
-v Be a little more verbose (for debuging)
-L Write names of changed files to /tmp/changed
-N No allocation mode. Only (old style) same length overwrites possible
See readme file on how to extract/read/write the NT's SAM file
if it's on an NTFS partition!
Source/binary freely distributable. See README/COPYING for details
NOTE: This program is somewhat hackish! You are on your own!

Resources/Good reading:

Wednesday, December 2, 2009

Sniffit, packet sniffer and monitoring tool

Sniffit is a nice little sniffer that gives you the ability to zoom in on already established connections and view the data. Its mainly useful in MITM situations. Picture being in the middle of a telnet session or in the middle of a netcat chat. With sniffit, you can watch the communications going back and forth and possible gaain the knowledge of confidential info.

To run sniffit:
# sniffit -i -F eth0 //opens up sniffit in [-i]nteractive mode and [-F]orces the program to listen on the specified interface

To listening in (zoom into) a connection just hit the Enter key. To get out of it, hit the "q" key. For some useful satatistics hit the "n" key. to completly close out of the program hit the "q" key again.

Tuesday, December 1, 2009

Steganography (using steghide)

Steganography is the ability to hide data in plain site. Hidden messages are hidden in such a way that no one other than the sender and the intended recipient should be aware of its existence. What that means is the picture that someone may have sent to you and a few other people could possible contain a hidden message and possibly only one or two of the recipients may know of its existence.

Steghide is a steganography program that has the ability to hide data in various image and audio file formats. The embeded data can be compressed and encrypted. Some supported file formats are JPEG, BMP, WAV and AU. There are no restrictions on the format of what the secret data should be. It runs on both Windows and linux OS's

Create a text file and type something in it that you wish to hide[name it confidential.txt].

Next, locate a jpg or bmp file that you would like to use as the cover file to hide the text file into.
When you get your image file run this command to test its storage capacity:
# steghide info image_file.jpg

Next lets embed our confidental.txt in the image file. By default, the embeded data would be encrypted with rijindale(aes - 128 bit) encryption in cbc mode. Note you would have to enter a password.
# steghide embed -cf image_file.jpg -ef confidential.txt

To extract the file run the following command then enter the password:
# steghide extract -sf image_file.jpg

Thats all to it.

"-cf": cover file to use
"-ef": file we want to hide
"-sf": this is the name of the stego file that we have created
"-e": specify encryptionto use if the default doesnt suit you.

To find out about the other encryption algorithms that you can use type:
# steghide encinfo

Resources/Good reading: