Web Security 13 🛡️ SSRF & Secure File Uploads — Blocking internal network probing, validating magic bytes, and isolating SVG/user uploads
Server-Side Request Forgery (SSRF) and insecure file uploads represent two of the most significant entry points for attackers seeking to pivot from the public internet into your internal infrastructure. SSRF exploits the trust your server places in its own ability to fetch resources, turning the application into a proxy that can probe internal networks, metadata services, and databases. Insecure file uploads, on the other hand, treat the server’s filesystem as an untrusted staging area where attackers can plant malicious payloads, bypass authentication, or execute cross-site scripting (XSS) attacks by forcing the browser to execute uploaded content.
The intersection of these two vulnerabilities is the “trusted” nature of the server. When an application fetches a URL provided by a user, or stores a file provided by a user, it often does so with the full privileges of the application process. This chapter dissects how to harden these interfaces. We will move beyond basic input filtering to architectural patterns such as request allowlisting, binary content validation via magic bytes, and the strict isolation of user-uploaded assets via isolated domains and Content Security Policies.
Key point: The defense against SSRF is not just input filtering but architectural separation: ensure requests to external resources are isolated from internal services, and treat all user-uploaded files as completely untrusted blobs that must be validated by content analysis (magic bytes) and served in an isolated context where script execution is impossible.
Why exists
The internal network bridge.
Cloud infrastructure relies on internal metadata services (e.g., 169.254.169.254 in AWS/GCP) to provide credentials and configuration. If your server is vulnerable to SSRF, an attacker can query these services, effectively “stealing” the IAM role of your server.
The trust in server-side requests.
Many applications include features like “link previews,” “image resizing,” or “webhooks.” These features inherently require the server to make requests. Attackers abuse this functionality because they know the server’s request will originate from a trusted IP address, bypassing firewalls that protect internal resources.
The file-execution paradigm.
Uploads are risky because file extensions (like .jpg or .png) are metadata, not security features. An attacker can rename a malicious script to .jpg. If your server blindly serves this file, or if the browser interprets it as HTML, the security boundary of your application is breached.
The SVG/XML vulnerability.
SVGs are XML files. Unlike standard images, they are parsed by the browser as active documents, meaning they can contain <script> tags, event handlers, and references to external entities. Serving SVGs directly from your main domain allows attackers to perform XSS attacks against your users.
The parser confusion.
File parsers (image processors, PDF libraries) are complex, memory-unsafe C/C++ libraries. Uploading a malformed file is a classic technique to trigger buffer overflows or memory corruption vulnerabilities within these parsers, leading to potential Remote Code Execution (RCE).
a. SSRF: Understanding the Request Forgery
SSRF occurs when an attacker supplies a URL to your application, and your server performs a request to that URL without sufficient validation. The attacker doesn’t need to be inside your network; they use your server as a bridge. Protection requires more than just checking for “localhost”; it requires an allowlist-based architecture.
// VULNERABLE: Allows access to any URL
async function fetchPreview(userUrl: string) {
const response = await fetch(userUrl);
return response.text();
}
To secure this, you must resolve the domain to an IP address, then check that the IP is not a private, loopback, or reserved address (e.g., 10.0.0.0/8, 127.0.0.1). Furthermore, implement a strict allowlist of permitted hosts or domains, ensuring your server only talks to known-good external endpoints.
b. Secure File Uploads: Content-Type and Magic Bytes
Never trust the Content-Type header sent by the client. It is easily spoofed. To verify a file, you must inspect the “magic bytes”—the specific hexadecimal signature at the beginning of the file (e.g., FF D8 FF for JPEG). Relying on file extensions or headers leads to RCE and XSS vulnerabilities.
import { fileTypeFromBuffer } from 'file-type';
async function uploadFile(buffer: Buffer) {
const type = await fileTypeFromBuffer(buffer);
// Strict allowlist
if (!type || !['image/jpeg', 'image/png'].includes(type.mime)) {
throw new Error('Invalid file type');
}
}
By enforcing a whitelist of allowed MIME types derived from binary inspection, you ensure that an uploaded file is actually what it claims to be, regardless of the filename extension provided by the user.
c. File Isolation and SVG Handling
Serving user uploads from your main application domain is a critical mistake. If an attacker uploads an HTML file or a malicious SVG, they can perform XSS or steal cookies because the file runs in the same origin as your app. The solution is to serve uploads from a separate, isolated domain (e.g., usercontent.com) and apply a restrictive CSP.
<!-- Served from a different domain, with a strict CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'none';">
For SVGs, you should either strip the <script> and <object> tags server-side or, preferably, serve them with a Content-Disposition: attachment header to force the browser to download the file rather than rendering it as an active document.
Complete Example Session
// ============================================
// PART 1: SSRF PROTECTION (ALLOWLIST)
// ============================================
const ALLOWED_DOMAINS = ['api.example.com', 'cdn.images.com'];
async function safeFetch(url: string) {
const parsed = new URL(url);
if (!ALLOWED_DOMAINS.includes(parsed.hostname)) {
throw new Error('Forbidden domain');
}
// Proceed with request
return await fetch(url);
}
// ============================================
// PART 2: MAGIC BYTES VALIDATION
// ============================================
import { fileTypeFromBuffer } from 'file-type';
async function validateUpload(fileBuffer: Buffer) {
const result = await fileTypeFromBuffer(fileBuffer);
// Verify it is an image
if (!result || !result.mime.startsWith('image/')) {
throw new Error('Not an image');
}
}
// ============================================
// PART 3: ISOLATED SERVING (CSP)
// ============================================
// In your storage bucket / CDN config, enforce headers:
// Content-Security-Policy: default-src 'none'; style-src 'none'; script-src 'none';
// X-Content-Type-Options: nosniff
// Content-Disposition: inline (or attachment to be safe)
This sequence covers the three layers of defense: SSRF prevention via host allowlisting, file validation via binary content analysis, and the deployment of restrictive security headers for asset serving.
Quick Reference
SSRF Defense Strategies
| Strategy | Protection Level |
|---|---|
| Allowlist | High (Best) |
| IP DenyList | Low (Bypassable via DNS) |
| Authentication | Medium (Does not block probing) |
File Validation Types
| File Format | Magic Bytes (Hex) |
|---|---|
| JPEG | FF D8 FF |
| PNG | 89 50 4E 47 |
25 50 44 46 | |
| ZIP | 50 4B 03 04 |
SVG/Asset Isolation Patterns
| Pattern | Implementation |
|---|---|
| Dedicated Domain | Uploads served from user-assets.com |
| CSP Headers | Disable script execution on asset origin |
| Sanitization | Strip XML/Script tags server-side |
Best Practices
✅ Do This:
// Whitelist hosts for external requests
if (allowedHosts.has(hostname)) { fetch(url); } // ✅
// Inspect binary content (Magic Bytes)
const type = await fileTypeFromBuffer(buffer); // ✅
// Serve files from an isolated domain
// (Use a separate bucket/subdomain) // ✅
// Set 'nosniff' headers
res.setHeader('X-Content-Type-Options', 'nosniff'); // ✅
❌ Don’t Do This:
// Block local IPs (can be bypassed with DNS rebind)
if (ip === '127.0.0.1') return; // ❌
// Rely on file extensions
if (filename.endsWith('.jpg')) { process(); } // ❌
// Serve uploads from your main domain
// (Opens door to XSS) // ❌
// Use user-provided filenames
save(userInputFilename); // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| DNS Rebinding | Attacker uses a custom domain | Use IP allowlisting + Host check |
| Mime-Sniffing | Browser “guesses” the file type | Set X-Content-Type-Options: nosniff |
| Path Traversal | Using filename directly | Rename files to UUIDs/Hashes |
| Incomplete CSP | Forgetting script block | Use default-src 'none' |
Real-World Examples
1. Validating URL Host
const url = new URL(input);
if (url.hostname !== 'api.trusted.com') return;
2. Magic Byte Check
const type = await fileTypeFromBuffer(buffer);
if (type?.mime !== 'image/png') throw new Error();
3. Generating Secure Filenames
const safeName = crypto.randomUUID() + '.png';
4. Setting CSP Header
res.setHeader('Content-Security-Policy', "default-src 'none'");
5. Stripping SVG Scripts
const cleanSvg = sanitizeSvg(dirtySvg);
6. Disabling Mime Sniffing
res.setHeader('X-Content-Type-Options', 'nosniff');
7. Restricting File Size
if (file.size > MAX_SIZE) throw new Error();
8. Forcing Download
res.setHeader('Content-Disposition', 'attachment');
9. Blocking Metadata Fetch
// Block 169.254.169.254
10. Sanitizing Filename
const base = path.basename(userProvidedName);
Visual
SSRF Attack Vector
┌────────────────────────────────────────────────────────┐
│ ATTACKER ──► [SERVER (Proxy)] ──► [INTERNAL SERVICE] │
│ │ │
│ SERVER acts as the │
│ authenticated caller │
└────────────────────────────────────────────────────────┘
Secure File Upload Pipeline
┌────────────────────────────────────────────────────────┐
│ UPLOAD ──► VALIDATE (Magic Bytes) ──► RENAME (UUID) │
│ │ │
│ STORE (S3/Disk) ◄────────────────────────┘ │
│ │ │
│ SERVE (Isolated Domain + CSP) ──► CLIENT │
└────────────────────────────────────────────────────────┘
SVG XSS Vulnerability
┌────────────────────────────────────────────────────────┐
│ SVG FILE │
│ <svg> │
│ <script>alert(document.cookie)</script> │
│ </svg> │
│ │ │
│ BROWSER: Executes script in Main Domain Context │
└────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| SSRF Mitigation | Host Allowlisting |
| File Validation | Magic Bytes (Binary) |
| Serving | Isolated Domain |
| Headers | CSP + nosniff |
Key takeaways:
- Allowlist, do not block. SSRF cannot be stopped by blocking IPs (due to DNS rebinding). You must only allow requests to explicitly trusted domains.
- Ignore the extension. File extensions are untrusted metadata. Always inspect the file’s binary signature (magic bytes) to determine its true type.
- Isolate your assets. Never serve user-uploaded content from the same domain as your application. Use a dedicated domain or bucket, and apply a strict CSP that forbids script execution.
- Defense in depth. Use
X-Content-Type-Options: nosniffto prevent the browser from guessing that a file is HTML when it isn’t. - Rename everything. Never use the filename provided by the user. Map it to a random UUID or hash to prevent path traversal and collision attacks.
Remember: Web security is not about cleaning input; it is about architectural isolation. Treat all external URLs as malicious proxies and all uploaded files as executable payloads. By isolating these components from your main application and enforcing strict validation at the binary level, you minimize the blast radius of any individual component compromise.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!