Fatskills
Practice. Master. Repeat.
Study Guide: CompTIA PenTest+ Certification: Basics of Web and Database Attacks
Source: https://www.fatskills.com/comptia-pentest-certification/chapter/comptia-pentest-certification-basics-of-web-and-database-attacks

CompTIA PenTest+ Certification: Basics of Web and Database Attacks

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~47 min read

Key topics:
- OWASP Top Ten - Injection Attacks
- Command Injection
- SQL Injection
- LDAP Injection
- Cross-Site Scripting
- Cross-Site Request Forgery
- Attacking Authentication and Session Management
- Brute-Force Login Pages
- Session Management Testing
- Data Exposure and Insecure Configuration
- Weak Access Controls
- Exposing Sensitive Data
- Directory and Path Traversals
- Sensitive Data Exposure
- Inclusion Attacks
- Race Conditions

- The OWASP Top Ten
- Research attack vectors for application-based attacks
- Various types of application-based attacks
- Complete various exercises to understand web testing tool behavior

During a pentest, you likely will come across some type of application or database server that will be in your list of authorized targets. When you identify these targets, you’ll need to know how to identify the best attack vector, tools, and attacks to use. But you’ll also need to know what mitigations work best. Remember, your value as a pentester is to help make security better with usable and effective report recommendations.

OWASP Top Ten
One of the resources OWASP provides is the OWASP Top Ten. In this guide, we’ll go into more depth about many of these attacks and remind you that being able to identify these attacks and the most appropriate mitigations may be important to your efforts during the exam. The OWASP Top Ten provides community awareness of the most serious web application security risks for a broad array of organizations. The data is compiled statistically from various firms that specialize in application security. Primarily, this list is put together to help organizations understand the importance of securing web services and the effects certain weaknesses can have on an organization.

Injection Attacks
Injection attacks are typically found where there are insecure user-controlled values. Examples are forms and parameters in the uniform resource identifier (URI). When testing, you should inspect application parameters for possible injection points that may not be validated by the web application—either through client-side code (JavaScript) or using server-side code, like PHP.
As an example of client-side code, Hypertext Markup Language (HTML) form validation can be handled through JavaScript, where data entered into user-input fields (e.g., Name, E-mail, Address, etc.) can be processed through a JavaScript function when the user clicks on the Submit button. If the input field contains invalid data, the form page will not be submitted. However, this process is on the client side, and input can be manipulated by the user to bypass this type of inspection.
Server-side code can provide an additional layer of protection by using similar validation rules to ensure data is validated and properly sanitized (i.e., removing invalid characters) during postprocessing. However, both may be vulnerable to injection attacks if the user-controlled input is improperly secured. In this section, we will dive deeper into different kinds of injection attacks.

Tip: Be able to recognize the types of injection and understand the appropriate remediation for each.

Command Injection
First, let’s talk about command injection attacks. Specifically, let’s talk about how they work, how we can leverage Metasploit to help build custom payloads using msfvenom, and how we can use those payloads with a multi/handler in order to generate a Meterpreter session. If we have a Meterpreter session, we can attempt to escalate privileges and to pivot further into the target organization’s network.

Note: : For these exercises, we downloaded the ISO disk image from the “Web for Pentester” exercise from the Pentester Lab website.

For this exercise we assume you have a working, updated copy of Kali Linux and some type of virtualization software (e.g., VMware Workstation, VMware Player, Oracle VirtualBox, etc.) to host the ISO disk image.
1.: Once you power on the VM, open your web browser and navigate to the home page located at http://<vulnerable vm ip>.
2.: Given the following vulnerable web parameter ip=, we can test various command injection attacks, the first being what type of operating system and architecture the web application is hosted on. Here’s an example output when appending uname -a in the vulnerable parameter.

We’re looking for signs of what this calls in the background. So, look at the response as well as what displays.



 

3.: Now that we know the architecture is x86 and the host OS is Linux (Debian), let’s create an exploit using msfvenom to generate a reverse Meterpreter shell payload that we can receive a callback from, using the Metasploit multi/handler. First, let’s generate the exploit called “cmd” with msfvenom, using a reverse Meterpreter payload for the x86 Linux architecture to connect back to your IP address and local port (4444/tcp):



 

4.: Then use Python to host a web server on port 80, using the SimpleHTTPServer module in the same directory where the “cmd” exploit is located:
# python3 -m SimpleHTTPServer 80
5.: In another terminal window on your Kali box, launch msfconsole and type the following commands at the msf> prompt:



 

6.: Now, let’s string together a series of commands to get our target to download the exploit, add an execution bit to the exploit, and then execute it so we can get a reverse shell. From your web browser, append the following command syntax to the ip= parameter and then execute the HTTP GET request:



 

7.: The web server should execute the wget first to download the “cmd” exploit from your Python SimpleHTTPServer, then append the execution bit using chmod, then execute the exploit; in return you should see a Meterpreter session spawn from within Metasploit, as shown in the example here:




Note: : For more practice, Portswigger has some additional exercises here: https://portswigger.net/web-security/os-command-injection
 

Recognizing Command Injection
Command injection often involves abuse of application programming interface (API) functions with names like exec, eval, cmd, or system. Anything that references a process (like os.popen in Python or proc_open in PHP) may also warrant close attention. Often, you’ll see these as .cgi files, .pl files, or .sh files or see parameters after a ? in a URI. Look for OS commands like whoami, ls, dir, and others in examples.

Following is a simple example.
URI before attack:
http://vulnerable-site/shopping?id=3856&name=AndersonPeachCobbler
URI after attack:
http://vulnerable-site/shopping?id=1|ls&name=AndersonPeachCobbler

This lists the contents of the current directory. Read more about testing for command injection in OWASP’s Web Security Testing Guide under the section Testing for Command Injection: https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/12-Testing_for_Command_Injection.

Remediation:
1.: Avoid having the application call commands directly in the OS.
2.: Use programming options to escape the command for the underlying OS before sending the command.
3.: Parameterize and perform input validation by using an allowlist for characters (potentially problematic characters include |, &, ;, >, <, !, , and \).
4.: Run applications at the lowest possible privilege.
Read more about remediation and mitigation in the OWASP OS Command Injection Defense Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html.

SQL Injection
In order to test for SQLi, you need to have some level of understanding of the commands and syntax used to carry out operations on a database. Structured Query Language (SQL) is used to manage data within remote database management systems (RDMSs). There is an online reference at www.sql-workbench.net/dbms_comparison.html that provides a comparison of common SQL features that can be used in SQL statements across different RDMSs.

Note: : Within this guide, we will be discussing and utilizing SQL command syntax relevant for the MySQL RDMS.

Common SQL terms you should be familiar with are shown below.



Table:   Common MySQL Commands

Finding Injections
To evaluate if a parameter is injectable, like the id= field, you may need to try a series of injection criteria to elicit an error from the database.

Parameters containing string values will look similar to the following in a web GET or POST request:
http://example.com/test.php?name=John%20Smith

In this case, %20 is URL encoding for white space. URLs processed by a web server or application cannot include spaces. Thus, URL encoding helps replace potentially harmful ASCII values with a % and two hexadecimal digits. Integer values will typically look similar to the following in a web GET or POST request: http://example.com/test.php?id=1

Tip: You can learn more about URL encoding and other web concepts such as HTML, CSS, and JavaScript at www.w3schools.com.

The following example PHP code shows how the HTTP GET request for the "id=" value might be processed on the server:


The mysql_query() function in the PHP code will build a query against the my.store table and return all selected data where the ID field matches the .jpg" width="400px"> request. The mysql_fetch_assoc() function will return the resulting array of values produced from the query.

Error-Based SQL Injection
When the database returns information about the programmed query structure in an error message or application response, attackers can use the information returned to craft an attack against the program’s logic.

Here’s an example of an error-based result:




Blind SQL Injection
In the case where the web server presents a generic error such as, “Sorry, your search criteria is incorrect,” the parameter may still be vulnerable, but you have an invalid query and need to troubleshoot it. In order to troubleshoot the query, you could use what is called blind SQLi, which is another way to exfiltrate data from a database when you can’t see the database output. Two common methods you can use to exploit blind SQLi are Boolean-based and time-based. Boolean-based SQLi is where you ask the database true (e.g., id=1 AND 1=1) or false (e.g., id=1 AND 1=2) questions and determine the answer based on the response  given by the application, where the response could be a content error or a blank page.

Time-based SQLi relies on the database pausing (or sleeping) for a given amount of time, then returning the results, indicating that the SQL query executed successfully.

For instance, executing a time-based SQLi against the mysql_query() from the example PHP code might look something like this:
http://example.com/test.php?id=1 and sleep(5)--

If the id= parameter is susceptible to blind SQLi, there will be a five-second delay in the web page loading. From this point, you could continue to use blind SQLi to enumerate valid characters that make up the database name, table names, and possibly passwords/hashes from the mysql.user table, depending on the permissions given to the database user executing the queries.

This is a type of linear search, where each value is evaluated until you find the correct character:
- If the first letter of the database name is an “a,” wait for five seconds.
- If the first letter of the database name is a “b,” wait for five seconds.

A binary search is another method that can help speed up blind SQLi attacks, where the position of a target value can be identified from within a sorted array. How this works is the binary search would determine the middle element of the array and compare it to the target value (the array would be all of the characters that make up the ASCII table). If the middle element matches, it is returned. However, if the value is greater than the middle element position, the lower half of the array is discarded from the search and only the remaining upper half is used within the search criteria. The “Faster Blind MySQL Injection Using Bit Shifting” paper on the Exploit Database website (https://www.exploit-db.com/papers/17073) provides examples of how to optimize binary search during blind SQLi attacks.

Blind SQLi is time consuming, but very possible. Follow along with an exercise as we demonstrate how to use sqlmap to test and evaluate web parameters for SQLi vulnerabilities in the My Awesome Photoblog PHP web application.

Note: : This example assumes you have downloaded the ISO disk image from the “From SQL Injection to Shell” exercise from the Pentester Lab website.  (see the appendix for details). For this exercise we assume you have a working, updated copy of Kali Linux and some type of virtualization software (e.g., VMware Workstation, VMware Player, Oracle VirtualBox, etc.) to host the ISO disk image.
 

1.: Once the vulnerable VM is up and running in your testing environment, navigate to the web page hosted by the VM: http://<ip address>.
2.: If you click on Test from the menu bar, you will be taken to another page that renders additional images posted to the blog page. The URL is populated with the following:
http://<ip address>/cat.php?id=1
3.: Let’s go ahead and test the id= parameter by inserting a single quote (')behind the number in the id field, as follows: “?id=1'”. After submitting the URL back to the web application, you should receive the MySQL 1064 error we discussed previously.
4.: Now that we know the database is processing our request and the application is not validating the input and filtering out special characters from the request, we can test the parameter with sqlmap. From the command line in Kali Linux, execute the following:
# sqlmap -u "http://<ip address>/cat.php?id=1"
The sqlmap command should identify the database as MySQL and will ask if it should skip the payload testing for other RDMSs. Type Y and press enter. Then type Y again to include all tests for MySQL and type N when asked to keep testing other parameters.

Note: : sqlmap will output the results (log, target.txt, and session.sqlite) under your user home directory (/root if using Kali) in .sqlmap/output/<ip address>.
5.: If we investigate the log file, we will see that the id parameter was evaluated with an HTTP GET request and was found to have multiple injection types, including
- Boolean-based blind
- Error-based
- AND/OR time-based blind

The following illustration shows the injection types along with each payload that was tested with sqlmap to demonstrate that injection was possible.



 

6.: The next step is to use sqlmap to exploit the SQLi vulnerabilities in order to read arbitrary data from the database. If you notice the PHP web application menu bar, there is an Admin login page. Let’s see if we can extract the users and possibly hashes from the database in order to compromise login access. Since this is a lab environment, let’s run the same sqlmap command we used in Step 4, but append “-a” to the command syntax and let sqlmap execute anything and everything against the MySQL database, using the privileges of the database user we are executing the queries as. You will see that sqlmap was able to extract the user and hash from the “users” table of the “photoblog” database. It was also nice enough to ask if we wanted to use a wordlist to crack the MD5 hash. You can just press ENTER to continue with the defaults. In a minute or two, SQL map should be able to crack the hash using its default wordlist.



 

7.: The sqlmap results are again stored in /root/.sqlmap/output/<ip address> to include a new directory called dump that has subdirectories for each database sqlmap could discover and enumerate information from. The dump/photoblog/users.csv file contains the username and password to use for logging into the Admin page. Here’s a successful login to the Admin page for the Photoblog application:




Tip: Instead of capturing everything with sqlmap using the -a option, you could strategically investigate what you are looking for by using --tables to look for all of the tables from the current database the application is querying from for the .jpg" width="400px"> HTTP parameter.

Then you could use --sql-query=”select * from photoblog.users” and return each record from the Users table. Then take the MD5 hash retrieved from sqlmap and pass it to a wordlist, using rules, with John the Ripper (JtR): # john --format=Raw-MD5 –-rules --wordlist=rockyou.txt <hash file>

On a separate note, testing everything with sqlmap using the –a option could be dangerous. Running simultaneous queries could inadvertently crash the database during testing if the database is already operating at full capacity. It is good practice to monitor the health and status of the database/web server after executing queries that could leave the database hanging, such as in the case with time-based attacks. SQL injection attacks and the use of sqlmap during the engagement should bear further discussion with the client when operating in a production environment to ensure the customer understands the potential risks imposed by the use of automated SQL injection testing tools.

Union Query SQL Injection
This type of injection builds two or more SELECT() statements that already exist within the application to create a single result in the application response. This is often useful in getting information from parts of the database that are not designed to be exposed to part of the application that allows user interaction.

To perform a successful UNION attack, both queries must return the same number of columns and the data types in each column have to match.
You can figure out the number of columns using “ORDER BY” until you get an error back from the database. It will usually say something about the parameter being out of range. Here’s an example of input:


And the error:


Another way is to use NULLs in a UNION SELECT statement until you have enough to match the queries and the error condition stops. Here’s an example of input:


This method is popular because you can also use it to figure out the data types of each column by trying a different value to NULL in each column:


An error will indicate when the type does not match a particular column, allowing you to figure out the right one for your attack. You can read more about these at https://portswigger.net/web-security/sql-injection/union-attacks.

Stacked Queries SQL Injection
This injection works by terminating the original query and executing another query, such as selecting all of the records from the mysql.users table.

An example would be http://example.com/test.php?id=1;select%20*%20from%20mysql.users--.

Other practice websites that you can use to sharpen your SQLi skills are
- https://portswigger.net/web-security/sql-injection
- https://hack.me/t/SQLi
- www.gameofhacks.com/
- https://sqlzoo.net/
- Pentester Lab (https://pentesterlab.com) provides free labs and exercises that you can use to demonstrate your pentesting skills, including SQLi.
 

Recognizing SQL Injection
SQL injection often involves use of terms specific to the query language. Terms like INSERT, SELECT, JOIN, UNION, WHERE, LIMIT, AND, OR, and error messages mentioning SQL are a dead giveaway. Examples often involve creative use of quotes (single or double). Following is a simple example.

URI after attack:
http://vulnerable-site/shopping?id=10 UNION SELECT 1,null,null--

This might list all of the IDs in the table. Read more about testing for SQL injection in OWASP’s Web Security Testing Guide under the section Testing for SQL Injection: https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/05-Testing_for_SQL_Injection.

Remediation:
1.: Parameterize queries and perform input validation by using an allowlist for characters.
2.: Use stored procedures.
3.: Escape all user input.

Read more about remediation and mitigation in the OWASP OS Command Injection Defense Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html.

LDAP Injection
Applications may pass authentication data or queries for data into back-end Lightweight Directory Access Protocol (LDAP) systems. Much as with SQL injection, if you can figure out enough information about the query being used or the data format being sent, you can abuse unsanitized, user-controlled input to modify the LDAP queries. Also like with SQL injection, LDAP injection may be aided by errors or conducted blindly based on application behavior.

The LDAP specification is defined by RFC 4515 (https://tools.ietf.org/html/rfc4515) and basically says that LDAP filters are constructed from key-value pairs in parentheses, chained together in any number. LDAP also recognizes wildcards as *, logical AND as &, Boolean NOT as !, approximately as ~=, and greater than as >=.

As an example, this query would match all entries using a logical OR (that’s the | symbol), where the common name (cn) matches anything starting with Antoine or Blanca, or ending in the string ‘inski’:
(&(|(cn=Antoine*)(cn=Blanca*)(cn=*inski))

Careful application of logic can use knowledge of the application’s behavior to guess the LDAP filter syntax and can use this to bypass authentication or get other information in the directory (such as a list of users or other resources) as examples.

Common injections may attempt to truncate an LDAP filter by supplying )(&) after valid input in order to attempt to bypass authentication, or using wildcards in parameters that are passed to the filter to cause an error condition that returns more values than expected.
 

Recognizing LDAP Injection
LDAP injection often involves an ou (organizational unit), cn (common name), or dc (domain component). Look for the key-value pairs, such as ou=computers or cn=Lindsey, in injected filters using the parentheses and comparison characters LDAP uses.
http://vulnerable-site/ldapsearch?user= *)(uid=*))(|(uid=*

This lists the contents of the current directory. Read more about LDAP injection in the OWASP Web Security Testing Guide under Testing for LDAP Injection: https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/06-Testing_for_LDAP_Injection.
 

1.: Escape all variables using LDAP encoding functions.
2.: Use language-specific built-in safe frameworks for interacting with LDAP.
3.: Run applications at the lowest possible privilege.

Read more about remediation and mitigation in the OWASP LDAP Injection Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html.

Cross-Site Scripting
In most of this guide, we have discussed attacks that are exploited on the server side. However, the client is just as easily a target when it comes to web-based attacks. The server content (e.g., HTML and JavaScript) could have flaws that could be exploited within the victim’s web browser or the browser plugin. The source code is always available, since it’s executed on the client side.

Cross-site scripting (XSS) is one such example. With XSS, attackers can inject client-side scripts or HTML code into other web pages to steal information or bypass authentication. This vulnerability is due to a lack of input inspection on the server side.

There are three kinds of XSS vulnerabilities:

- Reflected  Injecting code within a single HTTP response. Here’s an example of a successful reflected XSS execution:


Example:
index.php?page=<script>alert('Reflected XSS')</script>

- Stored  Injecting code in a log file to steal and redirect a session token, which is later accessed through a web interface by an administrative user:


- DOM-based  The Document Object Model (DOM) is passed down to the browser from the application during runtime and is used for structuring content. Unlike stored or reflected XSS attacks that get passed back to the server, the execution happens directly in the user’s browser, since not every object is treated as a query by the browser. This can make the detection process even more difficult if the logging only occurs on the client. Given the following example of a DOM object passed to the client’s browser:


everything passed after the “#” in the URL will be executed in the web browser:
http://example.com/xss/example9.php#message

Simply passing the URL:
http://example.com/xss/example9.php#<script>alert("DOM XSS")</script>
to a victim willing to click on the link would allow an alert box to appear, much like a reflected XSS attack.

Tip: Some web browsers have built-in content filters to prevent this type of an attack from occurring. NoScript (https://noscript.net) is a browser extension for Mozilla-based browsers that can help block unwanted scripts from executing in your browser and limit execution to only trusted websites.

For more exercises, take a look at the labs at https://portswigger.net/web-security/cross-site-scripting/stored.
 

Recognizing XSS
Cross-site scripting examples will often (but not always) involve HTML tags, with symbols such as <, >, =, and quotes. These may also be URL encoded (for example, %3C, %3E, etc.). It may include references to event handlers like onclick, onload or onmouseover or calls to other JavaScript functions. Use of the <script> tag is a giveaway.
A malicious POST request including XSS:
postId=399&content=%3Cscript%3Ealert(%27XSS%27)%3B%203C%2Fscript%3E

Read more about filter evasion in the OWASP XSS Filter Evasion Cheatsheet: https://owasp.org/www-community/xss-filter-evasion-cheatsheet and more about Testing for Stored Cross-Site Scripting in the OWASP WSTG: https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/02-Testing_for_Stored_Cross_Site_Scripting.
1.: Don’t insert untrusted data into a page between script tags; in attribute names, tag names, or comments; or directly in style sheets.
2.: Do not allow the application to run JavaScript or uniform resource locators (URLs) from untrusted locations.
3.: Encode data before inserting untrusted data into script values, page element contents, style property values, or URL parameters.
4.: Use libraries that implement an allowlist approach to sanitize input values and avoid the use of unsafe characters such as <, >, %, *, +, -, /, ;, =, |, and +.

Read more about remediation and mitigation in the OWASP Cross-Site Scripting Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html

Cross-Site Request Forgery
Cross-site request forgery (CSRF) is another type of client-side injection attack that causes a user to perform an action they do not intend against a trusted website. The most dangerous form of CSRF is when the user is already authenticated with a valid session. Attack vectors can include vulnerable web pages, blogs, e-mail, etc. These attacks are typically targeted and, when successful, can result in a victim purchasing an item, transferring money, or changing a password. If the victim is an admin or has elevated privileges, the attack could target the ability to create or modify existing accounts within an application.

An example would be embedding a hidden image inside of a web post to a news group that points to a malicious request to transfer funds using the “attack” servlet. If this was a real servlet from a banking application and the victims were already logged in to their accounts, $5,000 would be transferred out of their accounts. The message would appear harmless, and the image size could be significantly reduced such that it doesn’t call as much attention to itself within the body of the message.

The figure below provides an example of this scenario where a potentially harmless message is submitted to the user group. The figure below hows an example of what happens when the message is opened.



Figure:   CSRF example scenario message



Figure:   CSRF example scenario message contents

Attacking Authentication and Session Management
In this section, we will take a closer look at three different types of authentication attacks against login forms using usernames, passwords, and authenticated session tokens. We will cover the various tools and methods a pentester can use to exploit these types of vulnerabilities. This will be a web-specific exploration of the topic.

Brute-Force Login Pages
In the web world, authentication forms are used to read and process data from user-supplied input from a web browser. Once the user has entered data in the form fields and clicked the button to submit the data, the browser executes an HTTP POST request with the body of the message to the web application for processing. When you view the HTML source code in your web browser, the HTML form will look something like this:


This form page example processes two input fields from the user: a username and password. During a pentest engagement, you are likely to come across application servers that allow users to authenticate access via username and password. These types of forms are typically the target of brute-force login attacks.

Tip: Notice in the HTML source of the example login page that the text field size limit is set to 8, which means it will only process the first eight characters in the input box. Thus, if you were to build a wordlist or password rule to brute-force the login, you only need to define the passwords or rule up to eight characters in length.

The Damn Vulnerable Web Application (DVWA) (http://dvwa.co.uk) is free software and runs as a web application that is susceptible to many common types of web-based attacks. Users can download, install, and modify the application under the terms of the GNU General Public License. We will use the DVWA as a basic example of how to brute-force a login form page. After setting up the DVWA, you can access the login page using the following URL in a web browser: http://<ipaddress>/dvwa/login.php. The login page will look similar to below.



Figure:   DVWA login page

Wordlists
CeWL is a Ruby application that spiders a given URL and returns a wordlist. Wordlists can be useful for brute-forcing directory paths or passwords, as with Hydra or John the Ripper. As an example, if we are attacking a web login form whose username and password are unknown, you could use your favorite wordlist, one in /usr/share/wordlists in Kali Linux, or use CeWL against the URL to build a custom wordlist that uses words and phrases scraped from the target web pages. The following is an example of executing CeWL from the command line in Kali Linux, which is also shown below:



Figure:   CeWL command output
# cewl -v -d 2 -m 5 -w dvwa_wordlist http://192.168.1.52/dvwa

The following command options are available:
- -v Verbose output
- -d Depth to spider to; the default is 2
- -m Minimum word length
- -w Write the output to the file

Using a Wordlist for Attack
Now, we can use the wordlist with Hydra to brute-force the login page. However, before we can use Hydra, we need to capture the POST request sent to the server for processing, as we need the correct parameters to feed into Hydra so our brute-force requests can be properly formatted. So, fire up your favorite web proxy software to intercept a fake login request to the server. (We used Burp Proxy, but OWASP ZAP, Firefox Developer Tools, Tamper Data, etc., are other tools that can be used to accomplish this task as well.) After enabling the proxy in Burp and configuring the web browser to use a Burp Proxy port, we were able to capture a login request to the server, as shown below.



Figure:   Burp Proxy login request

As you can see in the body of the POST request, username=, password=, and Login= are the three valid parameters that make up the login request. Now that we have the correct web parameters to provide Hydra, we can execute the following syntax from the command line in Kali Linux:



The example output is shown:



Figure:   Hydra command output

The command options are as follows:
- -l User to log in as.
- -P Load several passwords from a file.
- http-post-form Service module to use for the request.
- " " Module options; in this case, we use the URL and POST message body. The ^USER^ and ^PASS^ are populated with user and password command options.
- -V Verbose mode.
Based on the output from Hydra, we were successful with identifying a valid password for the admin user, using 13 possible passwords scraped from the DVWA page. The “password” text was identified when CeWL scraped the “Hint” message at the bottom of the webpage.

Session Management Testing
Web sessions are designed to accompany the user’s interaction within the web framework. A unique session identifier is generated by the web server or web application and lasts for the duration of the user’s visit. A session ID (or token) can be stored locally on the user’s hard drive as a cookie, form field, or URL. Each token is used to validate a user’s session and can be used by the application to establish access rights or user settings for each transaction during the session. These may have a time-to-live value, depending on how the web framework is configured. These types of sessions are dynamically generated numbers, which should be difficult to guess. Similar to a hashing function, the token is used to verify the integrity of the user’s request. Tokens should use random number generators rather than simply incrementing static numbers. Otherwise, the user’s sessions could fall victim to session hijacking or replay attacks.

OWASP provides a Session Management Cheat Sheet on their official website, which describes common weaknesses and best practices when configuring session management for web applications. Burp Suite Pro is a commercial software product that provides web and web application security testing capabilities. Tokens found within HTTP responses can be battle-tested for known security weaknesses, such as weak token attributes, session expirations, and token entropy (or lack thereof), using Burp Sequencer. Once you identify the position of the field where the token is located, you can start the live capture.

As shown below, once you have collected enough samples of data, Sequencer will analyze the data and provide an assessment based on the randomness of the sample at each character position and the probability the same character will be repeated at the same position.



Figure:   Evaluating session randomness with Burp

Tip: Burp Suite Pro is a common tool used for web and web application penetration testing. Many questions on the exam are related to web-based testing. You should have a firm understanding of the OWASP Top Ten 2017 Application Security, as you may see questions that reference these criteria.

Most web frameworks are designed to use session token/cookie authentication. Session-based authentication is stateful, such that the server and client both keep a record of the session. Each time the user makes a request to access data, the session data is submitted in the query and validated by the server. The Set-Cookie header (example: Set-Cookie: sessionID=ksirut8jsl219485a1f459f2siper5) is included in the server response to the client, and the cookie value is stored in the client’s browser.

Additional attributes can accompany the Set-Cookie response header to inform the client’s browser on how to handle the cookie, including:
- HTTPOnly  The cookie cannot be accessed via JavaScript, such as cookie theft through XSS attacks.
- Path  This defines the URL where the cookie is valid.
- Domain  Defines the domain where the cookie is valid (e.g., example.com).
- Expires  This tells the browser to save the cookie locally for persistent storage and that it will be used by the browser for future requests until the expiration date. If not set, the cookie is only good for the life of the browser session.
- Secure  This is used to ensure the cookie never makes its way over a nonencrypted connection, like HTTP. This helps prevent against credential theft when a malicious user is sniffing the network.

When the client makes a subsequent request to the server, the cookie value will accompany each request. In some cases, the pentester may need to reverse-engineer the cookie to determine how the cookie was generated or protected. Some web frameworks may sign or encode (i.e., base64-encoded value) the cookie to obfuscate it and prevent tampering in transit. In the case where developers use their own session IDs, if randomness and complexity are not adequately applied into the equation, the cookie value can be manipulated to identify a valid session, which means the application could be susceptible to brute-force attacks.

Now let’s demonstrate this type of attack to manipulate a cookie value to steal a legitimate session from the server. We will use the OWASP WebGoat-Legacy Project (https://github.com/WebGoat/WebGoat-Legacy) to test against the Session Management Flaws “Hijack a Session” example. The first part of the attack will collect a sufficient sample of cookies to analyze in order to determine the web framework’s cookie generation scheme. Then, we will create a valid cookie (cookie manipulation) to conduct the attack.

Once you log in using a random username and password, you are told that you used an “Invalid username or password.” However, the application provides you with another cookie called WEAKID, with a value of WEAKID=17280-1531178283601. With a little digging we are able to decipher that the first part of the cookie, 17280, is a sequential number that is incremented by one digit each time we destroy the session and attempt to log back in. The second part of the cookie appears to be a timestamp in milliseconds (per the documentation).

After logging in and out about five times, we know we are not going to be able to guess the number easily. So, we turn to Burp Sequencer, which can help generate enough cookie values to guess an existing session cookie. We intercept a login request to the application, then forward the request to Sequencer. In Sequencer, we make sure to select the Cookie option, as shown below.



Figure:   Burp Sequencer token location

Then we click the Start Live Capture button. We wait until we have a fairly large sample of tokens before we stop the capture process. Once we have over 2,000 tokens, we click the Stop button to stop the capture process, then click Save Tokens to save the tokens to a file for offline analysis. Then, we use Sequencer and click the Manual Load tab. From here, we load the tokens from the file we just saved using the Load button, as shown below.



Figure:   Manual load of sample tokens in Sequencer

Starting from the top of the list, we notice immediately that there is a gap in the numbers between 17283 and 17285. Due to this break in sequence, we are pretty sure that there is already a token issued for 17284, which is not a token we have in our list. So, we look in Burp and forward the original login session to Repeater, where we can manipulate the cookie value in order to attempt to hijack the session. After testing our suspicions with the missing token value, we find the session is valid and we are successful in hijacking an existing session, as shown in Figure 5-10, based on the response message from the server. Of course, rather than guessing a session ID, you could also intercept it using some form of on-path attack and replay it, too.



Figure:   Hijacking a session in Burp

Now that you are aware of how session hijacking works, you should be aware of a couple of best practices. First, a session should be invalidated when the user logs out. Second, web applications should assign a new session ID upon authentication. In the first case, you can use session hijacking to take over an authenticated session after the user has logged out (as long as the session has not yet expired). In the second case, you can do something called session fixation, which means you can set up the session ID with the application, send a malicious link to a user, and the application will allow that session ID to be used during the user session. If that happens, you effectively gain their authenticated access using the session ID you generated and know.

Data Exposure and Insecure Configuration
Web application servers that are improperly configured or lack good security hygiene (like patch management) are likely to be the target of attack.

Default account passwords from product vendors are typically found in open-source wordlists, and that are found in /usr/share/wordlists within Kali Linux. At the time of this writing, the CIRT password list (https://cirt.net/passwords) (CIRT are the developers of the infamous Nikto web application scanning tool) listed over 2,080 default passwords used by more than 500 different vendors.

These accounts are meant to be used for initial setup and configuration. Most of the time, the vendor will recommend disabling the account or, at a minimum, changing the default password. Apache Tomcat (http://tomcat.apache.org) is a well-known open-source product used for hosting and deploying Java-based web applications.
In earlier releases of the software, the Tomcat Manager servlet (a servlet is a Java program that extends the communication capabilities of a server, such as receiving messages and sending responses, mostly using HTTP) was used to deploy and manage these applications. Tomcat was shipped with the Manager application enabled, along with a well-known default username and password of tomcat/tomcat. These credentials have been used and abused over time to compromise organizational systems; however, to mitigate against this common threat, Apache Tomcat started releasing the default product installation with the Manager application disabled. At least out of the box, the product was a little more secure, and now with the ability to deploy it as a Software as a Service (SaaS) solution, developers and system administrators should have less to worry about with regard to installation weaknesses.

OWASP suggests that attackers will often attempt to exploit unpatched flaws/bugs or access default accounts or unused web pages, unprotected files and directories, etc., in order to obtain unauthorized access or knowledge of a system. Example attack scenarios might be default plugins or accounts/passwords being installed with the application, poor access controls that enable access to files outside of the web root (topmost directory where publicly accessible web files and directories are located), or even applications displaying detailed error messages (e.g., stack traces) that could expose the web component versions that may have known vulnerabilities. In this section, we will cover a few of these attack methods, including path traversals, exposing sensitive data, and weak access controls.

Weak Access Controls
Once a user has logged in and authenticated, the web server (or web application) should be configured to restrict the content a user has access to, based on an access control policy. Access control policies define the requirements for how access to a resource should be managed and controlled based on the rule of least privilege.

An example would be an Apache HTTP Server that restricts access to a web directory based on hostname or IP address, as some of the content on the website may not be for public consumption. In the httpd.conf file (Apache HTTP configuration file), the following restriction may be applied to allow private IP addresses to access the restricted folder on the web server, and anyone else is denied:





Tip: The Apache HTTP Server uses modules to implement certain functionality within it. Modules are an extension of a server’s capability. For instance, the mod_authz_host module can be used to control access to directories, files, and locations on the server based on IP address, while the mod_ftp module can be used to allow users to download or upload files using FTP. Apache includes many modules in its core distribution; however, it supports a lot of other ones that are not installed by default. You can check out a list of supported modules for the Apache HTTP Server at http://httpd.apache.org/modules.

If the web server was missing this level of access control, any user who browsed to a page within the /restricted folder would be able to have access to the content. Another thing to consider with Apache is that directory indexing (or directory browsing) is enabled by default. This functionality is similar to an ls command in Unix or dir command in Windows. With directory browsing enabled and a lack of access controls, an attacker would not have to rely on brute-force methods to derive web pages and/or subdirectories. Figure 5-11 shows an example directory index for the /admin directory.



Figure:   Directory index

To mitigate this, you can add an index.html in the directory you wish to disable directory browsing for (if the HTML file is blank, the attacker would see a blank page), or you can remove the Indexes option from within the Apache HTTP configuration file for the given directory or the entire website. Web access controls for controlling the display of content are just as important as controlling the unnecessary exposure of sensitive objects or information from within web applications.

Exposing Sensitive Data
An application flaw is not always a programming error, but instead a weakness in how the data or information is being protected. Certain types of information, such as passwords, credit card numbers, Social Security numbers, and health and privacy information, require certain levels of protection.

Encryption is a method that can be used to protect the confidentiality of this type of data. However, if the implementation of the protection mechanism is misconfigured or inadequate, an attack against this vulnerability could be catastrophic.

OWASP presents three attack scenarios for sensitive data exposure:
- Scenario #1  An application encrypts credit card numbers in a database using automatic database encryption. However, this data is automatically encrypted when retrieved, allowing a SQL injection flaw to retrieve credit card numbers in cleartext.
- Scenario #2  A site doesn’t use or enforce Transport Layer Security (TLS) for all pages or it supports weak encryption. An attacker monitors network traffic (e.g., at an insecure wireless network), downgrades connections from HTTPS to HTTP, intercepts requests, and steals the user’s session cookie. The attacker then replays this cookie and hijacks the user’s (authenticated) session, accessing or modifying the user’s private data, or instead the attacker could alter all transported data (e.g., the recipient of a money transfer).
- Scenario #3  The password database uses unsalted or simple hashes to store everyone’s passwords. A file upload flaw allows an attacker to retrieve the password database. All the unsalted hashes can be exposed with a rainbow table of precalculated hashes. Hashes generated by simple or fast hash functions may be cracked by graphics processing units (GPUs), even if they were salted.

Sensitive data exposure can also come in the form of an error message or a reference to an internal function that inadvertently reveals the true nature of the request. This is called an insecure direct object reference (IDOR).

An example would be exposing a database record (such as a primary key) as a referenced object within a web parameter or URL. IDOR is not a vulnerability by itself; however, if the database or application server lacks proper access control, then an attacker can likely infer the schema or pattern of the object being referenced. For example, if a foreign key value is called directly through a web parameter, a malicious user who already authenticated into the system could modify the parameter to access the contents of another user’s profile.

To demonstrate, we used the OWASP WebGoat Project web application called Goat Hills Financial Human Resources and logged in as the user Tom to access the profile data for the user Eric.

Using Burp Proxy, we intercepted the HTTP GET request for the action ViewProfile to identify the parameters passed in the request, as shown below.



Figure:   Intercept IDOR parameter

The parameter employee_id=105, which looks to be a direct object pointer and unique to the user Tom. Using Burp Repeater, we modified the parameter and replayed the HTTP GET request, but now requesting employee_id=104 to see if the field was incremental.

After submitting the request, we were able to retrieve the profile for Eric, as shown below.



Figure:   Modify IDOR parameter

If the IDOR parameter had been hidden or obfuscated, it would have made this attack a little harder to be successful or possibly less visible. Regardless, this issue was a direct result of poor access controls and ultimately relies on the web and database server to properly validate these types of requests.

Directory and Path Traversals
Directory and path traversal attacks are a form of injection attack that enables a malicious actor to access content that would not normally be available by using shortcuts to browse outside of the web server’s root folder. Using the directory traversal example provided with the Web for Pentester ISO from the Pentester Labs website, we can demonstrate this type of attack.

Given the following URL:
http://192.168.1.108/dirtrav/example1.php?file=hacker.png
the file= parameter is used to retrieve the image named hacker.png.

If we take a look at the PHP code that makes this possible, we can get an idea of what is going on behind the scenes:





The $UploadDir variable identifies the absolute path on the operating system to be '/var/www/files/', which is where the file hacker.png is located. The $file variable is defined with the $_GET['file'] method, which parses the filename from the file= parameter. The $path variable declares the full path of where the file should be located on the server.

If the $path doesn’t exist, the request is null. Then $handle opens the path to the file for reading (‘rb’). The do-while loop is used to read the file variable up to a maximum chunk size of 8192 bytes. If the length is 0, the program breaks; if not, the file contents are read and echoed to the web browser. Then the fclose() function is used to close the file prior to exiting the program.

So, now let’s test if the parameter is vulnerable to a path traversal. In order to test this, we could use the following /../../../../../etc/passwd in place of hacker.png to access the local operating system passwd file, which is not served normally as a web page.

The forward slash and the dots tell the web operation to traverse back several directories in the path, much like the change directory “cd” command in a terminal window.

However, in Windows, the slash is a backward slash rather than a forward slash to separate directories in file paths (e.g., \..\..\..\C:\boot.ini). In Windows, the directory separator (“/” or “\”) can be either forward or backward. However, in Unix, it can only be a forward slash (“/”).

This means that in Windows to bypass or escape a web content filter that only looks for “/” in malicious requests, you can use the other directory separator.

As you can see below, the directory traversal attack against the Unix target was successful.



Figure:   Directory traversal with Burp

Tip: There are a number of variations to use when testing path traversal attacks. It’s mostly about encoding the directory path or initiating the correct escape sequence to break out of the typical web filter.

To bypass trivial content filters that look for special characters, such as the forward slash, an attacker might use Unicode / UTF-8 or even URL encoding, such as the following: %2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2fetc%2fpasswd to accomplish the same result.

The reason the path traversal was successful is because there was no program logic to prevent access to files outside of the web root. One way path traversal could be mitigated is to base-name the $file variable in the PHP code. This will return the trailing name component of $file, and any attempt to access files outside of the $UploadDir would fail.

An example of how to implement this function in our code would be as follows:
$file = basename($_GET['file']);

Note: : On the surface, it may be hard to distinguish between a file inclusion vulnerability (LFI and RFI) and a path or directory traversal. The primary difference is that with a traversal attack, you only have the ability to read the contents of a local resource (e.g., /etc/passwd), whereas with file inclusion, the resource can be loaded and executed within the context of the application, which can provide code execution.

Sensitive Data Exposure
Applications that don’t use encryption to protect data while it is stored or transmitted, or applications that implement weak encryption or risky encryption practices may also introduce risk to the client. Some compliance-based penetration tests have specific requirements involving the evaluation of encryption use. Examples of risky practices include the use of unsalted hashes, hashes that implement a weak hashing algorithm (such as MD5), or applications that automatically decrypt data when it is retrieved (this allows a SQL injection flaw to expose all data). Transmission of sensitive data over an unencrypted protocol (no TLS enforcement) or with a weak encryption scheme may subject the data to potential exposure in the event of a successful on-path attack over an unsecured wireless network, for example.

During on-path attacks, it may be necessary to set up a proxy service to force Secure Sockets Layer (SSL) stripping from client requests, such that when a client goes to connect to an SSL-enabled website, the certificate will be stripped from the session and the browser window will not display any SSL certificate message. Essentially, the HTTPS website was downgraded to HTTP. Once a user attempts to log in or enter sensitive data into a website when SSL has been stripped, the data will be sent via plaintext and can easily be captured in the session data.

To mitigate against this type of an attack, websites can enforce HTTP Strict Transport Security (HSTS) to protect against downgrade attacks like SSL stripping. Organizations can also block port 80/tcp at the firewall or force the website/application to only run on the SSL-enabled port.

Inclusion Attacks
The ability to load arbitrary content within a web page is known as an inclusion attack. Most web application frameworks (e.g., PHP) support file inclusion. File inclusion exploits take advantage of “dynamic file inclusion” capabilities in a web application. In PHP applications, these vulnerabilities typically exploit flaws in code using the following built-in functions: include() and require(). There are two kinds of file inclusions: local (LFI) and remote (RFI).

Local file inclusion includes files outside of the web root and renders the contents of local operating system files to the browser window, such as the password file, example.php?page=../../../../etc/passwd. In some cases LFI could lead to remote code execution. One method for testing remote code execution is by using PHP wrappers.

The PHP Expect wrapper allows the execution of system commands: example.php?page=expect://id; however, the Expect wrapper is not enabled by default.

Another PHP wrapper is the input stream, which allows you to read raw data from the request body. In the case of an HTTP POST message, you could use the following example to execute commands against the local operating system:
POST /example.php?page=php://input&cmd=id HTTP/1.1

In the body of the message, you could use the following PHP code that will be read and processed through the PHP input stream:
<?php echo shell_exec($_GET['cmd']);?>

The cmd command would be executed through the shell_exec() function and in this example return the userid of the user that owns the web server process.

Remote file inclusions allow files or even whole pages to be displayed inside the vulnerable web page. If the parameters within the HTTP request can be altered to point to a malicious location, it’s possible the web application is susceptible to RFI, which in turn could allow for malicious code to be run on the server or on the client (i.e., malicious JavaScript to steal cookie data).

An example RFI attack might look like the following:


LFI and RFI are both dangerous methods that can be mitigated with the proper use of input validation. Another way of taking advantage of a web application’s poor input validation and content control is by performing malicious file uploads. If a web application allows unauthorized users to upload a file and then execute it, attackers may be able to compromise the system. Web servers that support various web scripting languages such as PHP can easily fall victim to backdoor shells. Controlling access to where files are uploaded and controlling supported file types are ways to mitigate against this type of vulnerability.

A simple PHP one-liner is sometimes all you need!

The figure below provides an example of executing the Linux id command using a PHP web shell. The code used to develop the web shell is as follows:



Figure:   Malicious file upload




Race Conditions
A race condition occurs when two or more application logic components have co-dependent data, do not have appropriate concurrency protections, and execute simultaneously.
As a result, quick execution may retrieve data that has changed between when it is checked and when it is actioned. In short: the application may clobber itself when transactions run concurrently.
An example of a race condition would be when multiple threads access the same data (variables, files, etc.) at the same time without locking the data or synchronizing it. This sort of data integrity issue is pretty important when you’re dealing with applications that do things like manage balances or issue vouchers or money-based resources (like gift cards).

Normally, a web server would get a request from a client and serve a page. But more complex web applications add layers. The browser might make a request to the server, and the server might send that to Java Server Pages (JSP), which then compiles it into a servlet, where it is then interpreted and executed to generate the response details. Along the way, applications might use multithreading to scale these sorts of requests across multiple applications, systems, or application components. If each component doesn’t handle thread safety properly, it may be possible to attack the application and produce unexpected results. Normally, pentesters would find these issues with insight into the source code, as these are difficult (but not impossible) to identify using something like Burp Intruder. But let’s take a minute to think about that use case.
Assume you have an application that can transfer a balance from one card to another, and you can capture the POST request in Burp Intruder.

Intruder has an option to raise the threads to something like 25, just to pick a number. The default is 5. This will let you send many simultaneous requests. You wouldn’t even necessarily have to change the payload, so you can use a null payload to send the request as-is. Now, if there’s a race condition, it’s possible that the application will eventually generate an unexpected result. For example, the balance might become negative, as the value from one card is successfully debited and deposited before the previous transaction has been completed.

Review
- Web and database technology plays a significant role within most organizations. A few years ago, just having a website was good enough to contend in competitive markets and allow your customer base to see what it is your company can do. 
- Today, companies are investing additional time and energy into building a presence on social media sites such as Facebook, Twitter, Instagram, and LinkedIn, in order to stay connected with the digital world. 
- In today’s world, companies can move parts of their data center into the cloud to cut annual operational costs and achieve even higher levels of system availability. 
- It is imperative that organizations evaluate web and database security within their organization, since the digital age is most definitely upon us. Attacks against web-based technology are not just server-side any longer. 
- More sophisticated attacks are targeting end users, as most client-side exploits are fairly trivial, require little effort, and the attacker has much to gain. 
- As long as the reward outweighs the risk of getting caught, attackers will continue to find new ways to exploit advancements in web-based technology.



ADVERTISEMENT