Web and Database Hacking
Web and Database Hacking
Database
Encode XML
User Metacharacters
Sanitize output
Application
server
SOAP
service
Core Mechanisms
User-Directed Spidering
User interact with targeted website through a proxy tool
Resulting traffic is passed through spidering tool that
monitors all requests and responses
Done by WebScarab and Burp Suite, similar to IEWatch
Advantages
Unusual or complex navigation is done by user
User controls all data submitted to an application
User authenticates him/her-self
Dangerous functionality (such as deleteUser.jsp) will be
enumerated, but not performed
Mapping the Application
Discovering hidden content
Pages that are not linked from the portal, but are functional
Backup copies of life files such as dynamic pages
Backup archives
New functionality under test
Old versions of files (more likely to contain vulnerabilities)
Configuration and include files that could include credentials
Source files for life application files
Log files
…
Mapping the Application
Brute-Force Techniques
Map visible site, then decide on directory structure
Use dictionary to generate resource names
Example: bobadilla.engr.scu.edu/php-bin
Search for
bobadilla.engr.scu.edu/php-bin/access.php
bobadilla.engr.scu.edu/php-bin/account.php
bobadilla.engr.scu.edu/php-bin/accounts.php
bobadilla.engr.scu.edu/php-bin/accounting.php
bobadilla.engr.scu.edu/php-bin/admin.php
bobadilla.engr.scu.edu/php-bin/agent.php
bobadilla.engr.scu.edu/php-bin/agents.php
…
bobadilla.engr.scu.edu/php-bin/home/access.php
…
bobadilla.engr.scu.edu/php-bin/admin/access.php
…
bobadilla.engr.scu.edu/php-bin/accounting/access.php
…
Mapping the Application
HTTP Fingerprinting
Protected by tools such as ServerMask by Port80 Software
Performed by tools such as httPrint
File extensions
asp, aspx, jsp, cfm, php, d2w, pl, py, dll, nsf, ntf, …
Directory names
servlet – Java servlets, pls – Oracle application server pl/sql
gateway, cfdocs or cfide – cold fusion, silverstream, WebObjects or
****.woa – Apple WebObjects, rails – Ruby on rails, …
Session Tokens
JSESSIONID, ASPSESSIONID, ASP.NET_SessionId,
CFID/CFTOKEN, PHPSESSID
Third party code components
Mapping the Application
Authentication Technologies
HTML-forms
Multi-factor mechanisms (e.g. passwords and
physical tokens)
Client SSL certificates and smartcards
HTTP basic and digest authentication
Windows-integrated authentication using NTLM or
Kerberos
Authentication services
Attacking Authentication
Design flaws:
Poorly chosen passwords
Attack: discover password policies by registering several accounts or change
passwords
Brute-Forcible login
See whether cookies capture the number of login attempts
Poorly chosen usernames
Email addresses, easily guessable, …
Verbose Failure Messages
Classic case: different messages depending on whether username or password is
invalid, but the difference might be small
This could also be exploited if the timing is different
Hack steps:
Monitor your own login session with wireshark or web proxy
If login form is loaded using http, then application is vulnerable to man in the
middle attack, even if the authentication itself is protected by HTTPS
Attacking Authentication
Design Flaws:
“Forgotten password” functionality
Often not well tested
Secondary challenges are much easier to guess
User-set secret question
Password hints set by user
Authentication information sent to an email address
specified in password recovery procedure
“Remember me” functionality
Could use simple persistent cookie, …
Attacking Authentication
Design flaws:
User impersonation functionality
Used by websites to allow administrator to impersonate
normal users
Could be implemented as a “hidden” function such as
/admin/ImpersonateUser.php
Could trust user controllable data such as a cookie
Non-unique user names (rare but observed in the wild)
Application might or might not enforce different passwords
Hack steps: register multiple names with the same user name
with different passwords
Monitor for behavior differences when the password is already
used
This allows attacks on frequent usernames
Attacking Authentication
Predictable Initial Password
Commonly known passwords:
SCU common practice is to use the student id number
Hack steps: Try to obtain several passwords in quick
succession to see whether they change in a predictable
way
Insecure Distribution of Credentials
Typically distributed out of band such as email
If there is no requirement to change passwords, then
capturing messages / message archives yields valid
credentials
Attacking Authentication
messages
If there is self-registration, prevent a single user from creating a
This does not prevent someone from trying out various usernames
with a single weak password
Use CAPTCHA challenges
Protecting Authentication
Allow users to change passwords
Functionality only available for authenticated
sessions
No direct or indirect facility to provide a username
Can only change password for the user who owns this
session
Require users to reenter their old password
Instance of defense in depth: Attacker might have by-
passed authentication for a given user
New password should be entered twice
Notify users out of band of any password changes
Protecting Authentication
Prevent misuse of the account recovery function
Most secure application (banking,…): Out of band, such as
telephone call, …
Prevent impersonation by other users
Reconsider use of password hints
Usually only useful to attackers
Consider using a single-use, time-limited, unique recovery
URL
Consider using secondary challenges (though design is
tricky)
Attacking Session Management
Sessions need to store state
Performance dictates to store state at client
Cookies
Hidden forms
Asp.net view state (Not a session)
Fat URL
HTTP authentication (Not a session)
All or combinations, which might vary within a different
state
Weaknesses usually come from
Weak generation of session tokens
Weak handling of session tokens
Attacking Session Management
Predictable tokens
Most brazen weakness: sequential session ids
Typical weaknesses:
Concealed sequences
Such as adding a constant to the previous value
Time dependencies
Such as using Unix, Windows NT time
Weak random number generation
E.g. Use NIST FIPS-140-2 statistical tests to discover
Use hacker tools such as Stompy
Attacking Session Management
Horizontal
Distinction between what a particular user in a class can
do
Access to web email limited to one user
Attacking Access Controls
Common Vulnerabilities
Completely unprotected functionality
Only URL is necessary to perform actions that should be
restricted
“No lowly user will ever know this URL”
Identifier based functions
Access to resource is mitigated by a parameter that is
only handed out to a given user
Happens often when the application interacts with external
systems
Application logs will reveal this type of functionality
Attacking Access Controls
Common Vulnerabilities
Logic Flaws / False Assumptions
Multistage functionality
Example: User accesses “User Maintenance Menu” and
selects “Add User”
Page verifies that user has privileges to add users
Forwards user to the “Add User” page
But this one is not protected
Attacker needs to go directly to this page
Attacking Access Controls
Common Vulnerabilities
Use static files
Example: Web publisher interacts with user to sell /
ascertain right to view a given document
Once user has gained right to view, user is given the link
bobadilla.engr.scu.edu/downloads/final387002918.pdf
This is a static resource that cannot verify the rights
again
Attacking Access Controls
Common vulnerabilities
Insecure access control mechanisms
Example:
https://bobadilla.engr.scu.edu/login/home.asp?admin=true
Example: Use of the referer header
Hacking steps:
Use site mapping to find / guess hidden resources
Use two different level user accounts to look for
distinguishing parameters
Test for the use of the referer field
Review client side scripts and hidden forms to find
reference to hidden functionality
Code Injection
Hacking steps:
Supply unexpected syntax to cause problems
Identify any anomalies in the application response
Examine any error messages
Systematically modify input that causes
anomalous behavior to form and verify
hypotheses on the behavior of the system
Try safe commands to prove existence of injection
flaw
Exploit the flaw
Code Injection Into SQL
Gain knowledge of SQL
Install same database as used by application on local server to test SQL
commands
Consult manuals on error messages
Detection:
Cause an error condition:
String Data
Submit a single quotation mark
Submit two single quotation marks
Use SQL concatenation characters
‘ | | ‘ FOO (oracle)
‘ + ‘ FOO (MS-SQL)
‘ ‘ FOO (No space between quotation marks) (MySQL)
Numeric Data
Replace numeric value with arithmetic (Instead of 5, submit 2+3)
Use sql-specific keywords
67-ASCII(‘A’) is equivalent to 2 in SQL
Beware of special meaning of characters in http such as ‘&’, ‘=‘, …
Code Injection Into SQL
Detection:
Cause an error condition:
Select / Insert Statements
Entry point is usually ‘where’ clause, but ‘order by’ etc. might also
be injected
Example: admin’ or 1==1
Example injections into user name field for injection into
insert, where we do not know the number of parameters:
foo ’ ) - -
foo ‘ , 1) –
foo ‘ , 1 , 1) –
foo ‘ , 1 , 1 , 1) –
Here we rely on 1 being cast into a string.
Code Injection Into SQL
Union operator
SELECT author, title, year FROM books WHERE publisher = ‘Wiley’
Insert
Wiley’ UNION SELECT username, password, uid FROM users--
to obtain
SELECT author, title, year FROM books WHERE publisher = ‘Wiley’
Union SELECT username, password, uid FROM users--’
Pay attention to error messages in order to reformulate the
string more successfully
Try
‘ UNION SELECT NULL- -’
‘ UNION SELECT NULL, NULL--
‘UNION SELECT NULL, NULL, NULL --
Code Injection Into SQL
You can try ‘order by’ in order to find out how
many rows are in the table:
ORDER BY 1 --
ORDER BY 2 --
ORDER BY 3 --
Next, find out which columns have the string
data type by injection
UNION SELECT ‘a’, NULL, NULL--
UNION SELECT NULL, ‘a’, NULL--
UNION SELECT NULL, NULL, ‘a’--
Code Injection Into SQL
Fingerprinting the database
Important because of differences in SQL supported
E.g.: Oracle SQL requires a from clause in all selects
Obtain version string of database from
UNION SELECT banner,NULL,NULL from v$version
Use different ways in which databases concatenate strings:
Oracle: ‘Tho’||’mas’
MS-SQL: ‘Tho’+’mas’
MySQL: ‘Tho’ ‘mas’ (with space between quotes)
Use different numbering formats
Oracle: BITAND(1,1)-BITAND(1,1)
MS-SQL: @@PACK-RECEIVED-@@PACK_RECEIVED
MySQL: CONNECTION_ID() - CONNECTION_ID()
Code Injection Into SQL
Soap Injection
XPath injection
SMTP injection
LDAP injection
Exploiting Path Traversal
Simplistic Scenario
Webserver displays file based on user input:
1. Extracts the value of the “file” parameter from user input
2. Appends this value to a prefix: “C:\web\publicdocs\”
3. Opens file with this name
4. Reads file and returns contents to the reader
Simple Attack
Place “..\..\winnt\repair\sam” into input field
Webserver now opens file
C:\web\publicdocs\..\..\winnt\repair\sam
= C:\winnt\repair\sam
And disploys the Windows SAM backup file with might be
searched for passwords
Exploiting Path Traversal
Location of Targets
Review any instances where files are accessed based on
user input
Look for request parameters that appear to contain the
name of a file
If you have local access to the web application:
Monitor file system activity
Windows: filemon / ProcessMon from MS-Sysinternals
Consider using a specific name in all requests and then look
for this parameter in the file system logs
If you have found such an input, see what happens by
including the dot dot slash sequence
Exploiting Path Traversal
Most webservers try to prevent path traversal by disallowing dangerous
characters
Attacker can try
forward and backward slashes
simple URL encoding
dot %2e
forward slash %2f
backward slash %5c
16-bit unicode encoding
dot %u002e
forward slash %u002f
backward slash %u005c
double URL encoding (encode %)
dot %252e
forward slash %252f
backward slash %255c
try overlong UTF-8 Unicode encoding
dot %c0%2e %e0%40%ae
…
forward slash %c0%2f %e0%80%af …
backward slash %c0%5c %c0%80%5c …
Exploiting Path Traversal
XSS attacks
Vulnerability has wide range of consequences,
from pretty harmless to complete loss of
ownership of a website
Attacking other users: XSS
Reflected XSS
User-input is reflected to web page
Common vulnerability is reflection of input for an error message
Exploitation:
Attacker’s Javascript
Server responds with executes in user’s Attacker submits question
attacker’s Javascript browser containing malicious
Javascript
DOM-based XSS
A user requests a crafter URL supplied by the
attacker and containing embedded Javascript
The server’s response does not contain the
attacker’s script in any form
When the user’s browser processes this
response, the script is nevertheless executed.
Attacking other users: XSS
MySpace 2005
User Samy circumvented anti-XSS filters installed to prevent
community service
“The wonders” of AJAX: Asynchronous JavaScript and XML:
Only part of the user page is recreated upon user action
Attacking other users: XSS
XSS Payloads:
Virtual Defacement
Content of host is not affected, but loaded from other
sites
Injecting Trojan Functionality
“Google is moving to a pay to play model” proof of
concept created by Jim Ley, 2004
Inducing User Actions
Use payload script to perform actions
Exploit Any Trust Relationships
Attacking other users: XSS
Attacking other users: XSS
Other payloads for XSS
Malicious web site succeeded in the past to:
Log Keystrokes
Capture Clipboard Contents
Steal History and Search Queries
Enumerate Currently Used Applications
Port Scan the Local Network
Attack Other Network Hosts
<img src=http://192.168.1.1/hm_icon.gif”
onerror=“notNetgear()”
This checks for the existence of a unique image that is
present if a Netgear DSL router is present
And XSS can deliver those things, too
Attacking other users: XSS
Delivery Modes
Reflected and DOM-based XSS attacks
Use forged email to target users
Use text messages
Use a “third party” web site to generate requests that trigger
XSS flaws.
This is successful if the user is logged into the vulnerable site and
visits the “third party” web site at the same time.
Attackers can pay for banner ads that link to a URL containing an
XSS payload for a vulnerable application
Use the “tell a friend” or “tell administrator” functionality in
order to generate emails with arbitrary contents and recipients
Attacking other users: XSS
Delivery Modes
Stored XSS attacks
Look for user controllable data that is displayed:
Personal information fields
Names of documents, uploaded files, …
Feedback or questions for admins
Messages, comments, questions, …
Anything that is recorded in application logs and displayed
in a browser to administrators:
URLs, usernames, referer fields, user-agent field
contents, …
Attacking other users: XSS
Finding Vulnerabilities
Standard proof-of-concept attack strings such as
“><script>alert(document.cookie)</script>
String is submitted as every parameter to every page of the
application
Rudimentary black-list filters
Look for expressions like “<script>”, …
Remove or encode expression, or block request altogether
Counterattack:
Use exploits without the <script> or even “ < > / characters
Examples:
“><script > alert(document.cookie)</script >
“><ScRiPt>alertalert(document.cookie)</ScRiPt >
“%3e%3cscript%3ealert(document.cookie)%3c/script%3e
“><scr<script>ipt> alert(document.cookie)</scr</script>ipt>
%00”>script>alert(document.cookie)</script>
Attacking other users: XSS
Finding Reflected XSS Vulnerabilities
Look for input string that is reflected back to user
Test string needs to be unique and easily searchable
“Crubbardtestoin”
Submit test string as every parameter using every method, including HTTP headers
Review the HTML source code to identify the location of the test string
Change the test string to test for attack possibilities
XSS bullets at ha.ckers.org
Signature based filters (e.g. ASP.NET anti-XSS filters) will mangle reflection for simple attack
input, but
Often overlook:
whitespaces before or after tags,
capitalized letters,
only match opened and closed tags,
…
Data Sanitization
Can remove certain expressions altogether, but then no longer check for further vulnerabilities
<scr<script>ipt>
Can be beaten by inserting NULL characters
Escapes quotation characters with a backslash
…
Use length filters that can be avoided by contracting JavaScripts (free software available)
Attacking other users: XSS
Primarily arise when HTTP cookies are used to transmit session tokens.