0

I have webpages (basically business cards) whose titles are created based on user inputs. I am planning to use simple JS template string for this purpose, instead of some template engine. (I am using express.js/node.js for this purpose)

response.send(`
<html>

 <head>
  <title>${user_inputed_title_got_from_DB}</title>
  <meta property="og:title" content="${some_more_user_content}" />
 </head>

 <body>
  <script>
     window.location.href="/business-card/${user_input_number}";
  </script>
 </body>

</html>`)

How to avoid XSS injection from a malacious user?

Anurag Vohra
  • 1,781
  • 12
  • 28
  • 1
    https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html – madflow Feb 13 '22 at 14:12

1 Answers1

1

For normal HTML tags, this answer should suffice:

function escapeHtml(unsafe)
{
    return unsafe
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
 }

However, your redirect in the script tag needs to be treated a bit more carefully. One common approach is to put the redirect in an attribute, which can be escaped with the above function:

<script data-redir="/business-card/${escapeHtml(user_input_number)}">
    window.location.href = document.currentScript.dataset.redir;
</script>
Aplet123
  • 33,825
  • 1
  • 29
  • 55