Web and Database Security

Web and database security protects applications, users, APIs, and stored data from unauthorized access, manipulation, disclosure, and service disruption.

The main areas in this topic are:

  • OWASP Top 10 risks.

  • SQL injection.

  • Cross-site scripting.

  • Cross-site request forgery.

  • Secure coding practices.

  • Database hardening.

The central principle is:

Never trust user-controlled input, and never assume that a hidden interface or client-side control provides real security.

1. OWASP Top 10

Concept

The OWASP Top 10 is an awareness document that identifies important risks in web application security. The current 2025 list includes broken access control, security misconfiguration, software supply chain failures, cryptographic failures, injection, insecure design, authentication failures, software or data integrity failures, security logging and alerting failures, and mishandling of exceptional conditions.

The topics in this reviewer—SQL injection, XSS, and CSRF—are related to the OWASP categories of injection and broken access control.

OWASP Top 10: 2025

Rank

Category

General meaning

A01

Broken Access Control

Users can access functions or data beyond their permissions

A02

Security Misconfiguration

Insecure settings, defaults, or unnecessary services expose the application

A03

Software Supply Chain Failures

Dependencies, build tools, or delivery processes introduce risk

A04

Cryptographic Failures

Sensitive data is poorly protected through weak or incorrect cryptography

A05

Injection

Untrusted input is interpreted as commands or code

A06

Insecure Design

Security requirements are missing from the application design

A07

Authentication Failures

Login, session, or identity controls can be bypassed or abused

A08

Software or Data Integrity Failures

Untrusted code, updates, or data are accepted without proper verification

A09

Security Logging and Alerting Failures

Important security events are not recorded or acted upon

A10

Mishandling of Exceptional Conditions

Errors, failures, or unexpected states are handled insecurely

OWASP places SQL injection and cross-site scripting under the broader injection category in the 2025 list.

2. SQL Injection

Concept

SQL injection, or SQLi, occurs when an attacker manipulates an application’s database query by supplying specially crafted input.

The vulnerability commonly occurs when an application combines user input with SQL commands through string concatenation.

Vulnerable example

$username = $_POST["username"];

query="SELECT∗FROMusersWHEREusername=′query = "SELECT * FROM users WHERE username = 'username'";

The application treats the user’s input as part of the SQL command instead of treating it only as data.

Why SQL injection is dangerous

SQL injection may allow an attacker to:

  • Read confidential records.

  • Bypass authentication.

  • Modify database data.

  • Delete tables or records.

  • Access information belonging to other users.

  • Execute administrative database operations.

  • In some cases, interact with the underlying operating system.

Secure approach: parameterized queries

Parameterized queries separate SQL instructions from user-provided values.

$stmt = $pdo->prepare(
"SELECT * FROM users WHERE username = :username"
);

$stmt->execute([
"username" => $username
]);

The database treats the supplied username as a value, not as part of the SQL command.

OWASP recommends prepared statements or parameterized queries as a primary SQL injection defense. It also identifies properly constructed stored procedures and allow-list validation as additional options.

Other defenses
  • Use parameterized queries.

  • Validate input using allow-lists where possible.

  • Use stored procedures carefully.

  • Apply least privilege to database accounts.

  • Hide detailed database errors from users.

  • Keep database software updated.

  • Use web application firewalls as defense in depth.

  • Log suspicious database activity.

  • Test queries through secure code review and security testing.

Why escaping alone is weak

Manually escaping input is difficult because escaping rules vary between database systems and query contexts. Developers may forget to escape one parameter or apply the wrong escaping function.

OWASP strongly discourages relying only on escaping all user input.

SQL injection review example

Question: A search form accepts a product name and places it directly into a SQL query through string concatenation. What is the best correction?

Answer: Replace string concatenation with a parameterized query and validate the input according to the expected product-name format.

3. Cross-Site Scripting

Concept

Cross-Site Scripting, or XSS, occurs when an attacker causes a web application to deliver malicious script content to another user’s browser.

The injected script runs in the context of the trusted website. Depending on the situation, it may:

  • Read or manipulate page content.

  • Perform actions as the victim.

  • Capture sensitive information available to the page.

  • Steal non-protected session data.

  • Redirect the victim.

  • Modify displayed content.

  • Attack other users through stored content.

Types of XSS
Reflected XSS

Reflected XSS occurs when malicious input is immediately returned in a response.

Example:

https://example.com/search?q=<malicious-input>

The application places the search value into the response without proper output encoding.

Stored XSS

Stored XSS occurs when malicious content is saved by the application and later displayed to users.

Common locations include:

  • Comment sections.

  • User profiles.

  • Message boards.

  • Product reviews.

  • Support tickets.

  • Database records.

Stored XSS is especially dangerous because one submitted payload may affect many users.

DOM-based XSS

DOM-based XSS occurs when client-side JavaScript places untrusted data into a dangerous browser context.

Vulnerable example:

document.getElementById("output").innerHTML = userInput;

A safer approach for plain text is:

document.getElementById("output").textContent = userInput;

OWASP identifies avoiding unsafe DOM operations such as using innerHTML with untrusted data as a fundamental security practice.

XSS prevention
Contextual output encoding

Encode output according to where it will be inserted:

  • HTML body.

  • HTML attribute.

  • JavaScript string.

  • CSS value.

  • URL parameter.

Encoding appropriate for one context may not be safe in another.

Use safe framework features

Many web frameworks automatically encode output. Developers should avoid bypassing those protections unless the content is known to be safe.

Validate input

Input validation can restrict values to expected formats. However, validation should not replace output encoding because legitimate text can contain characters that are dangerous in a particular output context.

Content Security Policy

Content Security Policy, or CSP, is an HTTP response policy that restricts which scripts and resources a browser may load. CSP provides defense in depth against XSS but does not replace proper output encoding.

Secure cookies

Cookies containing session identifiers should generally use:

  • HttpOnly, to reduce access by client-side scripts.

  • Secure, so they are sent only over HTTPS.

  • Appropriate SameSite settings.

Example

A user enters this text into a comment field:

<script>maliciousAction()</script>

A secure application stores the value safely and displays it as text:

<script>maliciousAction()</script>

It does not allow the browser to interpret it as executable code.

4. Cross-Site Request Forgery

Concept

Cross-Site Request Forgery, or CSRF, tricks a victim’s browser into sending an unwanted state-changing request to a website where the victim is already authenticated.

The browser may automatically include the victim’s session cookie, making the request appear legitimate to the server.

Example scenario

A user is logged in to an online banking application. The user visits a malicious website that submits a hidden request to transfer money.

If the banking application only checks the session cookie and does not verify the origin or intent of the request, it may process the transfer.

CSRF requirements

CSRF is most likely when:

  • The victim is already authenticated.

  • Authentication uses automatically submitted cookies.

  • The application performs state changes through predictable requests.

  • The server does not require an additional request-specific value.

CSRF defenses
Anti-CSRF tokens

The server creates a random token and places it in the form or request. The server validates the token before processing the state-changing action.

The token should be:

  • Unpredictable.

  • Associated with the user session or request.

  • Validated on the server.

  • Required for state-changing operations.

OWASP recommends using framework-provided CSRF protection where available and adding tokens to state-changing requests when necessary.

SameSite cookies

The SameSite cookie attribute can reduce cross-site cookie sending.

Common settings include:

  • Strict.

  • Lax.

  • None; Secure.

Cookie settings must match the application’s legitimate cross-site requirements.

Origin and Referer validation

The server may check the Origin or Referer headers to determine whether the request came from an expected source. These checks should be implemented carefully because headers may be absent or affected by privacy controls.

Require POST or stronger methods

State-changing operations should not normally be performed through simple GET requests.

Unsafe example:

GET /delete-account

Better design:

POST /delete-account

The request should still require authorization and CSRF protection.

Reauthentication

Highly sensitive actions may require the user to reenter a password, provide multifactor authentication, or confirm the action.

XSS and CSRF relationship

XSS and CSRF are different vulnerabilities, but XSS may weaken some CSRF defenses because malicious script running in the trusted application context may be able to access page elements or submit requests.

Therefore, applications should defend against both.

5. SQLi, XSS, and CSRF Comparison

Vulnerability

Main target

Typical cause

Possible impact

Primary defense

SQL injection

Database

SQL query built with untrusted input

Data theft, modification, authentication bypass

Parameterized queries

XSS

User’s browser

Untrusted data rendered as executable content

Script execution, account abuse, data theft

Contextual output encoding

CSRF

Authenticated user’s session

State-changing request lacks proof of user intent

Unauthorized actions

Anti-CSRF tokens and SameSite cookies

6. Secure Coding

Concept

Secure coding means designing and implementing software so that it resists misuse, attack, data loss, and unauthorized access.

Security should be included throughout the software development lifecycle, not added only after the application is complete.

Secure coding principles
Validate all input

Treat input from the following sources as untrusted:

  • Forms.

  • URL parameters.

  • Cookies.

  • Headers.

  • Mobile applications.

  • APIs.

  • Uploaded files.

  • Databases.

  • Third-party services.

  • Other internal services.

Input validation should check:

  • Type.

  • Length.

  • Format.

  • Range.

  • Character set.

  • Allowed values.

  • File size.

  • File type.

Prefer allow-lists over deny-lists. An allow-list defines what is permitted instead of attempting to identify every malicious value.

Encode output

Output encoding must match the destination context. Data that is safe in plain text may be dangerous when inserted into HTML, JavaScript, CSS, or a URL.

Use safe APIs

Prefer APIs that separate data from commands:

  • Parameterized SQL queries.

  • Safe operating-system process APIs.

  • Framework output-encoding functions.

  • Secure file-handling libraries.

  • Built-in authentication and authorization features.

Enforce server-side authorization

Never rely only on:

  • Hidden buttons.

  • Disabled form fields.

  • Client-side JavaScript.

  • Mobile application checks.

  • URL obscurity.

  • User-supplied role values.

The server must verify whether the authenticated user is permitted to perform the requested action.

Use secure authentication
  • Store passwords using adaptive password-hashing functions.

  • Enable multifactor authentication.

  • Apply account lockout or rate limiting.

  • Protect password-reset flows.

  • Regenerate sessions after authentication.

  • Expire inactive sessions.

  • Invalidate sessions after logout.

  • Avoid exposing whether an account exists.

Protect secrets

Do not hardcode:

  • Database passwords.

  • API keys.

  • Private keys.

  • Cloud credentials.

  • Encryption keys.

Use protected environment configuration, secret-management systems, or platform key stores.

Handle errors safely

Errors should:

  • Avoid exposing passwords, tokens, SQL statements, and internal paths.

  • Use generic messages for users.

  • Record useful details in protected server logs.

  • Have consistent error handling.

  • Avoid revealing whether an account or record exists.

Use secure dependency management

Applications rely on frameworks and packages. Developers should:

  • Maintain a software inventory.

  • Update dependencies.

  • Remove unused packages.

  • Scan for known vulnerabilities.

  • Review package provenance.

  • Lock versions where appropriate.

  • Monitor security advisories.

Implement rate limiting

Rate limiting helps reduce:

  • Brute-force attacks.

  • Automated account testing.

  • Excessive API use.

  • Denial-of-service attempts.

  • Password-reset abuse.

Secure file uploads

A file-upload function should:

  • Restrict file size.

  • Validate file type.

  • Avoid trusting the file extension.

  • Rename uploaded files.

  • Store them outside executable web directories.

  • Scan them for malware.

  • Prevent path traversal.

  • Apply access controls.

  • Avoid executing uploaded content.

7. Authentication and Authorization

Authentication

Authentication answers:

Who are you?

Examples include:

  • Password.

  • One-time code.

  • Security key.

  • Certificate.

  • Biometric factor.

  • Device identity.

Authorization

Authorization answers:

What are you allowed to do?

A user may be authenticated but still not authorized to access another user’s records.

Broken access control example

An application uses:

/account?id=1001

A user changes the value to:

/account?id=1002

If the server returns another user’s account without checking ownership, the application has an access-control vulnerability commonly associated with insecure direct object references.

The server should verify authorization based on the authenticated identity, not only the requested object identifier.

8. Database Security and Hardening

Concept

Database hardening reduces the database’s attack surface and protects the confidentiality, integrity, and availability of stored data.

Hardening applies to:

  • Database software.

  • Database accounts.

  • Network access.

  • Permissions.

  • Encryption.

  • Configuration.

  • Monitoring.

  • Backups.

  • Patch management.

Database hardening controls
Use least privilege

Applications should use database accounts with only the permissions they need.

For example, an application that only reads product information should not have permission to:

  • Drop tables.

  • Create new users.

  • Alter database structure.

  • Read unrelated customer records.

Separate accounts may be used for:

  • Application runtime.

  • Database administration.

  • Reporting.

  • Backup.

  • Migration.

  • Monitoring.

Restrict network access

Databases should not be exposed directly to the public internet unless there is an exceptional and justified requirement.

Use:

  • Private subnets.

  • Firewalls.

  • Security groups.

  • Network access lists.

  • Bastion hosts.

  • VPN or private connectivity.

  • Restricted management networks.

Secure administrative access
  • Use named administrative accounts.

  • Avoid shared administrator credentials.

  • Require multifactor authentication where supported.

  • Restrict administrative connections.

  • Log administrative actions.

  • Disable unused accounts.

  • Review privileges regularly.

Encrypt data in transit

Use encrypted database connections between:

  • Application and database.

  • Database and replication nodes.

  • Administrators and database servers.

  • Backup systems and storage.

Encrypt data at rest

Encryption at rest may protect:

  • Database files.

  • Storage volumes.

  • Backups.

  • Temporary files.

  • Replicas.

Encryption does not replace access control. An attacker using an authorized application account may still access data through the application.

Protect sensitive fields

Particularly sensitive information may require:

  • Field-level encryption.

  • Tokenization.

  • Masking.

  • Data minimization.

  • Separate key management.

Keys should not be stored in the same location and manner as the encrypted data.

Patch and update

Database servers should be maintained with:

  • Security patches.

  • Supported versions.

  • Updated extensions.

  • Updated drivers.

  • Updated management tools.

Disable unnecessary features

Disable unused:

  • Network protocols.

  • Extensions.

  • Sample databases.

  • Default accounts.

  • Administrative interfaces.

  • Stored procedures or features that are not required.

Secure backups

Backups should be:

  • Encrypted.

  • Access-controlled.

  • Tested through restoration exercises.

  • Protected from ransomware.

  • Retained according to policy.

  • Monitored for unauthorized changes.

A backup that cannot be restored is not a reliable recovery control.

Monitor database activity

Monitor:

  • Failed logins.

  • Privilege changes.

  • New accounts.

  • Schema changes.

  • Unusual queries.

  • Large data exports.

  • Access outside normal hours.

  • Administrative actions.

  • Repeated errors.

  • Connections from unexpected hosts.

9. Database Access Architecture

A secure web application commonly follows this pattern:

text

User Browser
     |
 HTTPS
     |
Web/Application Server
     |
Restricted Database Connection
     |
Database Server

The browser should not connect directly to the database.

The application server should:

  • Authenticate the user.

  • Authorize the requested action.

  • Validate input.

  • Use parameterized queries.

  • Return only necessary data.

  • Log important events.

The database should accept connections only from approved application or administration systems.

10. Secure Database Example

Insecure pattern

$id = $_GET["id"];
$sql = "SELECT * FROM users WHERE id = " . $id;
$result = $db->query(sql);

Problems:

  • User input is inserted directly into SQL.

  • The query may allow SQL injection.

  • The application may expose unnecessary columns.

  • Authorization is not shown.

  • Detailed errors may leak information.

Safer pattern

id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);

if ($id === false || $id === null) {
http_response_code(400);
exit("Invalid request");
}

$stmt = $db->prepare(
"SELECT display_name, email FROM users WHERE id = :id"
);

$stmt->execute(["id" => $id]);

Additional authorization is still required:

if ($requestedUserId !== $authenticatedUserId && !$isAdmin) {
http_response_code(403);
exit("Forbidden");
}

Parameterization prevents the input from becoming SQL syntax, while authorization ensures that the user is allowed to access the selected record.

11. Secure Development Testing

Security testing should be performed throughout development.

Static Application Security Testing

SAST analyzes source code or compiled code without executing the application.

It can identify:

  • Dangerous functions.

  • Hardcoded secrets.

  • SQL query construction.

  • Weak cryptography.

  • Missing validation.

  • Insecure API use.

Dynamic Application Security Testing

DAST tests a running application from the outside.

It may identify:

  • Injection.

  • XSS.

  • Authentication problems.

  • Misconfigured headers.

  • Exposed services.

  • Session weaknesses.

Software Composition Analysis

SCA identifies vulnerabilities in third-party packages and dependencies.

Interactive Application Security Testing

IAST combines application execution with security instrumentation to observe how data flows through the application.

Manual testing

Manual review remains important for:

  • Business logic flaws.

  • Authorization errors.

  • Workflow abuse.

  • Race conditions.

  • Insecure design.

  • Context-specific vulnerabilities.

Automated tools are useful but cannot identify every security problem.

12. Security Headers

Security-related HTTP headers can add defense in depth.

Common examples include:

  • Content-Security-Policy.

  • Strict-Transport-Security.

  • X-Content-Type-Options: nosniff.

  • Referrer-Policy.

  • Permissions-Policy.

  • Set-Cookie security attributes.

  • frame-ancestors through CSP.

Headers should be tested carefully because incorrect policies may break application features or create a false sense of security.

13. Common Mistakes

  • Concatenating SQL strings with user input.

  • Trusting client-side validation.

  • Displaying user input without contextual encoding.

  • Using innerHTML with untrusted data.

  • Assuming POST automatically prevents CSRF.

  • Disabling CSRF protection during development and forgetting to restore it.

  • Giving the application database account administrative privileges.

  • Exposing the database directly to the internet.

  • Using default database passwords.

  • Storing secrets in source code.

  • Returning complete database records when only a few fields are needed.

  • Showing detailed SQL errors to users.

  • Failing to log database administration.

  • Using outdated frameworks or dependencies.

  • Treating a web application firewall as a replacement for secure coding.

  • Relying on a hash alone to prove who created a file.

  • Failing to test backup restoration.