🖥️ Desktop Application Security — Deep Dive: Electron Security, Win32 Reverse Engineering, .NET Analysis, Binary Patching

Panduan komprehensif keamanan aplikasi desktop — dari Electron app (asar unpack, Node.js integration, contextIsolation, IPC security) sampai Win32 native (PE analysis, API hooking, DLL injection, process injection, anti-debug bypass). Mencakup Electron security model (Chromium sandbox, contextIsolation, preload scripts, nodeIntegration), .NET reverse engineering (dnSpy, de4dot, obfuscation bypass), Win32 reversing (x64dbg, IDA, Ghidra, ScyllaHide), binary patching & cracking, dan desktop-specific attack surface (local file access, named pipes, COM objects, registry). Vault udah punya browser-security-exploitation-deepdive (browser web) dan web-hacking-exploitation (web app) — catatan ini melengkapi dari sisi desktop native app.

Posisi di Vault

Nota ini melengkapi browser-security-exploitation-deepdive (browser — Electron pake Chromium), web-hacking-exploitation (web app — sebagian Electron app adalah web app dalam shell native), malware-analysis-reverse-engineering-playbook (malware RE — tekniknya overlap), exploit-development (Win32 exploit — buffer overflow di desktop app), hardware-hacking-re (firmware RE — teknik reversing berbeda), dan endpoint-detection-playbook (detection — desktop app adalah endpoint utama).


Daftar Isi


Electron Security Model

Arsitektur Electron

┌────────────────────────────────────────┐
│              Main Process              │ ← Node.js, system access
│   (BrowserWindow, IPC, Menu, Tray)    │
└──────────┬─────────────────────────────┘
           │ IPC (send, on, invoke, handle)
           │
┌──────────▼─────────────────────────────┐
│           Renderer Process             │ ← Chromium, web content
│   (HTML, CSS, JS — isolated from OS)  │
│   preload.js → bridge (contextBridge)  │
└────────────────────────────────────────┘

┌────────────────────────────────────────┐
│          Utility Process               │ ← Node.js child process
│   (GPU, Network, Audio, etc)          │
└────────────────────────────────────────┘

Security Best Practices (Electron Security Checklist)

Wajib (Non-negotiable)

// ✅ AMAN — recommended for production
new BrowserWindow({
  webPreferences: {
    nodeIntegration: false, // ❌ JANGAN true — renderer bisa require('child_process')
    contextIsolation: true, // ✅ WAJIB — renderer isolated dari preload
    sandbox: true, // ✅ WAJIB — Chromium sandbox
    enableRemoteModule: false, // ❌ JANGAN true — remote module RCE
    preload: path.join(__dirname, "preload.js"), // ✅ preload = bridge
  },
})

❌ Common Insecure Patterns

// ❌ RCE via nodeIntegration
new BrowserWindow({ webPreferences: { nodeIntegration: true } })
// → renderer bisa: require('child_process').exec('rm -rf /')
 
// ❌ RCE via contextBridge yang salah
contextBridge.exposeInMainWorld('api', {
    exec: (cmd) => require('child_process').exec(cmd)
    // → renderer: window.api.exec('malicious command')
});
 
// ❌ Shell.openExternal tanpa validasi
shell.openExternal(userInput)  // → bisa diarahkan ke file:// atau protocol berbahaya
 
// ❌ webview tag tanpa restriction
<webview src="http://evil.com"></webview>  // → XSS di webview → RCE via IPC?

Secure IPC Pattern

// ✅ preload.js — bridge minimal
const { contextBridge, ipcRenderer } = require("electron")
 
contextBridge.exposeInMainWorld("appAPI", {
  getData: () => ipcRenderer.invoke("get-data"),
  saveFile: (data) => ipcRenderer.invoke("save-file", data),
  // JANGAN expose: exec, shell, fs, net
})
 
// ✅ main.js — validasi input dari renderer
ipcMain.handle("save-file", async (event, data) => {
  if (typeof data !== "string") throw new Error("Invalid input")
  // Validasi path — prevent path traversal
  const safePath = path.resolve(baseDir, path.basename(data.filename))
  if (!safePath.startsWith(baseDir)) throw new Error("Path traversal detected")
})

Electron Pentesting

1. ASAR Extraction

# Electron app = ASAR archive
npx asar extract app.asar extracted/
# Hasil: HTML, JS, CSS, Node modules
 
# Atau langsung
electron app.asar  # run tanpa extract
asar list app.asar  # list files in archive

2. Static Analysis

# Cari hardcoded API key, endpoint, secret
grep -r "api_key\|secret\|token" extracted/
grep -r "http:" extracted/  # HTTP non-HTTPS -> MITM
grep -r "nodeIntegration\|contextIsolation\|sandbox" extracted/
 
# Cek package.json — dependency dengan CVE
cat extracted/package.json | jq '.dependencies'

3. Runtime Analysis

# Open DevTools di Electron app
# Method 1: --auto-open-devtools-for-tabs
electron app.asar --auto-open-devtools-for-tabs
 
# Method 2: inject via preload + environment
# Method 3: Open console.log — lihat semua output
 
# Network interception
mitmproxy -p 8080  # Proxy
# Electron: set http_proxy=http://127.0.0.1:8080

4. Electron Attacks

AttackPrerequisiteImpact
RCE via nodeIntegrationnodeIntegration=trueFull system access
RCE via IPCVulnerable IPC handlerSystem command execution
XSS RCEXSS + insecure IPC bridgeRemote code execution
Context Isolation bypasscontextIsolation=false + XSSAccess Node.js API
ASAR integrity bypassUnsigned updateMalicious update injection
Protocol handler hijackCustom protocol (myapp://)Open app with malicious params
DevTools persistenceDevTools enabled in productionDebug access

Win32 Reverse Engineering

PE (Portable Executable) Structure

┌─────────────────┐
│     DOS Header  │ ← "MZ" magic
├─────────────────┤
│   NT Headers    │ ← PE signature, COFF header, Optional header
├─────────────────┤
│  Section Table  │ ← .text, .data, .rdata, .reloc, .rsrc
├─────────────────┤
│  Section .text  │ ← Executable code
│  Section .data  │ ← Global/static variables
│  Section .rdata │ ← Read-only data (imports, strings)
│  Section .rsrc  │ ← Resources (icons, version, manifest)
└─────────────────┘

Reverse Engineering Workflow

# 1. Information gathering
file target.exe
exiftool target.exe
strings target.exe | grep -i "http\|api\|secret\|key"
 
# 2. Static analysis (IDA/Ghidra/x64dbg)
# IDA: decompile to pseudo-C
# Ghidra: open source alternative
# Detect: packed? UPX/MPRESS/VMProtect?
 
# 3. Unpack if packed
upx -d target.exe -o target_unpacked.exe
 
# 4. Dynamic analysis (x64dbg)
# Set breakpoints
# API monitoring (API Monitor, Procmon)
# Trace execution
 
# 5. Import/Export analysis
dumpbin /imports target.exe
# API calls → determine app behavior

Win32 Key APIs for Security Analysis

APIFunctionUse in Analysis
CreateFileFile openCari file config, log, database
RegOpenKeyExRegistry accessCek registry persistence, config
InternetOpenHTTP requestNetwork communication analysis
CreateProcessProcess creationDeteksi child process, inject
VirtualAllocExRemote memory allocCode injection detection
SetWindowsHookExKeyboard/mouse hookKeylogger detection
CryptDecryptDecryptionCari decryption routine
IsDebuggerPresentAnti-debugBypass anti-debug
OutputDebugStringDebug outputDebug message analysis

Anti-Debug Bypass

Anti-Debug TechniqueBypass
IsDebuggerPresent()Patch return value (0)
NtQueryInformationProcess(ProcessDebugPort)ScyllaHide, TitanHide
NtSetInformationThread(HideThreadFromDebugger)x64dbg + ScyllaHide plugin
TLS CallbacksSet breakpoint BEFORE entry point
Timing checks (rdtsc)Patch timing check or use VM
INT3 / CC breakpoint detectionHardware breakpoint (DR0-DR3)
PEB BeingDebuggedScyllaHide forces PEBBeingDebugged=0

.NET Application Analysis

.NET vs Native

Native (C++):   .text → x86/x64 machine code → IDA/Ghidra
.NET (C#/VB):   .text → MSIL (CIL) → dnSpy/de4dot → C# source

.NET Reversing Tools

ToolFungsiHarga
dnSpy.NET debugger + decompilerFree
de4dot.NET obfuscation removerFree
ILSpy.NET decompilerFree
ConfuserEx.NET obfuscator (analisis)Free
DotPeek.NET decompiler (JetBrains)Free

.NET Security Issues

IssueSourceImpact
Hardcoded connection stringapp.config / App.configDatabase access leak
Unprotected license checkif-then-else in MSILEasy to patch (nop)
Serialization vulnerabilityBinaryFormatterRCE via deserialization
Weak obfuscationConfuserEx, ObfuscarReversible with de4dot
Embedded resources.resources filesSecret extraction
String encryptionCustom XOR/Base64Reverse decryption function

.NET Deobfuscation

# 1. Detect obfuscator → de4dot auto-detect
de4dot target.exe -o target_cleaned.exe
 
# 2. Open in dnSpy
dnspy target_cleaned.exe
 
# 3. Set breakpoint, analyze, patch
# Right-click → Edit Method → Save Module

Binary Patching

Types of Patch

Patch TypeToolUse Case
NOP patchx64dbg, HxDDisable check (jump → NOP)
JMP patchx64dbg, IDARedirect execution flow
Hex editHxD, 010 EditorChange constant, string
DLL proxyCustom DLLHook API calls
Memory patchCheat EngineRuntime modification
IL patch (dnSpy)dnSpy.NET method body edit

Example: Bypass License Check

Original:  je 0x4010A0    (jump jika license valid → success)
Patch:     jmp 0x4010A0   (always jump → always success)
Atau:      nop; nop        (disable jump entirely)

Desktop Attack Surface

SurfaceTeknikImpact
Local file accessPath traversal, symlinkRead/write arbitrary files
Named pipesPipe impersonationPrivilege escalation
COM objectsCOM hijackingPersistence, privilege escalation
RegistryRegistry modificationPersistence, config manipulation
DLL hijackingMissing DLL in PATHArbitrary code execution
DLL injectionCreateRemoteThread + LoadLibraryCode execution in target process
Process hollowingReplace process memoryStealth execution
DLL sideloadingLegitimate EXE loads malicious DLLBypass app whitelist
Local privilege escalationNamed pipe, token manipulationSYSTEM access
Clipboard monitoringSetClipboardViewerPassword theft

Toolchain

ToolPlatformFungsiHarga
Electron (asar, elect)CrossASAR analysisFree
x64dbgWindowsDebugger (32/64 bit)Free
IDA ProWindowsDisassembler + decompiler$$$
GhidraCrossOpen source reverse engineeringFree
dnSpyWindows.NET debugger + decompilerFree
de4dotCross.NET deobfuscatorFree
HxDWindowsHex editorFree
010 EditorCrossHex editor + templates$
Process MonitorWindowsFile, registry, process monitoringFree
API MonitorWindowsAPI call monitoringFree
ScyllaHideWindowsAnti-anti-debug pluginFree
Cheat EngineWindowsMemory scanning + patchingFree
PeStudioWindowsPE analysisFree
Detect It Easy (DiE)CrossPacker/compiler detectionFree

Koneksi ke Vault