0

I'm parsing the user inputted markdown into HTML using the marked library, and rendering it using the @html tag

But the issue is if the user input is something like <script>alert('hello')</script>, the element gets rendered as a normal html script element, but the code within that script is not executed (for some reason?)

Is this a possible attack vector for an XSS attack? (since the script is not executed for some reason)

And are there any alternative ways to render markdown safely?

I guess one solution is to sanitize the user input before rendering it, but I'm wondering if there are any alternatives

2 Answers 2

1

This generally is an XSS risk, there are other ways to get scripts executed in HTML that do not require a <script> tag, e.g.: <img src="non-existent" onerror="console.log(1)">

There are ways to mitigate the risk using a content security policy, but usually you would want to just sanitize the generated HTML using a library. There are quite a few of those, e.g. sanitize-html or dompurify. They generally only allow certain elements and attributes, removing or encoding dangerous content.

Sign up to request clarification or add additional context in comments.

Comments

0

Client-side

Most important thing is not allowing unsanitized user input straight into an @HTML template. See example REPL:

<script>
    import DOMPurify from 'dompurify';
    
    let value = `<b>bold</b>
<script>alert('hello')<\/script>`;
</script>

<!-- User input -->
<textarea bind:value />

<!-- Sanitized output -->
<div>
    {@html DOMPurify.sanitize(value)}
</div>

You should also further restrict exactly what HTML elements and attributes are allowed/disallowed by DOMPurify.

Server-side

On top of this, you will want to do some server-side filtering before saving user-input to your database. (eg. also run DOMPurify on submit, on the server).

A complete strategy would include HTTP Only cookies, CSP headers, and arguably some kind of firewall for detecting and alerting to common attacks from any malicous users.

Recommend running through the OWASP Cross Site Scripting Prevention Cheat-sheet.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.