惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
雷峰网
雷峰网
Recent Announcements
Recent Announcements
月光博客
月光博客
G
Google Developers Blog
腾讯CDC
S
Secure Thoughts
大猫的无限游戏
大猫的无限游戏
T
Tenable Blog
云风的 BLOG
云风的 BLOG
W
WeLiveSecurity
博客园 - 【当耐特】
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
博客园 - 聂微东
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
人人都是产品经理
人人都是产品经理
P
Privacy International News Feed
MyScale Blog
MyScale Blog
K
Kaspersky official blog
T
The Blog of Author Tim Ferriss
Attack and Defense Labs
Attack and Defense Labs
Spread Privacy
Spread Privacy
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
aimingoo的专栏
aimingoo的专栏
I
Intezer
Vercel News
Vercel News
小众软件
小众软件
Simon Willison's Weblog
Simon Willison's Weblog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
N
Netflix TechBlog - Medium
P
Proofpoint News Feed
Latest news
Latest news
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Tor Project blog
S
Security Affairs
P
Proofpoint News Feed
博客园 - 三生石上(FineUI控件)
博客园 - Franky
C
Cyber Attacks, Cyber Crime and Cyber Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
美团技术团队
Recent Commits to openclaw:main
Recent Commits to openclaw:main
S
Security @ Cisco Blogs
L
LINUX DO - 热门话题
Know Your Adversary
Know Your Adversary
Project Zero
Project Zero
D
Docker
L
Lohrmann on Cybersecurity
F
Full Disclosure

Mathias Bynens

A horrifying globalThis polyfill in universal JavaScript JavaScript engine fundamentals: optimizing prototypes JavaScript engine fundamentals: Shapes and Inline Caches Asynchronous stack traces: why await beats Promise#then() ECMAScript regular expressions are getting better! Unicode property escapes in JavaScript regular expressions ES2015 const is not about immutability Valid JavaScript variable names in ES2015 Unicode-aware regular expressions in ES2015 Dear Google, please fix plain text emails in Gmail PBKDF2+HMAC hash collisions explained JavaScript has a Unicode problem Processing Content Security Policy violation reports Hiding JSON-formatted data in the DOM with CSP enabled Loading JSON-formatted data with Ajax and xhr.responseType='json' Reserved keywords in JavaScript How to support full Unicode in MySQL databases How to speedrun Dropbox’s Dropquest 2012 Unquoted font family names in CSS Unquoted property names / object keys in JavaScript Valid JavaScript variable names in ES5 CSS character escape sequences JavaScript’s internal character encoding: UCS-2 or UTF-16? The smallest possible valid (X)HTML documents JavaScript character escape sequences JavaScript foo.prototype.bar notation Ambiguous ampersands HTML element + attribute notation How I detect and use localStorage: a simple JavaScript pattern Unquoted attribute values in HTML and CSS/JS selectors Using the oninput event handler with onkeyup/onkeydown as its fallback Everything you always wanted to know about touch icons In defense of CSS hacks — introducing “safe CSS hacks” AirPlay video support in iOS Safari — a bookmarklet Completing Dropbox’s Dropquest 2011 in 60 seconds Using CSS without HTML How to create simple Mac apps from shell scripts Using setTimeout to speed up window.onload Bulletproof JavaScript benchmarks Thoughts on Safari Reader’s generated HTML How to enable Safari Reader on your site? The XML serialization of HTML5, aka ‘XHTML5’ The id attribute got more classy in HTML5 The three levels of HTML5 usage The HTML5 document.head DOM tree accessor Bulletproof HTML5 <details> fallback using jQuery Displaying hidden elements like <head> using CSS Inline <script> and <style> vs. external .js and .css — what’s the size threshold? Using Showdown/PageDown with and without jQuery
The end-tag open (ETAGO) delimiter
Mathias · 2011-06-10 · via Mathias Bynens

Disclaimer: Many thanks to Juriy ‘kangax’ Zaytsev (Юрий Зайцев) for writing the test case that inspired me to investigate this further, and everyone in #whatwg for helping me parse the specification correctly.

ETAGO in HTML4

The HTML 4.01 spec says:

Although the <style> and <script> elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence </ (ETAGO or end-tag open delimiter) is treated as terminating the end of the element’s content. In valid documents, this would be the end tag for the element.

Section 3.2.1 in Appendix B is more specific:

When script or style data is the content of an element (<script> and <style>), the data begins immediately after the element start tag and ends at the first ETAGO (</) delimiter followed by a name start character ([a-zA-Z]); note that this may not be the element’s end tag. Authors should therefore escape </ within the content. Escape mechanisms are specific to each scripting or style sheet language.

(Note that this only applies to inline styles and scripts in HTML documents, not external files that are referenced from the HTML.)

This means that technically the following code is invalid HTML4, and it shouldn’t work:

<!-- Remember, this is HTML4 we’re talking about. Redundant @type attributes ftw! -->
<style type="text/css">
	p {
		background: red;
	}
</style>
<style type="text/css">
	p {
		content: '</abc';
		background: green;
	}
</style>

The second <style> element would be closed as soon as the parser reaches the ETAGO delimiter, and none of the style rules in it would be applied. Paragraphs would get a red background color (see the first <style> element). It would be equivalent to the following non-conformant markup:

<style type="text/css">
	p {
		background: red;
	}
</style>
<style type="text/css">
	p {
		content: '
</style>
bc'; background: green; }</style>

The same goes for <script> elements:

<script type="text/javascript">
	document.write('<p>Foo</p>');
</script>

As per HTML4, the <script> element should be closed prematurely, resulting in a JavaScript SyntaxError, since it would be interpreted as follows:

<script type="text/javascript">
	document.write('<p>Foo
</script>
');</script>

Well, that’s the theory. In reality, no browser ever implemented this. The ETAGO delimiter isn’t respected as a terminating sequence for <style> and <script> elements in any browser. You can easily confirm this yourself by viewing the test cases based on the above code examples: ETAGO delimiter inside a <style> element and ETAGO delimiter inside a <script> element.

Back to reality with HTML5

Rather than expecting existing implementations to change, ‘HTML5’ a.k.a. the HTML Living Standard standardizes the behavior that browsers had implemented (with a few security improvements). This is described in the spec as part of the full tokenization algorithm, specifically here and here.

This means the above examples are now valid HTML. And of course, they continue to work correctly, as they always did. Generally, ETAGO delimiters can be used inside of <style> and <script> elements. Just keep in mind that the full </style and </script strings followed by a space character, >, or / will close their respective opening tag.

Semi-related fun fact: Since the <title> element is an RCDATA element that uses the text content model, there’s no need to encode < inside of it unless you want to use </title followed by any of those characters. <title>foo < bar</title> and <title><i>foo</i></title> are perfectly valid markup as per HTML. The same goes for <textarea>. In spec lingo: <script> and <style> are raw text elements, <textarea> and <title> are RCDATA elements.

For backwards compatibility, there’s an interesting exception to this rule for <script> elements that contain <!-​- with a later occurence of -​->in that case, e.g. </script> is allowed in the <script> element’s content. Here’s a valid, working example:

<script>
	<!--
		document.write("<script>alert('LOLWAT')</script>")
	-->
</script>

While this is good to know, luckily there are better solutions than this old-school ’90s-style pattern (that only works for <script> elements anyway). Whenever you need to use </style> inside a <style> element, or </script> inside a <script> element, just escape these strings. In both CSS and JavaScript there are various ways of doing this, but using a backslash (\, also known as “reverse solidus character”) is by far the simplest:

<style>
	p {
		/* Using the Unicode code point for the solidus character (see https://mths.be/bax): */
		content: '<\00002Fstyle>';
		/* Using the shorthand notation for Unicode code points (see https://mths.be/bax): */
		content: '<\2F style>';
		/* Simply escaping the solidus character with a reverse solidus (\): */
		content: '<\/style>';
		background: green;
	}
</style>
<script>
	// Using `unescape()`:
	document.write(unescape('<script>alert("wtf")%3C/script>')); // Überlame.
	// Using string concatenation:
	document.write('<script>alert("heh")<' + '/script>'); // Lame.
	// Using the octal escape sequence for the solidus character (/):
	document.write('<script>alert("hah")<\57script>'); // Lame, deprecated, and disallowed in ES5 strict mode.
	// Using the Unicode escape sequence:
	document.write('<script>alert("hoh")<\u002Fscript>'); // Lame.
	// Using the hexadecimal escape sequence:
	document.write('<script>alert("huh")<\x2Fscript>'); // Lame.
	// Simply escaping the solidus character:
	document.write('<script>alert("O HAI")<\/script>'); // Awesome!
</script>

Both these examples are valid HTML, and of course they work as expected in any browser.

Note that while it’s an edge case, the </script character sequence can theoretically be used outside of strings in JavaScript, e.g. 42 </script/. Of course, the simple \/ escape won’t work here. In that case, make sure to use a space before the regex literal: 42 < /script/. (I can’t think of such a case for CSS though. Can you?)

Recommendations

The HTML Standard now has a section about the restrictions for contents of script elements, which includes the following piece of advice:

The easiest and safest way to avoid the rather strange restrictions described in this section is to always escape "<!-​-" as "<\!-​-", "<script" as "<\script", and "</script" as "<\/script" when these sequences appear in literals in scripts (e.g. in strings, regular expressions, or comments), and to avoid writing code that uses such constructs in expressions.