8/28/2008
LifeCycle Solutions - Home ( the software development blog )
 

<August 2008>
SunMonTueWedThuFriSat
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456

Subscribe to this feed:

RSS 2.0 | Atom 1.0 |CDF

On this Page:
Gets Me Every Time




Add to Technorati Favorites

Thursday, August 17, 2006

I recently data bound to a DateTime property in ASP.NET 2.0, and couldn't figure out why the formatting wasn't working properly.  I set the DataFormatString property to {0:d}, which should change the column to short date format.  But it wasn't formatting at all.  After a little digging, I found that it was because HtmlEncode wasn't set to false.  Setting HtmlEncode="false" on the column fixed the problem. 

Seems a bit odd at first, but the purpose of HtmlEncode is to prevent cross-site-script attacks.  Here's what's happening:

  • The property's value is retrieved.
  • ASP.NET converts the value to a string and formats it to remove any HTML.  For example a '<' gets changed to '&lt;'.  So, if someone were to somehow add the value <script>doSomethingTricksy()</script> to your database, it wouldn't get run here...
  • ASP.NET applies the DataFormatString, but by now the date is already a string. 
  • Formatting the string "1/1/2005 12:00:00 PM" doesn't do anything.

Since we know the type is a date, and it would be difficult to insert HTML into the date, then it's pretty safe to turn off this feature for this column.  Microsoft has a little note on this issue here.

I say pretty safe, because it's actually still possible that script or other HTML could be inserted into this column.  A recent post by Scott Hanselman may give you a clue.  Suppose you let users define their own DateTime formatting preferences, and did something really evil, like this:

customCulture.DateTimeFormat.ShortDatePattern = Request("format").ToString()
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture

And then suppose some crafty hacker sent a link to  yourpage.aspx?format=<script>doSomethingTricksy()</script>MM/dd/yyyy.  Any time you databound to a DateTime, if HtmlEncode was false, then the script would be run! Once somebody gets that far, they can do any number of bad things.

Granted, it's a pretty low threat, but it's worth knowing about.

Posted by Daniel Root

© 2006 LifeCycle Solutions, LLC | All Rights Reserved