0

I am new to HTML. So even if you find this question silly please answer it. It will help me lot.

I got what xss attack is. OWASP says do HTML Escape Before Inserting Untrusted Data into HTML Element Content.

https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

That means I should escape characters in following way:

& --> &
< --> &lt;
> --> &gt;
" --> &quot;
' --> &#x27;
/ --> &#x2F;

I searched lot that is there any method in HTML to apply this escaping? but couldn't find any. Please guide how can I do this in efficient way?

Adding code to explain:

<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
    <input type="text" id="userInput"=>give me input</input>
    <button onclick="test()">Submit</button>
    <p id="demo"></p>   
    <script>
        function test()
        {
            var userInput = document.getElementById("userInput").value;
            document.write(userInput);
        }
    </script>
</body>
</html>

If in userinput field user insert: alert("xss");

Then pop up will be there.

I wish to avoid this pop up and store value which user has provided in var userInput. Further I am planning to display this value on UI.

kalpesh
  • 328
  • 3
  • 14
  • 1
    HTML cannot programmatically insert text into itself. It's not a programming language that has that capability. As such, the question is moot. – deceze Dec 18 '17 at 10:32
  • @kalpesh — That's [tag:javascript], not [tag:html]. – Quentin Dec 18 '17 at 10:34
  • Please suggest for Javascript at least. It will be useful. – kalpesh Dec 18 '17 at 10:38
  • I have added more details into question to explain what I am trying to say. Please check. – kalpesh Dec 18 '17 at 10:39
  • 2
    When using Javascript, you simply use the DOM API to construct elements, which makes XSS a non-issue if used correctly. `document.write` is something you don't ever use in practice. No, don't use it. No, not even then. Nu-uh. – deceze Dec 18 '17 at 10:42
  • Thanks Hassan. But encodeURIComponent() reults %3C for '<'. OWASP says it should be escaped as < – kalpesh Dec 18 '17 at 10:44
  • @kalpesh you need to write custom logic for this. `encodeURIComponent` leaves some characters like `- _ . ! ~ * ' ( )`. @deceze thanks. – Hassan Imam Dec 18 '17 at 10:47
  • 1
    @kalpesh — encodeURIComponent encodes data so you can put it in a URI (hence the name), not HTML. – Quentin Dec 18 '17 at 10:51
  • 1
    @HassanImam — URIs are not HTML! – Quentin Dec 18 '17 at 10:51
  • Duplicate: https://stackoverflow.com/questions/3129899/what-are-the-common-defenses-against-xss – Quentin Dec 18 '17 at 11:25
  • Thanks for help. I got something working. But not exactly what i was expecting i.e. a predefined method. One may refer: http://shebang.brandonmintern.com/foolproof-html-escaping-in-javascript/. I dont know if adding a url is allowed at stack overflow or not. If not allowed please let me know, I will remove comment. – kalpesh Dec 18 '17 at 11:49

0 Answers0