Skip to content

A platform for community discussion. Free, open, simple.

FIX: better iframe sanitization

Régis Hanol8dc358e4d506
diff --git a/app/assets/javascripts/discourse/tests/unit/lib/sanitizer-test.js b/app/assets/javascripts/discourse/tests/unit/lib/sanitizer-test.js
index 56d4385d6f6..5bebc07817d 100644
--- a/app/assets/javascripts/discourse/tests/unit/lib/sanitizer-test.js
+++ b/app/assets/javascripts/discourse/tests/unit/lib/sanitizer-test.js
@@ -77,6 +77,24 @@ module("Unit | Utility | sanitizer", function (hooks) {
"it allows iframe to OpenStreetMap"
);
+ cooked(
+ `BEFORE\n\n<iframe src=http://example.com>\n\nINSIDE\n\n</iframe>\n\nAFTER`,
+ `<p>BEFORE</p>\n\n<p>AFTER</p>`,
+ "it strips unauthorized iframes - unallowed src"
+ );
+
+ cooked(
+ `BEFORE\n\n<iframe src=''>\n\nINSIDE\n\n</iframe>\n\nAFTER`,
+ `<p>BEFORE</p>\n\n<p>AFTER</p>`,
+ "it strips unauthorized iframes - empty src"
+ );
+
+ cooked(
+ `BEFORE\n\n<iframe src='http://example.com'>\n\nAFTER`,
+ `<p>BEFORE</p>`,
+ "it strips unauthorized partial iframes"
+ );
+
assert.strictEqual(engine.sanitize("<textarea>hullo</textarea>"), "hullo");
assert.strictEqual(
engine.sanitize("<button>press me!</button>"),
diff --git a/app/assets/javascripts/pretty-text/addon/sanitizer.js b/app/assets/javascripts/pretty-text/addon/sanitizer.js
index d765b8889de..f34cf7a8ad0 100644
--- a/app/assets/javascripts/pretty-text/addon/sanitizer.js
+++ b/app/assets/javascripts/pretty-text/addon/sanitizer.js
@@ -1,6 +1,10 @@
import xss from "xss";
import escape from "discourse-common/lib/escape";
+// Should match any <iframe> without a src attribute
+const IFRAME_REGEXP =
+ /<iframe(?![^>]*\s+src\s*=)[^>]*>[\s\S]*?(<\/iframe\s*>|$)/gi;
+
function attr(name, value) {
if (value) {
return `${name}="${xss.escapeAttrValue(value)}"`;
@@ -146,7 +150,8 @@ export function sanitize(text, allowLister) {
}
if (tag === "iframe" && name === "src") {
- return "-STRIP-";
+ // This iframe is not allowed
+ return "";
}
if (tag === "video" && name === "autoplay") {
@@ -176,7 +181,7 @@ export function sanitize(text, allowLister) {
return result
.replace(/\[removed\]/g, "")
- .replace(/\<iframe[^>]+\-STRIP\-[^>]*>[^<]*<\/iframe>/g, "")
+ .replace(IFRAME_REGEXP, "")
.replace(/&(?![#\w]+;)/g, "&amp;")
.replace(/&#39;/g, "'")
.replace(/ \/>/g, ">");