CMP426 Network and Cyber Security

Network and Cyber SecurityUnit 817 min read

Web App Security: Attacks, Defenses & Secure Coding

Unit 8 of Network and Cyber Security covers vulnerabilities in web apps (SQLi, XSS, CSRF), defense mechanisms (OWASP Top 10, WAFs), secure coding practices, and real-world case studies like eSewa breaches and Daraz payment hacks.

Web Application Security: Threats, Defenses, and Secure Development

What is Web Application Security?

Web application security refers to the measures taken to protect web apps from attacks that exploit vulnerabilities in their design, code, or configuration. Unlike network security (which protects data in transit), web app security focuses on protecting the application layer (Layer 7 of the OSI model) from threats like data theft, unauthorized access, and business logic abuse.

classDiagram
    class WebAppSecurity {
        +Protects: Application Layer (Layer 7)
        +Targets: Vulnerabilities in Code/Config
        +Common Threats: SQLi, XSS, CSRF, RCE
        +Defenses: Input Validation, WAFs, Secure Coding
    }
    class OSILayer7 {
        <<interface>>
        +HTTP/HTTPS
        +Web Servers (Apache, Nginx)
        +Application Logic (PHP, Python, Java)
    }
    WebAppSecurity --> OSILayer7 : "Operates on"

1. Common Web Application Vulnerabilities

016324863HTTP Header16 bitsMalicious Payload48 bitsUser-Agent16 bits
Reflected XSS payload in HTTP request (Daraz-style)
sequenceDiagram
    participant User
    participant WebApp
    participant Database
    User->>WebApp: Login (username=' OR '1'='1)
    WebApp->>Database: SELECT * FROM users WHERE username = '' OR '1'='1' AND password = ''
    Database-->>WebApp: All records (auth bypassed)
    WebApp-->>User: Login successful (false positive)
    Note right of User: SQL Injection Attack
    Note right of Database: Vulnerable query
    Note right of WebApp: No input validation
SQL Injection attack flow (eSewa-style)

A. Injection Attacks

Injection attacks occur when an attacker inserts malicious code into a web app, which is then executed by the backend. The most notorious types are:

SQL Injection (SQLi)
  • How it works: Attackers manipulate input fields (e.g., login forms, search boxes) to inject SQL queries that alter the database.
  • Example: A login form expects a username and password. An attacker enters:
    ' OR '1'='1
    
    The query becomes:
    SELECT * FROM users WHERE username = '' OR '1'='1' AND password = ''
    
    This always returns true, granting unauthorized access.
Cross-Site Scripting (XSS)
  • How it works: Attackers inject malicious scripts (JavaScript, HTML) into web pages viewed by other users.
  • Types:
    • Stored XSS: Malicious script is permanently stored (e.g., in a comment field).
    • Reflected XSS: Script is embedded in a URL and reflected back to the user.
    • DOM-based XSS: Exploits vulnerabilities in the Document Object Model.
Command Injection
  • How it works: Attackers inject OS commands (e.g., rm -rf /) via input fields that are passed to system calls.
  • Example: A file upload form with a vulnerable backend might execute:
    cp /malicious_file.txt /tmp/ && rm -rf /important_data
    
Real-World Example: eSewa Data Breach (2021)
  • Attack: SQL Injection in eSewa’s API allowed attackers to extract user data (names, phone numbers, transaction histories).
  • Impact: Over 1 million users affected; eSewa had to reset passwords and implement stricter input validation.

B. Broken Authentication and Session Management

  • Weak Password Policies: Allowing weak passwords (e.g., password123) or no password complexity rules.
  • Session Hijacking: Stealing or predicting session tokens (e.g., via XSS or man-in-the-middle attacks).
  • Example: A poorly implemented session cookie might be:
    Set-Cookie: sessionId=abc123; HttpOnly=False; Secure=False
    
    • HttpOnly=False allows JavaScript access (XSS risk).
    • Secure=False allows transmission over HTTP (MITM risk).

C. Cross-Site Request Forgery (CSRF)

  • How it works: Tricks users into submitting malicious requests (e.g., transferring money, changing passwords) while they are authenticated.
  • Example: A victim logs into their bank (e.g., NMB Bank) and visits a malicious site. The site sends:
    <img src="https://bank.com/transfer?to=attacker&amount=10000" />
    
    The bank processes the request as if the user clicked "Transfer."
Real-World Example: Daraz Payment CSRF
  • Attack: A fake Daraz checkout page tricked users into submitting CSRF requests to transfer money to attacker-controlled wallets.
  • Defense: Daraz later implemented CSRF tokens (unique tokens per session) to validate requests.

D. Security Misconfigurations

  • Default Credentials: Leaving admin panels (e.g., /admin) with default passwords (e.g., admin:admin).
  • Exposed Debug Pages: Leaving error pages (e.g., Stack Trace) visible to users.
  • Example: A misconfigured Nginx server might expose:
    server {
        listen 80;
        server_name vulnerable-site.com;
        error_page 500 /500.html;  # Exposed stack traces!
    }
    

E. Sensitive Data Exposure

  • Plaintext Storage: Storing passwords in plaintext or using weak encryption (e.g., MD5).
  • Example: A database table with:
    CREATE TABLE users (
        id INT,
        username VARCHAR(50),
        password VARCHAR(50)  -- Stored as "password123"!
    );
    
  • Real-World Example: Ncell Data Leak (2019)
    • Issue: Ncell stored customer data (including passwords) in plaintext.
    • Impact: Hackers sold 10 million records on the dark web.

2. Defense Mechanisms

classDiagram
    class WAF {
        +Block SQLi: true
        +Block XSS: true
        +Rate Limiting: true
    }
    class WebServer {
        +Apache/Nginx
        +Handles HTTP
    }
    class Database {
        +MySQL/PostgreSQL
        +Stores Data
    }
    WAF --> WebServer : "Filters Traffic"
    WebServer --> Database : "Secure Queries"
    Note right of WAF: ModSecurity rules
    Note right of Database: Prepared Statements
WAF protecting a web stack (NMB Bank example)

A. Input Validation and Sanitization

  • Whitelisting: Only allow known-safe inputs (e.g., alphanumeric usernames).
  • Blacklisting: Block known-bad inputs (e.g., ', ", ;, <script>).
  • Example: Validating a username in Python:
    import re
    username = input("Enter username: ")
    if not re.match("^[a-zA-Z0-9_]{3,20}$", username):
        raise ValueError("Invalid username!")
    

B. Web Application Firewalls (WAFs)

  • How WAFs Work: Filter malicious traffic before it reaches the web server.
  • Example Rules:
    • Block SQL keywords (DROP, UNION, SELECT) in input fields.
    • Block XSS payloads (<script>, onerror=, javascript:).
  • Real-World Use: Cloudflare, AWS WAF, and ModSecurity protect sites like Nepal Investment Bank from OWASP Top 10 attacks.

C. Secure Coding Practices

Best Practice Example
Use Prepared Statements cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
Enable HTTPS Redirect HTTP → HTTPS; enforce HSTS headers.
Implement CSRF Tokens Add a hidden token to forms: <input type="hidden" name="csrf_token" value="abc123">
Principle of Least Privilege Run web apps as non-root users (e.g., www-data in Linux).

D. Secure Authentication

  • Multi-Factor Authentication (MFA): Require a second factor (e.g., OTP from Khalti or Ncell).
  • Password Policies:
    • Minimum 12 characters.
    • Require uppercase, lowercase, numbers, and symbols.
    • Enforce password expiration (e.g., every 90 days).
  • Example: Google’s password strength meter enforces complexity rules.

3. OWASP Top 10: Critical Web Vulnerabilities

The Open Web Application Security Project (OWASP) lists the top 10 risks in web apps. Here’s a comparison table:

Rank Vulnerability Description Example Attack
1 Injection SQLi, OS Command Injection, LDAP Injection ' OR 1=1 -- in login form
2 Broken Authentication Weak session management, credential stuffing Session fixation attack
3 Sensitive Data Exposure Unencrypted data (PII, passwords) Plaintext passwords in database
4 XML External Entities (XXE) XXE attacks via malformed XML input <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE root [ ... ]>
5 Broken Access Control Unauthorized access to admin panels /admin accessible without login
6 Security Misconfiguration Default credentials, verbose error messages admin:admin login
7 Cross-Site Scripting (XSS) Stored/Reflected XSS attacks <script>alert('hacked')</script>
8 Insecure Deserialization Malicious data in serialized objects Tampered Java .ser files
9 Using Components with Known Vulnerabilities Outdated libraries (e.g., Log4j, jQuery) Exploiting CVE-2021-44228 (Log4Shell)
10 Insufficient Logging & Monitoring Lack of audit logs or alerts for attacks No logs for failed login attempts

4. Secure Development Lifecycle (SDL)

To build secure web apps, follow the Microsoft SDL or OWASP SDL framework:

stateDiagram-v2
    [*] --> Requirement
    Requirement --> Design
    Design --> Code
    Code --> Test
    Test --> Release
    Release --> [*]
    Note over Requirement: Threat Modeling
    Note over Code: Static Analysis
    Note over Test: Penetration Testing
    Note over Release: Secure Deployment
OWASP SDL phases with security gates
flowchart TD
    A["Requirements"] --> B["Design"]
    B --> C["Implementation"]
    C --> D["Verification"]
    D --> E["Release"]
    E --> F["Deployment"]
    F --> G["Monitoring"]
    G -->|"Feedback"| A

Key Phases:

  1. Requirements: Define security requirements (e.g., "All passwords must be hashed with bcrypt").
  2. Design: Use threat modeling (e.g., STRIDE) to identify risks.
  3. Implementation: Apply secure coding practices (e.g., input validation).
  4. Verification: Penetration testing (e.g., using OWASP ZAP or Burp Suite).
  5. Release: Deploy with security headers (e.g., Content-Security-Policy).
  6. Monitoring: Use tools like Splunk or ELK Stack to detect anomalies.
Real-World Example: Pathao’s Secure Checkout
  • Threat: CSRF in payment processing.
  • Solution:
    • Implemented CSRF tokens in checkout forms.
    • Used HSTS to enforce HTTPS.
    • Integrated Khalti’s PCI-DSS compliant API for secure transactions.

5. Web Security Headers

HTTP headers add an extra layer of security. Key headers include:

Header Purpose Example
Content-Security-Policy (CSP) Mitigates XSS by restricting sources of scripts/styles. default-src 'self'; script-src 'self' https://cdn.example.com;
Strict-Transport-Security (HSTS) Forces HTTPS and prevents SSL stripping. Strict-Transport-Security: max-age=31536000; includeSubDomains;
X-Content-Type-Options Prevents MIME-sniffing attacks. X-Content-Type-Options: nosniff
X-Frame-Options Prevents clickjacking by blocking iframe embedding. X-Frame-Options: DENY
X-XSS-Protection Enables XSS filtering in browsers. X-XSS-Protection: 1; mode=block
Example: Secure Headers in NMB Bank
HTTP/2 200 OK
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.nmb.com;
Strict-Transport-Security: max-age=63072000; includeSubDomains
X-Frame-Options: DENY
X-Content-Type-Options: nosniff

6. Penetration Testing and Tools

A. Manual Testing Techniques

  1. SQLi Testing:
    • Test login forms with ' OR 1=1 --.
    • Use tools like SQLmap to automate exploitation.
  2. XSS Testing:
    • Inject <script>alert(1)</script> into input fields.
    • Use XSS Hunter to detect reflected XSS.
  3. CSRF Testing:
    • Craft a malicious link and test on authenticated sessions.

B. Automated Tools

Tool Purpose
OWASP ZAP Automated scanner for OWASP Top 10 vulnerabilities.
Burp Suite Intercept and modify HTTP requests for manual testing.
Nmap Scan for open ports and misconfigurations.
Nikto Web server vulnerability scanner.
Metasploit Exploit development and testing.
Real-World Example: Testing a Daraz Clone
  1. Step 1: Use Burp Suite to intercept a login request.
  2. Step 2: Modify the request to:
    POST /login HTTP/1.1
    Content-Type: application/x-www-form-urlencoded
    username=' OR '1'='1&password='
    
  3. Result: If the app returns a success message, it’s vulnerable to SQLi.

7. Case Study: Kathmandu Traffic Management System (KTMS) Web Portal

Problem:

  • The KTMS web portal allowed SQL Injection in traffic fine queries.
  • Attackers could extract sensitive data (e.g., vehicle details, owner addresses).

Exploit:

An attacker sent a query like:

' UNION SELECT username, password FROM admin_users --

This dumped all admin credentials.

Fix:

  1. Implemented Prepared Statements in PHP:
    $stmt = $pdo->prepare("SELECT * FROM fines WHERE vehicle_id = ?");
    $stmt->execute([$vehicle_id]);
    
  2. Added WAF Rules to block SQL keywords.
  3. Enabled Logging to detect future attacks.

In the Real World

  1. eSewa (Nepal)

    • Vulnerability: SQL Injection in API endpoints.
    • Impact: 1 million user records leaked.
    • Fix: Implemented input sanitization and WAF rules.
  2. Khalti (Nepal)

    • Security Feature: PCI-DSS compliance for payment processing.
    • How it Works: Uses tokenization (replacing card details with tokens) to prevent data exposure.
  3. YouTube (Global)

    • Vulnerability: XSS in Comments (2015).
    • Fix: Implemented Content Security Policy (CSP) and automated moderation.
  4. Nepal Investment Bank (NIBL)

    • Defense: Uses AWS WAF to block OWASP Top 10 attacks on their online banking portal.
  5. Pathao (Nepal)

    • Threat: CSRF in Ride Booking.
    • Solution: Added CSRF tokens and HSTS headers to all forms.

Exam Tip

How This Unit is Examined

  1. Theory Questions (30-40%):

    • Define SQLi, XSS, CSRF and explain how they work.
    • Compare symmetric vs. asymmetric encryption in web security (though primarily covered in Unit 2/3, it’s relevant for HTTPS).
    • Explain OWASP Top 10 with examples.
  2. Scenario-Based Questions (30-40%):

    • Given a vulnerable code snippet, identify the flaw and suggest fixes.
      # Vulnerable Code (SQLi)
      username = request.args.get('username')
      query = f"SELECT * FROM users WHERE username = '{username}'"
      
    • Expected Answer:
      • Flaw: String formatting allows SQL injection.
      • Fix: Use parameterized queries:
        cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
        
    • Case Study: Describe how to secure a login system against brute force (e.g., rate limiting, MFA).
  3. Tool-Based Questions (20-30%):

    • Burp Suite/ZAP: Explain how to use these tools to test for XSS/SQLi.
    • WAF Rules: Write a rule to block SQLi attempts (e.g., SecRule ARGS "@detectSQLi").
  4. Short Answer (10-20%):

    • What is CSRF? How is it prevented?
    • List 3 security headers and their purposes.

Key Formulas/Concepts to Remember

Concept Formula/Example
Password Hashing bcrypt(password) or SHA-256(password + salt)
CSRF Token token = hash(user_id + session_id + timestamp)
CSP Header default-src 'self'; script-src 'self' https://cdn.example.com
HSTS Header Strict-Transport-Security: max-age=31536000; includeSubDomains

Common Pitfalls in Exams

  • Confusing XSS and CSRF: XSS is about script injection, while CSRF is about forcing actions.
  • Ignoring HTTPS: Always mention HSTS and TLS 1.2+ in secure web app discussions.
  • Overlooking Logging: Secure apps must log failed login attempts and suspicious activity.

Based on the PU BE Computer (PU) syllabus for Network and Cyber Security (CMP426), unit 8.

Discussion

Loading…