Showing posts with label kerberos. Show all posts
Showing posts with label kerberos. Show all posts

HackTheBox Scrambled: A Deep Dive into Kerberos Exploitation and Lateral Movement Defense

Date: October 1, 2022

Time: 10:38 AM

The hum of the servers was a low thrum against the silence of the late hour. Another box, another digital puzzle laid bare. This time, it was HackTheBox's "Scrambled." A name that, in this industry, often signifies tangled networks, obscured credentials, and the relentless pursuit of a foothold. Today, we're not just walking through a walkthrough; we're dissecting it. We're performing a post-mortem on a successful penetration to understand the vulnerabilities exploited and, more importantly, how a robust defense could have slammed the door shut.

This isn't about glorifying the breach. It's about learning from the shadows. It's about understanding the attacker's playbook so we can write a better defense manual. Let's peel back the layers of HackTheBox Scrambled, not as a victim, but as a security analyst armed with knowledge.

Table of Contents

Introduction

Welcome to the grim, gray world of network defense. Today, we tear into HackTheBox's "Scrambled" machine. This isn't just a walkthrough; it's a case study in how a well-orchestrated attack can unravel a network's security. From the initial reconnaissance to the final foothold, the techniques employed are common, yet their effectiveness hinges on overlooked configurations and a lack of granular monitoring. Our goal is to map these attack vectors, understand the underlying exploits, and crucially, identify the defensive blind spots that allowed them to succeed. This is about building resilience from understanding the threat.

The Initial Reconnaissance: Nmap and the Disabled Kerberos

The first step in any infiltration is mapping the terrain. The attacker initiated with Nmap, the ubiquitous port scanner. The logs would have shown a flurry of activity – probes testing for open ports and listening services. The critical discovery here was the apparent disabling of Kerberos. In a Windows domain environment, Kerberos is the gatekeeper, handling authentication. Its absence or misconfiguration is a siren call to any seasoned attacker. This initial finding shapes the entire attack vector, steering the adversary away from brute-force login attempts on standard user accounts and towards more sophisticated Kerberos-specific exploits.

00:00 - Intro
01:00 - Start of nmap

Kerberoasting: Enumerating Users and Password Spraying

With Kerberos potentially weakened, enumeration becomes paramount. The attacker employed Kerbrute, a tool designed to query Active Directory and identify valid user accounts. This isn't about guessing passwords yet; it's about building a list of legitimate targets. Once a substantial list of usernames was compiled, the next logical step was a password spray attack. This technique involves trying a small number of common or weak passwords against a large number of accounts. It's a stealthy approach, designed to avoid account lockouts by spreading the failed attempts across multiple users. If even a single account succumbs to a default or weak password, it’s the entry point.

04:00 - Viewing the website and discovering kerberos is disabled
07:45 - Using Kerbrute to enumerate valid users and then password spray with username

"Every system has a vulnerability. The trick is finding it before the other guy does. And sometimes, disabling a protocol is the loudest announcement that there's something interesting hidden behind it."

Understanding Kerberos Authentication (A Necessary Detour)

To truly grasp the attack, we need a brief detour into how Kerberos works. Think of it like a high-security movie theater. You, the user, want to see a movie (access a resource like an SQL server). First, you go to the Ticket Granting Service (TGS) with your ID (password) to get a Ticket Granting Ticket (TGT) from the Authentication Server (AS). This TGT is like your general admission pass to the entire multiplex. Then, when you want to see a specific movie (access a specific service), you present your TGT to the TGS and request a Service Ticket (ST) for that particular movie theater (service). The TGS verifies your TGT and issues an ST, which is then presented to the movie theater (the service itself) for entry. In "Scrambled," the attackers found ways to manipulate or bypass these ticket exchanges.

10:15 - Bad analogy comparing Kerberos works with TGT/TGS and Movie Theater Tickets

Leveraging GetTGT: Obtaining a Ticket Granting Ticket

The attackers moved deeper by using Impacket's `GetTGT.py` script. This tool is designed to retrieve a Ticket Granting Ticket (TGT) for a specific user account, provided they have the necessary credentials (often obtained through the previous password spray or enumeration). By obtaining a valid TGT for a user like 'ksimpson', the attacker effectively acquired a golden ticket, allowing them to impersonate that user in subsequent Kerberos authentication processes. The KRB5CCNAME environment variable was then set, directing Impacket tools to use this obtained TGT for further operations.

11:00 - Using Impacket's GetTGT Script to get Ticket Granting Ticket as Ksimpson and exporting KRB5CCNAME so Impacket uses it

Exploiting Service Principal Names (SPNs) with GetUserSPN

The next logical step for an attacker in a Kerberos-rich environment is Kerberoasting. This involves querying Active Directory for Service Principal Names (SPNs) and then attempting to crack the associated Kerberos service tickets offline. `GetUserSPN.py` from Impacket is a prime tool for this. It identifies accounts with SPNs configured, which are typically service accounts. By requesting and cracking the tickets associated with these SPNs, the attacker aims to obtain the plaintext password for the service account. In this scenario, they successfully obtained the password for `SqlSVC`.

12:30 - Using GetUserSPN to Kerberoast the DC with Kerberos Authentication and cracking to get SqlSVC's Password

The MSSQL Hurdle: When Initial Credentials Fail

A common pitfall for attackers, and a potential saving grace for defenders, is when initial credentials or compromised service accounts don't grant the expected access. Despite obtaining the password for `SqlSVC`, the attackers found themselves unable to access the MSSQL server. This indicates that either the `SqlSVC` account lacked the necessary permissions on the SQL server, or there were further network access controls in place. This often forces attackers to pivot their strategy, seeking alternative pathways to achieve their objectives.

16:40 - Both credentials we have cannot access MSSQL

Crafting a Silver Ticket: Bypassing SQL Access Controls

When direct access fails, impersonation and ticket manipulation become key. The attackers decided to craft a Silver Ticket. A Silver Ticket is a forged Service Ticket (ST) that allows an attacker to impersonate any user and access any service within a domain, assuming they know the NTLM hash of the domain's Kerberos Key Distribution Center (KDC). This is a powerful attack that bypasses normal authentication flows entirely by presenting a seemingly legitimate but entirely fabricated ticket.

18:50 - Creating a silver ticket to gain access to SQL

"The goal isn't to break into a system; it's to own it. And sometimes, owning it means rewriting the rules of authentication."

Gaining Domain SID: GetPAC and LDAP Search

To forge a Silver Ticket, knowledge of the domain's Security Identifier (SID) is crucial. The attackers used two methods to obtain this. First, `GetPAC.py`, another Impacket tool, can retrieve PAC (Privilege Attribute Certificate) information from a TGT, which often contains the domain SID. Alternatively, and perhaps more straightforwardly, they used `LDAPSearch` to query Active Directory directly for the domain SID. This information is foundational for crafting malicious Kerberos tickets that the domain will trust.

19:50 - Using GetPAC to get a Domain SID
20:30 - Showing getting Domain SID with LDAPSearch

Impacket's Ticketer: Forging the Silver Ticket

With the domain SID in hand and a TGT for an administrator account (or any account that can be forged into a Silver Ticket), the attackers used `Ticketer.py` from Impacket. This script allows an attacker to forge Kerberos tickets. By providing the necessary parameters—such as the target user, the domain SID, the NTLM hash of the domain-signing key (which they likely obtained earlier or through other means), and the target service—they could create a Silver Ticket granting them access to MSSQL.

24:00 - Creating the Silver Ticket with Impacket's Ticketer

The Ten-Year Ticket: A Defensive Oversight

A critical detail emerged: the forged Silver Ticket was created with a validity period of 10 years, not the typical 10 hours. This is a significant defensive lapse. While Kerberos tickets are meant to have lifespans, creating tickets with such extreme durations is a security risk, especially if they are forged. It indicates a lax security posture or a failure to properly configure ticket lifetime policies. For defenders, strict policies on ticket lifetimes, especially for administrative accounts and service accounts, are paramount. This extended validity provided the attackers with a long-term, persistent access method.

26:30 - Showing Impacket creates the ticket with 10 years instead of 10 hours

Enabling xp_cmdshell and Gaining a Reverse Shell

Possessing a valid Silver Ticket for MSSQL, the attackers could now execute commands on the target server. They enabled the `xp_cmdshell` stored procedure, a feature that allows SQL Server to execute arbitrary operating system commands. This is a double-edged sword; convenient for administrators, but a direct pathway for attackers. Once enabled, they used it to establish a reverse shell, giving them command-line access to the server from their own machine. This is a critical step in moving from service compromise to full system control.

27:40 - We now have MSSQL Access to the box, enabling xp_cmdshell and getting a reverse shell

Privilege Escalation with JuicyPotatoNG

Even with a reverse shell, an attacker aims for the highest privileges. On Windows systems, this often means gaining SYSTEM privileges. The attackers leveraged JuicyPotatoNG, a privilege escalation tool. This exploit takes advantage of the `SeImpersonatePrivilege` or `SeAssignPrimaryTokenPrivilege`. If an account possesses these privileges (which can sometimes be obtained through service misconfigurations or other vulnerabilities), JuicyPotatoNG can be used to impersonate the SYSTEM account, effectively granting the attacker SYSTEM-level shell access. The fact that it was successful suggests the compromised account had elevated privileges that were not properly restricted.

30:00 - Using JuicyPotatoNG to escalate privileges because we have SeImpersonate Privilege
32:00 - Running the JuicyPotatoNG Exploit and getting a shell in the unintended way

Database Enumeration and Credential Discovery

With SYSTEM privileges, a defender's worst nightmare begins. The attackers could now freely enumerate the MSSQL database. This involves querying tables, discovering schemas, and searching for sensitive information. Crucially, they found credentials within the database. This is a common pattern: compromise a service, gain access to its data, find more credentials, and pivot further into the network. The database, often seen as a secure vault, can become an accidental repository of credentials if not managed meticulously.

34:00 - Enumerating the MSSQL Database and finding credentials

Lateral Movement with Evil-WinRM and Kerberos

Armed with new credentials, the lateral movement phase began. The attackers used Evil-WinRM, a popular remote management tool that supports Kerberos authentication. By utilizing the credentials discovered in the MSSQL database and likely configuring Evil-WinRM to use Kerberos, they logged in as `MiscSvc` to another machine on the network. This demonstrates the cascading effect of compromising one system and finding credentials that grant access to others. This is where network segmentation and least privilege become your strongest allies.

35:40 - Using Evil-WinRM to login with Kerberos Auth
39:40 - Accessing the box as MiscSvc and finding a dotnet Application

Analyzing the .NET Application and Network Sniffing

On the `MiscSvc` machine, the attackers discovered a .NET application. This became the next target. To understand its communications, they set up their Linux host as a router. This allowed their compromised Windows machine to route traffic through the Linux box, enabling them to sniff network traffic. By analyzing the packets, they discovered that the .NET application was communicating with a specific port, `4411`. This detailed network analysis is crucial for identifying hidden communication channels or potentially vulnerable services.

43:40 - Setting up our linux host as a router so our Windows host can communicate to the HTB Network through the linux box
47:20 - Sniffing the traffic from the dotnet application and discovering it talks to port 4411

Crafting the Payload: YsoSerial.Net and Reverse Shells

The final stage of this particular breach involved exploiting the .NET application. By examining debug logs, the attackers found a serialized object. This is a common vulnerability where an application deserializes untrusted input, potentially leading to remote code execution. They used YsoSerial.Net, a tool for generating malicious serialized .NET objects. They crafted a payload designed to send them a reverse shell. This payload was then sent to the application listening on port 4411. The successful execution of this payload resulted in a final reverse shell, completing the compromise of the "Scrambled" box.

50:20 - Looking at debug logs and seeing a serialized object
52:40 - Using YsoSerial.Net to create a malicious base64 object to send us a reverse shell
55:30 - Sending our payload and getting a reverse shell

Defensive Strategies: Fortifying Against Scrambled's Tactics

The "Scrambled" box presented a multi-stage attack, highlighting several critical areas for defensive improvement:

  • Kerberos Hardening: Disable unnecessary SPNs, enforce strong password policies, implement account lockout policies judiciously, and monitor for Kerberoasting attempts. Regularly audit Kerberos configurations.
  • Privilege Management: Adhere to the principle of least privilege. Segment administrative roles. Prevent service accounts from having excessive privileges, especially `SeImpersonatePrivilege`.
  • Patch Management & Configuration: Ensure critical services like MSSQL are patched and hardened. Disable or restrict `xp_cmdshell` unless absolutely necessary and heavily monitored.
  • Network Segmentation: Isolate critical servers and services. Prevent easy lateral movement between different network zones. Network sniffing should ideally be a defensive tool, not an attacker's advantage.
  • Application Security: Validate all user input, especially deserialized objects. Employ static and dynamic analysis tools for .NET applications. Monitor for outbound connections on non-standard ports.
  • Logging and Monitoring: Centralize logs from all systems, especially Active Directory, MSSQL, and critical applications. Implement real-time alerts for suspicious activities like Kerberoasting, Silver Ticket creation attempts, and `xp_cmdshell` usage.
  • Credential Management: Avoid storing high-value credentials in databases or application configurations. Use secure credential management solutions.

Engineer's Verdict: The Cost of Neglecting Kerberos Security

HackTheBox Scrambled is a stark reminder that Kerberos, while a robust protocol, is not an impenetrable fortress. Its security hinges entirely on meticulous configuration and vigilant monitoring. The ease with which attackers moved from service enumeration to privileged access and lateral movement points to common oversights in Active Directory environments. The extended lifespan of the forged ticket is particularly alarming. Neglecting Kerberos security is akin to leaving the keys to the kingdom under the doormat. For any organization relying on Active Directory, a comprehensive Kerberos security audit and hardening strategy is not an option; it's a non-negotiable prerequisite for survival.

Operator's Arsenal: Essential Tools for Defense and Analysis

To counter the threats demonstrated in "Scrambled," an operator's toolkit must be robust:

  • For Kerberos Auditing & Hunting: Rubeus and SharpHound (for AD data collection), alongside custom SIEM queries for identifying suspicious Kerberos ticket events. Consider commercial threat hunting platforms for integrated AD analytics.
  • For Network Analysis: Wireshark for deep packet inspection, tcpdump for command-line sniffing, and SIEM solutions with network flow analysis capabilities.
  • For Application Security: YsoSerial.Net (for understanding deserialization vulnerabilities), Burp Suite or OWASP ZAP for web application analysis, and .NET decompiler tools.
  • For Forensics & Incident Response: Volatility Framework for memory analysis, Log2Timeline/Plaso for timeline creation, and forensic imaging tools.
  • For Privilege Escalation Study: Tools like JuicyPotatoNG, PrintSpoofer, and knowledge of Windows privilege escalation vectors.
  • Essential Learning Resources: Books like "Windows Internals" and "The Hacker Playbook" series, and advanced certifications such as OSCP or SANS GCFA are invaluable.

Frequently Asked Questions

What is the primary vulnerability exploited in HackTheBox Scrambled?

The machine exploits multiple layers, but the initial entry and lateral movement heavily rely on Kerberos misconfigurations, specifically Kerberoasting and the creation of forged Silver Tickets, leading to privilege escalation.

How can an organization prevent Kerberoasting attacks?

Implement strong password policies, enable account lockout, regularly audit SPNs for unusual configurations, and monitor for unusual service ticket requests using SIEM solutions.

Is enabling `xp_cmdshell` always a bad practice?

It is a high-risk feature. It should only be enabled if absolutely necessary for specific legitimate administrative tasks and should be heavily monitored for any unauthorized usage. Restricting its execution context is also crucial.

What is the significance of the .NET deserialization vulnerability?

.NET deserialization vulnerabilities allow attackers to execute arbitrary code by sending malicious serialized data to an application that doesn't properly validate input before deserializing it. This can lead to full system compromise.

The Contract: Hardening Your Network Against Kerberos Attacks

The "Scrambled" box has revealed its secrets. Now, it's your turn to act. Your contract is clear: harden your domain against the very techniques demonstrated here. Start by reviewing your Active Directory security posture. Are your SPNs configured correctly? Are service accounts being used with the least privilege necessary? Is Kerberos monitoring enabled and are alerts being acted upon? Conduct a thorough audit of your MSSQL configurations and application security. The digital world doesn't forgive negligence; it punishes it. Implement these defenses, and show the attackers that your network is not just another scrambled egg.

Manual de Red Team: Explotación Avanzada de Active Directory en Entornos de Pentesting

La red corporativa. Un ecosistema digital donde la información fluye, las transacciones se cierran y, a menudo, las puertas traseras permanecen abiertas. Active Directory (AD) es el corazón latente de muchas de estas infraestructuras, el guardián de identidades y accesos. Pero incluso los guardianes más vigilantes pueden ser engañados. Hoy no venimos a defender, venimos a entender cómo romper. Este no es un simple recorrido por una CTF; es una disección de un entorno real, una lección de cómo los atacantes entran, se mueven y controlan. Vamos a desmantelar las defensas, entender los protocolos y recuperar las credenciales que lo abren todo.

Las preguntas llegan como un caudal constante: ¿Qué herramientas son cruciales? ¿Cómo se pivotea de un sistema a otro? ¿Es el Kerberos solo un nombre o una puerta de entrada? A lo largo de este análisis, desgranaremos estas interrogantes, aplicando técnicas que resonarán en cada operación de Red Team. Estamos aquí para aprender las tácticas, las técnicas y los procedimientos (TTPs) que permiten un acceso sin restricciones, no para celebrar la brecha, sino para comprenderla en profundidad. Porque la mejor defensa es conocer al enemigo, sus métodos y sus debilidades fundamentales.

Tabla de Contenidos

¿Qué es Kerberos y Kerbrute?

En el corazón de Active Directory reside Kerberos, un protocolo de autenticación de red diseñado para proporcionar autenticación fuerte para aplicaciones de cliente/servidor utilizando criptografía de clave secreta. Es el sistema que permite a un usuario autenticarse una vez y acceder a múltiples servicios sin tener que volver a introducir credenciales. Imagínalo como un portero digital que emite pases verificados. Sin embargo, como cualquier sistema complejo, Kerberos tiene sus puntos ciegos. Aquí es donde herramientas como Kerbrute entran en juego. Kerbrute es una herramienta de código abierto escrita en Go, especializada en enumerar usuarios de dominio y realizar ataques de fuerza bruta contra Kerberos, buscando credenciales débiles o enumerando posibles objetivos de ataque como AS-REP Roasting.

El Debate de los Másters vs. Educación Formal

La pregunta sobre la valía de los Másters en Ciberseguridad frente a la formación profesional en áreas como Desarrollo de Aplicaciones Web (DAW), Desarrollo de Aplicaciones Multiplataforma (DAM) o Sistemas de Administración de Redes (ASIR) es recurrente. Si bien los másters ofrecen una perspectiva especializada, la formación técnica fundamental que proporcionan DAW, DAM o ASIR es a menudo el cimiento sobre el cual se construye el verdadero conocimiento en ciberseguridad. Entender cómo se desarrollan las aplicaciones o cómo funcionan las redes a bajo nivel es crucial para un pentester experimentado. No se trata de elegir uno u otro, sino de la sinergia: una base sólida complementada con especialización. Para un Red Teamer, comprender la arquitectura de AD y los protocolos subyacentes es tan importante como saber escribir un script de explotación.

Explotación de Kerberos: AS-REP Roasting y GetNPUsers

Dos de las técnicas más comunes para obtener credenciales o privilegios en un dominio son el AS-REP Roasting y el uso de GetNPUsers. El AS-REP Roasting explota una configuración específica de Kerberos. Si una cuenta de usuario no tiene activada la marca "Kerberos Pre-authentication Required" (el requisito de preautenticación), un atacante puede solicitar un Ticket Granting Ticket (TGT) para esa cuenta sin necesidad de conocer la contraseña. El TGT es cifrado con la contraseña del usuario. El atacante, al recibir este TGT, intenta descifrarlo offline utilizando un diccionario o fuerza bruta. La clave aquí es la marca de preautenticación; si está desactivada, el servicio de autenticación de Kerberos (KDC) emitirá un TGT que puede ser descifrado posteriormente.

Por otro lado, el método GetNPUsers busca cuentas que tengan la opción "Do not require Kerberos pre-authentication" habilitada. Un atacante puede solicitar directamente un Ticket Granting Service (TGS) para un servicio en particular (como recursos compartidos SMB) sin la necesidad de autenticación previa. Este TGS es cifrado con la clave de la cuenta de servicio, o en este caso, la clave de la cuenta de usuario objetivo. Nuevamente, el atacante puede descifrarlo offline para revelar la contraseña del usuario.

"La simplicidad es la máxima sofisticación." - Leonardo da Vinci, aplicado a la seguridad: los errores más fáciles de cometer son a menudo los más explotables.

Descifrando el TGT

Una vez que hemos obtenido un TGT o un TGS cifrado, el siguiente paso es descifrarlo. Esto se realiza típicamente con herramientas de cracking de contraseñas como Hashcat o John the Ripper. El proceso implica convertir el hash del TGT (o TGS) a un formato compatible con estas herramientas y luego ejecutar un ataque de diccionario o de fuerza bruta. La efectividad de este paso depende directamente de la complejidad de la contraseña del usuario objetivo y de los recursos computacionales del atacante. Para hashes de Kerberos, Hashcat es particularmente potente, con modos específicos para AS-REP Roasting (modo 13100) y TGS-REP (modo 13101 utilizando el hash `TGS-REQ`). El éxito aquí puede significar la obtención de credenciales de usuario válidas, abriendo puertas a más movimientos laterales.

Movilidad Lateral vía SMB y PassTheHash

Con las credenciales de un usuario obtenidas, ya sea mediante descifrado de hashes o de otras técnicas, el siguiente objetivo es la movilidad lateral: moverse a través de la red para acceder a otros sistemas o recursos. Uno de los protocolos más explotados para esto es Server Message Block (SMB). SMB se utiliza para el acceso a archivos y recursos compartidos, la comunicación de red y la impresión. Herramientas como Impacket, y específicamente scripts como psexec.py o smbexec.py, nos permiten abusar de SMB para ejecutar comandos o transferir archivos a máquinas remotas utilizando credenciales válidas.

La técnica de PassTheHash (PtH) es particularmente interesante. En lugar de descifrar un hash para obtener la contraseña y luego usarla para autenticarse, PtH permite usar el hash directamente para autenticarse en un sistema. Cuando un usuario se autentica, el sistema no almacena la contraseña en texto plano, sino su hash. PtH abusa de este mecanismo, inyectando el hash en el proceso de autenticación. Esto significa que un atacante puede moverse lateralmente sin nunca conocer la contraseña en texto plano del usuario, haciendo mucho más difícil la detección basada en la exposición de contraseñas. Herramientas como Mimikatz son fundamentales para extraer hashes de memoria o para realizar ataques PtH.

Veredicto del Ingeniero: Active Directory en el Campo de Batalla Digital

Active Directory, a pesar de ser el estándar de facto para la gestión de identidades en entornos Windows, presenta una superficie de ataque considerablemente grande cuando no se configura y mantiene adecuadamente. Los protocolos de autenticación como Kerberos, si bien robustos en su diseño, son susceptibles a vulnerabilidades derivadas de configuraciones incorrectas que facilitan ataques como AS-REP Roasting o Silver/Golden Tickets. La movilidad lateral a través de SMB y técnicas como PassTheHash son el pan de cada día de los Red Teams porque aprovechan la confianza inherente dentro del dominio. Para los administradores, la postura de seguridad de AD debe ser proactiva: auditorías regulares de configuraciones de Kerberos, gestión estricta de permisos, segmentación de red y la implementación de soluciones de detección de amenazas que monitoricen activamente actividades sospechosas, como la enumeración de usuarios o la autenticación anómala. Ignorar estas debilidades es invitar a los fantasmas a tu castillo.

Arsenal del Operador/Analista: Red Team

  • Enumeración y Fuerza Bruta:
    • Kerbrute (Go): Para enumeración de usuarios y AS-REP Roasting.
    • BloodHound (Python/C#): Para visualización de relaciones en AD y búsqueda de rutas de ataque.
    • SharpHound (C#): Data collector para BloodHound.
  • Explotación de Credenciales:
    • Hashcat / John the Ripper (GPU/CPU): Para cracking de hashes de Kerberos y NTLM.
    • Mimikatz (C#): Extracción de credenciales en memoria, PassTheHash, Golden Tickets.
  • Movilidad Lateral y Post-Explotación:
    • Impacket (Python): Suite de scripts para interactuar con protocolos de Windows/SMB (psexec.py, smbexec.py, etc.).
    • Metasploit Framework (Ruby): Módulos específicos para Active Directory.
    • PowerSploit / Empire (PowerShell): Frameworks para post-explotación y movimiento lateral.
  • Análisis y Aprendizaje:
    • "The Web Application Hacker's Handbook" (Libro): Para entender vulnerabilidades web que podrían ser un vector inicial.
    • "Red Team Field Manual" (RTFM) (Libro): Referencia rápida de comandos y herramientas.
    • Certificación OSCP (Offensive Security Certified Professional): Demuestra habilidades prácticas en pentesting ofensivo.
    • Plataformas como TryHackMe y Hack The Box: Entornos de práctica controlada.

Taller Práctico: Simulación de Ataque AD

Este taller simula escenarios comunes de Red Team centrados en Active Directory. Asumimos que ya hemos logrado un punto de entrada inicial en la red y tenemos una shell de bajo privilegio.

  1. Enumeración Inicial:
    • Usa SharpHound.ps1 (ejecutado desde una máquina comprometida o con acceso a un dominio) para recolectar datos de AD.
    • Analiza los resultados con BloodHound para identificar usuarios con privilegios, relaciones de confianza y posibles rutas de escalada.
    • Ejecuta Kerbrute userenum --domain example.com --threads 100 para enumerar usuarios y buscar cuentas sin preautenticación Kerberos.
  2. Ataque AS-REP Roasting:
    • Identifica usuarios sin preautenticación en los resultados de Kerbrute o SharpHound.
    • Utiliza GetUserSPNs.py (parte de Impacket) con los nombres de usuario identificados para solicitar TGTs cifrados. Ejemplo: GetUserSPNs.py -d example.com -u usuario.objetivo -p password.acceso -t targets.txt (donde targets.txt contiene los SPNs).
    • Extrae el hash del TGT obtenido.
    • Descifra el hash usando Hashcat -m 13100 hash.txt wordlist.txt.
  3. Movilidad Lateral con PassTheHash:
    • Supongamos que hemos obtenido un hash NTLM de un administrador (ej: Administrator:aad3b435b51404eeaad3b435b51404ee:f5a5d5d5a5d5d5d5d5d5d5d5d5d5d5d5).
    • Usa psexec.py con el hash para obtener una shell en otra máquina: psexec.py EXAMPLE.COM/Administrator:f5a5d5d5a5d5d5d5d5d5d5d5d5d5d5d5@TARGET_IP.
    • Alternativamente, usa Invoke-Mimikatz en PowerShell para extraer hashes de memoria y luego realizar PtH con otras herramientas.
  4. Persistencia (Opcional):
    • Considera técnicas de persistencia como la creación de usuarios con privilegios, la modificación de tareas programadas o el abuso de WMI, siempre documentando las acciones para entender el impacto y la detección.

Preguntas Frecuentes (FAQ)

¿Es legal realizar estos ataques?

Estas técnicas son éticamente aplicables en entornos controlados y autorizados, como CTFs, programas de bug bounty o ejercicios de Red Team con permiso explícito. Realizar estos ataques en sistemas sin autorización es ilegal.

¿Qué es más peligroso, AS-REP Roasting o PassTheHash?

Ambos son peligrosos en su contexto. AS-REP Roasting puede ser un vector de entrada para obtener credenciales válidas si la contraseña es débil. PassTheHash es una técnica de movilidad lateral muy potente que permite el acceso sin necesidad de conocer la contraseña en texto plano, dificultando su detección por medios tradicionales.

¿Cómo se defiende una organización contra estos ataques?

Requerir preautenticación Kerberos para todas las cuentas, usar contraseñas fuertes y únicas, segmentar la red, implementar monitorización de seguridad avanzada para detectar enumeración y accesos anómalos, y aplicar el principio de mínimo privilegio son defensas clave.

¿Existen alternativas a Active Directory?

Sí, existen soluciones como LDAP, soluciones de gestión de identidades en la nube como Azure AD, Okta, o sistemas de autenticación descentralizados. Sin embargo, AD sigue siendo predominante en muchas infraestructuras empresariales tradicionales.

¿Qué herramientas no mencionadas aquí son importantes para Red Teaming en AD?

Herramientas como `Responder` para ataques de envenenamiento LLMNR/NBT-NS, `PowerShell Empire` para post-explotación avanzada, y el uso intensivo de scripts personalizados en Python o PowerShell son también vitales.

El Contrato: Asegura el Perímetro

Has navegado por las profundidades de Active Directory, has visto cómo se desmantelan las defensas Kerberos y cómo se abusa de la confianza interna. Ahora, el contrato es tuyo: aplica este conocimiento. Tu desafío final es auditar la configuración de Kerberos en un entorno de laboratorio (como una máquina virtual con AD configurado) y buscar activamente cuentas que no requieran preautenticación. Una vez identificadas, intenta realizar un AS-REP Roast. Documenta tus hallazgos y, lo más importante, las medidas de mitigación que implementarías para cerrar esa brecha. La defensa empieza con la comprensión profunda del ataque.