Ideas clave
1. Establecer una Base para las Pruebas de Penetración
Para lograrlo, es necesario contar con un sistema estándar, herramientas y procesos definidos.
Proceso Repetible. Un enfoque constante es fundamental para realizar pruebas de penetración efectivas. Esto implica configurar sistemas de ataque, herramientas y metodologías estandarizadas. Tener tanto un equipo con Windows como uno con Linux, equipados con las herramientas esenciales, permite realizar pruebas consistentes en distintos entornos.
Instantáneas de Máquinas Virtuales. Tomar instantáneas de máquinas virtuales limpias y configuradas es una salvación. Esto permite regresar rápidamente a un estado conocido, aplicar parches, actualizar herramientas y añadir cualquier recurso adicional necesario para cada compromiso específico. Así se ahorra tiempo y se garantiza uniformidad en las pruebas.
Hardware y Software. Los requisitos básicos de hardware incluyen una laptop con al menos 8 GB de RAM, 500 GB de espacio en disco (preferiblemente SSD) y un procesador Intel i7 Quad Core. En cuanto al software, es esencial contar con VMware Workstation/Fusion/Player o VirtualBox, y Kali Linux. Herramientas comerciales como Nexpose/Nessus y Burp Suite son altamente recomendadas para pruebas profesionales.
2. Dominar la Recolección Pasiva de Información
Comienza con el Descubrimiento Pasivo, que busca información sobre el objetivo, la red, los clientes y más, sin interactuar directamente con el host.
Reconocimiento No Intrusivo. La recolección pasiva implica obtener datos sobre el objetivo sin interactuar directamente con sus sistemas. Esto es crucial para evitar ser detectado y para obtener una visión inicial de la infraestructura, el personal y la presencia en línea del objetivo.
Scripts de Descubrimiento. Herramientas como Discover-scripts automatizan diversas búsquedas, incluyendo la identificación de personas dentro de la organización, dominios, direcciones de correo electrónico y archivos. Esta herramienta recopila información de múltiples fuentes, como LinkedIn, Google dorks y registros WHOIS, en un solo informe.
Listas Comprometidas. Utilizar bases de datos de credenciales filtradas puede ser muy efectivo para detectar reutilización de contraseñas. Al analizar bases de datos comprometidas, como la filtración de Adobe, es posible identificar direcciones de correo electrónico y contraseñas cifradas asociadas al dominio objetivo. Esta información puede emplearse para ataques de descifrado o campañas de spear phishing.
3. Emplear Técnicas de Escaneo Activo
El descubrimiento activo consiste en identificar sistemas, servicios y posibles vulnerabilidades mediante interacción directa.
Identificación de Sistemas y Servicios. El descubrimiento activo implica interactuar directamente con la red objetivo para identificar sistemas, servicios y vulnerabilidades potenciales. Para ello, se utilizan escáneres de red como Nmap y escáneres de vulnerabilidades como Nexpose o Nessus.
Proceso de Escaneo. Un proceso típico de escaneo incluye:
- Escaneo de vulnerabilidades en la red (Nexpose/Nessus)
- Escaneo con Nmap
- Escaneo con scripts personalizados de Nmap
- Captura de pantalla con PeepingTom
Captura de Banners con Nmap. Ejecutar un escaneo personalizado de detección de sistema operativo y servicios con Nmap en puertos comunes (o en los 65,535 puertos) es esencial. Usar un script de captura de banners como banner-plus.nse permite identificar rápidamente la página de bienvenida de los puertos abiertos, proporcionando información valiosa sobre los servicios activos en la red objetivo.
4. Explotar Vulnerabilidades con Precisión
Cuando un escáner detecta una vulnerabilidad, normalmente busco un exploit funcional.
Herramientas de Explotación. Metasploit es una herramienta común para explotar vulnerabilidades. Permite seleccionar un exploit, configurar opciones, ajustar cargas útiles y ejecutar el ataque. Sin embargo, es fundamental comprender cómo funcionan los exploits y saber modificarlos si es necesario.
Explotación Manual. Muchas veces, los exploits no están disponibles en Metasploit y deben buscarse en otros lugares. Estos pueden estar escritos en diversos lenguajes de scripting como Python, C++, Ruby, Perl o Bash. Como tester de penetración, es imprescindible saber editar, modificar, ejecutar y entender estos scripts.
Validación de Scripts. Antes de ejecutar cualquier script, es vital probarlo primero. Algunos pueden contener código malicioso que dañe el sistema objetivo. Siempre valida el código shell y comprende el posible impacto del exploit.
5. Navegar Lateralmente por la Red
Esta etapa se centra en moverse dentro de la red, pasando de un usuario limitado a controlar toda la red.
Recolección de Credenciales. Una vez dentro de la red, el objetivo es desplazarse lateralmente y escalar privilegios. Esto suele implicar la captura de credenciales mediante herramientas como Responder.py, WCE (Windows Credential Editor) y Mimikatz.
Responder.py. Responder.py escucha solicitudes LLMNR y NBT-NS y responde a ellas, capturando hashes de desafío/respuesta NTLM. Estos hashes pueden ser descifrados con John the Ripper o oclHashcat.
Preferencias de Políticas de Grupo (GPP). Las GPP son extensiones de Active Directory que permiten a los administradores configurar ajustes en máquinas unidas al dominio. Sin embargo, si se usan para distribuir cuentas de administrador local, los nombres de usuario y contraseñas pueden almacenarse en formato legible en el controlador de dominio, lo que permite a cualquier usuario del dominio recuperarlos.
6. Dominar las Tácticas de Ingeniería Social
Si los ataques a clientes están dentro del alcance de tus pruebas, la ingeniería social es tu ataque predilecto.
Dominios Doppelganger. Comprar dominios doppelganger (por ejemplo, uscompany.com en lugar de us.company.com) puede ser muy efectivo para capturar información sensible. Al configurar un servidor SMTP con una configuración catch-all, puedes interceptar correos enviados al dominio mal escrito.
Spear Phishing. El spear phishing consiste en crear correos electrónicos dirigidos a individuos o grupos específicos dentro de una organización. Esto requiere recopilar información sobre el objetivo, como sus intereses, relaciones y patrones de comunicación.
Social Engineering Toolkit (SET). SET es un marco poderoso para crear y lanzar ataques de ingeniería social. Incluye módulos para clonar sitios web, crear recolectores de credenciales y generar cargas útiles maliciosas.
7. Evadir la Detección de Antivirus
Mi opinión sobre los escáneres antivirus es que están diseñados para detener a los script kiddies.
Detección Basada en Firmas. Los antivirus suelen basarse en la detección por firmas, que identifica patrones conocidos de código malicioso. Para evadirlos, es necesario modificar u ocultar las cargas útiles para evitar activar estas firmas.
Herramienta Evade. Herramientas como Evade ayudan a identificar las cadenas o patrones de código que activan la detección antivirus. Al dividir el archivo y escanear cada parte, puedes localizar con precisión la firma problemática.
Cargas Útiles en Python. Python es un lenguaje versátil para crear cargas útiles maliciosas que pueden evadir antivirus. Los scripts en Python pueden ser fácilmente ofuscados y convertidos en ejecutables usando herramientas como py2exe o pyinstaller.
8. Optimizar Estrategias para Romper Contraseñas
Aquí he reunido todo lo demás que ayuda en las pruebas de penetración, pero que no encajaba en otras secciones.
Herramientas para Romper Contraseñas. John the Ripper (JtR) y oclHashcat son dos herramientas potentes para descifrar hashes de contraseñas. JtR es versátil y soporta una amplia variedad de algoritmos de hash, mientras que oclHashcat aprovecha la potencia de las GPUs para acelerar el proceso.
Listas de Palabras, Reglas y Algoritmos de Hash. Para optimizar el descifrado, es fundamental definir listas de palabras, reglas y algoritmos de hash. Las listas contienen contraseñas comunes, las reglas modifican estas listas para generar variaciones, y los algoritmos especifican el tipo de hash que se intenta romper.
oclHashcat. oclHashcat es una herramienta poderosa para romper hashes usando GPUs. Soporta una amplia gama de algoritmos y puede usarse para descifrar hashes WPAv2 y NTLMv2.
Resumen de reseñas
The Hacker Playbook ha recibido opiniones encontradas, con una calificación general de 3.96 sobre 5. Los lectores valoran su estructura para pruebas de penetración y su enfoque práctico, considerándolo útil para profesionales, aunque no tanto para principiantes. Algunos destacan su cobertura amplia y consejos valiosos, mientras que otros critican su falta de profundidad y su excesiva dependencia en la descripción de herramientas. El libro es reconocido por sus capítulos sobre post-explotación y movimientos laterales, pero también señalado por contener información desactualizada y un formato deficiente. Muchos lo recomiendan como una guía de referencia para pentesters experimentados, aunque algunos opinan que carece de explicaciones detalladas sobre los conceptos fundamentales.
Preguntas frecuentes
What’s "The Hacker Playbook: Practical Guide to Penetration Testing" by Peter Kim about?
- Comprehensive Penetration Testing Guide: The book is a hands-on, practical guide to penetration testing, structured like a football playbook with each chapter representing a different phase or tactic in a penetration test.
- Real-World Techniques: It covers real-world tools, techniques, and methodologies used by professional penetration testers, focusing on efficiency and effectiveness.
- Step-by-Step Playbook: The content is organized into ten sections, from setting up your environment to reporting, each with actionable steps and tool recommendations.
- Focus on Practicality: Rather than exhaustive theory, the book emphasizes practical, repeatable processes and encourages readers to adapt and experiment with their own methods.
Why should I read "The Hacker Playbook" by Peter Kim?
- Learn from Experience: The book distills years of the author’s penetration testing experience, offering lessons learned, best practices, and real-world scenarios.
- Up-to-Date Tools and Methods: It introduces current industry-standard tools (like Kali Linux, Metasploit, Burp Suite) and how to use them effectively.
- Practical, Not Just Theoretical: Readers gain actionable knowledge that can be immediately applied in lab or real-world environments.
- Encourages Critical Thinking: The book stresses creativity, adaptability, and understanding over rote tool usage, helping readers become better security professionals.
What are the key takeaways from "The Hacker Playbook" by Peter Kim?
- Establish a Repeatable Process: Building a consistent, baseline testing environment is crucial for effective penetration testing.
- Blend Passive and Active Recon: Use both passive information gathering and active scanning to maximize discovery while minimizing detection.
- Exploit and Move Laterally: After initial compromise, leverage post-exploitation techniques to escalate privileges and pivot within networks.
- Report Effectively: Clear, actionable reporting is as important as technical skill—clients value understandable, validated findings and remediation advice.
How is "The Hacker Playbook" by Peter Kim structured, and what is the football playbook analogy?
- Ten-Section Playbook: Each section is named after a football play (e.g., Pregame, The Drive, The Throw), representing a phase in a penetration test.
- Sequential Progression: The structure mirrors the flow of a real engagement, from setup and reconnaissance to exploitation, lateral movement, and reporting.
- Analogy for Strategy: The football theme emphasizes strategy, adaptability, and teamwork, paralleling the mindset needed for successful penetration testing.
- Memorable Framework: This analogy helps readers remember the stages and tactics, making the methodology more accessible and engaging.
What are the essential tools and setup steps recommended in "The Hacker Playbook" by Peter Kim?
- Dual-Platform Setup: The author recommends configuring both a Windows and a Linux (Kali) virtual machine for comprehensive testing.
- Key Tools List: Essential tools include Kali Linux, Metasploit, Burp Suite Pro, Nessus/Nexpose, SMBExec, Veil, Mimikatz, WCE, and various browser add-ons.
- Baseline and Snapshots: Take clean snapshots of your VMs after setup to quickly revert and maintain a consistent testing environment.
- Regular Updates: Keep all tools and systems patched and updated to ensure effectiveness and security during engagements.
How does "The Hacker Playbook" by Peter Kim approach network and web application scanning?
- Passive and Active Discovery: Start with passive reconnaissance (using tools like Discover Scripts and OSINT) to gather information without alerting targets.
- Vulnerability Scanning: Use tools like Nessus or Nexpose for broad vulnerability assessment, complemented by Nmap for detailed port and service discovery.
- Web Application Scanning: Employ Burp Suite Pro for spidering, content discovery, and active scanning of web applications, focusing on efficiency and depth.
- Organizing Results: Tools like Peeping Tom help visualize and prioritize web targets by capturing screenshots of discovered web services.
What exploitation techniques and tools are highlighted in "The Hacker Playbook" by Peter Kim?
- Metasploit Framework: Central to exploitation, with guidance on module selection, payload configuration, and running exploits (e.g., MS08-067).
- Custom Exploits: Encourages understanding and modifying exploits in various languages (Python, Perl, C++) for situations where Metasploit modules are unavailable.
- Script Safety: Stresses the importance of testing and validating scripts to avoid unintended damage to client systems.
- Post-Exploitation Focus: Emphasizes the need to understand why exploits work, not just how to run them, to adapt to different environments.
How does "The Hacker Playbook" by Peter Kim cover web application attacks like SQL injection and XSS?
- SQL Injection Tools: Detailed walkthroughs of using SQLmap and Sqlninja for both GET and POST parameter attacks, including shell access and database extraction.
- Cross-Site Scripting (XSS): Explains reflective and stored XSS, with exploitation using the BeEF framework for advanced client-side attacks.
- Bypassing Filters: Provides resources and scripts for XSS obfuscation and filter evasion, including crowd-sourced payloads and OWASP cheat sheets.
- Other Web Attacks: Covers CSRF, session token analysis, fuzzing, and business logic testing, with practical Burp Suite examples.
What methods for lateral movement and privilege escalation are described in "The Hacker Playbook" by Peter Kim?
- Credential Harvesting: Tools like Responder.py, WCE, and Mimikatz are used to capture or extract credentials from memory or network traffic.
- Group Policy Preferences (GPP): Exploiting GPP to retrieve cleartext local admin passwords from domain controllers.
- PSExec and SMBExec: Using these tools to execute code or extract hashes across multiple systems, leveraging obtained credentials.
- PowerShell Post-Exploitation: PowerSploit and Nishang frameworks enable in-memory attacks, persistence, and data exfiltration without dropping files.
How does "The Hacker Playbook" by Peter Kim address social engineering and physical attacks?
- Doppelganger Domains: Registering typo-squatted domains to intercept emails and credentials, and even set up malicious SSH servers.
- Phishing Campaigns: Using Metasploit Pro and the Social Engineering Toolkit (SET) to craft and track spear phishing and credential harvesting attacks.
- Physical Access Attacks: Techniques include wireless cracking, card cloning, and deploying drop boxes (e.g., Odroid U2) for persistent network access.
- Creative Payload Delivery: Advice on using Excel macros, USB/CD drops, and leveraging trust relationships for successful social engineering.
What strategies for evading antivirus and maintaining stealth are recommended in "The Hacker Playbook" by Peter Kim?
- Signature Evasion: Demonstrates how to identify and modify AV signatures in binaries (e.g., WCE) using tools like Evade and hex editors.
- Custom Payloads: Use Veil and SMBExec to generate obfuscated Meterpreter payloads that bypass AV detection.
- Python-Based Attacks: Leverage Python for custom shells and keyloggers, often whitelisted and less likely to be flagged by AV.
- In-Memory Execution: Employ PowerShell and post-exploitation frameworks to run attacks entirely in memory, reducing forensic artifacts.
What reporting and professional development advice does "The Hacker Playbook" by Peter Kim offer?
- Effective Reporting: Emphasizes clear, validated, and actionable reports over raw scanner output; includes rating vulnerabilities and providing remediation steps.
- Continuous Learning: Recommends attending conferences, taking specialized training, and reading both technical and non-technical books.
- Practice and Community: Encourages participation in Capture The Flag (CTF) events, using vulnerable frameworks, and engaging with the security community.
- Staying Current: Suggests following curated RSS feeds, email lists, and Twitter accounts to keep up with the rapidly evolving security landscape.
What are the best quotes from "The Hacker Playbook" by Peter Kim and what do they mean?
- "Practice makes perfect. The rule I’ve always heard is that it takes 10,000 hours to master something. However, I don’t believe that there is ever a time that anyone can completely master penetration testing..."
- Emphasizes the importance of continual learning and practice in the ever-changing field of security.
- "You really can’t just run tools, but you have to use your own creativity to give your customer the best and most real type of attack they might receive."
- Highlights the need for creativity and adaptability beyond automated tools.
- "To become a better security professional, some of the most important things to do are: Learn, study, and understand vulnerabilities and common security weaknesses; Practice exploiting and securing vulnerabilities in controlled environments; Perform testing in real world environments; Teach and present to the security community."
- Outlines a holistic approach to professional growth in security.
- "Do not test systems that you do not own or do not have permission to scan or attack."
- Stresses the ethical and legal responsibilities of penetration testers.