My Notes

Study Timer
25:00
Today: 0 min
Total: 0 min
🏆

Achievement Unlocked!

Description

+50 XP

14 Security Building Continued

Reading Timer
25:00
Chapter 14: Security Building Continued | BBA 1233
1
Topic 14.1
Firewalls and Network Security
Firewall

A firewall is a network security device (hardware or software) that monitors and controls incoming and outgoing network traffic based on predefined security rules. Firewalls operate at the network layer (packet filtering) or application layer (stateful inspection / deep packet inspection).

💡
Analogy — Security Checkpoint
A firewall is like a security checkpoint at a building entrance. Every person (packet) must show ID (source/destination IP, port, protocol). Some are allowed through (permitted ports), others are turned away (blocked ports). Some checkpoints even check what's inside briefcases (deep packet inspection).
Interactive Firewall Rule Demo
🔒 Firewall Rule Set — navinniroula.com.np
ALLOW TCP port 80 — HTTP web traffic
ALLOW TCP port 443 — HTTPS encrypted web
ALLOW TCP port 22 — SSH remote administration
ALLOW TCP port 25/587 — SMTP email sending
DENY TCP port 23 — Telnet (insecure)
DENY TCP port 21 — FTP (unencrypted)
DENY All other ports — default deny
Test a port:
Types of Firewalls
TypeHow It WorksStrengthsWeaknesses
Packet FilterChecks IP/port headers onlyFast, simpleCannot inspect payload — misses app-layer attacks
Stateful InspectionTracks TCP connection state — allows only valid packets for established connectionsBetter than packet filterStill cannot inspect encrypted payloads
Application ProxyActs as intermediary — inspects full application dataUnderstands protocols deeplySlower, complex, protocol-specific
WAF (Web Application Firewall)Inspects HTTP/HTTPS specifically for web attacksBlocks SQL injection, XSS, CSRFOnly for HTTP — needs SSL offloading to inspect HTTPS
🎯 Q14_1
A server has a firewall rule "DENY ALL" as its last rule, with specific ALLOW rules above it. Why is this "default deny" approach better than "default allow"?
ADefault deny is faster because the firewall processes fewer rules
BAny new unknown service or attack vector is automatically blocked until explicitly permitted
CDefault allow is equally secure as long as the DENY rules cover all known threats
DDefault deny prevents the firewall from being bypassed by VPN connections
✅ Correct! Default deny means anything not explicitly permitted is automatically blocked. New attack methods and unknown services are blocked by default. Default allow means you must anticipate every possible attack to block it — which is impossible.
❌ The answer is B. Default deny is the security baseline: block everything, explicitly permit only what is needed. This is "least privilege" applied to networking. Default allow requires enumerating all threats in advance — inherently impossible.
2
Topic 14.2
Common Web Application Vulnerabilities

Building a secure Internet application requires protecting against common attack patterns. The OWASP Top 10 lists the most critical web application security risks. Every developer building Internet applications must understand these.

Critical Vulnerabilities — OWASP Top 10 (Selected)
SQL Injection
Attacker inserts SQL code into input fields — can read, modify, or delete the entire database.
✓ Fix: Parameterised queries, prepared statements. Never concatenate user input into SQL.
XSS (Cross-Site Scripting)
Attacker injects JavaScript into a page — executed in other users' browsers, stealing cookies or credentials.
✓ Fix: Encode all output. Use Content-Security-Policy headers. Validate input.
Broken Authentication
Weak passwords, no MFA, predictable session tokens — allows account takeover.
✓ Fix: Strong passwords + MFA. Secure random session tokens. Rate-limit login attempts.
Directory Traversal
Request with ../../ paths accesses files outside the web root (covered in Chapter 8).
✓ Fix: Sanitise paths. Reject .. sequences. Validate path stays within web root.
Insecure Direct Object Reference
User changes an ID in the URL to access another user's data: /invoice?id=1234 → ?id=1235
✓ Fix: Check authorisation on every resource access. Never trust user-supplied IDs alone.
Security Misconfiguration
Default passwords, open ports, detailed error messages — give attackers free information.
✓ Fix: Disable unused features. Custom error pages. Principle of least privilege.
Interactive — SQL Injection Detector
🔍 Input Validation — SQL Injection Test

Try: ' OR 1=1 -- or ; DROP TABLE users

🎯 Q14_2
A developer builds a login system: SELECT * FROM users WHERE name='" + username + "'. An attacker enters admin' -- as the username. What happens?
AThe query fails safely because single quotes are invalid in usernames
BThe attacker logs in as admin without a password — the -- comments out the password check
CThe database rejects the query automatically due to built-in security
DThe firewall blocks the request because it contains special characters
✅ Correct! The attacker's input turns the query into: SELECT * FROM users WHERE name='admin' --'. The -- comments out the rest (including the password check), so any user named 'admin' is returned without needing the password. This is SQL injection.
❌ The answer is B. SQL injection: admin' -- turns the query into where -- comments out the password condition. Fix: use parameterised queries (prepared statements) — never concatenate user input.
3
Topic 14.3
Secure Coding Checklist for Winsock Apps

Every Internet application built in this course — Finger, Whois, FTP, HTTP server, IRC, email — must be hardened against the security vulnerabilities we have studied. Here is a practical security checklist for Winsock-based applications.

Security Checklist — Interactive (tap to check)
✅ Winsock Application Security Checklist
Use TLS/SSL — wrap all Winsock connections with SChannel or WinINet for encryption
Validate all input — never trust data received from the network; check length, characters, and format
Sanitise file paths — reject ../ sequences; validate paths stay within the web root (HTTP server)
Set connection timeouts — use select() with a timeout; never block forever waiting for a malicious client
Limit buffer sizes — always check received data length before copying to fixed-size buffers (prevent overflow)
Rate-limit connections — reject clients that open too many connections; prevent DoS
Log all activity — record connection timestamps, IP addresses, and commands for audit trails
Run with minimal privileges — server processes should not run as Administrator/root
Handle errors gracefully — never reveal internal error details or stack traces to remote clients
Always call WSACleanup() — prevent resource leaks even when an error occurs
Buffer Overflow Prevention in Winsock Code
// DANGEROUS — no length check: char buf[256]; recv(sock, buf, 99999, 0); // ⚠ Could overflow buf! strcpy(dest, buf); // ⚠ No length check = buffer overflow vulnerability // SAFE — always limit recv to buffer size: char buf[256]; int n = recv(sock, buf, sizeof(buf)-1, 0); if(n <= 0){ closesocket(sock); return; } // Check for error/close buf[n] = '\0'; // Null-terminate safely // Now process buf — max 255 chars, always null-terminated
Always pass sizeof(buffer) as the recv() limit. Never use more than what you allocated.
🎯 Q14_3
A Winsock server calls recv(sock, buf, 99999, 0) but buf is only 256 bytes. An attacker sends 10,000 bytes. What security risk does this create?
AThe recv() call will fail silently — no risk
BThe server uses more bandwidth than needed — only a performance issue
CA buffer overflow — data beyond 256 bytes overwrites adjacent memory, potentially allowing code execution
DTCP automatically limits packets to 256 bytes to match the buffer size
✅ Correct! Passing a larger size to recv() than the buffer can hold causes a buffer overflow — received data overwrites adjacent memory. This is one of the most exploited vulnerabilities. Always use recv(sock, buf, sizeof(buf)-1, 0).
❌ The answer is C — buffer overflow. Writing more data than a buffer can hold overwrites adjacent memory, potentially corrupting the stack and allowing an attacker to execute arbitrary code. Always limit recv() to sizeof(buf).
4
Topic 14.4
Authentication, Authorization & Best Practices
Authentication vs Authorization

Authentication = verifying identity ("Who are you?"). Authorization = verifying permission ("What are you allowed to do?"). Both are required: authenticating a user does not automatically mean they can access every resource.

Authentication Methods — Comparison
MethodHow It WorksStrengthWeakness
PasswordUser proves knowledge of a secret stringSimple to implementPhishing, weak passwords, credential stuffing
Multi-Factor (MFA)Password + second factor (OTP, hardware key)Stops most password attacksUser friction; SMS OTP can be SIM-swapped
Public Key / CertificateClient proves ownership of a private keyPhishing-resistant; no password to stealKey management complexity
OAuth 2.0 / OpenID ConnectDelegate auth to trusted provider (Google, GitHub)No password management; provider handles securityDepends on third-party availability
API KeysStatic secret in requestsSimple for server-to-serverMust be rotated; risky if exposed
Security Best Practices Summary — All Chapters
Chapter / FeatureSecurity Practice
Ch3 WinsockAlways call WSACleanup() — prevent resource leaks. Validate recv() return values.
Ch5 FingerDisable on modern systems. Never expose user data without authentication.
Ch6 WhoisRate-limit queries. Do not expose internal network info.
Ch7 FTPUse SFTP or FTPS. Never plain FTP — credentials sent in clear text.
Ch8 HTTP ServerSanitise paths (../). Return 403 not 404 for traversal attempts. Use HTTPS.
Ch9 IRCValidate all incoming messages. NickServ for identity. Use TLS port 6697.
Ch11 EmailUse STARTTLS/SSL for SMTP, IMAP, POP3. Hash + salt passwords. SPF/DKIM/DMARC.
Ch13 TLSVerify certificates. Check hostname. Reject expired or self-signed certs.
Ch14 GeneralInput validation. Parameterised queries. Least privilege. Security logging.
Key Terms Drill
Firewall
Tap to reveal

Network security system controlling traffic by IP, port, and protocol rules. Default deny = most secure posture.

SQL Injection
Tap to reveal

Inserting SQL code into user input to manipulate database queries. Fix: parameterised queries.

Buffer Overflow
Tap to reveal

Writing more data than a buffer can hold — overwrites adjacent memory. Fix: always limit recv() to sizeof(buf).

Authentication
Tap to reveal

Verifying WHO someone is. Passwords, MFA, certificates, OAuth.

Authorization
Tap to reveal

Verifying WHAT someone is allowed to do. Separate from authentication.

Least Privilege
Tap to reveal

Grant only the minimum permissions needed. Servers should not run as Administrator.

📌 Chapter 14 — Key Takeaways (and Course Summary)
  • Firewalls control network traffic by rules. Default deny (block all, allow specific) is the most secure posture.
  • Stateful inspection firewalls track TCP connection state — more secure than simple packet filtering.
  • OWASP Top 10: SQL injection, XSS, broken authentication, directory traversal, insecure direct object reference, misconfiguration.
  • Fix SQL injection with parameterised queries — never concatenate user input into SQL strings.
  • Buffer overflow: always pass sizeof(buf)-1 to recv() — never a larger size than allocated.
  • Authentication = who are you? Authorization = what can you do? Both are required separately.
  • Secure Winsock checklist: TLS, input validation, path sanitisation, timeouts, rate limiting, logging, least privilege.
  • Apply security from design — retrofitting security into finished code is difficult and error-prone.
  • Every protocol in this course (Finger, FTP, HTTP, IRC, Email) has a secure variant — always prefer the encrypted version.