4

I know this type of question might have asked many times but I am sure that this one is different than all of them. I have a Input TextArea control on server side, I am trying to remove all inline script or html injection. I was able to get rid of Script tags by doing this-

$(document).ready(function () {
            $('#btnHTML').click(function () {
                var textarea = document.getElementById("txtar1");
                var stringOfHtml = textarea.value;
                var wrappedString = '<div>' + stringOfHtml + '</div>';
                var noScript = wrappedString.replace(/script/g, "THISISNOTASCRIPTREALLY");
                var html = $(noScript);
                html.find('THISISNOTASCRIPTREALLY').remove();
                var tmp = document.createElement("DIV");
                tmp.id = "tmp";
                tmp.innerHTML = html.html().replace(/THISISNOTASCRIPTREALLY/g, 'script');
                document.body.appendChild(tmp);
                alert(html.html().replace(/THISISNOTASCRIPTREALLY/g, 'script'));
            });
<textarea id="txtar1" style="width:200px;height:100px"></textarea><br/>
<input type="button" id="btnHTML" value="Remove HTML" />

But my purpose is not solved, I am trying to restrict or remove all types of inline script injection. Few examples are-

<div>
<table border="2">
<tr>
<td><b>ABCD</b></td>
<td onclick="javascript:alert('Hello')">
EFGH</td>
</tr>
</table>
</div>

<div>
<table border="2">
<tr>
<td><b>Test</b></td>
<td alert('Hello')>
Success</td>
</tr>
</table>
</div>

<META HTTP-EQUIV="refresh" CONTENT="1;url=http://www.test.com">
<BR SIZE="&{alert('Injected')}"> 
<DIV STYLE="background-image: url(javascript:alert('Injected'))">

Any help or suggestions would be very very helpful.

1 Answer 1

4

Instead of using inline JavaScript <script> ... source ... </script>, using external JavaScript files and importing them using <script src="..."> helps to mitigate the attacks and make your website safe. The way to do this in the modern browsers is to set the 'Content-Security-Policy' (CSP) property, either via meta attribute or headers.

you can use this tutorial to get more knowlege regarding this.

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

2 Comments

Thanks @Sachintha for sharing the tutorial link with me. I have been going through this link and I agree that we can achieve by following CSP. But is it possible to implement this in IE8?

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.