Malware and Cyber Attacks
Open in the Padhaiko app5.1 Types of Malwares (Viruses, Worms, Trojans, Ransomware)
Malware (malicious software) refers to any program intentionally designed to infiltrate, damage, disrupt, spy on, or extort a computer system or network.
| Malware Type | Host File Needed? | Self-Replicating? | Propagation Mechanism | Typical Payload / Harm |
|---|---|---|---|---|
| Virus | Yes (attaches to executable, macro, or boot sector) | Yes (when host executes) | Infected files, USB drives, macro documents (requires user action) | File corruption, data wiping, system instability |
| Worm | No (standalone program) | Yes | Automatically scans and exploits network services/vulnerabilities (zero user interaction) | Bandwidth exhaustion, massive rapid outbreak, dropping backdoors |
| Trojan (Trojan Horse) | No (standalone, disguised as useful software) | No | Social engineering ("free crack", fake invoice, trojanized installer) | Remote Access Trojan (RAT) backdoor, credential theft, botnet enrollment |
| Ransomware | No | Sometimes (worm-like variants like WannaCry) | Phishing attachments, exposed RDP, exploited SMB/VPN flaws | Encrypts user files & shadow backups, demands ransom + double extortion (data leak threat) |
Key Defensive Takeaways
- Viruses vs. Worms: A virus needs a host file and user execution to replicate; a worm is self-contained and spreads autonomously over networks.
- Trojans: Do not self-replicate, relying instead on deception; once executed, they silently open a backdoor or drop secondary payloads (spyware, keyloggers, ransomware).
- Ransomware: Modern ransomware gangs combine fast hybrid encryption (AES/ChaCha20 per file + RSA/ECC for file keys) with data exfiltration before encryption (double extortion). The single strongest recovery defense is offline, immutable backups (3-2-1 rule) paired with EDR and network segmentation.
5.2 Social Engineering Attacks (Phishing, Spear Phishing, Vishing, Quishing)
Social engineering exploits human psychology—urgency, fear, curiosity, helpfulness, or deference to authority—rather than technical software flaws to trick victims into divulging secrets, approving MFA prompts, or running malware.
Common Phishing Variants
- Phishing: Mass, untargeted deceptive messages (usually email) impersonating banks, cloud providers, or IT support to harvest passwords, OTPs, or card numbers on spoofed login pages.
- Spear Phishing: Highly targeted phishing tailored to a specific person or organization using harvested context (colleague names, ongoing projects, vendor invoices). When targeting C-suite executives or finance directors, it is called Whaling or Business Email Compromise (BEC).
- Vishing (Voice Phishing): Social engineering conducted over phone calls or VoIP—such as impersonating bank fraud teams or IT helpdesk staff—increasingly enhanced by AI voice cloning and caller-ID spoofing.
- Quishing (QR-Code Phishing): Embedding malicious URLs inside QR codes in emails, PDFs, or physical posters. Because traditional email gateways scan text links rather than decoding images, quishing bypasses URL filters and shifts the victim onto an unmanaged personal smartphone.
Multi-Layered Defenses Against Social Engineering
- Email Authentication: Enforce SPF (Sender Policy Framework), DKIM (cryptographic message signing), and DMARC (
p=reject) to block domain spoofing. - Phishing-Resistant MFA: Hardware-bound FIDO2/WebAuthn verifies the exact TLS domain origin before signing, so even a tricked user cannot authenticate to a lookalike phishing domain.
- Procedural Controls: Out-of-band callback verification for wire transfers/password resets, link isolation, and regular phishing-simulation awareness training.
5.3 Denial of Service (DoS) and Distributed DoS (DDoS) Attacks, Man-in-the-Middle Attacks, Password Attacks
1. DoS and DDoS Attacks
A DoS attack degrades or blocks legitimate availability from a single source; a DDoS attack marshals thousands of compromised devices (botnet) under a Command-and-Control (C2) infrastructure to overwhelm bandwidth, state tables, or server CPU.
| Category | Layer | Mechanism & Examples | Primary Mitigation |
|---|---|---|---|
| Volumetric Flood | L3 / L4 | Saturates link bandwidth; UDP flood, ICMP flood, DNS/NTP Reflection & Amplification (small spoofed query huge reply to victim) | Upstream ISP/CDN scrubbing centers, Anycast absorption, BCP 38 egress filtering |
| Protocol / State Exhaustion | L4 | Exhausts firewall/OS connection tables; TCP SYN Flood (many SYNs with spoofed IPs, never sending final ACK), Ping of Death | SYN Cookies (stateless handshake until ACK arrives), connection timeouts |
| Application-Layer | L7 | Mimics valid traffic to exhaust CPU/DB/worker pools; HTTP GET/POST flood, Slowloris (holds partial HTTP headers open) | WAF, rate limiting, CAPTCHA/bot challenges, reverse-proxy buffering |
2. Man-in-the-Middle (MITM) Attacks
In a MITM attack, the adversary secretly inserts themselves into the communication path between two victims, relaying traffic while silently reading or altering it.
- Common Techniques: ARP Spoofing/Poisoning on a LAN (sending forged gratuitous ARP replies mapping the gateway IP to the attacker's MAC), Rogue Wi-Fi Evil Twin, DNS Spoofing, and SSL Stripping (downgrading
https://links tohttp://). - Defenses: End-to-end TLS 1.3 with strict certificate validation, HSTS (blocks HTTP downgrades), Dynamic ARP Inspection (DAI) + DHCP snooping on switches, and DNSSEC.
3. Password Attacks
- Brute-Force Attack: Exhaustively tries every character combination until the password matches; feasibility shrinks exponentially with password length and character-set size.
- Dictionary Attack: Tests common passwords, leaked wordlists, and mangled variants (
P@ssw0rd1). - Credential Stuffing: Automatically replays username/password pairs leaked from one breached website against other services (exploiting password reuse).
- Password Spraying: Tries one or two common passwords (e.g.,
Welcome2026!) across thousands of accounts simultaneously to evade per-account lockout thresholds. - Rainbow Table Attack: Uses precomputed hash chains for instant plaintext lookup—completely defeated by assigning a unique cryptographic salt per user before hashing with Argon2id or bcrypt.
5.4 Zero-Day Exploits, Reconnaissance Attacks (IP probes, port scans, vulnerability scans)
1. Zero-Day Exploits
Zero-Day Vulnerability, Exploit, and Attack
- Zero-Day Vulnerability: A previously unknown software/hardware flaw for which the vendor has had zero days to create or release a patch.
- Zero-Day Exploit: Working code crafted to trigger that unpatched vulnerability.
- Zero-Day Attack: Active deployment of the exploit against targets before defenses or patches exist.
Because signature-based antivirus/IDS lacks signatures for zero-days, defense requires behavioral EDR, Defense in Depth (least privilege, sandboxing, ASLR/DEP), virtual patching (WAF/IPS behavioral rules), and rapid vendor patching once disclosed.
2. Reconnaissance Attacks
Before launching an exploit, attackers map the target's attack surface using passive (OSINT, Shodan, DNS records, job postings) and active reconnaissance:
- IP Probes (Host Discovery / Ping Sweeps): Sending ICMP Echo Requests, ICMP Timestamp requests, or TCP SYN/ACK probes across an IP range (e.g.,
nmap -sn 10.10.0.0/24) to discover which hosts are alive. - Port Scans: Probing TCP/UDP ports to enumerate open services and OS/banner versions:
- TCP Connect Scan (
-sT): Completes full 3-way handshake (SYNSYN-ACKACK); easily logged by applications. - TCP SYN ("Half-Open / Stealth") Scan (
-sS): SendsSYN; ifSYN-ACKreturns, port isopen, and scanner sendsRSTimmediately without completing the connection; ifRSTreturns, port isclosed. - UDP Scan (
-sU): Infersclosedfrom ICMP Port Unreachable andopen|filteredfrom silence.
- TCP Connect Scan (
- Vulnerability Scans: Automated scanners (Nessus, OpenVAS, Nuclei) test discovered open ports and web endpoints against thousands of known CVE signatures, outdated banners, weak TLS ciphers, and default credentials.
DNS Amplification Factor and Password Search Space Math
(a) In a DNS Amplification DDoS attack, a botnet sends spoofed -byte DNS queries at a combined rate of , triggering -byte responses toward the victim. Compute the amplification factor and the resulting attack bandwidth hitting the victim. (b) An offline GPU rig tests guesses per second against a fast unsalted hash. Compare the worst-case brute-force time for an -character lowercase password ( symbols) versus a -character alphanumeric password ( symbols; ).
Compute DNS Amplification Factor and Victim Bandwidth:
Compare Password Keyspaces and Cracking Times:
- 8-character lowercase ():
- 10-character alphanumeric ():
(a) Amplification factor ; victim receives . (b) -char lowercase breaks in (), whereas -char alphanumeric takes at .
5.5 Web Application Security (XSS, CSRF/XSRF, SQL injection, Authentication, Authorization, Validation, Secure Session)
Web applications sit directly on the public Internet and interact closely with backend databases and user browsers, making them prime targets (reflected in the OWASP Top 10).
1. SQL Injection (SQLi)
SQL Injection occurs when untrusted user input is concatenated directly into a SQL query string, allowing an attacker to alter query logic, dump entire databases, bypass login, or execute OS commands.
- Vulnerable pattern:
"SELECT * FROM users WHERE user='" + u + "' AND pass='" + p + "'"enteringu = admin' --comments out the password check. - Primary Defense: Use Parameterized Queries (Prepared Statements) so the database driver separates SQL code structure from data values, combined with Least Privilege database accounts.
Fixing Vulnerable SQL Query and Output Rendering Code
Examine the vulnerable Python backend snippet below, identify the two web vulnerabilities present, and rewrite both securely.
# 1. Vulnerable SQL lookup
query = f"SELECT id, role FROM users WHERE username = '{username}'"
cursor.execute(query)
# 2. Vulnerable HTML greeting (Reflected XSS)
return f"<h1>Welcome, {username}</h1>"Identify the two vulnerabilities:
- SQL Injection (SQLi): Direct f-string interpolation into
queryallows an attacker supplying' OR 1=1 --to manipulate the SQL statement. - Reflected Cross-Site Scripting (XSS): Embedding raw
usernameinto HTML lets an attacker send a link with<script>...</script>that executes in the victim's browser.
Rewrite using Parameterized Queries and Context-Aware HTML Escaping:
import html
# 1. Parameterized query: SQL engine treats username strictly as data
cursor.execute(
"SELECT id, role FROM users WHERE username = %s",
(username,)
)
# 2. HTML-encode untrusted data before inserting into HTML body
safe_name = html.escape(username, quote=True)
return f"<h1>Welcome, {safe_name}</h1>"Replace string interpolation in SQL with parameterized queries (%s placeholders) to stop SQL injection, and apply HTML entity escaping (html.escape) plus a Content Security Policy (CSP) to block XSS.
2. Cross-Site Scripting (XSS) vs. Cross-Site Request Forgery (CSRF / XSRF)
| Aspect | Cross-Site Scripting (XSS) | Cross-Site Request Forgery (CSRF / XSRF) |
|---|---|---|
| Core Mechanism | Attacker injects malicious JavaScript into a trusted website; victim's browser executes it | Attacker's malicious site tricks victim's browser into sending an unwanted forged request to a trusted site where victim is logged in |
| Trust Violated | Trust the user's browser has in the website | Trust the website has in requests coming from the user's browser (ambient cookies) |
| Variants | Stored (saved in DB), Reflected (echoed from URL/form), DOM-based (client JS sink) | Forced GET (<img> tag) or hidden auto-submitting POST form |
| Primary Defenses | Context-aware output encoding, strict Content Security Policy (CSP), HttpOnly cookies | Anti-CSRF tokens (unpredictable per-session/request secret), SameSite=Strict/Lax cookies, re-auth on sensitive actions |
3. Authentication, Authorization, Validation, and Secure Sessions
- Authentication vs. Authorization: Authentication verifies who you are (MFA, salted Argon2id passwords, brute-force throttling). Authorization verifies what you are permitted to do; checking session login without verifying object ownership leads to Broken Access Control / IDOR (e.g., changing
/invoice?id=104to105). - Input Validation: Always validate on the server side using strict allowlists (expected type, length, character set, numeric range). Client-side HTML/JS validation improves UX only and is bypassed effortlessly via
curlor a proxy. - Secure Session Management:
- Generate session IDs with a cryptographically secure PRNG ( bits of entropy).
- Transmit solely over HTTPS and set cookie attributes:
Secure(HTTPS only),HttpOnly(unreadable by JS, protecting tokens from XSS), andSameSite=LaxorStrict(mitigating CSRF). - Regenerate the session ID immediately upon login (prevents Session Fixation) and enforce idle/absolute timeouts plus server-side invalidation on logout.
Securing an Online Banking Session Against Web Attacks (Exam Model)
Explain how the three cookie flags HttpOnly, Secure, and SameSite=Strict, together with session ID regeneration, protect an authenticated banking session against Sniffing, XSS token theft, CSRF, and Session Fixation.
Map each defense to its targeted attack:
Secureflag (with HTTPS/HSTS): Instructs the browser never to transmit the session cookie over unencrypted HTTP, preventing passive network sniffing and active cookie capture.HttpOnlyflag: Blocksdocument.cookieaccess from JavaScript, preventing an XSS payload from reading and exfiltrating the session token.SameSite=Strict(plus Anti-CSRF token): Prevents the browser from attaching the session cookie on cross-origin requests initiated from third-party sites, neutralizing CSRF transfers.- Regenerating Session ID at Login: Replaces any pre-authentication cookie with a fresh random token once credentials succeed, defeating Session Fixation.
Secure blocks plaintext cookie sniffing, HttpOnly blocks JS/XSS cookie theft, SameSite=Strict (with CSRF tokens) blocks cross-site forged requests, and post-login session ID regeneration prevents Session Fixation.
Exercises
(a) An NTP amplification DDoS uses -byte spoofed requests sent at to trigger -byte monlist responses. Find the amplification factor and the bandwidth hitting the victim. (b) Compute the size of an -character alphanumeric password space ( symbols) and the worst-case cracking time at guesses/second.
Part (a) — Amplification factor and victim bandwidth:
Part (b) — Password search space and worst-case time:
(This shows why characters is no longer sufficient against modern GPU clusters and why + character passphrases + salted slow hashing are required.)
(a) Amplification factor ; victim traffic (). (b) ; worst-case cracking time ().
Differentiate between Viruses, Worms, Trojans, and Ransomware in terms of host dependency, self-replication, propagation vector, and effective countermeasures.
Contrast the four malware families:
- Virus: Attaches code to an existing host executable/document; self-replicates only when the host is opened/run; spreads via shared files/USBs.
- Worm: Standalone self-replicating malware requiring no host file or user click; scans networks and exploits unpatched services directly.
- Trojan: Standalone program disguised as legitimate software; does not self-replicate; opens backdoors or steals credentials after a user installs it.
- Ransomware: Encrypts files/backups to extort payment (often adding data theft for double extortion); enters via phishing, exposed RDP, or worms.
State key countermeasures: Patch network-facing services (stops worms), enforce least privilege and application allowlisting (limits Trojans/viruses), deploy behavioral EDR and email filtering, and maintain offline immutable backups (beats ransomware).
Viruses need a host file and user execution; worms self-propagate autonomously over networks; Trojans deceive users without self-replicating; ransomware encrypts (and often steals) data for extortion. Defenses include patching, EDR, least privilege, and immutable offline backups.
Define Phishing, Spear Phishing, Vishing, and Quishing, and explain how DMARC and FIDO2/WebAuthn reduce social-engineering risk.
Define the four attacks:
- Phishing: Broad, untargeted fraudulent emails/messages impersonating trusted brands to steal credentials or drop malware.
- Spear Phishing: Personalized phishing aimed at specific individuals or departments using researched organizational details.
- Vishing: Voice/phone-based social engineering impersonating IT support, banks, or executives.
- Quishing: Phishing via QR codes in emails or physical notices to bypass email URL scanners and redirect victims on mobile devices.
Explain DMARC and FIDO2/WebAuthn:
- DMARC (building on SPF and DKIM) instructs receiving mail servers to reject emails that spoof an organization's exact sender domain.
- FIDO2/WebAuthn cryptographically binds authentication responses to the exact TLS origin domain in the browser, so even if a victim clicks a quishing/phishing link to
examp1e.com, the security key refuses to authenticate.
Phishing is mass deception, Spear Phishing is targeted, Vishing uses voice calls, and Quishing hides malicious links in QR codes. DMARC stops exact-domain email spoofing, while FIDO2/WebAuthn provides origin-bound phishing-resistant MFA.
Compare Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF), and explain how SQL Injection occurs and how it is prevented.
Contrast XSS and CSRF:
- XSS injects attacker-controlled JavaScript into a trusted web page (Stored, Reflected, or DOM-based), running in the victim's browser with access to the page's DOM and non-
HttpOnlycookies. Prevented via context-aware output encoding and strict CSP. - CSRF forces a logged-in victim's browser to issue an unintended HTTP request from a third-party site using ambient session cookies. Prevented via unpredictable anti-CSRF tokens and
SameSite=Strict/Laxcookies.
Explain SQL Injection and its fix: SQLi occurs when untrusted input is concatenated into raw SQL commands, letting attackers alter the query syntax. Parameterized queries (prepared statements) bind user values separately from the compiled SQL command so input can never be parsed as SQL keywords.
XSS executes malicious scripts inside a trusted site (prevented by output encoding + CSP), CSRF exploits ambient cookies to forge cross-site actions (prevented by CSRF tokens + SameSite), and SQLi alters database queries via unsanitized input (prevented by parameterized queries).
Distinguish between a TCP Connect scan (-sT) and a TCP SYN scan (-sS) during reconnaissance, and explain what a Zero-Day exploit is and how organizations defend against it.
Compare TCP Connect vs. TCP SYN scans:
- TCP Connect (
-sT): Uses the OSconnect()syscall to complete the full 3-way handshake (SYN,SYN-ACK,ACK) before closing, leaving obvious connection logs in target daemons. - TCP SYN (
-sS, Half-Open): Sends a rawSYN; upon receivingSYN-ACK(indicating an open port), the scanner immediately replies withRSTinstead ofACK, avoiding full socket establishment at the application layer.
Explain Zero-Day exploits and defenses: A Zero-Day exploit targets an unpatched vulnerability unknown to the vendor (zero days of available fixes). Organizations defend using Defense in Depth: behavioral EDR/HIDS (detecting anomalous process chains rather than known file hashes), network segmentation, least privilege, ASLR/DEP exploit mitigations, and virtual patching via IPS/WAF rules.
A TCP Connect scan completes the full 3-way handshake, whereas a TCP SYN scan resets after SYN-ACK without finishing the handshake. Zero-Day exploits target undisclosed/unpatched flaws and are mitigated via behavioral EDR, least privilege, segmentation, and virtual patching.