Web & Application Security

Chapter 5
Common Web Vulnerabilities and Defences

Advance Diploma in Cybersecurity
Web & Application Security   •   Advance Diploma

Common Web Vulnerabilities and Defences

Introduction

Web applications process valuable information, perform business-critical transactions and connect users, organisations and external services. Their security depends not only on cryptographic algorithms or network controls, but also on how application code interprets input, enforces authority, manages state and handles unexpected conditions. A vulnerability occurs when a weakness can be exploited to violate confidentiality, integrity, availability or accountability.

The Open Worldwide Application Security Project (OWASP) provides widely used guidance for identifying and reducing web application risk. The OWASP Top 10 is an awareness document rather than a complete security standard. It groups recurring classes of weaknesses, while resources such as the OWASP Application Security Verification Standard (ASVS), Web Security Testing Guide and Cheat Sheet Series provide more detailed requirements and testing practices.

This chapter examines major vulnerabilities relevant to contemporary web systems: injection, cross-site scripting, cross-site request forgery, broken access control, insecure design, server-side request forgery, file-handling weaknesses, insecure deserialisation, HTTP request smuggling, business-logic abuse and security misconfiguration. The emphasis is on analysis and defence rather than exploit construction.

Learning Objectives

By the end of this chapter, students should be able to:

  1. Explain how common web vulnerabilities arise from flawed interpretation, trust or authority decisions.
  2. Distinguish preventive, detective and corrective controls for major vulnerability classes.
  3. Analyse application designs using OWASP-oriented threat modelling and verification principles.
  4. Recommend secure coding, architectural and operational mitigations.
  5. Evaluate the security, ethical and governance implications of testing and operating web applications.

1. A Risk-Based View of Web Vulnerabilities

A useful security analysis considers four related questions:

  • What is the asset? Examples include credentials, personal data, payment records, business rules and infrastructure access.
  • Who is the actor? Actors may be unauthenticated visitors, ordinary users, administrators, insiders or compromised third parties.
  • What trust boundary is crossed? Boundaries may exist between browsers and servers, users and tenants, application tiers, or an organisation and an external service.
  • What security property is affected? Confidentiality prevents unauthorised disclosure; integrity prevents unauthorised modification; availability preserves dependable access; authenticity and accountability support trustworthy identity and action.

Risk is commonly discussed as a combination of likelihood and impact. This is a prioritisation model, not a precise physical law:

Risk priority ≈ Likelihood × Impact

Likelihood reflects exploitability, exposure, attacker capability and the effectiveness of existing controls. Impact reflects affected assets, scale, legal consequences, safety implications and recovery cost. The expression should not be treated as an exact probability calculation unless the organisation has defined a formal quantitative method.

A secure lifecycle integrates security requirements, design review, implementation controls, testing, deployment hardening, monitoring and incident response. Fixing a vulnerability after release is often more expensive than preventing the underlying design error.

2. Injection Vulnerabilities

Injection occurs when an application combines untrusted data with an interpreter’s commands or syntax. The interpreter may be a relational database, operating-system shell, LDAP service, template engine, expression evaluator or browser. The central failure is confusion between data and instructions.

2.1 SQL and Other Interpreter Injection

In SQL injection, attacker-controlled input changes the meaning of a database query. Risky code constructs a query by concatenating strings. Secure code uses parameterised queries, in which the SQL structure is defined separately from values. For example, a data-access layer should conceptually execute:

SELECT account_id, balance FROM accounts WHERE account_id = ?

The account identifier is bound as a value rather than interpreted as SQL syntax. Parameterisation is the primary defence. Input validation remains useful for business constraints, such as requiring an identifier to be a positive integer, but validation alone is not a substitute for separation of code and data.

Additional controls include least-privilege database accounts, restricted network access, safe error handling, allow-listed dynamic identifiers and security testing. Stored procedures are not automatically safe; procedures that concatenate untrusted strings remain vulnerable.

The same principle applies to command injection, LDAP injection, NoSQL injection and template injection. Where a command must be invoked, applications should prefer a library API over a shell, pass arguments through a structured interface, use allow-lists and run with minimal operating-system privileges.

2.2 Defensive Design Pattern

A robust input-handling sequence is:

  1. Identify the expected type, format, range and business meaning.
  2. Parse input using a well-defined parser rather than ad hoc string operations.
  3. Reject or safely handle invalid input.
  4. Bind values through an API designed to preserve data boundaries.
  5. Apply least privilege to the interpreter account.
  6. Log relevant security events without recording secrets.

Escaping is context-dependent. HTML escaping, SQL escaping, shell escaping and URL encoding solve different problems and must not be substituted for one another.

3. Cross-Site Scripting

Cross-site scripting (XSS) occurs when an application causes a browser to execute attacker-controlled script in the security context of a trusted site. It can compromise sessions, alter displayed content, perform actions as the victim and capture sensitive page data.

The principal categories are:

  • Reflected XSS: malicious input is returned immediately in a response.
  • Stored XSS: malicious content is persisted and later served to users.
  • DOM-based XSS: client-side code places untrusted data into an unsafe browser sink.

The primary defence is context-sensitive output encoding. Data inserted into HTML text, an HTML attribute, a JavaScript string, CSS or a URL requires different treatment. Safe templating frameworks generally encode by default, but vulnerabilities can reappear when developers disable escaping or use raw HTML features.

Other controls include:

  • sanitising HTML with a well-maintained, restrictive library when rich text is genuinely required;
  • avoiding dangerous sinks such as unsafe HTML insertion and dynamic code evaluation;
  • using Content Security Policy (CSP) as defence in depth;
  • setting cookies with HttpOnly, Secure and appropriate SameSite attributes;
  • validating content types and response headers.

CSP reduces the consequences of some XSS attacks but is not a replacement for correct output encoding. Security teams should test both server-rendered and client-side code, including framework escape-hatches.

4. Cross-Site Request Forgery

Cross-site request forgery (CSRF) exploits a browser’s automatic inclusion of credentials. If a victim is authenticated to an application, a malicious site may attempt to cause the browser to submit an unwanted state-changing request.

Effective defences include unpredictable, session-bound anti-CSRF tokens validated on every relevant request, the SameSite cookie attribute, origin or referer checks where appropriate, and requiring reauthentication or step-up verification for high-impact actions. Applications should not rely solely on a secret custom header unless the architecture ensures that another origin cannot cause the browser to send that header.

CSRF protection is particularly important for cookie-based authentication. APIs using bearer tokens stored and submitted in a way unavailable to cross-origin forms have a different threat profile, but they still require careful cross-origin policy and token protection. GET requests should be safe and idempotent in meaning; state-changing actions should use appropriate methods and CSRF controls.

5. Broken Access Control

Access control determines whether an identified subject may perform an action on a particular object under specified conditions. Broken access control occurs when the application fails to enforce this decision consistently or correctly.

Common examples include:

  • Horizontal privilege escalation: one user accesses another user’s records.
  • Vertical privilege escalation: an ordinary user invokes an administrator function.
  • Insecure direct object reference: changing an identifier reveals an unauthorised object.
  • Missing function-level control: a hidden administrative URL remains callable.
  • Tenant isolation failure: one organisation accesses another organisation’s data.

Secure design uses server-side enforcement, deny-by-default policies, centralised authorisation services, explicit ownership checks and tests for every role and tenant boundary. Hiding buttons or relying on client-side checks provides usability, not security.

A useful authorisation decision can be represented conceptually as:

Permit(subject, action, resource, context)

All four elements matter. A user may be permitted to view an invoice but not modify it; may access a record only within a particular tenant; or may perform an action only during an approved workflow state. Logs should record significant denied and permitted administrative actions while protecting personal data.

6. Insecure Design and Business-Logic Abuse

Insecure design is a weakness in requirements, architecture or security assumptions rather than merely an implementation defect. Examples include password-reset processes without adequate identity proof, unrestricted high-value transfers, missing transaction limits and workflows that permit approval by the same person who created a request.

Business-logic abuse uses legitimate application functions in unintended combinations or sequences. Unlike injection, the attacker may send completely valid requests. Examples include replaying a discount, changing the price between quotation and payment, bypassing a required approval step, submitting a negative quantity, or exploiting race conditions in inventory reservation.

Defences begin before coding:

  1. Identify assets, actors, abuse cases and trust boundaries.
  2. Define business invariants, such as “a refund cannot exceed the settled payment.”
  3. Model workflow states and permitted transitions.
  4. Apply server-side limits, atomic transactions and idempotency keys.
  5. Separate duties for high-risk operations.
  6. Test sequences, concurrency and failure recovery—not only individual endpoints.

Security requirements should be measurable. “Users must not exceed their credit limit” is stronger when translated into an enforced rule at the transaction boundary and covered by automated tests.

7. Server-Side Request Forgery

Server-side request forgery (SSRF) occurs when an attacker influences a server into making a request to an unintended destination. The target may be an internal administration service, cloud metadata endpoint, local service or another network zone. SSRF can expose secrets, scan internal systems or trigger privileged actions.

Defences include avoiding arbitrary server-side URL fetching, using allow-listed schemes and destinations, validating after DNS resolution, restricting redirects, applying outbound network policies and isolating fetching services. Network controls should deny access to loopback, link-local, private and management ranges unless explicitly required. Because DNS rebinding and alternate address representations can defeat naïve filters, validation and connection policy must be applied close to the actual network operation.

Cloud environments require particular attention to metadata services. Provider-specific protections should be enabled, workload identity should be narrowly scoped and sensitive credentials should not be broadly available to application processes.

8. File-Handling Flaws

File vulnerabilities arise from unsafe upload, storage, processing or download. Risks include unrestricted executable uploads, path traversal, malicious archive extraction, parser vulnerabilities, resource exhaustion and disclosure through predictable filenames.

A secure upload design should:

  • allow-list business-approved file types and enforce size and quantity limits;
  • verify content using trusted parsing or file-signature analysis rather than trusting only the filename or client MIME type;
  • generate server-side names and store files outside executable web roots;
  • apply least privilege and malware scanning where appropriate;
  • process files in isolated, resource-limited services;
  • defend archive extraction against path traversal and excessive expansion;
  • serve downloads with safe content-disposition and content-type headers;
  • prevent access-control bypasses through direct storage URLs.

Image, document and archive libraries should be patched and monitored. “Rename the extension” is not a complete defence because content parsers, polyglot files and server configuration may still create risk.

9. Insecure Deserialisation

Serialisation converts structured objects into a transport or storage representation; deserialisation reconstructs them. Insecure deserialisation occurs when untrusted data is reconstructed in a way that permits code execution, object substitution, unexpected method invocation or privilege manipulation.

The safest strategy is to avoid native object deserialisation for untrusted data. Prefer simple data-transfer formats with explicit schemas, strict type validation, bounded sizes and no executable behaviour. Cryptographic signing can provide integrity and origin assurance, but it does not make a dangerous deserialisation mechanism safe if an authorised signer can be induced to sign harmful content. Deserialised data must still be authorised and validated against current business rules.

10. HTTP Request Smuggling

HTTP request smuggling exploits disagreement between front-end and back-end components about where one request ends and another begins. This commonly results from inconsistent interpretation of Content-Length and Transfer-Encoding or from intermediary parsing differences.

Consequences may include bypassing access controls, poisoning connection reuse, misrouting requests and affecting other users. Defences include using consistently patched, standards-conforming components; eliminating ambiguous request framing; normalising or rejecting conflicting headers; using compatible proxy configurations; and testing the complete proxy chain. Security review must cover load balancers, CDNs, gateways and application servers together, because a component that is safe in isolation may be unsafe in combination.

11. Security Misconfiguration

Security misconfiguration includes insecure defaults, unnecessary services, excessive permissions, verbose error messages, exposed administrative interfaces, missing security headers, weak TLS settings and inconsistent environment configuration.

A configuration baseline should define approved settings for development, testing and production. Controls include infrastructure as code, automated configuration scanning, secret management, removal of sample accounts, patch management, restricted management access, secure headers, centralised logging and regular review of cloud permissions. Development diagnostics must not be enabled in production.

Configuration is a lifecycle concern. A secure initial deployment can become insecure through emergency changes, unmanaged dependencies or drift. Therefore, organisations need change control, monitoring and periodic independent verification.

12. Integrated Case Study: Illustrative Online Marketplace

Background

An illustrative online marketplace allows customers to browse products, upload product images, receive discount codes and pay through an external payment provider. It uses a single-page web client, an API gateway, several microservices and a cloud object store.

Problem

A security review identifies that customers can alter an order identifier in an API request, product descriptions are rendered with unsafe HTML, the image-fetching feature accepts arbitrary URLs, and the gateway and application server parse request bodies differently. The discount service also permits repeated redemption after a failed payment.

Analysis

The order identifier issue is broken object-level access control. The product-description issue is stored XSS. Arbitrary image retrieval creates SSRF. Parser disagreement indicates request-smuggling risk. Repeated discount redemption is business-logic abuse. These weaknesses interact: XSS could target privileged staff, SSRF could reach internal services, and access-control failures could expose other customers’ orders.

Approach and Solution

The organisation first defines security requirements and business invariants. Every order query checks both the authenticated subject and tenant or ownership relationship. Product descriptions are sanitised with a restricted HTML policy and rendered using contextual encoding. Image retrieval is replaced with direct client upload where possible; remaining server-side fetching uses an allow-list, isolated worker, redirect restrictions and egress filtering.

The gateway and application server are upgraded and configured to reject ambiguous request framing. Discount redemption is made atomic, linked to an order and protected by an idempotency key and a one-time-use record. CSP, secure cookie attributes, centralised audit logging and automated authorisation tests are added. The team conducts regression testing across the entire request path and commissions an independent assessment.

Outcome and Learning Points

The changes reduce attack surface rather than merely blocking known payloads. The case demonstrates that vulnerabilities often arise from design assumptions and component interaction. It also shows why security testing must cover workflows, infrastructure and data flows, not only isolated source-code patterns.

13. Testing, Governance and Ethical Practice

Security verification should combine code review, dependency analysis, automated tests, dynamic testing, configuration review, threat modelling and carefully authorised penetration testing. Tests should include negative cases, role matrices, tenant boundaries, malformed inputs, race conditions and failure recovery.

Testing must be authorised, scoped and conducted to minimise harm. Researchers should protect personal data, avoid unnecessary service disruption, preserve evidence securely and disclose findings through an agreed process. Organisations should define vulnerability disclosure procedures, remediation priorities and exception management.

Regulatory obligations vary by jurisdiction and sector, but common governance themes include data minimisation, privacy protection, retention control, breach response and demonstrable security measures. Compliance is not equivalent to security; a compliant system may still be exploitable, while strong security practices support compliance objectives.

Artificial intelligence can assist code review, test generation, log analysis and detection of anomalous behaviour. However, generated code may contain insecure assumptions, and sensitive source code or logs may create confidentiality risks when submitted to external services. Human review, secure development standards and controlled data handling remain necessary.

14. Defence-in-Depth Checklist

A practical programme should:

  • define security requirements and abuse cases before implementation;
  • use safe frameworks and parameterised interfaces;
  • validate at trust boundaries and encode output by context;
  • enforce authorisation on the server for every sensitive operation;
  • isolate file processors and outbound-fetching components;
  • minimise privileges, secrets and network reachability;
  • harden gateways, servers, containers and cloud services;
  • patch dependencies and remove unsupported components;
  • log meaningful security events and monitor for abuse;
  • test workflows, component interactions and configuration drift;
  • rehearse incident response and recovery;
  • measure remediation by risk, not by the number of scans completed.

Chapter Summary

Common web vulnerabilities arise when applications confuse data with instructions, trust the wrong party, fail to enforce authority, expose dangerous capabilities or implement business rules incompletely. Injection is best controlled through parameterised interfaces and least privilege. XSS requires context-sensitive output encoding and safe browser policies. CSRF protection prevents unauthorised state changes made through a victim’s authenticated browser. Broken access control requires server-side, deny-by-default and object-aware authorisation.

Insecure design and business-logic abuse must be addressed through threat modelling, explicit invariants, workflow analysis and transaction controls. SSRF requires strict destination control and network egress restrictions. File handling demands safe storage, parsing, isolation and resource limits. Untrusted deserialisation should be avoided or constrained by explicit schemas. Request smuggling is reduced by consistent parsing across the proxy chain. Security misconfiguration is controlled through hardened baselines, automation and continuous review.

OWASP guidance provides a useful foundation, but secure application engineering also requires organisational governance, ethical testing, monitoring, incident response and continual reassessment as technologies and threats change.

Key Terms

Injection: Introducing untrusted data into an interpreter so that it changes command or query meaning.

Parameterised query: A database operation that separates query structure from supplied values.

Cross-site scripting (XSS): Browser execution of attacker-controlled script in a trusted application context.

Reflected XSS: XSS in which input is immediately returned in a response.

Stored XSS: XSS in which malicious content is persisted and later served.

Cross-site request forgery (CSRF): Causing an authenticated browser to submit an unintended state-changing request.

Access control: Rules determining which subjects may perform actions on resources.

Horizontal privilege escalation: Unauthorised access to another user’s resources at the same privilege level.

Vertical privilege escalation: Unauthorised use of a higher-privilege function.

Insecure design: A weakness in requirements, architecture or security assumptions.

Business-logic abuse: Misuse of valid functions, sequences or rules to achieve an unintended outcome.

SSRF: Causing a server to make a request to an attacker-selected or unintended destination.

Path traversal: Manipulating file paths to access locations outside the intended directory.

Deserialisation: Reconstructing structured objects from a stored or transmitted representation.

Request smuggling: Exploiting inconsistent HTTP request parsing between intermediaries.

Security misconfiguration: Unsafe, incomplete or inconsistent security settings.

Content Security Policy: A browser policy restricting permitted content and script sources.

Least privilege: Granting only the access required for an actor or component to perform its function.

Trust boundary: A point where data, authority or assumptions change between components or actors.

Defence in depth: Using multiple complementary controls so that one failure does not produce total compromise.

Review Questions

Short Answer Questions

  1. Why are parameterised queries preferred to string concatenation for database access?
  2. Distinguish reflected XSS from stored XSS.
  3. What is the purpose of an anti-CSRF token?
  4. Give two examples of broken access control.
  5. Why is server-side URL fetching a potential SSRF risk?

Long Answer Questions

  1. Explain how a secure application should handle file uploads from receipt through storage and download.
  2. Compare preventive controls for injection, XSS and CSRF.
  3. Discuss why insecure design cannot be solved solely through input validation.
  4. Explain the causes and consequences of HTTP request smuggling in a proxy chain.
  5. Analyse how security misconfiguration can emerge after a secure deployment.

Analytical / Application Questions

  1. An API allows a customer to request /orders/1842 after changing the identifier from their own order. Analyse the vulnerability and propose a layered solution.
  2. A marketplace permits a server to download images from URLs supplied by sellers. Develop a secure architecture for this feature and identify residual risks.
  3. A discount may be redeemed twice when two requests arrive simultaneously. Identify the business-logic weakness and describe controls involving transactions, idempotency and testing.

Multiple Choice Questions with Answers

Question 1

Which control most directly prevents SQL injection?

A. Parameterised queries

B. Hiding database error messages

C. Increasing session timeout

D. Adding a larger database server

Correct Answer: A. Parameterised queries

Question 2

Which type of XSS occurs when malicious content is saved and later displayed to users?

A. Reflected XSS

B. Stored XSS

C. Network XSS

D. Transport XSS

Correct Answer: B. Stored XSS

Question 3

What is the primary purpose of a CSRF token?

A. To encrypt database records

B. To prove that a state-changing request was intentionally issued by the application user

C. To compress HTTP responses

D. To assign an IP address

Correct Answer: B. To prove that a state-changing request was intentionally issued by the application user

Question 4

Changing an object identifier to access another customer’s record is most directly an example of:

A. Broken object-level access control

B. Security misconfiguration

C. Clickjacking only

D. Insecure TLS negotiation

Correct Answer: A. Broken object-level access control

Question 5

Which feature creates the clearest SSRF risk?

A. A server fetches a URL supplied by a user

B. A browser displays a local image

C. A database stores a hashed password

D. A server rejects oversized requests

Correct Answer: A. A server fetches a URL supplied by a user

Question 6

Which is the strongest general approach for untrusted structured input that might otherwise invoke object behaviour?

A. Use native deserialisation without validation

B. Use explicit schemas and simple data-transfer formats

C. Trust the client because it uses HTTPS

D. Disable application logging

Correct Answer: B. Use explicit schemas and simple data-transfer formats

Question 7

HTTP request smuggling commonly results from disagreement between components about:

A. User password length

B. Request boundary and body framing

C. Database table names

D. Screen resolution

Correct Answer: B. Request boundary and body framing

Question 8

Which practice best supports defence against stored XSS when rich text is required?

A. Allow all HTML and rely on users to report abuse

B. Use a restrictive, maintained HTML sanitiser and contextual output encoding

C. Disable database backups

D. Increase cookie expiration time

Correct Answer: B. Use a restrictive, maintained HTML sanitiser and contextual output encoding

Question 9

Which control most directly reduces the impact of a compromised file-processing service?

A. Running it with broad administrator privileges

B. Isolating it and applying least privilege and resource limits

C. Allowing arbitrary outbound connections

D. Storing executable uploads in the web root

Correct Answer: B. Isolating it and applying least privilege and resource limits

Question 10

A discount redeemed twice because two simultaneous requests both pass an availability check illustrates:

A. A race condition in business logic

B. A certificate expiry

C. A DNS naming issue

D. A rendering-only defect

Correct Answer: A. A race condition in business logic

Web & Application Security
Chapter 5 of 14