Friday, May 18, 2012

Be Sure to Escape Untrusted Data


Escaping is a method of rendering untrusted data non-executable by ensuring that the characters that comprise the data are treated as data and not characters of significance by the parser that will process the data.  As such, escaping is a common defense against cross site scripting attacks, whereby a user attempts to inject malicious JavaScript content into a Web page.  For example, the typical JavaScript is enclosed in a set of <script></script> tags which are used to identify which elements of the HTML page need to be forwarded to a browser's JavaScript engine.  Escaping characters like, <, >, “, ‘,  /, and & into an HTML entity encoded (e.g. &lt; for <) form will allow the untrusted data to display as written, but will prevent its execution.  To get a feel for how escaping works, consider the following Perl code snippet:

 #!usr/bin/perl

# Copyright 2012- Christopher M. Frenz
# This script is free software - it may be used, copied, redistributed, and/or modified
# under the terms laid forth in the Perl Artistic License

use HTML::EscapeEvil;
use strict;

#simulated input containing JavaScript
my $input=q{<script type="text/javascript">

   var d=new Date();
   document.write(d);

   </script>
};

#code to escape the tags from JavaScript input   
my $escape = HTML::EscapeEvil->new;
$escape->parse($input);
my $html = $escape->filtered_html;
$escape->clear;

#prints out escaped html output
print "<p>$html</p>";

In its original form, the script stored in the $input variable would be able to execute inside a browser and result in an output such as the following:

 Fri May 18 2012 15:44:24 GMT-0400 (Eastern Daylight Time) 

The escaped version is non-executable and would be output from the Perl script as follows:

<p>&lt;script type=&quot;text/javascript&quot;&gt;

   var d=new Date();
   document.write(d);

   &lt;/script&gt;</p>

If the resultant HTML was displayed in a browser, it would not be executed and would yield the following:

<script type="text/javascript"> var d=new Date(); document.write(d); </script>



334771_Hungry Devices 125x125

No comments: