> For the complete documentation index, see [llms.txt](https://aashraymt.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://aashraymt.gitbook.io/docs/apisec/api-security/api-authentication.md).

# API Authentication

### &#x20;**What Is Error Disclosure?** <a href="#brain-what-is-error-disclosure" id="brain-what-is-error-disclosure"></a>

* **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** <a href="#warning-why-its-dangerous" id="warning-why-its-dangerous"></a>

* 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** <a href="#hammer_and_wrench-examples-of-bad-vs-good-error-handling" id="hammer_and_wrench-examples-of-bad-vs-good-error-handling"></a>

#### Bad Error <a href="#x-bad-error" id="x-bad-error"></a>

* 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**

#### Good Error <a href="#white_check_mark-good-error" id="white_check_mark-good-error"></a>

* 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](file:///C:/Users/art_t/.config/joplin-desktop/resources/731dc1081aea424abdcee6c94f18b6f2.png?t=1744037555104)

***

### **Security-Aware Error Handling Tips** <a href="#test_tube-security-aware-error-handling-tips" id="test_tube-security-aware-error-handling-tips"></a>

#### Do: <a href="#white_check_mark-do" id="white_check_mark-do"></a>

* **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: <a href="#x-dont" id="x-dont"></a>

* 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** <a href="#male-technologist-code-patterns-to-watch" id="male-technologist-code-patterns-to-watch"></a>

* `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** <a href="#brain-mindset-shift-think-like-an-attacker" id="brain-mindset-shift-think-like-an-attacker"></a>

* 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 <a href="#art-fun-example-githubs-404" id="art-fun-example-githubs-404"></a>

* 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 <a href="#pushpin-summary-checklist" id="pushpin-summary-checklist"></a>

| 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?** <a href="#brain-what-are-server-information-leaks" id="brain-what-are-server-information-leaks"></a>

* 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?** <a href="#mailbox_with_mail-where-does-the-leak-happen" id="mailbox_with_mail-where-does-the-leak-happen"></a>

* **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** <a href="#hammer_and_wrench-real-world-examples" id="hammer_and_wrench-real-world-examples"></a>

* **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)** <a href="#compass-attack-process-step-by-step" id="compass-attack-process-step-by-step"></a>

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** <a href="#white_check_mark-checklist-how-to-detect-and-prevent-server-info-leaks" id="white_check_mark-checklist-how-to-detect-and-prevent-server-info-leaks"></a>

#### **Detection Tools** <a href="#mag-detection-tools" id="mag-detection-tools"></a>

* Chrome DevTools
* Postman
* Node.js scripts
* Curl with `-I` flag
* Any tool that shows response headers

#### **Look For These Headers** <a href="#mag_right-look-for-these-headers" id="mag_right-look-for-these-headers"></a>

| 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)** <a href="#fire_extinguisher-how-to-remove-server-info-by-server-type" id="fire_extinguisher-how-to-remove-server-info-by-server-type"></a>

| 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** <a href="#brain-key-takeaways" id="brain-key-takeaways"></a>

* 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 <a href="#pushpin-summary-table" id="pushpin-summary-table"></a>

| 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  |

***

### **What Are Cookies in Security Context?** <a href="#cookie-what-are-cookies-in-security-context" id="cookie-what-are-cookies-in-security-context"></a>

* 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.

***

### **Common Cookie Security Risks** <a href="#warning-common-cookie-security-risks" id="warning-common-cookie-security-risks"></a>

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).

***

### **Key Cookie Security Attributes** <a href="#closed_lock_with_key-key-cookie-security-attributes" id="closed_lock_with_key-key-cookie-security-attributes"></a>

| 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** <a href="#test_tube-how-attackers-exploit-cookies" id="test_tube-how-attackers-exploit-cookies"></a>

* **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.

***

### **Cookie Attack Example Workflow** <a href="#hammer_and_wrench-cookie-attack-example-workflow" id="hammer_and_wrench-cookie-attack-example-workflow"></a>

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

***

### **Best Practices for Cookie Security** <a href="#white_check_mark-best-practices-for-cookie-security" id="white_check_mark-best-practices-for-cookie-security"></a>

#### 🔎 Treat Cookies as **Untrusted Input** <a href="#mag_right-treat-cookies-as-untrusted-input" id="mag_right-treat-cookies-as-untrusted-input"></a>

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

#### Always Set These Flags: <a href="#closed_lock_with_key-always-set-these-flags" id="closed_lock_with_key-always-set-these-flags"></a>

| 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 <a href="#mag-offensive-mindset-analyze-your-own-cookies" id="mag-offensive-mindset-analyze-your-own-cookies"></a>

* 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 <a href="#pushpin-quick-summary-checklist" id="pushpin-quick-summary-checklist"></a>

| 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   |

&#x20;

***

### What Is Path Traversal? <a href="#brain-what-is-path-traversal" id="brain-what-is-path-traversal"></a>

* 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 <a href="#rotating_light-why-its-dangerous" id="rotating_light-why-its-dangerous"></a>

* 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 <a href="#warning-common-causes" id="warning-common-causes"></a>

| 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 <a href="#test_tube-exploitation-examples" id="test_tube-exploitation-examples"></a>

#### Example: <a href="#example" id="example"></a>

plaintext

CopyEdit

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

#### Techniques Used: <a href="#techniques-used" id="techniques-used"></a>

* `../` 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 <a href="#toolbox-developer-mistake-example" id="toolbox-developer-mistake-example"></a>

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 <a href="#closed_lock_with_key-defense-strategy-solutions" id="closed_lock_with_key-defense-strategy-solutions"></a>

#### 1. **Sanitize Input** <a href="#white_check_mark-1-sanitize-input" id="white_check_mark-1-sanitize-input"></a>

* Define **exact values** allowed (whitelist IDs, paths, formats)
* Avoid accepting raw file paths or strings from users

#### 2. **Fix API Specs** <a href="#white_check_mark-2-fix-api-specs" id="white_check_mark-2-fix-api-specs"></a>

* Avoid using `"type": "string"` for critical parameters
* Add:
  * **Max lengths**
  * **Patterns/Enums**
  * Use of **strict schemas**

#### 3. **Harden Server Config** <a href="#white_check_mark-3-harden-server-config" id="white_check_mark-3-harden-server-config"></a>

* **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** <a href="#white_check_mark-4-improve-file-access-logic" id="white_check_mark-4-improve-file-access-logic"></a>

* 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** <a href="#white_check_mark-5-error-safely" id="white_check_mark-5-error-safely"></a>

* If file access fails or request is suspicious:
  * ❌ Don’t proceed
  * ✅ Log the error securely and stop execution

***

### Testing Techniques <a href="#test_tube-testing-techniques" id="test_tube-testing-techniques"></a>

* 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 <a href="#pushpin-summary-table-2" id="pushpin-summary-table-2"></a>

| 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 <a href="#shield-final-thoughts" id="shield-final-thoughts"></a>

* **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? <a href="#vertical_traffic_light-what-is-rate-limiting" id="vertical_traffic_light-what-is-rate-limiting"></a>

* **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? <a href="#brain-why-is-rate-limiting-important" id="brain-why-is-rate-limiting-important"></a>

#### **Security** <a href="#closed_lock_with_key-security" id="closed_lock_with_key-security"></a>

* Prevents brute-force attacks on **login endpoints**, **API keys**, and **tokens**.
* Helps identify **malicious actors** by limiting abusive behavior.

#### **Stability** <a href="#gear-stability" id="gear-stability"></a>

* Ensures **fair usage** across users.
* Prevents API downtime due to **overuse** or **abuse**.

#### **Cost Control** <a href="#moneybag-cost-control" id="moneybag-cost-control"></a>

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

***

### How Rate Limiting Works <a href="#abacus-how-rate-limiting-works" id="abacus-how-rate-limiting-works"></a>

#### Common Methods: <a href="#common-methods" id="common-methods"></a>

| 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? <a href="#no_entry_sign-what-happens-when-a-limit-is-hit" id="no_entry_sign-what-happens-when-a-limit-is-hit"></a>

* **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 <a href="#hammer_and_wrench-where-to-apply-rate-limits" id="hammer_and_wrench-where-to-apply-rate-limits"></a>

| 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 <a href="#warning-common-pitfalls-to-avoid" id="warning-common-pitfalls-to-avoid"></a>

* **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 <a href="#white_check_mark-best-practices-for-rate-limiting" id="white_check_mark-best-practices-for-rate-limiting"></a>

| 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 <a href="#shield-rate-limiting-for-security-use-cases" id="shield-rate-limiting-for-security-use-cases"></a>

| 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      |
