EHP 10 - Web Attacks
EHP 10 - Web Attacks
hacking
Web technology
Web applications attacks
SQL Injection attacks
Web application attacks I
• Vulnerabilities exist in web applications because of a single core
problem - users can submit arbitrary input!
• HTTP Secure (SSL/TLS) does not protect web server applications!
– Authenticate server and data in transit - web browser is enemy territory!
• Account harvesting
– Hammer on web service logins etc. with different user IDs
– If a web service in some (any) way indicates a valid or a invalid user ID
logon attempt, a scripted account harvesting can begin
• Undermine session tracking (Session ID)
– Allows web application to maintain the state of a session with a user
(HTTP is stateless!)
• Session tracking is done
with either
– URL rewriting
– Hidden form elements
– Cookies and session
variables Hidden input tag: <INPUT TYPE="hidden" NAME="sid" VALUE="34112323">
URL rewriting
• By using REST (REpresentational State Transfer) and HTTP GET we
can pass variables to a PHP script for example
• http://localhost/myhome/demo.php?fname=Hans&sname=Jones
• In the URL above we pass two strings,
”Hans” and ”Jones” <?php
if(isset($_GET["fname"]))
• We receive the parameters with $fname = $_GET["fname"];
$_GET[”variable-name”] in PHP else
$fname = '';
• For every new variable in the URL we
put an ampersand (&) in between if(isset($_GET["sname"]))
$sname = $_GET["sname"];
• Passing variables via a form else
$sname = '';
<html><body>
<form method="get" action="demo.php"> $person = $fname . " " . $sname;
<label>First Name: </label>
<input type="text" name="fname" size="40" /> </ br>
echo "<html>";
<label>Last Name: </label>
<input type="text" name="sname" size="40" /> </ br> echo "<body>";
<label>Send: </label> echo "Hello ";
<input type="submit" value="Submit" size="40" /> echo $person;
</form> echo ", how are you today?";
</body> echo "</body>";
</html>
echo "</html>";
?>
Hidden form elements
• Can be used to ”remember” values on the webpage if the page
is reloaded – remember HTTP is a stateless protocol!
– A better method is to use session variables
• Can also be used to hide values in the form which are sent in
to adjust the running script in some way
• For example to know the time between the HTML code was
loaded and when it is received in the form PHP code
# creates something like: <input type="hidden" name="timecode" value="12345" />
<?php
$t = time(); # returns the number of seconds since 1970-01-01
echo "<input type='hidden' name='timecode' value='" . $t . "' />";
?>
echo $t . "<br />";
# check to see if the form was answered to quickly – spam-proofing
<?php
$timecode = $_POST["timecode"];
if(time() < $timecode + 5) # current time vs. old time
exit();
else { response time not to short ... }
?>
HTML Forms 1
• Forms are user interfaces for data input
• Main application: to provide user input for
– Programs, scripts and databases located on a web server
– Local (client-side) scripts associated with the form
• Server-based scripts/programs may return data to the
client as a web page
• Client-side scripts can read input data
– To validate the data, prior to sending to server
– To use in local processing which may output web page content
that is displayed on the client
• Examples
– Questionnaires to provide feedback on a web site
– e-commerce, to enter name, address, details of purchase and
credit-card number
– Run a database query and receive results
HTML Forms 2
• There are two ways of sending information into a
PHP program (server script)
– One is to use parameters on the URL, and retrieve them
with $_GET in PHP (in the form you set: method=”get”)
• Just as we did earlier with REST (hyperlinks) but the form
create the URL with parameters
– The other method, which is more powerful and secure is to
use a form with $_POST in PHP (in the form you set:
method=”post”)
• The data goes within the HTTP message body (not visible on
the browsers address field)
• To see (debug) what you send set: method=”get”
• There is a variety of form field types that you can
use, depending on the type of information that you're
requesting from a visitor
HTML Forms 3
• A form consists of
two main
components
– First, one or more
input fields into
which the visitor
types or clicks the
information you
have requested
– Second, a "submit"
button which, when
clicked, sends the
contents of the
form to a server-
side program for
processing in
whatever way it
wishes
Input types
• text
• checkbox
• radio (buttons)
• select (options)
• textarea
• password
• button
• submit
• reset
• hidden
• file
• image
Example form (post)
• Having designed a form, there are 3 more things you need to
do before it's ready for use
– Ensure that each form object is named properly
– Add an "action" to the <form> tag which is the server program
that processes the data
– Write some PHP code to handle the submitted forms
• When the site visitor presses the Submit button, the contents
of the form will be sent to a PHP program as a series of
variables (with values if they are used in the form)
• The names of those variables will be the names that you
have assigned to the objects in the form
<form method="post" action="breakfast.php">
<label>Name: </label> <input type="text" name="tb_name" size="40" />
<label>Bacon: </label> <input type="checkbox" name="cb_bacon" value="Y" />
<label>Boiled: </label> <input checked type="radio" name="rb_eggs" value="F" />
<label>Order your breakfast?</label> <input type="submit" value="Submit" />
</form>
Cookies 1
• Two cookie types exist
– A persisten cookie is stored as a text file on the browsers client disk
– A session (or transient) cookie is stored in RAM and just lives for the
session (no expire date is set when creating the cookie) – this is the default
• A cookie is a string with name=value pairs
– Cookies are like persistent variables that the browser can store and read when
accessing the website in question
– Name, password and date are common cookie values
• The browser may not store more than 300 cookies in total or 20
per web server or 4kB in size
• Persistent cookies expires after a certain max-age (in seconds)
when the browser will delete them
- Cookie name
• Cookie - Cookie value
example - Domain/path for the web
content server setting the cookie
- Flags
- Expiration time (low)
- Expiration time (high)
- Creation time (low)
- Creation time (high)
- Record delimiter (*)
Cookies 2
• Cookies were introduced to provide a way to implement a
shopping basket (or cart)
– The boolean attribute secure specify transfer - HTTP or HTTPS
• When combined with a DB backend on the server storing
the shopping list one can continue shopping next day
– A web server typically sends a cookie containing a unique
session identifier
– The web browser
will send back that
session identifier with
each subsequent
request and shopping
basket items are
stored and associated
with an unique session
identifier
The HTTP protocol
TCP/IP based request/response protocol
HTTP requests (known as methods)
– GET or POST
HTTP response
– In all cases a
resonse code
– will be returned
HTTP message
– Request/response
line - the http
method/status
– Header variables -
request metadata
– Message body -
content of message
HTTP status codes
• Each HTTP response message must contain a status code in
its first line, indicating the result of the request
• The status codes fall into five groups, according to the code’s
first digit
– 1xx— Informational.
– 2xx— The request was successful.
– 3xx— The client is redirected to a different resource.
– 4xx— The request contains an error of some kind.
– 5xx— The server encountered an error fulfilling the request.
• Some examples
– 100 Continue
– 200 OK, 201 Created
– 301 Moved Permanently
– 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found,
405 Method Not Allowed
– 500 Internal Server Error, 503 Service Unavailable
Cookies 3
1. HTTP request (browser)
3. When browser request another page the server recognize the string
if(!isset($_SESSION["my_session_var1"]))
{
$_SESSION["my_session_var1"] =
"I like session variables!";
}
else
{
$_SESSION["my_session_var1"] .= "!";
}
# Get and/or set the current session name
$sess_name = session_name();
echo "The session name was $sess_name";
echo "<br />";
echo $_SESSION["my_session_var1"];
?>
HTTP request message
• The first line of every HTTP request consists of three items, separated by
spaces
– A verb indicating the HTTP method, the requested URL and the HTTP version being
used
• Other points of interest in the sample request (many other headers exists)
– The Referer header is used to indicate the URL from which the request originated
– The User-Agent header is used to provide information about the browser or other
client software that generated the request.
– The Host header specifies the hostname that appeared in the full URL being
accessed
– The Cookie header is used to submit additional parameters that the server has
issued to the client
– An empty line (\r\n) and an optional message body
GET /auth/488/YourDetails.ashx?uid=129 HTTP/1.1
Accept: application/x-ms-application, image/jpeg, application/xaml+xml,
image/gif, image/pjpeg, application/x-ms-xbap, application/x-shockwaveflash, */*
Referer: https://mdsec.net/auth/488/Home.ashx
Accept-Language: en-GB
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64;
Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR
3.0.30729; .NET4.0C; InfoPath.3; .NET4.0E; FDM; .NET CLR 1.1.4322)
Accept-Encoding: gzip, deflate
Host: mdsec.net
Connection: Keep-Alive
Cookie: SessionId=5B70C71F3FD4968935CDB6682E545476
HTTP response message
• The first line of every HTTP response consists of three items, separated by spaces
– The HTTP version being used, a numeric status code indicating the result of the
request and a textual “reason phrase” further describing the status of the response
• Other points of interest in the sample response (many other headers exists)
– The Server header contains a banner indicating the web server software being used,
and sometimes other details
– The Set-Cookie header issues the browser a further cookie; this is submitted back in
the Cookieheader of subsequent requests to this server
– The Pragma header instructs the browser not to store the response in its cache
– The Content-Type header indicates that the body of this message contains an HTML
document. Almost all HTTP responses contain a message body after the headers
– The Content-Length header indicates the length of the message body in bytes
– An empty line (\r\n) and an optional message body
HTTP/1.1 200 OK
Date: Tue, 19 Apr 2011 09:23:32 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
Set-Cookie: tracking=tI8rk7joMx44S2Uu85nSWc
X-AspNet-Version: 2.0.50727
Cache-Control: no-cache
Pragma: no-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 1067
<!DOCTYPE html><head><title>Your details</title>
...
HTTP request methods 1
• HTTP defines methods to indicate the desired action to be performed
on the identified resource (the web server page)
• HEAD
– Asks for the response identical to the one that would correspond to a
GET request, but without the returned response body.
– This is useful for retrieving meta-information written in response
headers, without having to transport the entire content.
• GET
– Requests a representation of the specified resource.
– Requests using GET should only retrieve data and should have no other
effect.
• POST
– Submits data to be processed (e.g., from an HTML form) to the identified
resource.
– The data is included in the body of the request. This may result in the
creation of a new resource or the updates of existing resources or both.
• PUT
– Uploads a representation of the specified resource.
HTTP request methods 2
• DELETE
– Deletes the specified resource.
• TRACE
– Echoes back the received request, so that a client can see what (if any)
changes or additions have been made by intermediate servers.
• OPTIONS
– Returns the HTTP methods that the server supports for specified URL.
This can be used to check the functionality of a web server by requesting
'*' instead of a specific resource.
• CONNECT
– Converts the request connection to a transparent TCP/IP tunnel, usually
to facilitate SSL-encrypted communication (HTTPS) through an
unencrypted HTTP proxy.
• PATCH
– Is used to apply partial modifications to a resource.
• HTTP servers are required to implement at least the GET and HEAD
methods and, whenever possible, also the OPTIONS method.
More about forms and HTTP
• A typical form using method post can look like this
<form action="/secure/login.php?app=quotations" method="post">
username: <input type="text" name="username"><br>
password: <input type="password” name="password">
<input type="hidden" name="redir" value="/secure/home.php">
<input type="submit" name="submit" value="login">
</form>
• When the user enters values and click the submit button the browser
makes a request like the following
POST /secure/login.php?app=quotations HTTP/1.1
Host: wahh-app.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 39
Cookie: SESS=GTnrpx2ss2tSWSnhXJGyG0LJ47MXRsjcFM6Bd
username=daf&password=foo&redir=/secure/home.php&submit=login
http://portswigger.net/
burp/help/suite_using
burp.html
Web application attacks VI
Intercepting Proxy
Fiddler 2/4
http://www.telerik.com/fiddler
Web application attacks VII
• Web application spiders
– Web application spiders work in a similar way to traditional web
spiders - by requesting web pages, parsing these for links to
other pages, and then requesting those pages, continuing
recursively until all of a site’s content has been discovered
• Application fuzzers and scanners
– Manual and auto scans to detect common vulnerabilities
– Built-in attack payloads and versatile functions to generate
arbitrary payloads in user-defined ways
– Functions for extraction of data and analyzing responses,
cookies etc.
• Manual and scripted request tools
• Various functions and utilities that address specific needs that
arise when you are attacking a web application
• Paros, Burp suite, WebScarab and Fiddler handles all this and
much much more
Defending against
web application attacks
• Integrity checks
– Sign or hash all variables sent to client with HMAC (Hash-based
Message Authentication Code)
– Encrypt the information in session ID, hidden form element, cookies,
variables etc. in addition to SSL
– Ensure long enough session ID numbers preventing collision
– Use dynamic session IDs (time) - changing from page to page
●
Make sure checks works everywhere and session IDs terminate at exit/logout
Alternatives to the Intercepting Proxy
• In-browser tools – which have
some limitations
• They do not perform any spidering
or fuzzing and you are restricted to
work completely manually
• Internet Explorer
– TamperIE
– HttpWatch or IEWatch
• Firefox
– Tamper Data, FoxyProxy
– LiveHTTPHeaders
– AddNEditCookies
– CookieWatcher
• Chrome
– Request Maker
FireCAT (Firefox Catalog of Auditing exTensions)
http://firecat.toolswatch.org/
OWASP Mantra - Security Framework
http://www.getmantra.com/
• The project's goal is to create a framework to find and
exploit web application vulnerabilities that is easy to use
and extend
– Performs scanning as Nikto and Nessus
– Performs exploitation as Metasploit etc.
– Platform-Independent
• Pyton and GTK for GUI
(console mode is available)
– Plugin support
– Easy updating via SVN
(Subversion)
– Good homepage
• Rapid7 sponsored
• http://w3af.org/
SQL Injection I
• SQL or code injection is a very large and complex area
– Client side - presentation (first tier)
• Java, JavaScript, DHTML, Flash, Silverlight, Ajax etc.
– Server side - Web application logic (middle tier)
• ASP, ASP.NET, CGI, ColdFusion, JSP/Java, PHP, Perl, Python,
Ruby on Rails etc.
– Database - storage (third tier)
• MS SQL server, MySQL, Oracle, PostgreSQL, Sybase, DB2,
Ingres etc.
– Web server software and operating systems
• String SQL injection (first order attack)
– Bypass authorization by piggybacking additional SQL statements
– Create two or more SQL statements to add or modify data
– Try to run commands in the underlaying OS via command injection
• Inject into trusted persistent storage as tables (second order attack)
– An attack is subsequently executed by another activity
SQL Injection II
• Figure out how the Web application interacts with the back-end
database and see how the system reacts to submitted information
– Fuzz input forms and probe for descriptive error messages
– Find a user supplied input string which is part of a DB-query
– Then by adding quotation characters as for example: ' or ”
and command delimiters as ; try to fuzz the DB
• Pretty hard to set up a good testing environment!
– Luckily we have WebGoat!
– http://www.owasp.org (web security organization)
• Common SQL injection works on SQL statements as
– SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER
– UNION, WHERE, LIKE, AND, OR, NOT, VALUES
• Suppose we forced an error message in an web application as
– Error in query expression string: 'userid = 101'” (we just added one ”)
– SELECT * FROM user_data WHERE userid = 101 OR 'TRUE'
– Injecting the last SQL logic may present the whole user_data table
WebGoat – Hacker Firefox
u/p: guest/guest
SQL Injection III
• Some examples of SQL Injections (Hacking Exposed)
http://sqlmap.sourceforge.net/
• The Mole
– http://sourceforge.net/projects/themole/
• Sqlsus (MySQL) Commercial tools
– http://sqlsus.sourceforge.net/ Pangolin - free edition
http://www.nosec-inc.com
• Sqlninja (MSSQL) Havij Advanced SQL Injection - free version
– http://sqlninja.sourceforge.net/ http://www.itsecteam.com/
• SQL Injection cheat sheats
– http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/
– http://devcheatsheet.com/tag/sql-injection/
Never forget to sanitize input!
• An attacker could put in *anything*, even scripts as parameters
to your REST service!
– http://localhost/myhome/demo.php?
fname=<b>Hans</b>&sname=<h1>Jones</h1>
• We must get rid of tags (<) etc. and could for example use the
str_replace() function
– $person = str_replace("<","",$person);
• A better option is to use the preg_replace(); function
– $person = preg_replace("/[^A-Z,a-z,0-9, ,.,',;,:,?]/", "", $str);
• It will filter out everything except the characters following the ^
• It is much better to delete everything EXCEPT a specified
range of characters than allow everything apart from the
following ...
• Failure to do this will mean that your site WILL get hacked!
Searching a table 1
<?php
# Start the page properly
echo "<html>";
echo "<body>";
function sanitize_form_text($t)
{
$t = strip_tags($t);
$t = preg_replace("/[^A-Za-z0-9@._-]/", "", $t);
return $t;
}
?>
Preventing SQL Injection Attacks
• In the previous example we did something like: select firstname, surname
from customers where surname = 'Smith'
– But what if the visitor enters some search text as follows: Smith' or surname !=
'Smith
– We end up with: select firstname, surname from customers where surname =
'Smith' or surname != 'Smith'
– In other words, it will return the entire contents of the table!
• Consider what happens if the following is entered as a surname: Smith' or
surname != 'Smith; delete from customers
– The semicolon is the standard character in MySQL for separating multiple
commands on a single line. So now, after your program searches for the entered
surname, it will then delete the entire contents of your customer database!
• Note that we can enter characters in HEX code as well %3B = ; which means
that we must block the % too
• Attackers have sophisticated tools that automatically look for such errors on
web sites and try to exploit them!
• Use DB access layers which support prepared
statements for DB access as for example PDO
PDO – create and update
• Using PDO, create and update is normally a two-step process
<?php
# The most basic type of insert, STH means "Statement Handle", no binding here
$STH = $DBH->prepare("INSERT INTO folks ( first_name ) values ( 'Cathy' )");
$STH->execute();
?>
# insert one row - once the query have been prepared ...
$name = "Daniel";
$addr = "1 Wicked Way";
$city = "Arlington Heights";
$STH->execute();
# ... insert another row with different values – multiple times (looping)
$name = "Steve"
$addr = "5 Circle Drive";
$city = "Schaumburg";
$STH->execute();
# Does this seem a bit unwieldy for statements with a lot of parameters? It is!
# However, if your data is stored in an array, there’s an easy shortcut.
# We do not need to use ->bindParam() - the execute($values) method does this!
# the array data we want to insert must be in the arg. ->execute(argument)
$data = array('Cathy', '9 Dark and Twisty Road', 'Cardiff');
$STH = $DBH->prepare("INSERT INTO folks (name, addr, city) values (?, ?, ?)");
$STH->execute($data);
?>
PDO - prepared statements 2
• Named placeholders
<?php
$STH = $DBH->prepare("INSERT INTO folks (name, addr, city) value (:name, :addr, :city)");
# the first argument is the named placeholder name - notice named placeholders always start with a colon
$STH->bindParam(':name', $name); $STH->bindParam(':addr', $addr); $STH->bindParam(':city', $city);
# insert one row - insert as many rows as you want just updating the variables and ->execute()
$name = "Daniel"; $addr = "1 Wicked Way"; $city = "Arlington Heights";
$STH->execute();
# You can use a shortcut here as well, but it works with associative arrays. The data we want to insert
$data = array(':name' => 'Cathy', ':addr' => '9 Dark and Twisty', ':city' => 'Cardiff');
$STH = $DBH->prepare("INSERT INTO folks (name, addr, city) value (:name, :addr, :city)");
# And the array shortcut ->execute(arg)!
$STH->execute($data);
# Another nice feature of named placeholders is the ability to insert objects directly into your
# database, assuming the properties match the named fields - a simple object
class person {
public $name; public $addr; public $city;
function __construct($n,$a,$c) {
$this->name = $n; $this->addr = $a; $this->city = $c;
}
# etc ...
}
$cathy = new person('Cathy','9 Dark and Twisty','Cardiff');
# here's the fun part
$STH = $DBH->prepare("INSERT INTO folks (name, addr, city) value (:name, :addr, :city)");
# By casting the object to an array in the execute, the properties are treated as array keys
$STH->execute((array)$cathy);
?>
PDO - prepared statements 3
• Update and delete with named placeholders
<?php
// update using named place holders
$id = 5;
$name = "Joe the Plumber";
try {
$DBH = new PDO('mysql:host=localhost;dbname=someDatabase', $username, $password);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);