[3/6] Level 3: Context Matters
Mission Description
This level shows how context matters in XSS. The vulnerability exists in how user input is placed into HTML attributes. You'll need to break out of the single-quoted attribute context to execute JavaScript.
Mission Objective: Use the address bar to craft a value that will execute JavaScript when the image loads.
Image Gallery
Hints
Click on any image or enter a value in the address bar. Notice how it
updates the URL hash and loads the image. The hash value is being
concatenated into the img src attribute with single quotes.
Look at the source code. The img src uses single quotes. You need to break
out with a single quote (
'), add an event handler, then start
a dummy attribute to consume the trailing .jpg'
Try this in the address bar or modify the URL hash:
' /> <script>alert(1);</script> <img src='
function chooseTab(num) {
// VULNERABLE: Direct string concatenation without escaping
var html = "Image " + parseInt(num) + "<br>";
html += "<img src='https://picsum.photos/400/300?random=" + num + ".jpg' />";
const container = document.getElementById('selected-image');
container.innerHTML = html;
// Execute any script tags (simulates server-side rendering)
const scripts = container.querySelectorAll('script');
scripts.forEach(script => eval(script.textContent));
}
window.onload = function() {
// unescape() decodes URL-encoded characters from the hash
chooseTab(unescape(window.location.hash.substr(1)) || "1");
}