0

I have a .NET backend with a AngularJS frontend. It all works (no JavaScript executed) when a user enters his name as

<script>alert('xss');</script>

The data is sent, as Json, to my backend unencoded, I save the text as entered in the database, and send the text, as Json, unencoded back to the frontend when the data is read.

This all works as said, but watching a security course they advised to encode the Json.

In my case, should I better encode my Json?

This is a part of the Json when saving and loading:

,"aanvragernaam":"<script>alert('xss');</script>","
Michel
  • 23,085
  • 46
  • 152
  • 242

3 Answers3

1

You probably want to do input validation and reject brackets, as names rarely contain those. However that is not a sufficient security control, as if we want to support other types of data (e.g. comments), we may need to support those characters and thus our control does not work.

The risk of having HTML (script tags etc.) in JSON, is if the attacker can somehow trick a user into loading and displaying it as HTML in the browser. This used to be quite straight forward in < IE9 as those browsers did not know what the Content-Type application/json was. Thus the browser would try to guess (sniff) the content. However this type of sniffing can be disabled by using the header X-Content-Type-Options: nosniff.

You can strengthen the protection further by adding

Content-Disposition: attachment;filename=data.json
X-Download-Options: NoOpen

If a user tries to open the JSON directly in a browser window, the file will be downloaded in stead of being displayed.

IMHO no encoding necessary in the JSON.

Erlend
  • 4,336
  • 22
  • 25
1

As long as you are setting the content-type to application/json then this content type will not be sniffed by browsers, because it is not "known". Therefore this should be secure against XSS.

There is no need to further encode it.

JSON Hijacking is another vulnerability with GET requests, however it is not an issue in modern browsers.

The only other risk I see is DOM XSS. As long as you are not writing the value "as is" into the DOM, then there is no XSS risk. If you are, then you should HTML encode it, or use JQuery or JavaScript to properly set text/textContent as required so that the browser does not interpret it as script.

Note that the risk here isn't <script>alert('xss')</script>, it would have to be something like <img src=x onload="alert('xss');" /> for it to execute when dynamically added to a document.

Community
  • 1
  • 1
SilverlightFox
  • 32,436
  • 11
  • 76
  • 145
0

I think you should encodeURI(name) before you send a request to back end to save the name to database.

And you will use decodeURI function when you receive data from back end.