- ¿Trabajas en una **empresa de ciberseguridad**? ¿Quieres ver tu **empresa anunciada en HackTricks**? ¿O quieres tener acceso a la **última versión de PEASS o descargar HackTricks en PDF**? ¡Consulta los [**PLANES DE SUSCRIPCIÓN**](https://github.com/sponsors/carlospolop)!
- **Únete al** [**💬**](https://emojipedia.org/speech-balloon/) [**grupo de Discord**](https://discord.gg/hRep4RUj7f) o al [**grupo de telegram**](https://t.me/peass) o **sígueme** en **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/hacktricks_live)**.**
- **Comparte tus trucos de hacking enviando PR al [repositorio de hacktricks](https://github.com/carlospolop/hacktricks) y al [repositorio de hacktricks-cloud](https://github.com/carlospolop/hacktricks-cloud)**.
Ya ha habido varios casos de **escalada de privilegios** en los que un **proceso privilegiado** con **handles abiertos e heredables** ha **ejecutado** un **proceso no privilegiado** dándole **acceso a todos esos handles**.
Por ejemplo, imagina que **un proceso que se ejecuta como SYSTEM abre un nuevo proceso** (`OpenProcess()`) con **acceso completo**. El mismo proceso **también crea un nuevo proceso** (`CreateProcess()`) **con bajos privilegios pero heredando todos los handles abiertos del proceso principal**.\
Entonces, si tienes **acceso completo al proceso de bajos privilegios**, puedes obtener el **handle abierto al proceso privilegiado creado** con `OpenProcess()` e **inyectar un shellcode**.
Como se leyó en el ejemplo inicial, si un **proceso no privilegiado hereda un handle de proceso** de un **proceso privilegiado** con suficientes permisos, podrá ejecutar **código arbitrario en él**.
En [**este excelente artículo**](http://dronesec.pw/blog/2019/08/22/exploiting-leaked-process-and-thread-handles/) se puede ver cómo explotar cualquier handle de proceso que tenga alguno de los siguientes permisos:
Similar a los handles de proceso, si un **proceso no privilegiado hereda un handle de hilo** de un **proceso privilegiado** con suficientes permisos, podrá ejecutar **código arbitrario en él**.
En [**este excelente artículo**](http://dronesec.pw/blog/2019/08/22/exploiting-leaked-process-and-thread-handles/) también se puede ver cómo explotar cualquier handle de hilo que tenga alguno de los siguientes permisos:
Si un **proceso no privilegiado hereda** un **handle** con **permisos equivalentes de escritura** sobre un **archivo privilegiado o registro**, podrá **sobrescribir** el archivo/registro (y con mucha **suerte**, **escalar privilegios**).
Los **Handles de Sección** son similares a los handles de archivo, el nombre común de este tipo de objetos es **"File Mapping"**. Se utilizan para trabajar con **archivos grandes sin mantener todo el archivo en memoria**. Eso hace que la explotación sea "similar" a la explotación de un Handle de Archivo.
[**Process Hacker**](https://github.com/processhacker/processhacker) es una herramienta que se puede descargar de forma gratuita. Tiene varias opciones increíbles para inspeccionar procesos y una de ellas es la **capacidad de ver los handles de cada proceso**.
Ten en cuenta que para **ver todos los handles de todos los procesos, se necesita el SeDebugPrivilege** (por lo que debes ejecutar Process Hacker como administrador).
El binario [**Handles** ](https://docs.microsoft.com/en-us/sysinternals/downloads/handle)de Sysinternals también mostrará los handles por proceso en la consola:
[**Esta herramienta**](https://github.com/lab52io/LeakedHandlesFinder) te permite **monitorear** los **handles filtrados** e incluso **autoexplotarlos** para escalar privilegios.
Ahora que sabes cómo encontrar los handles de los procesos, lo que necesitas verificar es si algún **proceso no privilegiado tiene acceso a handles privilegiados**. En ese caso, el usuario del proceso podría ser capaz de obtener el handle y abusar de él para escalar privilegios.
Se mencionó antes que se necesita el SeDebugPrivilege para acceder a todos los handles. Pero un **usuario aún puede acceder a los handles de sus procesos**, por lo que podría ser útil si quieres escalar privilegios solo desde ese usuario para **ejecutar las herramientas con los permisos regulares del usuario**.
Por ejemplo, el siguiente código pertenece a un **servicio de Windows** que sería vulnerable. El código vulnerable de este binario de servicio se encuentra dentro de la función **`Exploit`**. Esta función comienza **creando un nuevo proceso de handle con acceso completo**. Luego, está **creando un proceso de baja privilegiado** (copiando el token de baja privilegiado de _explorer.exe_) ejecutando _C:\users\username\desktop\client.exe_. La **vulnerabilidad reside en el hecho de que está creando el proceso de baja privilegiado con `bInheritHandles` como `TRUE`**.
Por lo tanto, este proceso de baja privilegiado puede tomar el handle del proceso de alta privilegiado creado primero e inyectar y ejecutar un shellcode (ver la siguiente sección).
En un escenario real, probablemente **no podrás controlar el binario** que será ejecutado por el código vulnerable (_C:\users\username\desktop\client.exe_ en este caso). Probablemente **comprometerás un proceso y tendrás que buscar si puedes acceder a algún handle vulnerable de algún proceso privilegiado**.
En este ejemplo se encuentra el código de una posible explotación para _C:\users\username\desktop\client.exe_.\
La parte más interesante de este código se encuentra en `GetVulnProcHandle`. Esta función **comenzará a buscar todos los handles**, luego **comprobará si alguno de ellos pertenece al mismo PID** y si el handle pertenece a un **proceso**. Si se cumplen todos estos requisitos (se encuentra un handle de proceso abierto accesible), intentará **inyectar y ejecutar un shellcode abusando del handle del proceso**.\
La inyección del shellcode se realiza dentro de la función **`Inject`** y simplemente **escribirá el shellcode dentro del proceso privilegiado y creará un hilo dentro del mismo proceso** para ejecutar el shellcode.
En un escenario real, probablemente **no podrás controlar el binario** que será ejecutado por el código vulnerable (_C:\users\username\desktop\client.exe_ en este caso). Probablemente **comprometerás un proceso y tendrás que buscar si puedes acceder a algún handle vulnerable de algún proceso privilegiado**.
En este ejemplo, **en lugar de abusar del handle abierto para inyectar** y ejecutar un shellcode, se **utilizará el token del proceso con handle privilegiado abierto para crear uno nuevo**. Esto se hace en las líneas del 138 al 148.
Observa cómo se utiliza la **función `UpdateProcThreadAttribute`** con el **atributo `PROC_THREAD_ATTRIBUTE_PARENT_PROCESS` y el handle del proceso privilegiado abierto**. Esto significa que el **hilo del proceso creado que ejecuta \_cmd.exe**\_\*\* tendrá el mismo token de privilegio que el proceso con handle abierto\*\*.
Esta herramienta te permite monitorear handles filtrados para encontrar aquellos vulnerables e incluso explotarlos automáticamente. También tiene una herramienta para filtrar uno.
- ¿Trabajas en una **empresa de ciberseguridad**? ¿Quieres ver tu **empresa anunciada en HackTricks**? ¿O quieres tener acceso a la **última versión de PEASS o descargar HackTricks en PDF**? ¡Revisa los [**PLANES DE SUSCRIPCIÓN**](https://github.com/sponsors/carlospolop)!
- **Únete al** [**💬**](https://emojipedia.org/speech-balloon/) [**grupo de Discord**](https://discord.gg/hRep4RUj7f) o al [**grupo de telegram**](https://t.me/peass) o **sígueme** en **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/hacktricks_live)**.**
- **Comparte tus trucos de hacking enviando PRs al [repositorio de hacktricks](https://github.com/carlospolop/hacktricks) y al [repositorio de hacktricks-cloud](https://github.com/carlospolop/hacktricks-cloud)**.