This question already has an answer here:

We have an application with a form where user can enter a comment. The form is submitted using AJAX. Values are read also through AJAX and returned by the backend as JSON, and then parsed by JavaScript to present it on the page.

This form was vulnerable of XSS attack so we protected the application on the frontend only, we escape HTML and JavaScript characters when we parse JSON response.

We think that there is no need to do similar thing on the backend, i.e., to escape risky characters before storing them in the DB, because the JSON response will always be parsed by the frontend before rendering.

Is it correct approach or there is some threat or attack still possible?

marked as duplicate by paj28, Xander, AJ Henderson, Eric G, Mark Oct 9 '14 at 18:54

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    A duplicate question was asked in security.stackexchange.com/questions/44532/…, but the answer it got there is completely different than here: it is enough to rely only on client-side control for security for JSON services – dzieciou Oct 11 '14 at 10:52

Yes, there's a possible attack: You someday change the frontend, and stop using JSON and start using something else. The XSS stored on the database kicks in and your users are attacked.

It is a very good practice to sanitize the user input as soon as possible. I always sanitize them as soon as it reaches my code.

  • 2
    If you are expecting common text, filter out HTML data. If you expect integer, filter out strings and symbols. If are email, check the email validity. You know what kind of data you should be receiving, but where you will use it later is harder to predict. – ThoriumBR Oct 9 '14 at 14:36
  • 1
    Perhaps I am expecting a surname. This could be alphabetic like "smith" but "o'brien" would be valid too. At some later point in the code I use the surname in an SQL query. Where does the sanitisation go? At the point of input, or where the data is used? – paj28 Oct 9 '14 at 14:42
  • 1
    The point is that if you are expecting a surname, a "Smith<script>alert('XSS')</script>" should be filtered before reaching your database. Or a numeric product ID "123' or 1=1 or '" should be filtered too. – ThoriumBR Oct 9 '14 at 14:45
  • 1
    @paj28 All inputs need to be sanitized, even between internal boundaries, for the very reason Thorium explains. In addition, all inputs stored need to be 'sane', or enforced to be within the expected input type (names, ints, symbols, code snippets, etc.) – schroeder Oct 9 '14 at 15:12
  • 1
    @paj28 Input sanitation protects the code receiving it, and 'stored sanity' helps protect the calling code, just like normal code contracts are meant to enforce. – schroeder Oct 9 '14 at 15:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.