<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>

	<overview>
		<p>

			Sanitizing untrusted input for HTML meta-characters is an
			important technique for preventing cross-site scripting attacks. But
			even a sanitized input can be dangerous to use if it is modified
			further before a browser treats it as HTML.

			A seemingly innocent transformation that expands a
			self-closing HTML tag from <code>&lt;div attr="{sanitized}"/&gt;</code>
			to <code>&lt;div attr="{sanitized}"&gt;&lt;/div&gt;</code> may
			in fact cause cross-site scripting vulnerabilities.

		</p>
		
	</overview>

	<recommendation>
		<p>

			Use a well-tested sanitization library if at all
			possible, and avoid modifying sanitized values further before treating
			them as HTML.

		</p>
	</recommendation>

	<example>

		<p>

			The following function transforms a self-closing HTML tag
			to a pair of open/close tags.  It does so for all non-<code>img</code>
			and non-<code>area</code> tags, by using a regular expression with two
			capture groups. The first capture group corresponds to the name of the
			tag, and the second capture group to the content of the tag.

		</p>

		<sample src="examples/UnsafeHtmlExpansion.js" />

		<p>

			While it is generally known regular expressions are
			ill-suited for parsing HTML, variants of this particular transformation
			pattern have long been considered safe.

		</p>

		<p>

			However, the function is not safe. As an example, consider
			the following string:


		</p>

		<sample src="examples/UnsafeHtmlExpansion-original.html" />

		<p>

			When the above function transforms the string, it becomes
			a string that results in an alert when a browser treats it as HTML.

		</p>

		<sample src="examples/UnsafeHtmlExpansion-transformed.html" />

	</example>

	<references>
		<li>jQuery:
		<a href="https://blog.jquery.com/2020/04/10/jquery-3-5-0-released/">Security fixes in jQuery 3.5.0</a>
		</li>
		<li>
			OWASP:
			<a href="https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html">DOM based
			XSS Prevention Cheat Sheet</a>.
		</li>
		<li>
			OWASP:
			<a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html">XSS
			(Cross Site Scripting) Prevention Cheat Sheet</a>.
		</li>
		<li>
			OWASP
			<a href="https://owasp.org/www-community/Types_of_Cross-Site_Scripting">Types of Cross-Site</a>.
		</li>
		<li>
			Wikipedia: <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">Cross-site scripting</a>.
		</li>
	</references>

</qhelp>
