API Authentication

What Is Error Disclosure?

  • Error Disclosure = Exposing too much information in error messages (especially via APIs).

  • Even if not shown in the UI, errors returned in responses (e.g., in Postman, console, or scripts) can help attackers understand your system.


⚠️ Why It’s Dangerous

  • Exposes internal details like:

    • Frameworks (e.g., Spring = Java)

    • Database technologies

    • Stack traces

    • Library versions (potential CVEs!)

  • Attackers use this info to:

    • Learn about your tech stack

    • Find known vulnerabilities

    • Craft better attacks


🛠️ Examples of Bad vs. Good Error Handling

❌ Bad Error

  • Detailed message: "SQL syntax error at line 4 in com.spring..."

  • Tells the attacker you use Spring Framework and possibly Java → gives them a starting point to attack

1cf218baf31123559c8d452c3f01c0b0.png

✅ Good Error

  • Generic message: "An error occurred. Please try again."

  • Doesn’t confirm if the email exists or if injection succeeded

  • Stops information leaks — attacker gains nothing useful

11d17e268494ba77b4f11ecb7dcacde1.png

🧪 Security-Aware Error Handling Tips

✅ Do:

  • Fail early (stop malicious attempts quickly)

  • Use generic error messages for users

  • Send detailed error info only to developers/support, e.g., through internal logs

  • Use error IDs to trace errors without revealing details to users

  • Use try/catch blocks to:

    • Stop execution on unexpected errors

    • Control what gets logged vs. returned

❌ Don’t:

  • Return raw stack traces or system errors to users

  • Let unhandled exceptions propagate to the frontend or client

  • Leak info about your backend tech or logic

  • Show different error responses that allow user enumeration


👨‍💻 Code Patterns to Watch

  • try/except in Python or try/catch in Node.js

    • ❗ Don't just print(error) or return error

    • ✅ Log errors securely on the backend instead

  • Uncaught errors might be automatically returned by some frameworks (e.g., Express, Django)


🧠 Mindset Shift: Think Like an Attacker

  • Ask: “How could this error help someone attack me?”

  • Don't assume people only use the UI — attackers hit the API directly

  • Be consistent — protect both frontend and backend


🎨 Fun Example: GitHub’s 404

  • GitHub gives a 404 even if the page exists but you're not authorized.

    • Helps prevent enumeration of private resources.

    • Combines security + fun UX (e.g., Octocat Star Wars error page)


📌 Summary Checklist

Do ✅
Don’t ❌

Error early

Return detailed tech info

Use generic public errors

Let stack traces reach the client

Log details privately

Help attackers learn your system

Use error IDs to link logs

Show user/email existence differences

Stop on unknown exceptions

Assume everyone uses the UI


🧠 What Are Server Information Leaks?

  • When a server reveals information (like server type, version, tech stack) in HTTP response headers

  • This info can be used by malicious users to:

    • Understand your stack

    • Find known vulnerabilities (CVEs)

    • Exploit your system

🔐 Security risk: These details provide a roadmap for attackers.


📬 Where Does the Leak Happen?

  • Response headers in network tools like Chrome DevTools, Postman, Node.js scripts, etc.

  • Common headers that leak info:

    • Server: Uvicorn / nginx

    • X-Powered-By: Express

    • Version: 1.2.3 or similar

🧪 Even logged-in APIs can leak info—attackers can bypass the UI and go directly to APIs.


🛠️ Real-World Examples

  • Uvicorn server

    • Leaks it’s a Python-based web server

    • Publicly available source code and CVEs

  • nginx

    • Very common (over 160+ known CVEs)

    • Also used as cache or reverse proxy

The more unique or less-known the server, the more tempting it is for attackers.


🧭 Attack Process (Step-by-Step)

  1. Open Chrome DevTools > Network tab > Headers

  2. Identify server header (e.g., Server: Uvicorn)

  3. Look up the server online → understand its ecosystem

  4. Search for known vulnerabilities (e.g., Uvicorn CVEs)

  5. Use that info to craft attacks or find misconfigurations


Checklist: How to Detect and Prevent Server Info Leaks

🔍 Detection Tools

  • Chrome DevTools

  • Postman

  • Node.js scripts

  • Curl with -I flag

  • Any tool that shows response headers

🔎 Look For These Headers

Header Name
Why It’s Risky

Server

Reveals server software (e.g., Apache)

X-Powered-By

Exposes framework (e.g., Express)

Version

Gives attacker exact version


🧯 How to Remove Server Info (By Server Type)

Server Type
Method to Remove Header

Uvicorn

Use --server-header flag to disable server info

Nginx

In nginx.conf: server_tokens off;

Express/Node.js

Use helmet package or app.disable('x-powered-by')

IIS

Remove via configuration settings

Others

Search: "[YourServer] remove server header"

💡 Most modern servers offer built-in options to hide or remove identifying headers.


🧠 Key Takeaways

  • Leaked headers = attack surface

  • Info like Server: Uvicorn or X-Powered-By: Express is useless to customers but valuable to attackers

  • Attackers can:

    • Look up open-source code

    • Search for CVEs

    • Tailor exploits to your stack


📌 Summary Table

Do ✅
Don’t ❌

Analyze headers for leaks

Leave default server/version headers exposed

Remove unnecessary identifying headers

Assume attackers won’t look at HTTP headers

Use caching-aware tools or logged-in APIs

Only check public pages for info leaks

Use standard removal methods per server

Think "obscure servers" are safe by default


  • Cookies store key-value data on a user's device.

  • They persist across sessions and are used for things like authentication, session tracking, or personalization.

  • Risk: Data in cookies can be stolen, modified, or exploited if not properly protected.


  1. Cookie Forging

    • Malicious user alters cookie data to impersonate a user or escalate privileges.

  2. Cookie Data Harvesting via JavaScript

    • If cookies are accessible to JavaScript and a Cross-Site Scripting (XSS) vulnerability exists, cookies can be harvested.

  3. Cookie Data Harvesting in Transit

    • If cookies are sent over non-encrypted connections (HTTP), they can be intercepted by attackers (e.g., man-in-the-middle).


Attribute
Purpose

Secure

Ensures cookie is only sent over HTTPS (encrypted connections)

HttpOnly

Prevents JavaScript from reading the cookie

Path

Restricts cookie to specific URLs or subdirectories

SameSite

Prevents cross-site request forgery (CSRF) by limiting cookie scope

Expires/Max-Age

Sets timeout or lifespan of the cookie


🧪 How Attackers Exploit Cookies

  • Inspect using browser dev tools (e.g., Chrome DevTools → Network tab → Headers)

  • Parse cookie strings using delimiters (; for each pair, = for key-value)

  • Look for:

    • Session IDs

    • User roles

    • Booleans or numeric values (easy to guess/change)

    • Base64-encoded or URL-encoded values

🧠 Base64-encoded data can be decoded and modified, then re-encoded and reused.


  1. Extract cookie

  2. Decode or inspect data

  3. Modify values (e.g., session ID, role)

  4. Re-encode if necessary (e.g., Base64)

  5. Inject cookie back into request

  6. Observe if access is gained or behavior changes


🔎 Treat Cookies as Untrusted Input

  • Never trust data from cookies—validate and sanitize just like any user input.

🔐 Always Set These Flags:

Flag
Why It’s Important

HttpOnly

Prevents access via JS → mitigates XSS risks

Secure

Prevents theft over unsecured HTTP

Expires

Ensures cookie auto-deletes after a defined period

💡 Only allow cookies to store what’s necessary (e.g., session ID), not sensitive business logic.


🔍 Offensive Mindset: Analyze Your Own Cookies

  • Open your site in a browser and inspect cookies

  • Ask:

    • Can I decode or understand anything easily?

    • Is sensitive logic stored in plain or encoded form?

    • Are cookie values guessable or modifiable?

🚫 Don’t store table names, roles, or sensitive IDs in cookies.


📌 Quick Summary Checklist

Do ✅
Don’t ❌

Set HttpOnly, Secure, and Expires

Let JavaScript access cookies unless necessary

Treat cookies as untrusted input

Store sensitive data or business logic in them

Decode and test cookie values offensively

Assume cookies can’t be modified or stolen

Analyze all cookies through headers

Forget that cookies are visible & modifiable


🧠 What Is Path Traversal?

  • A path traversal vulnerability allows attackers to access files or directories outside of the intended web root.

  • Can happen through:

    • Dynamic file includes (e.g., user input directly used in file paths)

    • Misconfigured servers

    • Insecure specs (e.g., overly generic input types)


🚨 Why It’s Dangerous

  • Allows attackers to retrieve sensitive files like:

    • /etc/passwd (Linux)

    • Environment configs

    • Log files

    • Source code files

  • Can expose secrets, credentials, internal logic


⚠️ Common Causes

Category
Examples

❌ Insecure coding

Using user input directly in file paths

❌ Loose input validation

Accepting raw strings with no constraints

❌ Server misconfig

Directory listings enabled, includes outside web root allowed

❌ Poor API specs

Parameters defined too loosely (e.g., string with no restrictions)


🧪 Exploitation Examples

Example:

plaintext

CopyEdit

GET /view?file=../../../../etc/passwd

Techniques Used:

  • ../ or ..\\ to move up directories

  • Multiple encoding tricks:

    • URL encoded: %2e%2e%2f

    • Unicode/ASCII variants

    • Double encoding to bypass filters

Attackers use fuzzing tools to generate thousands of such payloads.


🧰 Developer Mistake Example

php

CopyEdit

// Vulnerable codeinclude($_COOKIE['template']);

  • If template=../../etc/passwd is in the cookie, it can be exploited.

  • Assumes input is safe because it's stored in a cookie → Big mistake!


🔐 Defense Strategy & Solutions

✅ 1. Sanitize Input

  • Define exact values allowed (whitelist IDs, paths, formats)

  • Avoid accepting raw file paths or strings from users

✅ 2. Fix API Specs

  • Avoid using "type": "string" for critical parameters

  • Add:

    • Max lengths

    • Patterns/Enums

    • Use of strict schemas

✅ 3. Harden Server Config

  • Disable directory listings

  • Disallow includes above the web root

  • Move sensitive files outside the web root or even onto separate drives

✅ 4. Improve File Access Logic

  • Never access file paths directly from user input

  • Instead:

    • Map user input → validated ID

    • Use ID to lookup file path from server

✅ 5. Error Safely

  • If file access fails or request is suspicious:

    • ❌ Don’t proceed

    • ✅ Log the error securely and stop execution


🧪 Testing Techniques

  • Use tools to perform automated path traversal fuzzing

  • Perform static code analysis to find:

    • file_get_contents(), include(), fs.readFile(), etc. with variable input


📌 Summary Table

What To Do ✅
What To Avoid ❌

Validate and sanitize all user input

Using raw strings for file paths

Harden server configs (disable listings, etc)

Leaving web root unrestricted

Use safe logic to reference files (via ID)

Including user-controlled paths

Add strict API specs (e.g., maxLength)

Using loose "string" types everywhere

Log and stop on unexpected input

Proceeding blindly with unknown file access

Keep sensitive files off web root

Assuming cookies or headers are safe by default


🛡️ Final Thoughts

  • Path Traversal is still common, even in recent CVEs (e.g., AutoGPT)

  • It’s easy to introduce accidentally and easy to exploit if unchecked

  • Combine:

    • ✅ Secure coding

    • ✅ Strong input validation

    • ✅ Tight specs

    • ✅ Server-side controls

    • ✅ Logging and safe failure

🔎 Prevention starts with the mindset of treating all user input as dangerous, including paths, cookies, and headers.


🚦 What Is Rate Limiting?

  • Rate limiting is a technique used to control how many requests a client can make to a server within a specific time frame.

  • It protects servers from:

    • Abuse

    • DDoS attacks

    • Brute-force login attempts

    • Resource exhaustion


🧠 Why Is Rate Limiting Important?

🔐 Security

  • Prevents brute-force attacks on login endpoints, API keys, and tokens.

  • Helps identify malicious actors by limiting abusive behavior.

⚙️ Stability

  • Ensures fair usage across users.

  • Prevents API downtime due to overuse or abuse.

💰 Cost Control

  • Protects from unexpected spikes in usage that could drive up cloud/server costs.


🧮 How Rate Limiting Works

Common Methods:

Method
Description

Fixed Window

Limits requests per fixed time block (e.g., 100 requests per minute)

Sliding Log

Records timestamp for each request; checks how many were made recently

Token Bucket

Tokens added at a set rate; each request removes a token

Leaky Bucket

Requests are processed at a fixed rate, queues overflow if too many

🔄 Many APIs use token or leaky bucket algorithms for flexibility and accuracy.


🚫 What Happens When a Limit Is Hit?

  • HTTP Status Code 429: Too Many Requests

  • Response may include:

    • Retry-After header (when to try again)

    • Rate limit info (X-RateLimit-Limit, X-RateLimit-Remaining, etc.)


🛠️ Where to Apply Rate Limits

Layer
Why It Matters

API Gateway

Central point for limiting all requests

Endpoint Level

Apply tighter limits on sensitive endpoints

User/IP Level

Prevent a single user/IP from exhausting resources

Per Token/API Key

Rate limit based on credential type or tier


⚠️ Common Pitfalls to Avoid

  • Over-restricting can hurt legitimate users

  • Ignoring distributed abuse (e.g., attackers using multiple IPs)

  • Not providing clear rate limit headers for devs

  • Not resetting limits consistently (especially in fixed windows)

  • No fallback or error handling when rate limits are triggered


✅ Best Practices for Rate Limiting

Practice
Benefit

Use 429 Too Many Requests consistently

Standard HTTP response for rate limits

Provide Retry-After header

Helps clients back off and retry properly

Different limits for different users

Premium vs. free, anonymous vs. authenticated

Monitor and log rate limit hits

Detect abuse or misconfigurations

Use API gateway tools or middleware

Automates and standardizes enforcement


🛡️ Rate Limiting for Security Use Cases

Use Case
What to Limit

Login attempts

Limit per username/IP to prevent brute-force

Token generation

Prevent API key abuse or token spamming

Sensitive endpoints

Limit access to data or admin operations

Search endpoints

Avoid scraping and enumeration attempts

Last updated