In the following HTL code, where I'm using a method that returns a JSON string, I am concerned that it might cause XSS vulnerabilities when the data is rendered in the HTML:
<sly data-sly-use.obj="com.components.models.class">
${ obj.method @ context= 'unsafe'}
</sly>
Also, in my JavaScript code, I am accessing the DOM and parsing the JSON data, which I then manipulate and render back into the DOM. I’m worried that this could lead to XSS vulnerabilities as well:
const Script = document.querySelector(' script');
const data = JSON.parse(Script.innerHTML.trim());
Script.innerHTML = JSON.stringify(data, null, 2)
.replace(/},\s*{/g, '},\n{')
.replace(/\[\s*{/g, '[\n{')
.replace(/}\s*\]/g, '}\n]');
How can I fix both of these to prevent XSS vulnerabilities?
Views
Replies
Total Likes
You can escape the source JSON inside your Sling Model by leveraging StringEscapeUtils.escapeHtml4. This ensures that any potentially harmful content in the JSON string is escaped before being rendered.
BTW the primary issue lies in the use of context='unsafe', which disables HTL's built-in escaping mechanisms. To mitigate XSS vulnerabilities:
if i remove unsafe in htl, method is not able to print anything
Views
Replies
Total Likes
Hi @user96222
Can you try using ${ obj.method @ context= 'html'} ? is it showing the output or trimming it?
if you are using npm to build your ui.frontend then we can use the `DOMPurify` dependency to sanitize the script content before parsing it. This helps remove any potentially malicious scripts or HTML that might be present in the data.
example:
const sanitizedContent = DOMPurify.sanitize(script.textContent || '')
const data = JSON.parse(sanitizedContent.trim())
Instead of using `innerHTML`, we use `textContent` to get and set the script content. This is safer because `textContent` doesn't parse the content as HTML, reducing the risk of script execution.
script.textContent = formattedData;
by following the above methods you can prevent the XSS vulnerabilities.
if i use context as html , output is coming ,but is not readable
Views
Replies
Total Likes
Hi @user96222
Please use StringEscapeUtils.escapeHtml4 in the Sling Model to Sanitize the output in the java and then refer to the shared JS to sanitize the data in the JS as well. In this way, the data will not have XSS vulnerability issues.
@user96222 Did you find the suggestions helpful? Please let us know if you need more information. If a response worked, kindly mark it as correct for posterity; alternatively, if you found a solution yourself, we’d appreciate it if you could share it with the community. Thank you!
Views
Replies
Total Likes
still looking for solution !
Views
Replies
Total Likes
Views
Likes
Replies