Web Security

Web Applications, Authentication and Authorization

Introduction to Web Security

  • Web Security Basics
  • Understanding the OWASP Top 10
  • Authentication & Authorization
  • Secure Authentication & Data Validation
  • Browser extensions
  • Cheat Sheets
  • Conclusion / Q&A

1. Web Security Basics

XSS (Cross-Site Scripting)

Allows malicious scripts to be injected into a website.

  • Theft of cookies and session tokens
  • Actions on behalf of the user
  • Fake UI and phishing
<p>Hi, <span id="user"></span></p>
<script>
  const name = new URLSearchParams(location.search).get("name");
  document.getElementById("user").innerHTML = name;
</script>

Example: https://example.com?name=<script>alert("XSS")</script>

XSS protection

  • Escaping (textContent instead of innerHTML)
  • CSP: Content-Security-Policy: default-src 'self'
  • Frameworks: Angular, React, Vue
<p>{{ userInput }}</p> // Angular template

CSRF (Cross-Site Request Forgery)

The attack forces actions using authorization cookies.

<img src="https://bank.com/transfer?amount=1000&to=attacker" />

Protection:

  • CSRF-tokens:
    <form method="POST" action="/transfer">
    	<input type="hidden" name="csrfToken" value="abc123" />
    	...
    </form>
  • Origin / Referer
  • SameSite cookies

SQL Injection

Implementing SQL code through query parameters.

https://site.com/login?user=admin&pass=123
https://site.com/login?user=admin'--&pass=whatever

app.get('/login', (req, res) => {
  const { user, pass } = req.query;
  db.query(`SELECT * FROM users WHERE username = '${user}' AND password = '${pass}'`);
});

SELECT * FROM users WHERE username = 'admin' --' AND password = '123'

Protection:

  • Parameterization of requests
  • ORM libraries
  • Restricting access rights

MITM (Man-in-the-middle)

[Client] <---> [😈 MITM] <---> [Server]

Protection:

HTTPS = HTTP + TLS. Encrypts data and authenticates the server.

  • Encryption
  • Authentication
  • Integrity
https

CORS

Controls cross-domain requests. Requires configuration on the server.

cors

CSP (Content-Security-Policy)

Restricts where resources are downloaded from.

  • XSS attacks (injection of malicious scripts)
  • Clickjacking
  • Uploading unauthorized resources
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.com;

Secure Headers

  • Strict-Transport-Security
    (Enforces HTTPS for all future connections)
  • X-Frame-Options
    (Prevents clickjacking via iframes)
  • X-Content-Type-Options
    (Prevents MIME type sniffing attacks)
  • Referrer-Policy
    (Controls how much referrer information is sent)

2. Understanding the OWASP Top 10

Open Web Application Security Project

API1: Broken Object Level Authorization (BOLA)

Objects are available without checking authorization by ID.

GET /api/v1/users/{id}/profile

API2: Broken Authentication

Authentication mechanisms are often flawed. This allows attackers to bypass security or impersonate users.

No password verification when changing email.

PUT /account
Authorization: Bearer <token>
{ "email": "..." }

API3: Property Level Authorization

APIs return more data than necessary. Clients should only receive authorized properties.

Changing hidden properties of objects.

PUT /api/video/update_video

{
  "description": "a funny video about cats"
}

{
  "description": "a funny video about cats",
  "blocked": false
}

API4: Resource Consumption

APIs consume resources like network bandwidth, CPU, memory, and storage. Unrestricted consumption can lead to Denial of Service (DoS) or increased operational costs. Implement proper rate limiting and quotas.

API4: Resource Consumption

SMS API attack. Huge costs.

POST /initiate_forgot_password

{
  "step": 1,
  "user_number": "6501113434"
}
POST /sms/send_reset_pass_code

Host: willyo.net

{
  "phone_number": "6501113434"
}

API5: Function Level Authorization

This vulnerability arises from poorly implemented authorization at the function level. Attackers can bypass authorization checks to access privileged functions or data.

API call to GET /api/invites/{invite_guid}
POST /api/invites/new

{
  "email": "attacker@somehost.com",
  "role":"admin"
}

API6: Sensitive Business Flows

This risk occurs when APIs expose business flows that can be abused if used excessively in an automated manner. This is not necessarily due to implementation bugs, but rather a lack of business logic protection.

API7: SSRF (Server Side Request Forgery)

SSRF vulnerabilities occur when an API fetches a remote resource without properly validating the user-supplied URI. This allows attackers to coerce the application into making requests to unexpected destinations.

API7: SSRF (Server Side Request Forgery)

Requests to internal resources via API.

POST /api/profile/upload_picture

{
  "picture_url": "http://example.com/profile_pic.jpg"
}

{
  "picture_url": "localhost:8080"
}
					

API8: Security Misconfiguration

Default configs, missing security headers, open ports.

A social network website offers a "Direct Message" feature that allows users to keep private conversations. To retrieve new messages for a specific conversation, the website issues the following API request (user interaction is not required):

GET /dm/user_updates.json?conversation_id=1234567&cursor=GRlFp7LCUAAAA

Because the API response does not include the Cache-Control HTTP response header, private conversations end-up cached by the web browser, allowing malicious actors to retrieve them from the browser cache files in the filesystem.

API9: Inventory Management

Undocumented APIs, deprecated versions, debug endpoints.

A social network allows developers of independent apps to integrate with it. As part of this process a consent is requested from the end user, so the social network can share the user's personal information with the independent app.

The data flow between the social network and the independent apps is not restrictive or monitored enough, allowing independent apps to access not only the user information but also the private information of all of their friends.

A consulting firm builds a malicious app and manages to get the consent of 270,000 users. Because of the flaw, the consulting firm manages to get access to the private information of 50,000,000 users. Later, the consulting firm sells the information for malicious purposes.

API10: Unsafe Consumption of APIs

Misconfigurations, poor inventory practices, and unsafe third-party API consumption can open doors for various attacks. Prioritizing these areas is crucial for comprehensive API security.

API10: Unsafe Consumption of APIs

An API integrates with a third-party service provider to safely store sensitive user medical information. Data is sent over a secure connection using an HTTP request like the one below:

POST /user/store_phr_record
{
  "genome": "ACTAGTAG__TTGADDAAIICCTT…"
}
HTTP/1.1 308 Permanent Redirect
Location: https://attacker.com/

Since the API blindly follows the third-party redirects, it will repeat the exact same request including the user's sensitive data, but this time to the attacker's server.

3. Authentication & Authorization

Authentication

Authentication is the process of confirming a user's identity. It ensures only legitimate users can access resources.

Authentication Methods: Single to Multi-Factor

OAuth

OAuth

JWT (JSON Web Tokens)

JWT Structure

{
  "alg": "HS256",
  "typ": "JWT"
}.
{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}.
[Signature]
jwt

Cookies

State Management and Security

Cookies are essential for session management. Proper attribute usage enhances security

HttpOnly, Secure, and SameSite are critical for preventing common web vulnerabilities

Cookies

cookies

Authorization

Authorization takes over after authentication. It's about what an authenticated user is allowed to do. It prevents unauthorized actions within an application.

Role-Based Access Control (RBAC)

Roles are defined with specific permission sets. Users are assigned one or more roles. This streamlines access control greatly.

4. Secure Authentication & Data Validation

Secure Authentication

  • JWT Security
    Use short-lived tokens, sign with strong secret keys, store securely (e.g. HttpOnly cookie).
  • Session Management
    Use secure, HttpOnly cookies with SameSite=strict. Set session timeout.
  • Password Hashing
    Store only hashed+salted passwords using bcrypt, Argon2 or scrypt.
  • Multi-Factor Authentication
    Add extra security layers beyond passwords.
  • Avoid Pitfalls
    Enforce strong passwords, rate-limit login attempts, and avoid sending secrets in URL.
  • Account Lockout
    Lock account after X failed attempts to defend against brute-force attacks.

Data Validation

  • XSS Prevention
    Sanitize user input using trusted libraries. Avoid eval(), Function(), setTimeout() with code strings.
  • SQL Injection Mitigation
    Use parameterized queries and ORM safeguards.
  • Input Validation
    Validate type, format, and range on both client and server.
  • Output Encoding
    Encode HTML, JavaScript, URL, etc., to prevent code execution in output.
  • File Upload Validation
    Check MIME type, size, filename, and use antivirus scan for uploaded files.

Examples

const userColor = 'red; background-image: url("https://hack.com/steal-cookie")';
document.body.style = `color: ${userColor}`;
const userColor = 'red; background-image: url("hack.com")';
const safeColor = CSS.escape(userColor);
document.body.style.color = safeColor;

const userQuery = 'javascript:alert("XSS")';
const safeUrl = `https://example.com?redirect=${encodeURIComponent(userQuery)}`;
// https://example.com?redirect=javascript%3Aalert(%22XSS%22)

5. Browser extensions

Manifest file format

{
  "manifest_version": 3,
  "name": "Run script automatically",
  "description": "Runs a script on www.example.com automatically when user installs the extension",
  "version": "1.0",
  "icons": {
    "16": "images/icon-16.png",
  },
  "content_scripts": [
    {
      "js": [
        "content-script.js"
      ],
      "matches": [
        "http://*.example.com//"
      ]
    }
  ],
  "background": {
    "service_worker": "service-worker.js"
  },
  "permissions": ["activeTab", "storage"]
}

Web Scrapping

Web Scraping is the process of automatically collecting data from websites using software tools.

robots.txt

robots.txt is a text file in the root of a website (https://example.com/robots.txt) that tells search bots (e.g. Googlebot) what can and cannot be indexed.

User-agent: *
Disallow: /api/
Disallow: /admin/
Allow: /public/
Sitemap: https://example.com/sitemap.xml
  • all bots are not allowed to scan /api/ and /admin/
  • allowed /public/
  • sitemap is explicitly specified

6. Cheat Sheets:

7. Conclusion / Q&A