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:


# 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();


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

#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();


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


john said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me..
I am a regular follower of your blog. Really very informative post you shared here.
Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai .
or Javascript Training in Chennai.
Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai

jai said...

I was recommended this web site by means of my cousin. I am now not certain whether this post is written through him as nobody else recognise such precise about my difficulty. You're amazing! Thank you!
Data Science course in Indira nagar
Data Science course in marathahalli
Data Science Interview questions and answers
Data science training in tambaram
Data Science course in btm layout
Data science course in kalyan nagar