Chapter 9 Web Application Attacks – GCIH GIAC Certified Incident Handler All-in-One Exam Guide

CHAPTER 9

Web Application Attacks

In this chapter, you will learn about

•   OWASP (Open Web Application Security Project)

•   Command injection

•   Account harvesting

•   SQL injection

•   XSS (cross-site scripting)

•   CSRF (cross-site request forgery)

•   Tools like Nikto, ZAP, Burp Suite, WPScan, and sqlmap

As you have seen so far, an attacker may try to compromise your physical or infrastructural security to gain access to your devices. That means if a host attacker can gain entry at your premises, he will take advantage of that fact to possibly plug in a cable on your network, socially engineer one of your employees, or find the server room and connect to one of your devices. When working over the network, reconnaissance and service scans will be commonly performed to identify open ports that can hide vulnerable services, which then can be leveraged to compromise a victim. However, what happens if a device like a web server is adequately hardened and running an up-to-date operating system?

In those instances, the only available services might be HTTP and HTTPS, which is what the attacker will try to target in an effort to gain access to any underlying database that these interact with.

Web Proxies

A web browser may be all that it takes for a web application vulnerability to be exploited and give the attacker an entry point to a web server. Of course, that’s not usually the only tool attackers use, as it will allow for more basic attacks to take place. Using a web browser like Google Chrome or Mozilla Firefox and enabling the developer tools, an attacker can review the basic elements of a web page and assess how data is being passed from the client to the web server.

In addition to that, web proxies can be used so the attacker is able to intercept a web browser’s request and modify it before reaching the web server. Items like cookie information and session state can easily be manipulated using such tools. Common ones include ZAP (https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project), Burp Suite (https://portswigger.net/burp), w3af (http://w3af.org), Fiddler (https://www.telerik.com/fiddler) and Web Scarab (https://www.owasp.org/index.php/Category:OWASP_WebScarab_Project), which is an older project but may still be seen used from time-to-time.

TIP   Since a web proxy intercepts requests, you have to ensure that its security certificate is installed on your web browser. That will help you avoid any SSL warning messages about a dangerous connection each time you attempt to access a web page.

ZAP supports spidering a website and scanning it for web application vulnerabilities (actively or passively), anti-CSRF token detection, brute forcing directories, analyzing parameters, fuzzing, and traffic interception.

Burp Suite keeps track of all requests that are made and uses them to construct a website map. It is easily able to remove elements from the attack scope, crawl a website, and perform active and passive scanning for vulnerabilities. It also has various tools that can provide more aid, like intruder, repeater, sequencer, comparer, decoder, extender, and many more. For a full overview browse to https://portswigger.net/burp/documentation/desktop/tools.

EXAM TIP   Ensure you familiarize yourself with how ZAP and Burp Suite work, what their GUIs look like, and where you can find the options to perform simple tasks. Examples include spidering a website, intercepting traffic, and identifying vulnerabilities that you can exploit (like XSS and SQL injection).

TIP   To demonstrate the numerous types of web application attacks discussed in the rest of this chapter, Metasploitable’s Mutillidae and Damn Vulnerable Web Application (DVWA) will be used. This is the easiest way of being able to test against various web application vulnerabilities without using various test domains. Each time external connectivity is required to test something (like in the command injection section), remember to switch both Kali and Metasploitable VMs to NAT or bridged mode.

OWASP (Open Web Application Security Project)

Before discussing the various web application attacks, it’s worth mentioning OWASP, which is a nonprofit organization focused on providing software security. They have various projects that are of interest, like ZAP (which was mentioned earlier), the OWASP testing project, and the famous OWASP top ten (https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project), which contains the top ten web application security vulnerabilities as seen in the industry. Every web developer should be ideally addressing these issues when developing new applications. Security analysts and testers should also be highlighting these to their organizations, as they are the ones that are used by attackers to commonly gain access. Table 9-1 contains the most recent publication of the OWASP top ten vulnerabilities, released in 2017.

Table 9-1  OWASP Top Ten Application Vulnerabilities as of 2017

(Source: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project)

EXAM TIP   The current GCIH exam objectives include typical web application vulnerabilities such as command and SQL injection, XSS, and CSRF. As such, the rest of the chapter will be focusing on those. However, it’s highly recommended that you spend time practicing and researching the rest, as that will prove really beneficial in real-life attack scenarios. Following the OWASP top ten links is a great start to accomplish this, as they provide enough detail about what each attack does and how it can be used against a target system. You can use that to practice attacks in your lab environment and reach out to your developers to make sure they address them, if they’re present in your organization. Don’t forget to also look at the cloud top ten category (https://github.com/OWASP/Cloud-Native-Application-Security-Top-10).

Command Injection

A web application will typically contain one or more user input fields. Let’s browse to one of the tools in Mutillidae to see how this works. First of all, ensure your Metasploitable VM is running. After that, use Kali Linux’s Firefox browser to navigate to it using http://192.168.1.111/mutillidae.

TIP   Remember to replace the IP address with the one corresponding to your Metasploitable VM.

Then navigate to OWASP Top 10 | A1 – Injection | Command Injection | DNS Lookup, as seen in Figure 9-1.

Figure 9-1  Command injection vulnerability in Mutillidae

Once you do that, you will be presented with a tool that is able to perform a DNS lookup, pretty similar to any of the online tools you have used so far. Test its operation by looking up a hostname or IP address. Figure 9-2 shows an example of looking up mheducation.com.

Figure 9-2  Using the DNS Lookup tool to perform a DNS lookup on mheducation.com

As you can see, my local gateway (192.168.1.1) listening for DNS requests on port 53 responded to this one and identified mheducation.com residing at 204.74.99.100, which is exactly what an nslookup from Kali Linux provides:

However, the twist here is that this tool is vulnerable to command injection. The goal of the attacker is to use the vulnerable application (in this case, the DNS lookup tool) to execute commands (over a shell) at the web server. You can commonly verify a command injection vulnerability is present by trying to append a command to be executed in sequence with the normal argument that would be used. You can append that using the semicolon character (;). As an example, try running mheducation.com; whoami. If a command injection vulnerability is present, the first argument should pass through the tool as before (and will be used to execute a DNS lookup for mheducation.com), but it will also accept the second argument and run the whoami command, thus displaying the username of the current user. Figure 9-3 verifies that fact and displays www-data as the username of the current user.

Figure 9-3  Command injection used to run whoami

In general, command injection allows commands to be executed with web server privileges, but as you can imagine, that still allows for quite a wide range of commands that can provide interesting output. A typical example? Check Figure 9-4 for the magic.

Figure 9-4  Command injection used to display the passwd file

The attacker managed to get a copy of the passwd file just by running a single command through a web browser.

EXAM TIP   Sometimes a web server may be found running with admin (or root) privileges (instead of the typical web server ones). If that’s the case, an attacker is handed the keys to the kingdom, as he would get admin (or root) access on that machine.

Any command that can run without elevated privileges can be used by an attacker to successfully identify a command injection vulnerability. In addition, the attacker may use all possible methods of passing arguments to the web server, which commonly are form fields and URL parameters.

Another common example is using the ping command. An attacker can run a packet capture on his system, checking to see if ICMP traffic from the web server is reaching him successfully. To test this, run a tcpdump filter in Kali, like the one shown here:

The command used for injection is

Kali shows the following eight ICMP packets reaching it, indicating a successful command injection operation:

Defending Against Command Injection

The primary reason for a command injection vulnerability being present is poor application development and improper input validation. Most web developers aren’t really aware of this attack, so when they write source code, they just want it to work. They don’t really tend to think about how it can be exploited by an attacker. As such, you should ensure your developers are made aware of these issues so they properly validate any input the web server accepts for further processing (for example, characters like ; and &). Performing frequent code reviews also helps to stay on top of these challenges.

Using a WAF is also a great idea, as it can identify and block command injection attempts. In addition, you can use any vulnerability scanner (like Nessus or Qualys), as they will usually identify command injection vulnerabilities, which you can then promptly address.

Remember to ensure that your web server is not running with root or admin privileges so the damage is limited even if an attacker manages to compromise it.

Checking web server logs also greatly helps because you may notice various command injection attempts or a successful command execution that will prompt further investigation. You wouldn’t expect anyone external to your network to be interacting with the web server and using it to execute commands like who, whoami, ping, nslookup, traceroute, or anything similar. Along the same lines, you can search your logs for any response traffic that any such commands generate. For example, if you see ICMP request packets originating from your web server destined for an external destination, it can indicate traffic to a ping command the attacker executed while managing to perform remote command injection on that server. Even worse, if the attacker has already managed to compromise that system, you might see data being exfiltrated, like the example provided in Figure 9-4, where the attacker managed to get a copy of the password file.

Account Harvesting

Account harvesting (also known as username enumeration) allows the attacker to identify legitimate usernames or user IDs that can be used later for brute-force or social engineering attacks. For example, if an attacker has a really large database of passwords that have been leaked in the past, those can be used to create a large password dictionary. Once valid accounts have been identified, that dictionary of passwords can be used to brute-force those accounts and gain access. In order to harvest valid accounts, the attacker may try to take advantage of the web application’s response codes to a login request or any error messages that are provided as a part of that. An organization may be providing such information, which will be really useful for an attacker. This can be done either manually or using a tool like Burp Suite. Figure 9-5 shows an example of manual inspection on a financial institution’s login web page.

Figure 9-5  Financial institution’s login web page

Selecting “Forgotten your customer number?” very handily states what the actual expected format is. In this case, it’s the date of birth, followed by a three-digit number. An attacker can easily select a random working date of birth and add various three-digit numbers at the end of it to form a working customer number. An example follows shortly of how Burp Suite can be used to automate this task when trying this method on Yahoo Mail. But first, let’s see how an attempt to login usually looks like. Figure 9-6 shows an example of an attempt to log in to Yahoo Mail.

Figure 9-6  Yahoo Mail invalid username error message

If an invalid username (like AmIValid) is provided, the server immediately states it’s not recognized by providing a related error message: “Sorry, we don’t recognise this email address.” However, if a valid username is provided, a related password is requested, as seen in Figure 9-7. Note that the actual username has been redacted for privacy reasons. Burp Suite can be used to help an attacker leverage this information to his advantage.

Figure 9-7  Yahoo Mail requesting a password for a valid username

Note that before moving to the next section and start using Burp Suite, you need to install its CA certificate in your browser.

TIP   Detailed instructions on how to install Burp Suite’s CA certificate can be found at https://support.portswigger.net/customer/portal/articles/1783075-installing-burp-s-ca-certificate-in-your-browser.

After that’s done, go to your browser’s settings and set Burp Suite as a proxy. If you are using Firefox, perform the following:

1.  Go to Edit | Preferences | Network Settings.

2.  In the Connection Settings pop-up window, select Manual Proxy Configuration.

3.  Set HTTP Proxy to 127.0.0.1 and port to 8080, as shown in Figure 9-8.

Figure 9-8  Firefox settings for Burp Suite

After the previous steps have been performed, start Burp Suite. You don’t need to create a new project, so you can skip the first pop-up window. Now let’s see how an attacker would commonly try to automate the username validation effort, using the earlier mentioned error message about an account being present or not.

CAUTION   This is just an example, and you shouldn’t be using it to attack Yahoo! or any other public service. It just highlights the risk of using error messages that an attacker can leverage on a real production system.

Navigate to the login page again, ensuring that Burp Suite’s intercept is on (located in Proxy | Intercept). Use a nonexistent username, which will cause the server to respond with the error message mentioned earlier, and as soon as that is present in Burp Suite, right click and select Send To Intruder (as seen in Figure 9-9). After that, click on Intercept Is On to release the interception.

Figure 9-9  Burp Suite request being sent to intruder

Then go to the Intruder tab and follow these steps:

1.  Go to the Positions subtab and select Clear $.

2.  Select the value next to Username= and select Add $.

3.  Move to the Payloads subtab.

4.  In the Payload Options section, you can either input a list of usernames (using Load) or enter them manually and use Add to add them one by one. Figure 9-10 shows a few entries that have been added as an example (redacted for privacy).

5.  Move to the Options subtab.

6.  In the Grep - Match section select Clear to remove prepopulated options.

7.  Go to Add and enter the error message identified earlier: Sorry, we don’t recognize this email (Figure 9-11).

8.  Go to the Intruder menu and select Start Attack.

Figure 9-10  Username list for enumeration

Figure 9-11  Adding error message in intruder options

Once the attempt is started, a new window will pop up with the progress and related results, as seen in Figure 9-12.

Figure 9-12  Intruder results

As you can see, six usernames were tested. Out of those, one was an existing username and the other five were nonexistent accounts. Of course, an attacker would use a dictionary of names with possibly hundreds of values to identify working ones. That will then allow him not only to try and brute-force valid accounts on the target system but also to use working e-mail accounts for phishing attempts. Figure 9-13 shows an example of intruder results filtered based on response length.

Figure 9-13  Intruder results filtered by response length

Look closely at each value. The first two depict valid accounts (with a response length of 1667), while everything else represents invalid usernames (where the response seems to be four times larger). In addition to the length, an attacker will commonly try to distinguish differences in URL responses, response codes, and response times to distinguish working versus nonworking accounts.

Defending Against Account Harvesting

As you saw in the earlier example, the attacker could easily use the error message provided by the web server to distinguish between working and nonworking accounts. As such, you should ensure your applications don’t specify that to external entities. The rule is to keep messages provided to external entities generic in nature. Detailed messages can be added to the internal logs, which an administrator would view later. Try to make responses for valid and invalid account logins as identical as possible in terms of response codes, timing, and response length.

Use CAPTCHA and 2FA/MFA whenever possible and enforce account lockouts to prevent brute-force attacks against your user accounts. If any IP addresses are identified as attempting to log in to various accounts, block those at your perimeter security devices, at least temporarily.

Using more complicated usernames can also go a long way because most organizations tend to use very predictable values that an attacker can easily identify (for example, e-mail address composed of first name and last name separated by a “.” or “_”). Also consider renaming any privileged accounts to make it more difficult for attackers to identify them (for example, rename “administrator” or “admin” to “Paulie182743”).

SQL Injection

In an SQL injection attack, the attacker will try to leverage the communication to a web server with an ultimate goal of executing commands on the underlying SQL database that the web application has access to. Examples of SQL server types are Oracle SQL, Microsoft SQL, DB2 SQL, Ingres SQL, and Postgres SQL. Basically, the web application acts as a means of communication with the backend database, which is not exposed to direct external communication. Depending on the type of commands being injected by the attacker, anything from extracting confidential data to manipulating the database schema and modifying entries or dropping tables may be possible.

TIP   It’s really helpful to familiarize yourself with basic SQL commands to understand how those can be leveraged more efficiently by an attacker. Portswigger has a cheat sheet available at https://portswigger.net/web-security/sql-injection/cheat-sheet, and pentestmonkey has a collection of various cheat sheets at http://pentestmonkey.net/category/cheat-sheet/sql-injection. Just note that depending on the SQL version being used, the commands will differ.

Normal SQL Operation

It’s imperative to grasp how a web application, interconnected to a backend SQL database, works under normal conditions to understand how that can be leveraged by an attacker.

Figure 9-14 shows a login prompt displayed by Mutillidae when attempting to log in. User Jack has already been created earlier, so an attempt to provide a username of Jack and the corresponding password will display the username, password, and signature field values.

Figure 9-14  Details displayed for user Jack

In essence, this request is passed from the web server to a backend SQL database, where a query is performed against Jack’s username and password, which are then retrieved and displayed by the web application. The request would look similar to this SQL syntax:

This basically tells SQL to retrieve the User, Password, and Signature columns (from a table named Users) where the username is “Jack” and password is “Jack123” (which is what was entered in the login form).

Another example is a music store that has various tables of artists in its database. If a client comes in and asks for available Coldplay albums, this SQL query could be run:

If the store just got some David Bowie albums, the following query could be used to update the related table and add the new artist in the database, under artistid 176:

Some characters that have special meaning for SQL are

•   --  The double dash is used to denote a comment (anything after the double dash will be ignored).

•   *  The asterisk character acts as a wildcard (like in the earlier example of selecting all fields from the albums table).

•   ;  The semicolon character is used to terminate statements.

•   '  Single quote marks denote a string contained in a query. For example, 'Nick' will tell SQL to search for Nick.

EXAM TIP   Remember that different SQL versions have variations on these. For example, MySQL uses the # character to denote comments.

Examples of specific keywords used in SQL are

•   SELECT  Extracts data residing in a database

•   UPDATE  Updates data within a database

•   CREATE/DROP TABLE  Creates/deletes a table of the database

•   CREATE/ALTER DATABASE  Creates/deletes a whole database

TIP   For a full list of operators, go to https://www.w3schools.com/sql/sql_operators.asp.

Checking for SQL Injection

The first thing an attacker will try to do before leveraging an SQL injection attack is to check if the web application is susceptible to it. Try entering a name of Jack and a single quote mark as a password to Mutillidae and review the output, shown in Figure 9-15.

Figure 9-15  Single quote character entered in the password field

The error states “Error executing query: 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.” The attacker has just verified there’s a MySQL server running in the background, so any further commands can be adjusted accordingly. Inputting a string followed by a single quote mark (like Jack') would have the same effect. The reason is that when you input something in the login and password fields, that input is then passed to the MySQL server in the background, which encloses any string in single quote marks to form a working expression. When you already include a single quote mark, you are effectively creating an unbalanced quote condition, which generates the error that was displayed. Compare the following two queries (the second one denotes a username of Jack' and password of Jack123' being used):

Correct Query

Invalid Query

As you can see, the only difference is the additional single quote mark at the end of the username and the password provided through the form, which generates a MySQL error.

If an attacker wants to isolate specific fields to identify if they are vulnerable to SQL injection, they will try inserting the single quote mark into one field at a time. But what exactly do you think the attacker can do with this? Let’s try a few examples of strings that can be inserted and review the related outputs.

Testing Manual SQL Injection Strings

Let’s try a few manual SQL injection strings and see what the results are.

Jack' or 1=1#

As you can see in Figure 9-16, using Jack' or 1=1# results in extracting all the related table records, which include usernames, passwords, and signatures of registered users.

Figure 9-16  SQL injection using Jack' or 1=1#

That’s because a condition that is always true has been met (1=1), so all the table records have been returned by SQL. The previous query is translated into the following SQL statement:

As you can see, SQL will check the earlier WHERE statement and search for Jack or 1=1 (which is always true) while ignoring the rest of it, since everything that comes after the # character signifies a comment.

Jack' ORDER BY 6#

The keyword ORDER BY is used to sort results by either ascending or descending order. An attacker can manipulate that to identify the actual number of columns contained in a table. To do this, you can start by using ORDER BY 1 (to sort out data using column 1) and continue increasing the number to 2, 3, 4, and so on until an error is returned.

Using Jack' ORDER BY 1# returns

Results are also returned for anything up to Jack' ORDER BY 5#. However, using Jack' ORDER BY 6# displays the error seen in Figure 9-17.

Figure 9-17  Error generated when using Jack' ORDER BY 6#

Jack' or 1=1 union select null, table_name from information_schema.tables#

Let’s try two more examples but this time in DVWA. Figure 9-18 shows the output of the Jack' or 1=1 union select null, table_name from information_schema.tables# string.

Figure 9-18  DVWA SQL injection displaying database table list

The key here is extracting information from SQL’s information_schema.tables, which stores a list of all the tables contained in the database. Column table_name is used to extract all those names.

Jack' OR 1=1 UNION SELECT user.password from users#

Now that the attacker has accessed the database’s tables, a useful next step would be to try and identify working usernames and passwords. The users table contains usernames and MD5 representations of the current passwords, and Jack'OR 1=1 UNION SELECT user.password from users# can be used to extract that information, as seen in Figure 9-19.

Figure 9-19  DVWA SQL injection displaying usernames and password hashes

Breaking those hashes is fairly trivial. You can even try online tools. For example, pablo’s hashed password is “0d107d09f5bbe40cade3de5c71e9e9b7”, as seen in Figure 9-19. Using https://hashkiller.co.uk identifies that the actual password matching that hash is “letmein.”

Automating SQL Injection Using Burp Suite

As you may have noticed, using a manual approach takes time, especially if multiple fields are involved. You will also miss any SQL injection strings you don’t test for, and there will just be too many for you to exhaust manually. That’s why using tools to automate the process can greatly expedite it and give you accurate results. As an example, let’s see how sqlmap (http://sqlmap.org) can be used in combination with Burp Suite to perform SQL injection.

First of all, you need to start Burp Suite and intercept the initial login request to get the cookie value, which can then be inserted into sqlmap for information extraction. Once you start interception (exactly as you did earlier in the chapter, in the “Account Harvesting” section), obtain the cookie value (as seen in Figure 9-20).

Figure 9-20  Getting the DVWA cookie value

After that, use sqlmap to execute the following command to get all the database’s table names:

TIP   Remember to adjust the DVWA URL to correspond to your DVWA IP address.

Review the following extract of that command’s output and compare it with the one in Figure 9-18, which is when a manual approach was used to achieve the same outcome:

As you can see, they are identical. What this proves for one more time is that using tools is great for automating tasks, but it’s ideal when you know how the underlying commands and concepts work to get the same results. The same logic can be applied to various other sqlmap queries. For example, if you want to generate a list of all available databases, use the following command:

If you want to check the available tables in DVWA, use

Defending Against SQL Injection

Input validation and using WAFs (like ModSecurity or cloud WAF providers) are two great ways to defend against SQL injection attempts in addition to using IPS devices with the ability to perform application-layer inspection. Identify any dangerous characters that might be used to signify SQL injection at the web server level and block those, creating a blacklist of such characters. Another method is to only allow specific characters that you expect your web server will be using to perform specific operations and not allow anything else, following a whitelist approach.

Ensure you are adequately monitoring your web servers for any type of SQL injection attempts. Perform tests using the previously mentioned techniques and see what types of entries are generated in your logs. Use those to set up alerting at your SIEM or any other monitoring tools so you get promptly notified of any suspicious attempts.

Ensure your web server is accessing the backend database with limited permissions to restrict the amount of damage that can be done in the event of a successful SQL injection attack.

Using prepared statements will not allow a field’s input to be separated in different sections. If that’s enforced, any web application will get all of the input of a field and take that to apply it as a query on the SQL database. For example, if there’s a field for the username and someone enters Jack' or 1=1# that whole string will be used as a username. So, the application will look for a user named Jack' or 1=1#.

A variation of the earlier concept of prepared statements is using stored procedures, which use code that is stored in the SQL database and called from the web application and basically does the same job as a prepared statement.

Only allow generic error messages to be present when there’s an SQL error. That won’t allow the attacker to gain valuable information about the database and its type, which may result in abuse.

Use strong encryption and hash algorithms to protect the database’s sensitive data. For example, refrain from using MD5 and replace it with SHA-3 or replace DES encryption with AES. Also note that you should only be storing sensitive data if there’s an actual use for it.

Remember to patch, update, and test your systems regularly to promptly identify any issues that require addressing.

XSS (Cross-Site Scripting)

An attacker uses a web server (which is vulnerable to XSS) to send a malicious script to a victim’s web browser, with the goal of performing some type of activity or extracting valuable information (most commonly a cookie value) using that browser. For this to succeed, a specially crafted URL would be created by the attacker and sent to the victim (reflected XSS). Another way is to store a malicious script in a public web page (like an online shop’s feedback page) or one that the attacker owns or has compromised. Again, the goal is to have the victim access that URL (stored XSS). It’s important to note that the vulnerable website is used to pass the script to the victim’s web browser, which is where it actually runs. One of the most common ways used to check if a website is vulnerable to XSS is using JavaScript for a quick test:

TIP   Before testing XSS attacks, switch the DVWA security level to low. To do that, just log in to DVWA, navigate to DVWA Security, switch the security level to Low, and select Submit.

Log in to DVWA and navigate to the XSS Reflected section. Then enter the previous script in the name field, as seen in Figure 9-21.

Figure 9-21  XSS script in DVWA’s XSS reflected web page

The result should be a pop-up window, reflecting the content of that message back to you, as seen in Figure 9-22.

Figure 9-22  XSS test in DVWA’s XSS reflected web page

The attacker will try to identify any type of available script that can be used for an XSS attack, like JavaScript, PHP, and ASP.

Some common things an attacker can use XSS for are

•   Obtain cookie values

•   Perform fund transfers

•   Perform malicious redirections to other websites controlled by the attacker

•   Phishing for credentials

•   Entice a victim to download adware/spyware

•   Use a compromised machine’s browser to attack other machines on the network

•   Use it through a tool like BeEF (already discussed in Chapter 5) to get a browser hook (for example, <script src="http://172.16.197.136:3000/hook.js"></script>)

Reflected XSS

There are two main types of XSS: reflected and stored. Let’s see how each one of them works, starting with reflected.

The victim starts an interaction on a website. The attacker sends an e-mail to the victim, which contains a URL with a malicious script. The victim then clicks on that URL and unintentionally sends a malicious request to the vulnerable web server, which responds with a reflection of that to the web browser that sent the original request. Finally, that web browser is used to execute the code, interacting with the target web server, as it assumes this is a valid script provided by that server. Figure 9-23 illustrates how this works.

Figure 9-23  Reflected XSS attack steps

Use DVWA to test another example of reflected XSS. After logging in, select XSS Reflected from the options on the left. Begin by providing your name to see what the web application actually does. Providing Nick just displays a message stating Hello Nick. Earlier you used a script that generated a pop-up window displaying a message. Figure 9-24 shows how you can use DVWA to extract the cookie value using the following script:

Figure 9-24  XSS script to get cookie value

<script>alert(document.cookie)

The result of that attempt is shown in Figure 9-25, where the cookie’s value is displayed.

Figure 9-25  Cookie value displayed using XSS

Another way is to manually inject that value in the URL, replacing Nick with the XSS script:

Original string

http://172.16.197.136/dvwa/vulnerabilities/xss_r/?name=Nick#

Altered string (containing script)

This will again result in the cookie value being displayed on the victim’s machine. However, in a more realistic scenario, an attacker would send a phishing e-mail to the victim containing a URL that allows the theft of a cookie (without displaying a pop-window).

Look at the following example that could be used to extract a victim’s cookie and could easily be sent via e-mail:

That victim browses to http://vulnerable-domain.com (note that this is a website susceptible to XSS) using a script named name.php. That PHP script uses the parameter depicted earlier, which contains an XSS script, which is reflected to the victim’s browser, where it runs. As it runs in that browser, a document is retrieved from the malicious domain owned (or controlled) by the attacker, providing the current cookie value over the page.php script.

Stored XSS

The difference between a reflected and a stored XSS attack is that during a stored XSS attack, the attacker will store the script to the vulnerable website, which will be used to reflect it back to a victim’s browser at some later point in time. That’s because the attacker manages to find a vulnerable element that can store his script (like a file or message board entry) and that will only be passed to a victim when accessing that particular element or location of the website. Figure 9-26 shows an example of a stored XSS attack.

Figure 9-26  Stored XSS attack steps

EXAM TIP   As you can see, there’s no set time frame on this because someone can access that element in a few hours or even years after it’s been created. As such, this will not have the immediate effect of a reflected XSS attack.

Most of the attack steps are the same as with a reflected XSS attack, but the major difference is that here the attacker manages to store a malicious script to one of the website’s elements so it can be reflected to a victim’s web browser later on. You can test this concept in DVWA’s XSS Stored option. That uses a message board that visitors can use to leave comments. Try entering some text in the name field and in the message field; enter the XSS script you used before:

Figure 9-27 shows this code being entered, and Figure 9-28 shows the resulting pop-up window.

Figure 9-27  XSS script being entered

Figure 9-28  Stored XSS pop-up window

Now try navigating to another DVWA section and then come back to XSS Stored. As you can see, the same pop-up appears each time you access that part of the website. That’s because the previous XSS script has been added to that part of the website, so any victim browsing to that web page will have that script reflected on their browser.

EXAM TIP   Attackers will try to access any type of web page that’s susceptible to XSS. That means if your router, firewall, or other devices are accessible via a web page, you need to ensure that they are adequately protected against these attacks. In fact, be very cautious about what type of devices are accessible via a web browser, as that’s what XSS attacks use.

Defending Against XSS

The goal is not to allow an unsafe script to run within your browser. Similar to SQL injection defenses, input validation and WAFs (like ModSecurity) help defend against XSS attacks. Try to identify any dangerous characters that might be used to signify scripts at the web server level (like <, >, ;, *, and %) and block them, creating a blacklist of such characters. Remember to test passing any such characters to your web applications and see if this works or not. Since attackers often use simple encoding schemes (like hex or UTF), remember to also include those in your requests and test how your web applications cope.

If you prefer following a whitelist approach, allow only specific characters that you expect your web server will be using and don’t allow anything else.

Ensure you are adequately monitoring your web servers for any type of XSS attacks. Perform tests using the earlier-mentioned techniques and see what types of entries are generated in your logs. Use those to set up alerting in your SIEM or any other monitoring tools so you get promptly notified of any suspicious attempts.

EXAM TIP   Remember that when trying to protect against SQL injection and XSS attacks, it’s important for filtering to take place at the server side because an attacker can easily use an interception proxy to bypass any client-side filtering you apply.

Modern web browsers allow you to configure them to block unsafe scripts (or even all types of scripts unless you allow some for specific websites).

Developers can use security headers (XSS-protection) and functions for data escaping and sanitization so no unsafe scripts are reflected from a web application back to the web browser.

CSRF (Cross-Site Request Forgery)

A CSRF attack aims at leveraging static content (usually made available on a third-party website that the attacker has access to and that the victim can also access) to make the victim’s browser perform an action on the user’s behalf without his knowledge or consent. One of the most common targets is a victim’s banking website, since that offers direct monetary gain to the attacker. The steps of such an attack can be similar to the following:

1.  Jodie logs into her bank account at mymostamazinbank.com to check if her monthly salary has been deposited

2.  The attacker posts a new picture on iloverockclimbingandtheoutdoors.com. The picture contains CSRF code, as the attacker aims to perform a transaction allowing a transfer of funds to his account. An example of such code is

Note that this CSRF attack is specifically addressed to mymostamazinbank.com, which the attacker has found to be vulnerable to CSRF and made it one of his targets.

3.  Jodie loves rock climbing, so she browses to iloverockclimbingandtheoutdoors.com and accesses the attacker’s picture.

4.  Once Jodie accesses that picture, the earlier web request is sent from her browser. Since Jodie is already logged in to mymostamazinbank.com, her session cookie is used to accompany that request. The bank thinks this is totally legitimate and has no reason to suspect anything suspicious is taking place.

5.  An amount of $20,000 is transferred to account 192836109732, which the attacker owns.

If the attack is performed properly, the victim doesn’t even realize anything has happened in the background. You can use DVWA to test this concept by selecting its CSRF option. Figure 9-29 shows how to access and inspect that web page’s source code (the related menu is displayed by right-clicking anywhere in the web page).

Figure 9-29  Accessing the CSRF web page’s source code

The crucial part of the code that allows you to change the password is the following:

Copy and save it in a text file named csrf-attack.html. Two things need to be changed for a successful CSRF attack against DVWA:

•   Replace the password with your desired value.

•   Designate the destination URL where the request will be sent to.

Edit csrf-attack.html and modify the following lines:

Once these changes have been made, just use Firefox to open csrf-attack.html.

TIP   Remember that for the CSRF attack to work, you have to be logged in to DVWA.

Figure 9-30 shows how the csrf-attack.html web page looks before the attack is executed. There are two tabs open: the csrf-attack.html webpage and the existing session to DVWA.

Figure 9-30  csrf-attack.html webpage

After the web page is loaded, click Change and review the result, seen in Figure 9-31.

Figure 9-31  CSRF attack resulting in password change

As you can see, the password has successfully been changed to the new value that was provided. Depending on the underlying commands being run, an attacker can perform anything from cookie theft, to account impersonation, to financial theft, or any other activity that a victim would be likely to perform on the vulnerable target website via their web browser.

Defending Against CSRF

Using specialized anti-CSRF tokens is a good way to thwart CSRF attacks. Those are random strings of characters that are used to distinguish a valid user session and accompany each web request being sent to the web server so the identity of a legitimate request can be verified. Note that the anti-CSRF algorithm in use should be complicated enough to not allow an attacker to generate any predictable values.

Customizing request headers or using HTTP standard headers (like the origin and referrer headers) is another way of protecting against CSRF, as it allows you to identify the source and target origin.

Performing web application vulnerability tests will provide insight as to which fields might be susceptible to this type of attack. Developers can then go back and amend the vulnerable code accordingly.

Nikto

Nikto (https://gitlab.com/kalilinux/packages/nikto) is a great tool for identifying web application vulnerabilities. The full manual is located at https://cirt.net/nikto2-docs. It can perform all sorts of tasks like identifying server and software misconfigurations, insecure files, outdated plugins and technologies in use, and even perform target reconnaissance and full scans. Run a test from Kali and see what vulnerabilities the tool identifies in Metasploitable. An abbreviated output is provided here:

From a quick look, an outdated Apache version seems to be running on that machine. The first thing that an attacker would do is search online for any published exploits that take advantage of that. Nikto also states there’s a PHP administrator web page located at http://172.16.197.136/phpMyAdmin. You might think you already know that by now. But consider what would happen if this was a scan on a publicly facing machine. That means anyone from the outside world would have access to the administrator panel login page and could brute-force an account’s password. Dangerous stuff.

Finally, take a look at http://172.16.197.136/phpinfo.php. Look at how much detail is disclosed in that web page. Examples include

As you can see, one simple scan may be enough to point you in exactly the right direction. Depending on what that scan finds, you might get a lot of confidential information, including a way to access the target system.

Jikto is a similar type of tool but focuses on XSS vulnerabilities. It’s able to run in any JavaScript-enabled browser and aims to initially exploit XSS vulnerabilities to run on the browser and then identify additional XSS vulnerable targets and present them to the attacker. Wikto is a Windows-friendly version of Nikto (https://github.com/sensepost/wikto).

WPScan

WPScan (https://wpscan.org) is a vulnerability scanner for WordPress websites. It’s really amazing, and since WordPress is one of the most commercially available technologies for most websites, there’s a really big attack surface. A scan of one of my websites shows some very interesting results. Note that I have replaced its name with “example.com”:

Among other things, it seems that WPScan identified

•   My nginx engine

•   Some administrational web pages of interest, which are used to manage the website (in general, the default WordPress administration web page is https://example.com/wp-admin)

•   Two outdated plugins

There are some other goodies, but I would prompt you to install WordPress on your local VM and try running a few scans while tweaking the website settings to see what WPScan can identify. Another solution is to purchase a domain that you can use as a testing website (which is exactly what I have done), or if you own any actual WordPress websites, you can scan those and assess their security posture.

Chapter Review

Even if a target system is efficiently hardened and only has required services running (like a web server only having HTTP and HTTPS ports open), an attacker may still leverage web application attacks to compromise it.

Tools like Nikto, WPScan (if the target is a WordPress website), or other web application vulnerability assessment tools can be used to identify vulnerabilities. In addition, interception proxies (like ZAP or Burp Suite) can be used to manipulate web browser requests before they are sent to web servers, which is why any input validation is recommended to take place at the server side so an attacker can’t bypass it.

The attacker’s common starting points are the various vulnerabilities mentioned in detail in OWASP’s top ten application vulnerabilities list. That’s where developers should also start and ensure that all their applications are sufficiently protected against those before actually being released in production.

Examples of application attacks include using

•   Command injection to allow the attacker to execute arbitrary commands on the web server

•   SQL injection to view/modify sensitive data stored in an SQL database running at the back end of a web server

•   Account harvesting to identify live accounts that can later be compromised via brute-force or phishing attacks

•   XSS to force the victim’s browser to execute malicious scripts

•   CSRF to embed malicious code in static content, which a victim will try to access

Various defenses exist to protect against these attacks, including using WAFs, performing adequate input validation and sanitization (including character whitelists and blacklists), keeping systems and applications patched and updated, monitoring system logs for suspicious activities, and regularly testing your systems (implementing appropriate vulnerability management programs) to identify issues before an attacker takes advantage of them.

Questions

1.  Which of the following is not a part of OWASP’s top ten application vulnerabilities list?

A.  Broken authentication

B.  Security misconfiguration

C.  Using default passwords

D.  XSS

2.  Based on the following illustration, what is most likely the attacker’s goal?

A.  SQL injection attempt

B.  Command injection

C.  CSRF attack

D.  DNS lookup on mheducation.com

3.  What is the attacker most probably trying to perform, according to the following command output?

A.  Account harvesting

B.  SQL injection

C.  Brute-force attack

D.  Verify the existence of particular users

4.  Which of the following wouldn’t be useful when attempting to identify valid accounts on a target system?

A.  Using Burp Suite

B.  Having a file containing various passwords

C.  Inspecting response length

D.  Reviewing response time

5.  Which of the following should be avoided if you’re trying to protect against account harvesting?

A.  Implementing 2FA

B.  Implementing CAPTCHA

C.  Enforcing account lockout

D.  Detailed error messages

6.  Which of the following will result in a successful SQL injection attack when MySQL is being used in the back end?

A.  Jane' OR 1=1

B.  'OR 1=1

C.  Jane' OR 1=1#

D.  Jane OR '1'=1hjkhjk

7.  Which of the following would provide an attacker a list of the tables contained in an SQL database?

A.  ' or 1=1 union select null, table_name from information_schema.tables#

B.  Tron' ORDER BY 6#

C.  SELECT * FROM test.tables

D.  Jack' or 1=1#

8.  Which of the following would you use to test a website for SQL injection?

A.  Form fields

B.  URL parameters

C.  Burp Suite

D.  All of the above

9.  Which of the following would you use to check if a website is vulnerable to XSS attacks?

A.  ‘Nick

B.  <script> alert ("XSS");</script>

C.  <img src="http://example.com/a98266132"> </script>

D.  <script alert (XSS);</script>

10.  An attacker is targeting a WordPress website and wants to quickly identify vulnerabilities that can be used to gain access. Which of the following tools would be most suitable for that purpose?

A.  Nikto

B.  Jikto

C.  WPScan

D.  ZAP

11.  Which of the following would be a suitable defense to protect your web server against XSS attacks?

A.  Disabling HTTP and HTTPS services

B.  Using nonstandard ports to run HTTP and HTTPS services

C.  Implementing MFA

D.  Using ModSecurity

12.  Review this output:

Which statement is most accurate?

A.  There’s an HTTPS server running on the target.

B.  A web server is running on a nonstandard port.

C.  The server is externally facing.

D.  A firewall is present.

13.  Jamie is using a web browser to access his corporate e-mail account. An attacker has placed malicious code in an iframe, which Jamie just accessed. He now seems to have been logged out of his account. What is the most likely reason for that?

A.  Session timed out

B.  Cookie expired

C.  CSRF attack

D.  Account harvesting

14.  Which of the following vulnerabilities does Jikto take advantage of?

A.  XSS

B.  SQL injection

C.  Command injection

D.  WordPress default configuration

Answers

1.  C. Using default passwords is not one of the items on the OWASP top ten application vulnerabilities list. However, it would fall under security misconfiguration, which, of course, is present in that list.

Remember to read questions very carefully before answering. It’s still a fairly straightforward question, but the way it’s formatted might confuse someone into answering incorrectly.

2.  B. The attacker is attempting to display the contents of the web server’s current directory and is appending the related command (ls) to a legitimate DNS lookup request to accomplish that. If the server in question is vulnerable to command injection, ls will be executed and provide the current directory’s contents.

3.  A. Although sqlmap is being used (which is a common SQL injection tool), the output indicates the attacker is using it to obtain valid system accounts. That’s only possible if an SQL injection vulnerability is present. However, the question is asking “what is the attacker most probably trying to perform,” and that’s account harvesting (which is possible due to the SQL vulnerability being present). Note that the attacker wouldn’t need to verify the existence of any accounts, since he can use the tool to extract those directly from the database.

4.  B. Having a file with passwords will only be useful during a password-related attack, like a dictionary or brute-force attack attempting to identify a working password. When attempting to identify valid accounts, there won’t be any attempt to log in to them, but rather just attempts to verify if those accounts exist on the system or not.

5.  D. Providing too much detail in error messages might indicate the existence of valid accounts to an attacker. For example, if an attacker inputs a username of John and the application responds with an error message stating “Sorry, username John is already in use. Please select another username,” it provides a clear message of an existing username to the attacker.

6.  C. Remember that each input a user provides is then enclosed in single quote marks. The best way to test this is to get each of the queries provided as options in this question, enclose them in single quote marks, and see which one would work. Using Jane' OR 1=1# would actually become 'Jane' OR 1=1#'. As you can see, the use of a single quote mark after Jane causes SQL to consider it the first parameter of a logical OR operation. The second parameter of that is 1=1, while everything else will be ignored, since a # is placed to indicate a comment. Since 1=1 is true, this query results in extracting all records of that SQL table.

The easiest way for you to answer this question is to test it in Mutillidae. However, you won’t have that option during the exam. As such, you need to get comfortable with how SQL injection works. To that end, it’s recommended to test manual SQL injection in Mutillidae as much as possible, so you get comfortable with its operation.

7.  A. SQL’s information_schema.tables stores a list of all the tables contained in the database. Column table_name contains all those names. As such, submitting this SQL injection query will result in extracting them.

8.  D. To effectively test for SQL injection vulnerabilities, you can use any item that allows input to be provided to the web server, like forms and URL parameters. Burp Suite can assist you to do that or just be configured to scan for SQL injection vulnerabilities altogether.

Be careful when choosing “All of the above” as an answer, as you need to be completely sure that all of those items are correct. If you have doubts about even one of them, this might not be the correct answer.

9.  B. Using <script> alert ("XSS");</script> can be used to display a pop-up box containing the message XSS, which would indicate the website is susceptible to XSS attacks.

10.  C. WPScan would be the best option, as it’s a vulnerability scanner specifically written for WordPress websites.

11.  D. ModSecurity is an open-source web application firewall that can help protect your web server against various web application attacks, including XSS.

12.  B. The scan mentions port 5145, which has been identified as running an Apache server (as per the results). That means there’s a web server running on port 5145, which isn’t the standard port 80 (note that there isn’t enough information to understand if HTTPS is running on the server).

13.  C. It seems that the attacker embedded malicious code in the iframe, which resulted in changing Jamie’s password, thus logging him out of his account. A session timeout or cookie expiration could also technically be possible, but it’s highly unlikely any of those would happen at the exact same time of the user accessing that iframe.

14.  A. Jikto exploits XSS vulnerabilities to run on a victim’s web browser and is able to identify additional XSS-vulnerable targets and present them to the attacker.

References and Further Reading