Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Escape attribute values in attribution markup builder (#5607)

Konstantin Obenlandbda5a56845cc
diff --git a/frontend/shared/utils/attribution-html.ts b/frontend/shared/utils/attribution-html.ts
index 5a7feb6bb..b1e825ad1 100644
--- a/frontend/shared/utils/attribution-html.ts
+++ b/frontend/shared/utils/attribution-html.ts
@@ -63,7 +63,7 @@ const h = (
]
const map = Object.entries(attrs)
- .map(([key, value]) => `${key}="${value}"`)
+ .map(([key, value]) => `${key}="${escapeHtml(value)}"`)
.join(" ")
if (selfClosingTags.includes(name)) {
@@ -143,6 +143,29 @@ const licenseElementImg = (licenseElement: LicenseElement): string => {
})
}
+/**
+ * Drop URLs with a non-http(s)/mailto scheme to `about:blank`, so a
+ * `javascript:` or `data:` URL can't yield an executable link. Escaping the
+ * attribute value does not stop these, as they contain nothing to escape.
+ *
+ * @param href - the untrusted URL to sanitise
+ * @returns the URL if its scheme is safe, otherwise `about:blank`
+ */
+const sanitizeHref = (href: string): string => {
+ // Strip the C0 controls and spaces a browser ignores when parsing, else `\x01javascript:` or `java\tscript:` evades the check but still runs.
+ const stripped = Array.from(href)
+ .filter((char) => (char.codePointAt(0) ?? 0) > 0x20)
+ .join("")
+ const scheme = stripped.match(/^([a-z][a-z0-9+.-]*):/i)
+ if (
+ scheme &&
+ !["http", "https", "mailto"].includes(scheme[1].toLowerCase())
+ ) {
+ return "about:blank"
+ }
+ return href
+}
+
/**
* Get an HTML `<a>` tag set up with the `target` and `rel` attributes.
*
@@ -151,7 +174,7 @@ const licenseElementImg = (licenseElement: LicenseElement): string => {
* @returns the HTML markup of the `<a>` tag
*/
const extLink = (href: string, text: string) =>
- h("a", { rel: "noopener noreferrer", href }, [text])
+ h("a", { rel: "noopener noreferrer", href: sanitizeHref(href) }, [text])
/**
* Generate a Dublin Core conforming XML attribution snippet.
diff --git a/frontend/test/unit/specs/utils/attribution-html.spec.ts b/frontend/test/unit/specs/utils/attribution-html.spec.ts
index efc242f54..75e113bea 100644
--- a/frontend/test/unit/specs/utils/attribution-html.spec.ts
+++ b/frontend/test/unit/specs/utils/attribution-html.spec.ts
@@ -67,6 +67,57 @@ describe("getAttribution", () => {
expect(attrText).not.toContain(mediaItemWithHtml.originalTitle)
})
+ it("escapes HTML in URL fields to prevent attribute-injection XSS", async () => {
+ const mediaItemWithUrlPayload = {
+ ...mediaItem,
+ creator_url: 'https://x"><img src=x onerror=alert(1)>',
+ }
+ const attrText = getAttribution(mediaItemWithUrlPayload, t, {
+ includeIcons: false,
+ })
+ expect(attrText).not.toContain("<img src=x onerror")
+ expect(attrText).toContain("&quot;&gt;&lt;img")
+ document.body.innerHTML = attrText
+ expect(document.getElementsByTagName("img")).toHaveLength(0)
+ })
+
+ it("drops javascript: URLs from hrefs", async () => {
+ const mediaItemWithJsUrl = {
+ ...mediaItem,
+ creator_url: "javascript:alert(document.domain)",
+ }
+ document.body.innerHTML = getAttribution(mediaItemWithJsUrl, t)
+ const links = Array.from(document.getElementsByTagName("a"))
+ expect(
+ links.some((a) => a.getAttribute("href")?.startsWith("javascript"))
+ ).toBe(false)
+ expect(links.some((a) => a.getAttribute("href") === "about:blank")).toBe(
+ true
+ )
+ })
+
+ it("drops javascript: URLs obfuscated with control characters", async () => {
+ const mediaItemWithObfuscatedUrl = {
+ ...mediaItem,
+ creator_url: "java\tscript:alert(1)",
+ }
+ document.body.innerHTML = getAttribution(mediaItemWithObfuscatedUrl, t)
+ const links = Array.from(document.getElementsByTagName("a"))
+ // The raw attribute keeps the obfuscation verbatim; only the parsed `href` property reveals the effective javascript: scheme.
+ expect(links.some((a) => a.href.startsWith("javascript:"))).toBe(false)
+ expect(links.some((a) => a.getAttribute("href") === "about:blank")).toBe(
+ true
+ )
+ })
+
+ it("preserves safe http(s) URLs in hrefs", async () => {
+ document.body.innerHTML = getAttribution(mediaItem, t)
+ const creatorLink = Array.from(document.getElementsByTagName("a")).find(
+ (a) => a.getAttribute("href") === mediaItem.creator_url
+ )
+ expect(creatorLink).toBeTruthy()
+ })
+
it("does not use anchors in plain-text mode", async () => {
document.body.innerHTML = getAttribution(mediaItem, t)
expect(document.getElementsByTagName("a")).not.toHaveLength(0)