PadhaikoAll subjects

Malware and Cyber Attacks

Network and Cyber Security (ENCT 463)

Open in the Padhaiko app

5.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.

Comparison of Major Malware Types
Malware TypeHost File Needed?Self-Replicating?Propagation MechanismTypical Payload / Harm
VirusYes (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
WormNo (standalone program)YesAutomatically 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)NoSocial engineering ("free crack", fake invoice, trojanized installer)Remote Access Trojan (RAT) backdoor, credential theft, botnet enrollment
RansomwareNoSometimes (worm-like variants like WannaCry)Phishing attachments, exposed RDP, exploited SMB/VPN flawsEncrypts user files & shadow backups, demands ransom + double extortion (data leak threat)

Key Defensive Takeaways


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.

Definition

Common Phishing Variants

  1. 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.
  2. 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).
  3. 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.
  4. 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


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.

Categories of DoS / DDoS Attacks
CategoryLayerMechanism & ExamplesPrimary Mitigation
Volumetric FloodL3 / L4Saturates 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 ExhaustionL4Exhausts firewall/OS connection tables; TCP SYN Flood (many SYNs with spoofed IPs, never sending final ACK), Ping of DeathSYN Cookies (stateless handshake until ACK arrives), connection timeouts
Application-LayerL7Mimics 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.

3. Password Attacks


5.4 Zero-Day Exploits, Reconnaissance Attacks (IP probes, port scans, vulnerability scans)

1. Zero-Day Exploits

Definition

Zero-Day Vulnerability, Exploit, and Attack

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:

  1. 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.
  2. Port Scans: Probing TCP/UDP ports to enumerate open services and OS/banner versions:
    • TCP Connect Scan (-sT): Completes full 3-way handshake (SYN SYN-ACK ACK); easily logged by applications.
    • TCP SYN ("Half-Open / Stealth") Scan (-sS): Sends SYN; if SYN-ACK returns, port is open, and scanner sends RST immediately without completing the connection; if RST returns, port is closed.
    • UDP Scan (-sU): Infers closed from ICMP Port Unreachable and open|filtered from silence.
  3. 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.
Example 1

DNS Amplification Factor and Password Search Space Math (6 marks)

(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 ():
Answer:

(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.

Example 2

Fixing Vulnerable SQL Query and Output Rendering Code (5 marks)

Examine the vulnerable Python backend snippet below, identify the two web vulnerabilities present, and rewrite both securely.

Vulnerable Login and Profile DisplayPython
# 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:

  1. SQL Injection (SQLi): Direct f-string interpolation into query allows an attacker supplying ' OR 1=1 -- to manipulate the SQL statement.
  2. Reflected Cross-Site Scripting (XSS): Embedding raw username into 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:

Secure Parameterized Query and Escaped OutputPython
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>"
Answer:

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)

AspectCross-Site Scripting (XSS)Cross-Site Request Forgery (CSRF / XSRF)
Core MechanismAttacker injects malicious JavaScript into a trusted website; victim's browser executes itAttacker's malicious site tricks victim's browser into sending an unwanted forged request to a trusted site where victim is logged in
Trust ViolatedTrust the user's browser has in the websiteTrust the website has in requests coming from the user's browser (ambient cookies)
VariantsStored (saved in DB), Reflected (echoed from URL/form), DOM-based (client JS sink)Forced GET (<img> tag) or hidden auto-submitting POST form
Primary DefensesContext-aware output encoding, strict Content Security Policy (CSP), HttpOnly cookiesAnti-CSRF tokens (unpredictable per-session/request secret), SameSite=Strict/Lax cookies, re-auth on sensitive actions

3. Authentication, Authorization, Validation, and Secure Sessions

Example 3

Securing an Online Banking Session Against Web Attacks (Exam Model) (5 marks)

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:

  • Secure flag (with HTTPS/HSTS): Instructs the browser never to transmit the session cookie over unencrypted HTTP, preventing passive network sniffing and active cookie capture.
  • HttpOnly flag: Blocks document.cookie access 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.
Answer:

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

Question 1

(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.)

Answer:

(a) Amplification factor ; victim traffic (). (b) ; worst-case cracking time ().

Question 2

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).

Answer:

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.

Question 3

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.
Answer:

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.

Question 4

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-HttpOnly cookies. 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/Lax cookies.

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.

Answer:

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).

Question 5

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 OS connect() 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 raw SYN; upon receiving SYN-ACK (indicating an open port), the scanner immediately replies with RST instead of ACK, 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.

Answer:

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.

← Securing Wireless and Mobile NetworksIncident Response and Risk Management →