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

Proyecto del Laboratorio II de Ciberseguridad CMPT733
.
├── README.md
├── heaplens.png
├── heaplens.py
├── logs
│ ├── sudoedit-#.txt
│ └── ...
└── tests
├── Makefile
├── env-in-heap
└── ...
README.md: ¡aquí mismo!heaplens.py: el script principallogs/: contiene algunos registros de ejemplo que capturamos durante el desarrollo y las pruebastests/: contiene algunos binarios (y sus códigos fuente) para pruebasAquí 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.
python 3.8.10glibc 2.34gdb 9.2gef 2022.01
gef no está habilitado bajo root, echa un vistazo a /root/.gdbinit~/.gdbinitsudo (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.
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
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.
Inicia gef y edita la configuración:
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).
Añade esta línea en ~/.gdbinit o /root/.gdbinit:
source <ruta a>/heaplens/heaplens.py
Se sugiere ejecutar gdb bajo root al depurar programas privilegiados:
$ sudo su
# gdb
Se proporcionan mensajes de ayuda para todos los comandos. Puedes acceder a ellos mediante <comando> -h en GDB.
heaplensRecopila 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.
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:
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-dumpVuelca 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.
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:
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-chunksGenera 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.
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:
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-clearLimpia todos los registros/datos internos recopilados y utilizados por heaplens.
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-envLista 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.
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:
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']
Para compilar los scripts de los casos de prueba (compilados en la VM)
$ cd tests
$ make all
tests/heap-dumpgef➤ file tests/heap-dump
gef➤ heaplens -b breakme
gef➤ heaplens-dump
sudoedit a output.txtgef➤ file sudoedit
gef➤ heaplens -b set_cmnd -- -s \\ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
gef➤ heaplens-dump -o output.txt
tests/env-in-heapgef➤ file tests/env-in-heap
gef➤ heaplens-list-env
...
----------------------------
2nd execution. Possible environment variables for heap grooming:
['ENV_IN_HEAP']
----------------------------
sudoeditgef➤ 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']
----------------------------
Consulta la página de Issues para más detalles.