4

From a data integrity standpoint, if I persist the following code into my database:

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

should I sanitize it before persistence, for instance making < into &lt and then on retrieval doing the decode? Or is it safer to only sanitize on retrieval, for instance in a UI?

9

Since injection attacks exploit control sequences in the way the output is interpreted, and since different output formats use different control sequences (think JavaScript versus SQL versus HTML), your sanitization technique needs to reflect where the output is going. If you sanitize for output upon input, you're making an assumption about where that output is going to be sent, which may prove to be incorrect, perhaps due to some future change or some usage case you didn't think fo.

Therefore, as a rule I would suggest sanitizing on output to reflect the specific injection sensitivity for the format you're outputting in.

Note that if you're storing pre-formatted input and the context of the formatting is not available upon output (such as storing HTML for a blog post), you may do some checks upon input, but this is a slightly different scenario than just general escaping.

So again, as a rule escape your output rather than your input, but make exceptions as necessary with the understanding that those exceptions need to be watched with extra scrutiny as you're creating a hole in your app that you need to carefully guard.

  • Good feedback. I figured as much that the consumer of the data would be where we would want the checks to go, to ensure zero data loss. – Woot4Moo Dec 5 '13 at 17:40
  • 4
    Downvoting without explanation is sad. Nobody wins, because the user doesn't know what he did wrong, he loses reputation and you lose reputation. – Lucas Kauffman Dec 5 '13 at 17:41
  • @LucasKauffman true – Ebenezar John Paul Dec 6 '13 at 6:48

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.