ECE4112 Internetwork Security

Lab X: Web Application Attacks

Group Number: ______

Member Names: ______

Date Assigned:

Due Date:

Last Edited on: December 11, 2007

Lab Authored By: Zafeer Khan and Simmon Yau

Please read the entire lab and any extra materials carefully before starting. Be sure to start early enough so that you will have time to complete the lab. Answer ALL questions and be sure you turn in ALL materials listed in the Turn-in ChecklistON or BEFORE the Date Due.

Goal:The goal of this lab is to introduce different kinds of web application attacks and how to secure your web applications to prevent being the victims of such attack.

Summary:The Lab will cover URL Interpretation Attacks which includes SQL injection and Cross-Site Scripting, Impersonation attacks, Buffer Overflow attacks and finally Remote Code Execution, divided into their own individual sections.

Background:The lab requires a basic understanding of web based applications, a combination of SQL, Apache servers and PHP and how they all work together. Appendix A has information on PHP, Appendix B on MySQL and Appendix C on setup of MySQL database and Apache Server. If you have no previous knowledge on web applications it is highly recommended you read those appendices before starting the lab. Other than that basic web browsing skills are required to complete this lab.

Below is a diagram of a typical web application setup.It shows where the different applications sit within the whole system. We will see during the lab that there are vulnerabilities in almost all the components in a web application.

Requirements:

  • VMWare with 1 – Windows XP image
  • XAMPP on XP image
  • Any web browser

Prelab Questions: None.

Section 0:Setup

Get the installer for XAMPP from the NAS server. Install XAMPP on your Windows XP image. Once installed go to the XAMPP folder and look for a folder named htdocs. This is the directory where your Apache server finds all the files to display under localhost. There should be a default index.html file, which is displayed when you open a browser. So basically if you have a file named test.html in the htdocs folder, opening a browser and typing in localhost/test.html will display your page. Inside xampp->apache->conf->httpd.conf file is the settings for your server. You can open and modify this file to change your directory root to point to a different location if you want to. If you don’t have any previous experience with Apache servers you can leave this file alone, however, the file is well commented and self explanatory so it is worthwhile going through it once. Inside xampp->php->php.ini is the settings for PHP. This is where you can turn Magic Quotes on/off and enable or disable other security features for PHP. Once again, refer to the appendices for more information.

Section 1:URL Interpretation Attacks

Section 1.1 – HTTP response splitting/Cross-Site Scripting

This attack targets applicationsthat use parameters to indicate redirects. For example, here is a potentially vulnerable URL:

A good input validation routine would ensure that the value for the page parameterconsists of a valid URL. Yet if arbitrary characters can be included, then the parametermight be rewritten with something like this:

world!%3c/html%3e

The original value of page has been replaced with a series of characters that mimic theHTTP response headers from a web server and includes a simpleHTMLstring for “Hello,world!” The malicious payload is more easily understood by replacing the encoded characters:

Content-Type: text/html

HTTP/1.1 200 OK

Content-Type: text/html

<html>Hello, world!</html>

The end result is that the web browser displays this faked HTML content rather thanthe HTML content intended for the redirect. The example appears innocuous, but a maliciousattack could include JavaScript or content that appears to be a request for the user’spassword, social security number, credit card information, or other sensitive information.

The point of this example is not how to create an effective phishing attack, but todemonstratehowa parameter’s content can be manipulated to produce unintended effects.

Let’s try out this for ourselves. In the source directory for your Apache server create these files with the following code:

welcome.html

<!DOCTYPE html

PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"

<html xmlns=" xml:lang="en" lang="en">

<head>

<link rel="stylesheet" href="style.css" type="text/css" />

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Welcome Page</title>

</head>

<body>

<h1>Welcome Page</h1>

<p>Welcome member!</p>

</body>

</html>

login.html

<!DOCTYPE html

PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"

<html xmlns=" xml:lang="en" lang="en">

<head>

<link rel="stylesheet" href="style.css" type="text/css" />

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Sample Web Page</title>

</head>

<body>

<h1>Sample Login Page</h1>

<p>Basic URL interpretation attack. </p>

<p>

<label>Username </label<input name="username" type="text" id="username" />

</p>

<p>

<label>Password </label<input name="password" type="password" id="password" />

</p>

<p>

<a href=" Here to Login</a<br />

</p>

</body>

</html>

redirect.php

<?php

if( (isset($_GET['page'])) ) {

$page = $_GET['page'];

header("Location: $page");

exit();

}

?>

hacked.html

<!DOCTYPE html

PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"

<html xmlns=" xml:lang="en" lang="en">

<head>

<link rel="stylesheet" href="style.css" type="text/css" />

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Welcome Page</title>

</head>

<body>

<h1>Welcome member!</h1>

<p>Please provide credit card number for validation</p>

<script type="text/javascript" src="nasty.js"</script>

<script>disp_prompt()</script>

</body>

</html>

nasty.js

function disp_prompt()

{

var num=prompt("Please enter your Credit Card Number");

if (num!=null & num!="")

{

document.write("<h1>You have just been hacked. Sucker!!!</h1>");

}

}

style.css

body {background-color: #000000;

font-family: "Times New Roman";

color: #4444CC;

font-size: 12pt;}

a {color: #A20000}

a:hover {color: #A27700}

a:active {color: #17A200}

a:visited {color: #00CDD8}

table {border: #FF8800 2px solid;}

td {border: white 1px solid;}

h3 {font-weight: bold;

font-size: 14pt}

If you look closely at the codes you will see that all redirect.php does is get the header information from the url, and redirects to the welcome page. The login page does nothing other than take you to the script redirect.php with the page information for welcome.html. Since login.html is a static html page it does nothing with the username and password typed in, you can leave them empty and just click the login link. We don’t really care about that, the purpose of this is to show how by not validating information passed between pages we can expose ourselves to attacks. style.css is just the stylesheet for the html pages. To carry out the attack we first load login.html and view page source. If you scroll down you will see the link for the login button. As you can see all you have to do is change the page value to an address you want the user to be redirected to when they click on the login link. Let’s try this now, type the following link into your browser’s URL address bar:

Q1.1.1 What happens once you do this?

Q1.1.2 How could you have prevented such an attack?

We ran the whole attack on localhost server but you can easily see how we can accomplish the same thing on any site. The only difference would be instead of localhost the URL would be something like:

where website is the actual website we are trying to attack.

Section 1.2 – SQL Injection

This attack targets the encoding of the URL. An attacker can take advantage of the multiple ways of encoding an URL and abuse the interpretation of the URL. An URL may contain special character that need special syntax handling in order to be interpreted. Special characters are represented using a percentage character followed by two digits representing the octet code of the original character (%HEX-CODE).For instance US-ASCII space character would be represented with %20. This is often referred as escaped ending or percent-encoding. Since the server decodes the URL from the requests, it may restrict the access to some URL paths by validating and filtering out the URL requests it received. An attacker will try to craft an URL with a sequence of special characters which once interpreted by the server will be equivalent to a forbidden URL. It can be difficult to protect against this attack since the URL can contain other format of encoding such as UTF-8 encoding, Unicode-encoding, etc. The attacker could also subvert the meaning of the URL string request by encoding the data being sent to the server through a GET request. For instance an attacker may subvert the meaning of parameters used in a SQL request and sent through the URL string.

Attack Execution Flow

1- The attacker accesses the server using a specific URL.

2- The attacker tries to encode some special characters in the URL. The attacker finds out that some characters are not filtered properly.

3- The attacker crafts a malicious URL string request and sends it to the server.

4- The server decodes and interprets the URL string. Unfortunately since the input filtering is not done properly, the special characters may have harmful consequences.

We will try this out for ourselves. First create the following files in your Apache htdocs directory:

process_login.asp

<HTML>

<BODY bgcolor='000000' text='ffffff'>

<FONT Face='tahoma' color='ffffff'>

<STYLE>

p { font-size=20pt ! important}

font { font-size=20pt ! important}

h1 { font-size=64pt ! important}

</STYLE>

<%@LANGUAGE = JScript %>

<%

function trace( str )

{

if( Request.form("debug") == "true" )

Response.write( str );

}

function Login( cn )

{

var username;

var password;

username = Request.form("username");

password = Request.form("password");

var rso = Server.CreateObject("ADODB.Recordset");

var sql = "select * from users where username = '" + username + "' and password = '" + password + "'";

trace( "query: " + sql );

rso.open( sql, cn );

if (rso.EOF)

{

rso.close();

%>

<FONT Face='tahoma' color='cc0000'>

<H1>

<BR<BR>

<CENTER>ACCESS DENIED</CENTER>

</H1>

</BODY>

</HTML>

<%

Response.end

return;

}

else

{

Session("username") = "" + rso("username");

%>

<FONT Face='tahoma' color='00cc00'>

<H1>

<CENTER>ACCESS GRANTED<BR>

<BR>

Welcome,

<% Response.write(rso("Username"));

Response.write( "</BODY</HTML>" );

Response.end

}

}

function Main()

{

//Set up connection

var username

var cn = Server.createobject( "ADODB.Connection" );

cn.connectiontimeout = 20;

cn.open( "localhost", "root", "" );

username = new String( Request.form("username") );

if( username.length > 0)

{

Login( cn );

}

cn.close();

}

Main();

%>

loginform.html

<HTML>

<HEAD>

<TITLE>Login Page</TITLE>

</HEAD>

<BODY bgcolor='000000' text='cccccc'>

<FONT Face='tahoma' color='cccccc'>

<CENTER<H1>Login</H1>

<FORM action='process_login.asp' method=post>

<TABLE>

<TR<TD>Username:</TD<TD<INPUT type=text name=username size=100%

width=100</INPUT</TD</TR>

<TR<TD>Password:</TD<TD<INPUT type=password name=password size=100% width=100</INPUT</TD</TR>

</TABLE>

<INPUT type=submit value='Submit'> <INPUT type=reset value='Reset'>

</FORM>

</FONT>

</BODY>

</HTML>

Open a browser and goto

Now try logging in with any username and password. It should redirect you to process_login.asp if you typed in a valid username and password from the users table. Now go to the URL address bar of your browser and type in the following:


%3d%270wn3d%27%3b--%00

Q1.2.1 What happens once you do this?

Q1.2.2 Can you figure out what SQL query gets executed?

Q1.2.3 How can you protect yourself from such an attack?

Section 2: Impersonation Attacks

In this section of the lab, you will learn about impersonation attacks or how people pretend to be another person or a popular and known organization and attempt to gain access to their private account information. These impersonation attacks are becoming more popular due to the large amount of money that hackers and organized crime can make off of them. There are many kinds of impersonation attacks, but we will only cover the ones people would encounter on the web. This section will show you an impersonation attack of an attacker pretending to be another person as a result of some poorly coded session management.

Http is basically a stateless protocol and has no way to track or remember information. However, web developers can use something called sessions which are similar to cookies to track information. Sessions and cookies are different in the way that sessions only exist until they are destroyed. Once a session is destroyed, the browser will not keep track of any information until a new session is created again on the same webpage. Let’s take a look at an example of a session.

First, install apache, mySQL, and PHP onto your hard drive if you have not already done so in your previous lab(s). If you do not know how to do this, please look in Appendix A of this lab on further instructions in doing so.

Mount the nas onto your hard drive and then proceed to download “session.php” from the LabX folder on the nas onto your RedHat WS 4.0 host machine. Save this file onto your …/apache2/htdocs/ folder so that we can view it in a web browser. Next, go to where x corresponds to the last byte of the IP of your RedHat WS 4.0 host machine. You could also do or

Q2.1. What do you see displayed on the webpage?

Q2.2. Click the refresh button on the browser. What do you see displayed on the webpage now?

Q2.3. Close the web browser(NOT just the tabbed window!) and open a new one. Go back to the site. What do you see displayed on the webpage now? Why?

Q2.4. Take a look at the source code for session.php below and explain what it is doing.

Session.php Source Code

<?php

session_start();

if ($PHPSESSID) {

echo $PHPSESSID;

} else {

print('This is your first time visiting this site. A session has been created to track your information.');

session_register('PHPSESSID');

$PHPSESSID=rand();

}

?>

Now that you know what the sessions are doing, let’s take a look at how someone could easily hijack sessions. In a web browser, go to your page again and click the refresh button so you can see your session ID printed on the webpage. Take this session copy and replace the X in this url and go to it in a NEW web browser: .

Now that you have seen an example of session creation on the web, let’s take a look at how someone could take advantage of sessions to gain another person’s account information.

Let us look at a poorly coded session management webpage. Mount the nas onto your hard drive and then proceed to download “badsession.php” from the LabX folder on the nas onto your RedHat WS 4.0 host machine. Save this file onto your …/apache2/htdocs/ folder so that we can view it on our webpage. Before you access the webpage, we must create the database for which our webpage will be pulling information out of.

Under a mySQL prompt, do the following commands:

mysql> create database ebank;

mysql> use ebank;

Next, we create the users table:

mysql> CREATE TABLE `users` (

`id` int(10) NOT NULL auto_increment,

`username` varchar(100) NOT NULL default '',

`password` varchar(100) NOT NULL default '',

`balance` varchar(100) NOT NULL default '',

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

mysql> INSERT INTO `users` VALUES (1, 'henry', 'owen', ‘$1’);

mysql> INSERT INTO `users` VALUES (5, 'bill', 'gates', ‘$10000000000’);

In the previous step, you created a database called ebank and a table called users. For the users table, you inserted the entries for two people and their account information. We will now try to log in to one of the accounts and see what happens.

Open a web browser and go to Use the username “henry” with the password “owen”. Your screen should look like the figure below.

Q2.5. After logging in with the username “henry” and the password “owen”, what do you see?

Q2.6. Try adding ?PHPSESSID=5 to the end of the url, what happens?

Q2.7. Obviously, what happened in the previous question is a very unsafe method of coding a website. Explain why this can occur and what you could do to as the web designer to prevent this from happening.

The code in badsession.php is not only bad, but there were also some other reasons that allowed this session hijacking. One of the reasons is because the options for global variables was turned on in the php.ini file. Also, the PHPSESSID variable was also enabled to be passed around in a cookie. This can be seen in the code below:

Php.ini

php.ini changes

; Option of whether or not to use cookies

session.use_cookies = 1

session.cookie_secure = 0

; This option enables administrators to make their users invulnerable to

; attacks which involve passing session ids in URLs; defaults to 1.

session.use_only_cookies = 0

; Name of the session (used as cookie name).

session.name = PHPSESSID

register_globals=on

Badsession.php

<?php

if(!$PHPSESSID){

$username = $_POST["username"]; // grab username from form

$password = $_POST["password"]; // grab password from form

$dbuser="root"; // database username

$dbpassword="password"; // database password

$database=" ebank"; // database name

mysql_connect(localhost,$dbuser,$dbpassword); // connect to database