0

for security purpose now i'm fetching all data from database with htmlEncoded format. it is correct? please help..

1
  • A particular technical choice in a design isn't "correct", it's a detail in a global strategy. The question is whether the strategy makes sense, globally.
    – curiousguy
    Jun 26, 2018 at 23:55

2 Answers 2

2

This works for data that you display as HTML - but only for some areas of HTML, and this is not best practice.

You want to encode data for the specific context it's being used or displayed - which means you should encode it correctly at the time you are using it or displaying it. Encoding it as it comes out of the DB not a good practice, you usually don't know how it's eventually going to be used, and it will lead to double encoding or encoding for the wrong context. You are likely encoding for HTML attributes. But this data might be used for HTML elements, javascript, URLs or maybe being used in other contexts such as being placed back in the database.

See the OWASP XSS Cheat Sheet for how to encode for various HTML contexts.

It's a common pattern to encode aggressively for HTML as it comes out of the DB, as you're doing here - or another similar pattern is encoding as parameters are pulled out of the servlet context. It seems more secure, and for legacy apps it can be a way to quickly retrofit code. But, in complex applications, it can lead to functional issues or poor security. I've seen several cases where common output functions expect strings to already be encoded, but many of the calls to the functions are from other contexts that pass unencoded strings.

If you do go ahead with "aggressively encoding" you need to very clearly name and document what functions expect encoded vs unencoded strings.

2
  • Thank you very much @Egret Actually our application is almost ready and now we take an security call that's why i'm encoding data all the the time and yes wherever we need HTML we decode back and used.
    – vishal9796
    May 6, 2018 at 16:55
  • @vishal9796 I've added some specific examples where I've seen this pattern cause problems
    – Egret
    May 27, 2018 at 17:35
1

Yes and no. It is correct to do for data you display as HTML. But there may be other uses for your data, where HTML encode may not be adequate. For example, if you process the data, encoding may cause problems. On the other hand, if you for example put the data into javascript, you may have to use different encoding.

Also if you use PHP or a language where html encode works similarly, you may want to use the flag ENT_QUOTES to also escape the character '.

1
  • Thanks you very much @Perer Harmann. now i am working on asp net. just tell mi If i encode data at fecting is an bad or good as per programming rules/practice??
    – vishal9796
    May 5, 2018 at 17:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .