0

I allow a user to enter text using the following:

<textarea ng-model="UserComment.text" rows="4" required maxlength="4000" />

Now this allows the user to enter

<script>alert('Hello world!');</script>

This will be saved to my db exactly as entered as the script tag (if not filtered) - which is extremely dangerous. I know when I render that input using the following ng-bind


<div class="user-comment-text">{{UserComment.text}}</div>

it will be sanitized by default and the script tags will be HTML encoded with < and > rendered as &lt; and &gt; so the script tags are not executed as script. But it is dangerous to save these tags in my DB so I want to filter the <script> tag (and any other dangerous input) from being input - what is the best way of doing that?

I hope there is a better solution than a regular expression (ng-pattern) as getting this right for multi-lingual is near impossible. My current thoughts are to sanitize on the server using a c# case-insensitive regular expression in my controller to strip out <script> tags - but there are other scripting concerns too - e.g. img onerror event and a href with javascript URLs. I'd like to tackle the script element first and worry about the others later. Thanks.

2
  • will it work https://docs.angularjs.org/api/ngSanitize/service/$sanitize Commented Dec 30, 2019 at 12:03
  • Thanks behzad for the edit - I'd have preferred you left the original. e.g In British English sanitise is the correct usage not sanitize as used in the USA. See grammarist.com/spelling/sanitise-sanitize . Commented Dec 30, 2019 at 12:55

1 Answer 1

1

Try a regex.

var rgx = /<\/?script>/gi;
var snippet = "<script>alert('alert1')</script> stuff <script>alert('alert2')</script>";
var result = snippet.replace(rgx, '[script]');

is a very simple example. The expected output would be

alert('alert1') stuff alert('alert2')

Instead of removing the completely, you can modify to [script][/script] so its not lost on you that someone was trying to malicious. You can also check for the < and >

As mentioned above, sanitise everything and if your database is SQL to use SqlParameters.

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

1 Comment

Thanks - that's similar to my thoughts of using a reg ex but using it on the client instead of server, and i like the idea of replacing with [script]. I'm hoping someone comes up with a pure angular solution as I can't believe everyone needs to use this type of reg expression to keep script away from the server. Lets see what other suggestions come in. Thanks again.

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.