penetration testing

Performing Thick Client Application Penetration Test

Conduct a thick client application penetration test to identify insecure local storage, hardcoded credentials, DLL hijacking, memory manipulation, and insecure API communication in desktop applications using dnSpy, Procmon, and Burp Suite.

api-interceptionbinary-analysisdesktop-applicationdll-hijackingdnspyprocmonthick-client
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

Thick client (fat client) penetration testing assesses the security of desktop applications that run locally on user machines and communicate with backend servers. Unlike web applications, thick clients present a broader attack surface including local file storage, binary analysis, memory manipulation, DLL injection, process interception, and client-server communication. Common targets include banking applications, ERP clients (SAP GUI), trading platforms, healthcare systems, and legacy enterprise software.

When to Use

  • When conducting security assessments that involve performing thick client application penetration test
  • When following incident response procedures for related security events
  • When performing scheduled security testing or auditing activities
  • When validating security controls through hands-on testing

Prerequisites

  • Application installer and valid credentials
  • Windows/Linux test machine (isolated)
  • Tools: dnSpy, Procmon, Process Hacker, Wireshark, Burp Suite, Echo Mirage, Fiddler, IDA Pro/Ghidra
  • Administrative access to test machine

Legal Notice: This skill is for authorized security testing and educational purposes only. Unauthorized use against systems you do not own or have written permission to test is illegal and may violate computer fraud laws.

Phase 1 — Information Gathering

Static Analysis

# Identify application technology
# Check file properties, signatures, framework (.NET, Java, C++, Electron)
file application.exe
# .NET -> dnSpy, JetBrains dotPeek
# Java -> JD-GUI, JADX
# C/C++ -> Ghidra, IDA Pro
# Electron -> extract asar archive
 
# Check for .NET framework
Get-ChildItem -Path "C:\Program Files\TargetApp" -Recurse -Filter "*.dll" |
  ForEach-Object { [System.Reflection.AssemblyName]::GetAssemblyName($_.FullName).FullName }
 
# Strings analysis
strings application.exe | findstr -i "password\|secret\|api\|key\|token\|jdbc\|connection"
 
# Check for hardcoded credentials
strings application.exe | findstr -i "username\|user=\|pass=\|pwd=\|admin"
 
# Review configuration files
type "C:\Program Files\TargetApp\app.config"
type "C:\Program Files\TargetApp\settings.xml"
type "%APPDATA%\TargetApp\config.json"
 
# Check for certificate pinning
strings application.exe | findstr -i "cert\|pin\|ssl\|tls"

.NET Decompilation with dnSpy

# Open application in dnSpy
1. Launch dnSpy
2. File > Open > Select application.exe and DLLs
3. Search for:
   - "password", "secret", "connectionString"
   - Authentication methods
   - Encryption/decryption functions
   - API endpoints and keys
   - License validation logic
 
# Look for:
- Hardcoded credentials in source
- Insecure encryption (DES, MD5, base64 "encryption")
- SQL queries (potential injection)
- Disabled certificate validation
- Debug/verbose logging with sensitive data

Phase 2 — Dynamic Analysis

Process Monitoring

# Monitor file system activity with Procmon
# Filters:
#   Process Name = application.exe
#   Operation = CreateFile, WriteFile, ReadFile, RegSetValue
 
# Key observations:
# - Where does the app store data? (AppData, temp, registry)
# - Does it write credentials to disk?
# - Does it create temporary files with sensitive data?
# - What registry keys does it access?
 
# Monitor with Process Hacker
# Check: loaded DLLs, network connections, handles, tokens
 
# Monitor network traffic
# Wireshark filter: ip.addr == <server_ip>
# Check for: unencrypted credentials, API keys, tokens

Traffic Interception

# Intercept HTTP/HTTPS traffic with Burp Suite
# Configure system proxy: 127.0.0.1:8080
# Install Burp CA certificate in Windows certificate store
 
# For non-HTTP protocols, use Echo Mirage
# Inject into process and intercept TCP/UDP traffic
 
# For HTTPS with certificate pinning:
# Method 1: Patch certificate validation in dnSpy
# Method 2: Use Frida to hook SSL validation
frida -l bypass_ssl_pinning.js -f application.exe
 
# Fiddler for .NET applications
# Enable HTTPS decryption
# Monitor API calls, request/response bodies

Phase 3 — Vulnerability Testing

Authentication Bypass

# Test local authentication bypass
1. Open dnSpy, find authentication method
2. Set breakpoint on credential validation
3. Modify return value to bypass (Debug > Set Next Statement)
4. Or: Patch binary to always return true
 
# Test for credential storage
# Check: registry, config files, SQLite databases, Windows Credential Manager
reg query "HKCU\Software\TargetApp" /s
type "%APPDATA%\TargetApp\user.db"
# SQLite: sqlite3 user.db ".dump"

DLL Hijacking

# Identify DLL search order vulnerability
# Use Procmon to find DLLs loaded from writable paths
# Filter: Result = NAME NOT FOUND, Path ends with .dll
 
# Create malicious DLL
# msfvenom -p windows/exec CMD=calc.exe -f dll -o hijacked.dll
# Place in application directory or writable PATH directory
 
# DLL sideloading
# If app loads DLL without full path:
# 1. Create DLL with same exports
# 2. Place in app directory
# 3. DLL loads before legitimate version

Memory Analysis

# Dump process memory
# Use Process Hacker > Process > Properties > Memory
# Search for plaintext credentials, tokens, session IDs
 
# Strings from memory dump
strings process_dump.dmp | findstr -i "password\|token\|session\|bearer"
 
# Modify memory values (license bypass, privilege escalation)
# Use Cheat Engine or x64dbg to:
# 1. Find memory address of authorization variable
# 2. Modify value (e.g., isAdmin = 0 -> isAdmin = 1)

Input Validation

# SQL Injection in local database
# Test input fields with: ' OR 1=1--
# If app uses local SQLite/SQL Server Express
 
# Command injection
# Test fields that interact with OS:
# File paths: ..\..\..\..\windows\system32\cmd.exe
# Print/export: | calc.exe
 
# Buffer overflow
# Send oversized input to text fields
# Monitor with x64dbg for crashes
# Check for SEH-based or stack-based overflows

Phase 4 — API Security Testing

# Capture API calls from thick client
# In Burp Suite, analyze:
 
# IDOR (Insecure Direct Object Reference)
# Change user IDs in requests to access other users' data
# GET /api/users/1001 -> GET /api/users/1002
 
# Authorization bypass
# Remove or modify JWT tokens
# Test role escalation: change role claim from "user" to "admin"
 
# Mass assignment
# Add additional parameters to API requests
# POST /api/profile {"name": "test", "isAdmin": true}
 
# Rate limiting
# Test for brute-force protection on login API
# Test for account lockout bypass

Findings Template

Finding Severity CVSS Remediation
Hardcoded database credentials in binary Critical 9.1 Use secure credential storage (DPAPI, vault)
DLL hijacking via writable app directory High 7.8 Use full DLL paths, validate DLL signatures
Plaintext credentials in memory High 7.5 Zero memory after use, use SecureString
No certificate pinning Medium 6.5 Implement certificate pinning
Local SQLite DB with cleartext passwords Critical 9.0 Use bcrypt/Argon2 hashing
Disabled SSL validation in code High 8.1 Enable proper certificate validation

References

Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md2.3 KB

API Reference: Thick Client Penetration Testing

Analysis Tools

Tool Purpose Target
dnSpy .NET decompilation and debugging .NET Framework/Core apps
ILSpy .NET decompilation (read-only) .NET assemblies
JD-GUI / JADX Java decompilation JAR/APK files
Ghidra / IDA Pro Native binary reverse engineering C/C++ executables
Procmon File/registry/network activity monitoring Any Windows app
Process Hacker Process inspection, memory, DLLs Running processes
Burp Suite HTTP/HTTPS traffic interception Client-server communication
Echo Mirage TCP/UDP traffic interception Non-HTTP protocols
Frida Dynamic instrumentation Any platform

Static Analysis Targets

Target Search Pattern Risk
Hardcoded credentials password, secret, apikey in strings Critical
Connection strings jdbc:, Server=, mongodb:// Critical
SQL queries SELECT, INSERT, UPDATE Medium
URLs and endpoints http://, https:// Info
Disabled SSL validation ServerCertificateValidationCallback High

DLL Hijacking Detection

Step Tool Action
1 Procmon Filter: Result = NAME NOT FOUND, Path ends with .dll
2 Check Verify if DLL search path includes writable directories
3 Validate Test with benign DLL in writable directory

Local Storage Locations

Location Type Risk
%APPDATA%\<app> Config, SQLite Credential storage
%LOCALAPPDATA%\<app> Cache, logs Data leakage
HKCU\Software\<app> Registry settings Stored credentials
App install directory Config files Hardcoded secrets

Python Libraries

Library Version Purpose
sqlite3 stdlib Audit local SQLite databases
re stdlib Pattern matching for credentials/URLs
subprocess stdlib Execute system analysis tools
pathlib stdlib File system traversal

References

standards.md0.5 KB

Standards — Thick Client Application Penetration Testing

Frameworks

OWASP Thick Client Top 10

  1. Improper Platform Usage
  2. Insecure Data Storage
  3. Insecure Communication
  4. Insecure Authentication
  5. Insufficient Cryptography
  6. Insecure Authorization
  7. Client Code Quality
  8. Code Tampering
  9. Reverse Engineering
  10. Extraneous Functionality
workflows.md0.8 KB

Workflows — Thick Client Penetration Testing

Attack Flow

Application Binary

    ├── Static Analysis (dnSpy/Ghidra/JD-GUI)
    │   ├── Hardcoded credentials
    │   ├── Encryption analysis
    │   └── API endpoint discovery

    ├── Dynamic Analysis (Procmon/Process Hacker)
    │   ├── File system monitoring
    │   ├── Registry access tracking
    │   └── Memory inspection

    ├── Traffic Interception (Burp/Fiddler/Echo Mirage)
    │   ├── API security testing
    │   ├── Certificate pinning bypass
    │   └── Authentication token analysis

    └── Binary Exploitation
        ├── DLL hijacking
        ├── Memory manipulation
        └── Binary patching

Scripts 2

agent.py8.5 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
# For authorized penetration testing and educational environments only.
# Usage against targets without prior mutual consent is illegal.
# It is the end user's responsibility to obey all applicable local, state and federal laws.
"""Agent for thick client application penetration testing.

Performs static analysis (strings extraction, .NET detection),
dynamic analysis (process monitoring, DLL search order checks),
local storage auditing, and API traffic interception assessment.
"""

import json
import sys
import os
import re
import sqlite3
from pathlib import Path
from datetime import datetime

_SAFE_TABLE_RE = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$')


class ThickClientPentestAgent:
    """Performs security assessment of thick/fat client applications."""

    def __init__(self, app_path, output_dir="./thick_client_pentest"):
        self.app_path = Path(app_path)
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        self.findings = []

    def extract_strings(self, min_length=6):
        """Extract readable strings from binary for credential/URL discovery."""
        patterns = {
            "url": re.compile(r'https?://[^\s"\'<>]{5,200}'),
            "email": re.compile(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'),
            "ip_addr": re.compile(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b'),
            "password_hint": re.compile(
                r'(?i)(password|passwd|pwd|secret|api.?key|token|'
                r'connectionstring|jdbc|bearer)', re.IGNORECASE),
            "sql_query": re.compile(r'(?i)(SELECT|INSERT|UPDATE|DELETE)\s+', re.IGNORECASE),
        }
        results = {k: [] for k in patterns}
        try:
            with open(self.app_path, "rb") as f:
                data = f.read()
            text = data.decode("ascii", errors="ignore")
            for name, pattern in patterns.items():
                matches = pattern.findall(text)
                results[name] = list(set(matches))[:50]

            if results["password_hint"]:
                self.findings.append({
                    "type": "Credential Reference in Binary",
                    "severity": "Medium",
                    "details": f"Found {len(results['password_hint'])} credential-related strings",
                })
            if results["sql_query"]:
                self.findings.append({
                    "type": "SQL Queries in Binary",
                    "severity": "Medium",
                    "details": "Embedded SQL may be vulnerable to injection",
                })
        except (OSError, PermissionError) as exc:
            results["error"] = str(exc)
        return results

    def detect_framework(self):
        """Detect the application framework (.NET, Java, Electron, C++)."""
        try:
            with open(self.app_path, "rb") as f:
                header = f.read(4096)

            if b"BSJB" in header or b".NET" in header or b"mscorlib" in header:
                return {"framework": ".NET", "decompiler": "dnSpy / ILSpy"}
            if b"PK" in header[:4]:
                return {"framework": "Java (JAR)", "decompiler": "JD-GUI / JADX"}
            if b"asar" in header or b"electron" in header:
                return {"framework": "Electron", "tool": "asar extract"}
            return {"framework": "Native (C/C++)", "decompiler": "Ghidra / IDA Pro"}
        except OSError as exc:
            return {"error": str(exc)}

    def check_local_storage(self, app_name=None):
        """Scan common local storage locations for sensitive data."""
        app_name = app_name or self.app_path.stem
        locations = []
        appdata = os.environ.get("APPDATA", "")
        localappdata = os.environ.get("LOCALAPPDATA", "")

        search_dirs = [
            Path(appdata) / app_name if appdata else None,
            Path(localappdata) / app_name if localappdata else None,
            self.app_path.parent,
        ]
        sensitive_exts = {".db", ".sqlite", ".sqlite3", ".json", ".xml",
                         ".config", ".ini", ".cfg", ".log"}

        for search_dir in search_dirs:
            if search_dir is None or not search_dir.exists():
                continue
            for root, dirs, files in os.walk(search_dir):
                for fname in files:
                    fpath = Path(root) / fname
                    if fpath.suffix.lower() in sensitive_exts:
                        size = fpath.stat().st_size
                        locations.append({
                            "path": str(fpath), "type": fpath.suffix,
                            "size_bytes": size,
                        })

        if locations:
            self.findings.append({
                "type": "Sensitive Local Files",
                "severity": "Medium",
                "details": f"Found {len(locations)} potentially sensitive files",
            })
        return locations

    def audit_sqlite_databases(self, db_paths):
        """Check local SQLite databases for plaintext credentials."""
        results = []
        for db_path in db_paths:
            try:
                conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
                cursor = conn.cursor()
                cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
                tables = [r[0] for r in cursor.fetchall()]

                sensitive_tables = []
                for table in tables:
                    lower = table.lower()
                    if any(kw in lower for kw in
                           ["user", "account", "credential", "auth",
                            "login", "password", "token", "session"]):
                        if not _SAFE_TABLE_RE.match(table):
                            continue
                        cursor.execute(f"SELECT COUNT(*) FROM [{table}]")
                        count = cursor.fetchone()[0]
                        sensitive_tables.append({"table": table, "rows": count})

                if sensitive_tables:
                    self.findings.append({
                        "type": "Sensitive SQLite Database",
                        "severity": "High",
                        "details": f"{db_path}: {sensitive_tables}",
                    })
                results.append({"database": db_path, "tables": tables,
                                "sensitive_tables": sensitive_tables})
                conn.close()
            except sqlite3.Error as exc:
                results.append({"database": db_path, "error": str(exc)})
        return results

    def check_dll_hijack_paths(self):
        """Check for DLL hijacking via writable directories in PATH."""
        writable_dirs = []
        path_dirs = os.environ.get("PATH", "").split(os.pathsep)
        for d in path_dirs:
            if os.path.isdir(d) and os.access(d, os.W_OK):
                writable_dirs.append(d)

        app_dir = str(self.app_path.parent)
        app_dir_writable = os.access(app_dir, os.W_OK)

        if writable_dirs or app_dir_writable:
            self.findings.append({
                "type": "DLL Hijacking Risk",
                "severity": "High",
                "details": f"Writable PATH dirs: {len(writable_dirs)}, "
                           f"App dir writable: {app_dir_writable}",
            })
        return {"writable_path_dirs": writable_dirs,
                "app_dir_writable": app_dir_writable}

    def generate_report(self):
        """Generate comprehensive pentest findings report."""
        report = {
            "target": str(self.app_path),
            "report_date": datetime.utcnow().isoformat(),
            "framework": self.detect_framework(),
            "total_findings": len(self.findings),
            "critical": sum(1 for f in self.findings if f["severity"] == "Critical"),
            "high": sum(1 for f in self.findings if f["severity"] == "High"),
            "medium": sum(1 for f in self.findings if f["severity"] == "Medium"),
            "findings": self.findings,
        }
        report_path = self.output_dir / "thick_client_report.json"
        with open(report_path, "w") as f:
            json.dump(report, f, indent=2)
        print(json.dumps(report, indent=2))
        return report


def main():
    if len(sys.argv) < 2:
        print("Usage: agent.py <application.exe> [output_dir]")
        sys.exit(1)
    app_path = sys.argv[1]
    output_dir = sys.argv[2] if len(sys.argv) > 2 else "./thick_client_pentest"
    agent = ThickClientPentestAgent(app_path, output_dir)
    agent.extract_strings()
    agent.check_local_storage()
    agent.check_dll_hijack_paths()
    agent.generate_report()


if __name__ == "__main__":
    main()
process.py6.9 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Thick Client Penetration Test — Static Analysis Helper

Performs basic static analysis on thick client applications: string extraction,
config file scanning, and DLL dependency analysis.

Usage:
    python process.py --app-dir "C:/Program Files/TargetApp" --output ./results
"""

import os
import re
import json
import argparse
import datetime
from pathlib import Path


SENSITIVE_PATTERNS = {
    "password": re.compile(r'(?i)(password|passwd|pwd)\s*[=:]\s*["\']?([^\s"\']+)'),
    "api_key": re.compile(r'(?i)(api[_-]?key|apikey)\s*[=:]\s*["\']?([^\s"\']+)'),
    "connection_string": re.compile(r'(?i)(connection[_-]?string|jdbc:)\s*[=:]\s*["\']?([^\s"\']+)'),
    "secret": re.compile(r'(?i)(secret|token)\s*[=:]\s*["\']?([^\s"\']+)'),
    "url_with_creds": re.compile(r'https?://[^:]+:[^@]+@[\w.]+'),
    "hardcoded_ip": re.compile(r'\b(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d{1,3}\.\d{1,3}\b'),
}


def extract_strings(filepath: str, min_length: int = 8) -> list[str]:
    """Extract printable strings from a binary file."""
    strings = []
    try:
        with open(filepath, "rb") as f:
            data = f.read()

        current = []
        for byte in data:
            if 32 <= byte <= 126:
                current.append(chr(byte))
            else:
                if len(current) >= min_length:
                    strings.append("".join(current))
                current = []
        if len(current) >= min_length:
            strings.append("".join(current))
    except (PermissionError, OSError):
        pass
    return strings


def scan_for_secrets(strings: list[str]) -> list[dict]:
    """Scan extracted strings for sensitive patterns."""
    findings = []
    for s in strings:
        for name, pattern in SENSITIVE_PATTERNS.items():
            match = pattern.search(s)
            if match:
                findings.append({
                    "type": name,
                    "match": s[:200],
                    "severity": "High" if name in ("password", "connection_string", "secret") else "Medium"
                })
                break
    return findings


def scan_config_files(app_dir: str) -> list[dict]:
    """Scan configuration files for sensitive data."""
    config_extensions = {".config", ".xml", ".json", ".ini", ".properties", ".yaml", ".yml", ".cfg"}
    findings = []

    for root, dirs, files in os.walk(app_dir):
        for filename in files:
            ext = os.path.splitext(filename)[1].lower()
            if ext in config_extensions:
                filepath = os.path.join(root, filename)
                try:
                    with open(filepath, encoding="utf-8", errors="ignore") as f:
                        content = f.read()
                    for name, pattern in SENSITIVE_PATTERNS.items():
                        matches = pattern.findall(content)
                        for match in matches:
                            findings.append({
                                "file": filepath,
                                "type": name,
                                "match": str(match)[:200],
                                "severity": "High"
                            })
                except (PermissionError, OSError):
                    continue
    return findings


def analyze_dlls(app_dir: str) -> list[dict]:
    """Analyze DLL dependencies for potential hijacking."""
    dlls = []
    for root, dirs, files in os.walk(app_dir):
        for filename in files:
            if filename.lower().endswith(".dll"):
                filepath = os.path.join(root, filename)
                dlls.append({
                    "name": filename,
                    "path": filepath,
                    "writable": os.access(filepath, os.W_OK),
                    "size": os.path.getsize(filepath)
                })

    writable = [d for d in dlls if d["writable"]]
    return dlls, writable


def generate_report(app_dir: str, string_findings: list[dict],
                     config_findings: list[dict], dll_info: tuple,
                     output_dir: Path) -> str:
    """Generate thick client analysis report."""
    report_file = output_dir / "thick_client_report.md"
    timestamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    all_dlls, writable_dlls = dll_info

    with open(report_file, "w") as f:
        f.write("# Thick Client Static Analysis Report\n\n")
        f.write(f"**Application:** {app_dir}\n")
        f.write(f"**Generated:** {timestamp}\n\n---\n\n")

        f.write("## Binary String Analysis\n\n")
        if string_findings:
            f.write(f"Found **{len(string_findings)}** potentially sensitive strings:\n\n")
            f.write("| Type | Match | Severity |\n|------|-------|----------|\n")
            for finding in string_findings[:50]:
                f.write(f"| {finding['type']} | `{finding['match'][:80]}` | {finding['severity']} |\n")
        else:
            f.write("No sensitive strings detected in binaries.\n")
        f.write("\n")

        f.write("## Configuration File Analysis\n\n")
        if config_findings:
            f.write(f"Found **{len(config_findings)}** sensitive entries in configs:\n\n")
            for finding in config_findings[:20]:
                f.write(f"- **{finding['type']}** in `{finding['file']}`: `{finding['match'][:80]}`\n")
        else:
            f.write("No sensitive data found in configuration files.\n")
        f.write("\n")

        f.write("## DLL Analysis\n\n")
        f.write(f"Total DLLs: **{len(all_dlls)}**\n")
        f.write(f"Writable DLLs (potential hijacking): **{len(writable_dlls)}**\n\n")
        if writable_dlls:
            f.write("| DLL | Path |\n|-----|------|\n")
            for dll in writable_dlls:
                f.write(f"| {dll['name']} | {dll['path']} |\n")
        f.write("\n")

    print(f"[+] Report: {report_file}")
    return str(report_file)


def main():
    parser = argparse.ArgumentParser(description="Thick Client Static Analysis")
    parser.add_argument("--app-dir", required=True, help="Application installation directory")
    parser.add_argument("--output", default="./results")
    args = parser.parse_args()

    output_dir = Path(args.output)
    output_dir.mkdir(parents=True, exist_ok=True)

    print(f"[*] Scanning {args.app_dir}...")

    # Scan binaries for strings
    all_findings = []
    for root, dirs, files in os.walk(args.app_dir):
        for filename in files:
            if filename.lower().endswith((".exe", ".dll")):
                filepath = os.path.join(root, filename)
                strings = extract_strings(filepath)
                findings = scan_for_secrets(strings)
                all_findings.extend(findings)

    # Scan config files
    config_findings = scan_config_files(args.app_dir)

    # Analyze DLLs
    dll_info = analyze_dlls(args.app_dir)

    generate_report(args.app_dir, all_findings, config_findings, dll_info, output_dir)
    print("[+] Analysis complete")


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 0.7 KB
Keep exploring