Rollup merge of #120250 - chadnorvell:rustdoc-xss, r=notriddle

rustdoc: Prevent JS injection from localStorage

It turns out that you can execute arbitrary JavaScript on the rustdocs settings page. Here's how:

1. Open `settings.html` on a rustdocs site.
2. Set "preferred light theme" to "dark" to initialize the corresponding localStorage value.
3. Plant a payload by executing this in your browser's dev console: ``Object.keys(localStorage).forEach(key=>localStorage.setItem(key,`javascript:alert()//*/javascript:javascript:"/*'/*\`/*--></noscript></title></textarea></style></template></noembed></script><html " onmouseover=/*&lt;svg/*/onload=alert()onload=alert()//><svg onload=alert()><svg onload=alert()>*/</style><script>alert()</script><style>`));``
4. Refresh the page -- you should see an alert.

This could be particularly dangerous if rustdocs are deployed on a domain hosting some other application. Malicious code could circumvent `same-origin` policies and do mischievous things with user data.

This change ensures that only defined themes can actually be selected (arbitrary strings from localStorage will not be written to the document), and for good measure sanitizes the theme name.
This commit is contained in:
Guillaume Gomez 2024-01-30 11:19:13 +01:00 committed by GitHub
commit b60707e174
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -101,6 +101,14 @@ const getVar = (function getVar(name) {
});
function switchTheme(newThemeName, saveTheme) {
const themeNames = getVar("themes").split(",").filter(t => t);
themeNames.push(...builtinThemes);
// Ensure that the new theme name is among the defined themes
if (themeNames.indexOf(newThemeName) === -1) {
return;
}
// If this new value comes from a system setting or from the previously
// saved theme, no need to save it.
if (saveTheme) {
@ -115,7 +123,7 @@ function switchTheme(newThemeName, saveTheme) {
window.currentTheme = null;
}
} else {
const newHref = getVar("root-path") + newThemeName +
const newHref = getVar("root-path") + encodeURIComponent(newThemeName) +
getVar("resource-suffix") + ".css";
if (!window.currentTheme) {
// If we're in the middle of loading, document.write blocks