Let's say that there is a website which has an input field from which the input is saved to a database and then displayed somewhere else on the website.

  • Is it safe to only sanitize/escape the output, when the data is displayed?

  • Do you have to also escape the input to prevent malicious data getting into the database in the first place?

The thing that I am worried about is that even if the application handles the output by for example escaping the data from the database, but some other application may not have such mechanism to protect the users which the data is displayed to.

Is it safe to keep malicious code stored in your database for the sake of not changing the user's input as long as you can prevent it from hurting the user?

  • 2
    All Stack Exchange sites do it this way - if you include something like <script>alert("XSS!");</script> in a post, it will not be included in the output, but hit edit and the code will still be there. – Anders May 26 '16 at 8:52

In my opinion it is a bad way to have escaped data in the database. Since the escaping rules vary depending on the input an output medium (HTML, JSON, ...) they belong at the place where you input and output data and not in the database.

I recommend to use a multitier architecture where the data tier (i.e. the database) contains the plain (unescaped) data, the logic tier (i.e. business logic) works on these plain data and only the presentation tier (i.e. website, REST API,...) cares about escaping and unescaping data. This way the data will be properly unescaped (input) and escaped (output) depending on the escaping rules of the various input and output mediums (HTML, JSON, PDF, YAML, whatever...).

... but some other application may not have such mechanism to protect the users which the data is displayed to.

I your fear such kind of broken applications then you should also fear applications that use pre-escaped data with HTML escaping for outputting JSON or which escape data again even they are already escaped in the database etc. You must have clear rules how the data are stored in the database (which not only includes escaping but also character encodings like UTF-8) and applications must know and follow these rules.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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