Skip to content
KitploitKITPLOIT
HerramientasBlog
Enviar
HerramientasBlog
Enviar

¡Herramientas de Hacking, PenTest y Ciberseguridad para tu Arsenal de Seguridad!

Kitploit es un directorio de herramientas de hacking, ciberseguridad y pentesting. Descubre las últimas actualizaciones de proyectos para encontrar vulnerabilidades, analizar sistemas, automatizar pruebas y fortalecer tu seguridad.

··Feeds·Contacto·Privacidad·© 2026 Kitploit

Directorio de Herramientas

Categorías

Ver todas las categorías
Loading categories
heaplens — # Proyecto del Laboratorio II de Ciberseguridad CMPT733: Plugin de GDB para exploits de heap inspirado en CVE-2021-3156 | Kitploit
Herramientas/GitHubGitHub/ypl6/heaplens
Análisis de VulnerabilidadesExplotaciónDepuradoresAnálisis de BinariosAprendizaje y Educación
GitHubypl6/heaplens

heaplens

# Proyecto del Laboratorio II de Ciberseguridad CMPT733: Plugin de GDB para exploits de heap inspirado en CVE-2021-3156

Ver Repositorio
2hace 4 añosAún no revisado

Más Populares

Ver todos →

Descubre las herramientas más usadas por nuestra comunidad.

Explora todas las herramientas

Explora nuestra colección de herramientas

Ver todas las herramientas →
Compartir

heaplens

🔎 Heaplens

Proyecto del Laboratorio II de Ciberseguridad CMPT733

📂 Estructura del Repositorio

root@kitploit:~
.
├── README.md
├── heaplens.png
├── heaplens.py
├── logs
│   ├── sudoedit-#.txt
│   └── ...
└── tests
    ├── Makefile
    ├── env-in-heap
    └── ...
  • README.md: ¡aquí mismo!
  • heaplens.py: el script principal
  • logs/: contiene algunos registros de ejemplo que capturamos durante el desarrollo y las pruebas
  • tests/: contiene algunos binarios (y sus códigos fuente) para pruebas

📦 Entorno

Aquí hay una lista de cosas (y versiones) que usamos para probar el exploit. Ya deberían estar instaladas en la VM. En caso de que falte algo, sigue las instrucciones a continuación.

Dependencias

  • Ubuntu 20.04.4 (64-bit)
  • python 3.8.10
  • glibc 2.34
  • gdb 9.2
  • gef 2022.01
    • Si gef no está habilitado bajo root, echa un vistazo a /root/.gdbinit
    • Si el archivo está vacío, simplemente copia lo que tengas en ~/.gdbinit

Dependencias de sudo (para ejecutar heaplens sobre sudo)

Se requiere un binario de sudo con depuración habilitada. Se ha instalado en la VM un binario precompilado con símbolos de depuración.

root@kitploit:~
cyberlab@ubuntu:~$ which sudo
/usr/local/bin/sudo

cyberlab@ubuntu:~$ sudo --version
Sudo version 1.8.31
Sudoers policy plugin version 1.8.31
Sudoers file grammar version 46
Sudoers I/O plugin version 1.8.31

cyberlab@ubuntu:~$ sudoedit -s /
sudoedit: /: not a regular file # sudo es vulnerable

📝 Cargando el Plugin

Esto ya se ha hecho en la VM. En caso de que la configuración sea errónea, puedes seguir las instrucciones aquí para cargar Heaplens.

Opción 1

Inicia gef y edita la configuración:

root@kitploit:~
gef➤ gef config gef.extra_plugins_dir <ruta a>/heaplens
gef➤ gef save
gef➤ q

Esto debería actualizar el archivo ~/.gef.rc o /root/.gef.rc (bajo root).

Opción 2

Añade esta línea en ~/.gdbinit o /root/.gdbinit:

root@kitploit:~
source <ruta a>/heaplens/heaplens.py

💡 Uso

Se sugiere ejecutar gdb bajo root al depurar programas privilegiados:

root@kitploit:~
$ sudo su
# gdb

Se proporcionan mensajes de ayuda para todos los comandos. Puedes acceder a ellos mediante <comando> -h en GDB.

heaplens

Recopila información del heap de las funciones de asignación y liberación de memoria, incluyendo malloc, realloc, calloc y free.

La idea de alto nivel es que, al enganchar estas funciones, podemos automatizar el proceso de verificar y actualizar la pila de llamadas, así como la dirección de retorno de la asignación de memoria. Al inspeccionar los rastros, podemos ver qué chunk es asignado por foo() en algunos archivos C, y podemos investigar más a fondo, por ejemplo, verificando los chunks adyacentes, para encontrar objetivos adecuados para la explotación del heap.

También admite añadir puntos de interrupción personalizados en medio si el usuario está interesado en un diseño de heap intermedio.

El comando en sí no es muy verboso y necesitarás usar heaplens-dump para imprimir los resultados.

root@kitploit:~
heaplens -h
usage: [-h] [-b BREAKPOINT] [-v]

Collect heap info from memory (de)allocation functions.

optional arguments:
  -h, --help            show this help message and exit
  -b BREAKPOINT, --breakpoint BREAKPOINT
                        stop the executions here (execute br {breakpoint} in gdb) (default: None)
  -v, --verbose         increase output verbosity (default: False)

Ejemplo de salida:

root@kitploit:~
gef➤  file sudoedit
gef➤  heaplens -b set_cmnd -- -s '\\' $(python3 -c 'print("A"*65535)')
----------------------------
Initializing Heaplens
----------------------------
Temporary breakpoint 1 at 0x5840: file ../../src/src/sudo.c, line 136.
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
usage: sudoedit [-AknS] [-C num] [-g group] [-h host] [-p prompt] [-T timeout] [-u user] file ...
[Inferior 1 (process 82934) exited with code 01]
Setting breakpoint at set_cmnd...
Function "set_cmnd" not defined.
Breakpoint 2 (set_cmnd) pending.
Hooking free function...
Breakpoint 3 at 0x7f25cc163700: free. (2 locations)
Hooking malloc function...
Breakpoint 4 at 0x7f25cc163110: malloc. (2 locations)
Hooking realloc function...
Breakpoint 5 at 0x7f25cc163eb0: realloc. (2 locations)
Hooking calloc function...
Breakpoint 6 at 0x7f25cc164b40: calloc. (2 locations)
Running -s '\' $(python3 -c 'print("A"*65535)')...
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Breakpoint 2, set_cmnd () at ../../../src/plugins/sudoers/sudoers.c:804
804	../../../src/plugins/sudoers/sudoers.c: No such file or directory.
Removing breakpoints from mem_bkps...

heaplens-dump

Vuelca los registros de Heaplens. Proporcionamos opciones para escribir los resultados en un archivo, generar la salida en formato JSON y ordenar los chunks por sus direcciones. En el volcado, cada chunk tendrá su dirección, tamaño, rastro de llamadas y la función de asignación de memoria relacionada registrados de una manera más legible.

root@kitploit:~
heaplens-dump -h
usage: [-h] [-o OUTPUT] [--json] [-s]

Dump Heaplens logs. Writes to stdout by default.

optional arguments:
  -h, --help            show this help message and exit
  -o OUTPUT, --output OUTPUT
                        write to file at path {output} (default: None)
  --json                dump in json (default: False)
  -s, --sort            sort the chunks by their addresses (default: False)

Ejemplo de salida:

root@kitploit:~
gef➤  heaplens-dump
----------------------------
Dumping...
----------------------------

...

[malloc] Chunk 3 @ 0x55f3908ed2a0 | size 0xc
Trace:
#0  __GI___strdup (s=0x7fff6fb3b8dc "en_US.UTF-8") at strdup.c:44
#1  0x00007f285df363c5 in _nl_load_locale_from_archive (category=category@entry=0xc, namep=namep@entry=0x7fff6fb29f50) at loadarchive.c:464
#2  0x00007f285df351fe in _nl_find_locale (locale_path=0x0, locale_path_len=0x0, category=category@entry=0xc, name=name@entry=0x7fff6fb29f50) at findlocale.c:152
#3  0x00007f285df34925 in __GI_setlocale (locale=<optimized out>, category=<optimized out>) at setlocale.c:337
#4  __GI_setlocale (category=<optimized out>, locale=<optimized out>) at setlocale.c:217
#5  0x000055f3901d5965 in main (argc=0x4, argv=0x7fff6fb2a298, envp=0x7fff6fb2a2c0) at ../../src/src/sudo.c:1430

...

Dump complete.

heaplens-chunks

Genera una versión ligeramente modificada de heap chunks de gef.

Esto extiende heap chunks de GEF (que muestra las direcciones, banderas, tamaños y metadatos de los chunks) integrando información sobre chunks libres de heap bins (que lista chunks previamente asignados y liberados de los bins de glibc). GEF proporciona funciones que ayudan a la inspección del heap, como las dos que mencionamos, pero es tedioso combinar ambas. A alto nivel, este comando recopila las direcciones de los chunks libres de la segunda y las etiqueta en el resultado de la primera.

root@kitploit:~
heaplens-chunks -h
usage: [-h] [--nocolor]

A modified `heap chunks` with info about free chunks.

optional arguments:
  -h, --help  show this help message and exit
  --nocolor   disable ANSI color codes

Ejemplo de salida:

root@kitploit:~
gef➤  heaplens-chunks
Showing current heap info with freed chunks:

...

Chunk(addr=0x55dd7f91ddb0, size=0xed0, flags=PREV_INUSE)  ←  free chunk
    [0x000055dd7f91ddb0     e0 fb ba e1 f8 7f 00 00 e0 fb ba e1 f8 7f 00 00    ...............]
Chunk(addr=0x55dd7f91ec80, size=0x50, flags=! PREV_INUSE)
    [0x000055dd7f91ec80     2f 75 73 72 2f 6c 6f 63 61 6c 2f 73 62 69 6e 3a    /usr/local/sbin]
Chunk(addr=0x55dd7f91ecd0, size=0x4010, flags=PREV_INUSE)  ←  free chunk
    [0x000055dd7f91ecd0     f0 02 bb e1 f8 7f 00 00 f0 02 bb e1 f8 7f 00 00    ...............]
Chunk(addr=0x55dd7f922ce0, size=0x50, flags=! PREV_INUSE)
    [0x000055dd7f922ce0     90 02 91 7f dd 55 00 00 00 00 00 00 00 00 00 00    .....U.........]
Chunk(addr=0x55dd7f922d30, size=0x2da0, flags=PREV_INUSE)  ←  free chunk
    [0x000055dd7f922d30     d0 02 bb e1 f8 7f 00 00 d0 02 bb e1 f8 7f 00 00    ...............]
Chunk(addr=0x55dd7f925ad0, size=0x110, flags=! PREV_INUSE)  ←  free chunk
    [0x000055dd7f925ad0     00 00 00 00 00 00 00 00 10 f0 90 7f dd 55 00 00    .............U.]
Chunk(addr=0x55dd7f925be0, size=0x30, flags=PREV_INUSE)
    [0x000055dd7f925be0     00 00 00 00 00 00 00 00 d2 78 b7 7e dd 55 00 00    .........x.~.U.]
Chunk(addr=0x55dd7f925c10, size=0x20, flags=PREV_INUSE)
    [0x000055dd7f925c10     65 6e 5f 55 53 2e 55 54 46 2d 38 00 00 00 00 00    en_US.UTF-8....]
Chunk(addr=0x55dd7f925c30, size=0xa3e0, flags=PREV_INUSE)  ←  top chunk

heaplens-clear

Limpia todos los registros/datos internos recopilados y utilizados por heaplens.

root@kitploit:~
heaplens-clear -h
usage: [-h] [-v]

Clear Heaplens logs.

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose  increase output verbosity

heaplens-list-env

Lista las variables de entorno que se almacenan y liberan en el heap. Es particularmente útil cuando quieres realizar heap grooming, ya que estas variables podrían afectar el diseño del heap.

root@kitploit:~
heaplens-list-env -h
usage: [-h] [-v] [--prefix PREFIX] [--suffix SUFFIX] [-b BREAKPOINT] [-s SKIP]

List environment variables that might affect the heap layout.

optional arguments:
  -h, --help            show this help message and exit
  -v, --verbose         increase output verbosity
  --prefix PREFIX       environment variable value prefix
  --suffix SUFFIX       environment variable value suffix
  -b BREAKPOINT, --breakpoint BREAKPOINT
                        stop the executions here (execute br {breakpoint} in gdb)
  -s SKIP, --skip SKIP  skip this environment variable

Ejemplo de salida:

root@kitploit:~
gef➤  file sudoedit
Reading symbols from sudoedit...
gef➤  heaplens-list-env -s LC_ALL -b set_cmnd --prefix C.UTF-8@ -- -s \\ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

...

1st execution. Found following environment variable:
['LOCPATH', 'LC_ALL', 'LC_IDENTIFICATION', 'LANG', 'LC_MEASUREMENT', 'LC_TELEPHONE', 'LC_ADDRESS', 'LC_NAME', 'LC_PAPER', 'LC_MESSAGES', 'LC_MONETARY', 'LC_COLLATE', 'LC_TIME', 'LC_NUMERIC', 'LC_CTYPE', 'TZ', 'SHELL', 'LANGUAGE']
  
...

2nd execution. Possible environment variables for heap grooming:
['LC_IDENTIFICATION', 'LC_COLLATE', 'TZ', 'LC_TIME', 'LANGUAGE', 'LC_NAME', 'LOCPATH', 'LC_MESSAGES', 'LC_NUMERIC', 'LC_ADDRESS', 'LC_TELEPHONE', 'LC_MONETARY', 'LC_MEASUREMENT', 'LC_CTYPE', 'LC_PAPER']

🛠 Casos de Prueba

Para compilar los scripts de los casos de prueba (compilados en la VM)

root@kitploit:~
$ cd tests
$ make all

Volcar el diseño del heap de tests/heap-dump

root@kitploit:~
gef➤  file tests/heap-dump
gef➤  heaplens -b breakme
gef➤  heaplens-dump

Volcar el diseño del heap de sudoedit a output.txt

root@kitploit:~
gef➤  file sudoedit
gef➤  heaplens -b set_cmnd -- -s \\ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
gef➤  heaplens-dump -o output.txt

Listar variables de entorno para heap grooming en tests/env-in-heap

root@kitploit:~
gef➤  file tests/env-in-heap
gef➤  heaplens-list-env

...

----------------------------
2nd execution. Possible environment variables for heap grooming:
['ENV_IN_HEAP']
----------------------------

Listar variables de entorno para heap grooming en sudoedit

root@kitploit:~
gef➤  file sudoedit
gef➤  heaplens-list-env -s LC_ALL -b set_cmnd --prefix C.UTF-8@ -- -s \\ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

...

----------------------------
1st execution. Found following environment variable:
['LOCPATH', 'LC_ALL', 'LC_IDENTIFICATION', 'LANG', 'LC_MEASUREMENT', 'LC_TELEPHONE', 'LC_ADDRESS', 'LC_NAME', 'LC_PAPER', 'LC_MESSAGES', 'LC_MONETARY', 'LC_COLLATE', 'LC_TIME', 'LC_NUMERIC', 'LC_CTYPE', 'TZ', 'SHELL', 'LANGUAGE']    
----------------------------

...

----------------------------
2nd execution. Possible environment variables for heap grooming:
['LC_CTYPE', 'LC_PAPER', 'LC_MONETARY', 'TZ', 'LC_ADDRESS', 'LC_MEASUREMENT', 'LC_IDENTIFICATION', 'LC_COLLATE', 'LC_NUMERIC', 'LC_MESSAGES', 'LC_TIME', 'LANGUAGE', 'LC_NAME', 'LOCPATH', 'LC_TELEPHONE']
---------------------------- 

🚨 Problemas Conocidos

Consulta la página de Issues para más detalles.

Descargar herramienta