SlideShare a Scribd company logo
MVC :: Preventing JavaScript Injection
Attacks
The goal of this tutorial is to explain how you can prevent JavaScript injection attacks in
your ASP.NET MVC applications. This tutorial discusses two approaches to defending your
website against a JavaScript injection attack. You learn how to prevent JavaScript injection
attacks by encoding the data that you display. You also learn how to prevent JavaScript
injection attacks by encoding the data that you accept.

What is a JavaScript Injection Attack?
Whenever you accept user input and redisplay the user input, you open your website to
JavaScript injection attacks. Let’s examine a concrete application that is open to JavaScript
injection attacks.
Imagine that you have created a customer feedback website (see Figure 1). Customers can
visit the website and enter feedback on their experience using your products. When a
customer submits their feedback, the feedback is redisplayed on the feedback page.
Figure 1 – Customer Feedback Website


The customer feedback website uses the controller in Listing 1. This controller contains
two actions named Index() and Create().

Listing 1 – HomeController.cs
   using System;
   using System.Web.Mvc;
   using CustomerFeedback.Models;


   namespace CustomerFeedback.Controllers
{
        [HandleError]
        public class HomeController : Controller
        {
             private FeedbackDataContext db = new FeedbackDataContext();


             public ActionResult Index()
             {
                  return View(db.Feedbacks);
             }


             public ActionResult Create(string message)
             {
                  // Add feedback
                  var newFeedback = new Feedback();
                  newFeedback.Message = message;
                  newFeedback.EntryDate = DateTime.Now;
                  db.Feedbacks.InsertOnSubmit(newFeedback);
                  db.SubmitChanges();


                  // Redirect
                  return RedirectToAction("Index");
             }
        }
   }


The Index() method displays the Index view. This method passes all of the previous
customer feedback to the Index view by retrieving the feedback from the database (using a
LINQ to SQL query).
The Create() method creates a new Feedback item and adds it to the database. The
message that the customer enters in the form is passed to the Create() method in the
message parameter. A Feedback item is created and the message is assigned to the
Feedback item’s Message property. The Feedback item is submitted to the database with the
DataContext.SubmitChanges() method call. Finally, the visitor is redirected back to the
Index view where all of the feedback is displayed.

The Index view is contained in Listing 2.
Listing 2 – Index.aspx
   <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
      AutoEventWireup="true" CodeBehind="Index.aspx.cs"
      Inherits="CustomerFeedback.Views.Home.Index" %>
   <%@ Import Namespace="CustomerFeedback.Models" %>
   <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent"
      runat="server">
        <h1>Customer Feedback</h1>
        <p>
        Please use the following form to enter feedback about our
       product.
        </p>
        <form method="post" action="/Home/Create">


        <label for="message">Message:</label>
        <br />
        <textarea name="message" cols="50" rows="2"></textarea>
        <br /><br />
        <input type="submit" value="Submit Feedback" />


        </form>


        <% foreach (Feedback feedback in ViewData.Model)
           {%>
              <p>
              <%=feedback.EntryDate.ToShortTimeString()%>
              --
              <%=feedback.Message%>
              </p>
        <% }%>


   </asp:Content>

The Index view has two sections. The top section contains the actual customer feedback
form. The bottom section contains a For..Each loop that loops through all of the previous
customer feedback items and displays the EntryDate and Message properties for each
feedback item.
The customer feedback website is a simple website. Unfortunately, the website is open to
JavaScript injection attacks.
Imagine that you enter the following text into the customer feedback form:
       <script>alert(“Boo!”)</script>

This text represents a JavaScript script that displays an alert message box. After someone
submits this script into the feedback form, the message Boo! will appear whenever anyone
visits the customer feedback website in the future (see Figure 2).




Figure 2 – JavaScript Injection
Now, your initial response to JavaScript injection attacks might be apathy. You might think
that JavaScript injection attacks are simply a type of defacement attack. You might believe
that no one can do anything truly evil by committing a JavaScript injection attack.
Unfortunately, a hacker can do some really, really evil things by injecting JavaScript into a
website. You can use a JavaScript injection attack to perform a Cross-Site Scripting (XSS)
attack. In a Cross-Site Scripting attack, you steal confidential user information and send the
information to another website.
For example, a hacker can use a JavaScript injection attack to steal the values of browser
cookies from other users. If sensitive information -- such as passwords, credit card
numbers, or social security numbers – is stored in the browser cookies, then a hacker can
use a JavaScript injection attack to steal this information. Or, if a user enters sensitive
information in a form field contained in a page that has been compromised with a JavaScript
attack, then the hacker can use the injected JavaScript to grab the form data and send it to
another website.
Please be scared. Take JavaScript injection attacks seriously and protect your user’s
confidential information. In the next two sections, we discuss two techniques that you can
use to defend your MVC applications from JavaScript injection attacks.

Approach #1: HTML Encode in the View
One easy method of preventing JavaScript injection attacks is to HTML encode any data
entered by website users when you redisplay the data in a view. The updated Index view in
Listing 3 follows this approach.
Listing 3 – Index.aspx (HTML Encoded)
   <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
      AutoEventWireup="true" CodeBehind="Index.aspx.cs"
      Inherits="CustomerFeedback.Views.Home.Index" %>
   <%@ Import Namespace="CustomerFeedback.Models" %>
   <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent"
      runat="server">
        <h1>Customer Feedback</h1>
        <p>
        Please use the following form to enter feedback about our
       product.
        </p>
        <form method="post" action="/Home/Create">


        <label for="message">Message:</label>
        <br />
        <textarea name="message" cols="50" rows="2"></textarea>
        <br /><br />
        <input type="submit" value="Submit Feedback" />
</form>


        <% foreach (Feedback feedback in ViewData.Model)
           {%>
            <p>
            <%=feedback.EntryDate.ToShortTimeString()%>
            --
            <%=Html.Encode(feedback.Message)%>
            </p>
        <% }%>


   </asp:Content>


Notice that the value of feedback.Message is HTML encoded before the value is displayed
with the following code:
            <%=Html.Encode(feedback.Message)%>

What does it mean to HTML encode a string? When you HTML encode a string, dangerous
characters such as < and > are replaced by HTML entity references such as &lt; and &gt;.
So when the string <script>alert("Boo!")</script> is HTML encoded, it gets converted
to &lt;script&gt;alert(&quot;Boo!&quot;)&lt;/script&gt;. The encoded string no
longer executes as a JavaScript script when interpreted by a browser. Instead, you get the
harmless page in Figure 3.
Figure 3 – Defeated JavaScript Attack


Notice that in the Index view in Listing 3 only the value of feedback.Message is encoded.
The value of feedback.EntryDate is not encoded. You only need to encode data entered by
a user. Because the value of EntryDate was generated in the controller, you don’t need to
HTML encode this value.

Approach #2: HTML Encode in the Controller
Instead of HTML encoding data when you display the data in a view, you can HTML encode
the data just before you submit the data to the database. This second approach is taken in
the case of the controller in Listing 4.

Listing 4 – HomeController.cs (HTML Encoded)
   using System;
   using System.Web.Mvc;
   using CustomerFeedback.Models;


   namespace CustomerFeedback.Controllers
   {
[HandleError]
        public class HomeController : Controller
        {
             private FeedbackDataContext db = new FeedbackDataContext();


             public ActionResult Index()
             {
                  return View(db.Feedbacks);
             }


             public ActionResult Create(string message)
             {
                  // Add feedback
                  var newFeedback = new Feedback();
                  newFeedback.Message = Server.HtmlEncode(message);
                  newFeedback.EntryDate = DateTime.Now;
                  db.Feedbacks.InsertOnSubmit(newFeedback);
                  db.SubmitChanges();


                  // Redirect
                  return RedirectToAction("Index");
             }
        }
   }



Notice that the value of Message is HTML encoded before the value is submitted to the
database within the Create() action. When the Message is redisplayed in the view, the
Message is HTML encoded and any JavaScript injected in the Message is not executed.
Typically, you should favor the first approach discussed in this tutorial over this second
approach. The problem with this second approach is that you end up with HTML encoded
data in your database. In other words, your database data is dirtied with funny looking
characters.
Why is this bad? If you ever need to display the database data in something other than a
web page, then you will have problems. For example, you can no longer easily display the
data in a Windows Forms application.
Summary
The purpose of this tutorial was to scare you about the prospect of a JavaScript injection
attack. This tutorial discussed two approaches for defending your ASP.NET MVC applications
against JavaScript injection attacks: you can either HTML encode user submitted data in the
view or you can HTML encode user submitted data in the controller.

More Related Content

What's hot

WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data ServicesWP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
MICTT Palma
 
Mockito junit
Mockito junitMockito junit
Mockito junit
Santiago Plascencia
 
Building richwebapplicationsusingasp
Building richwebapplicationsusingaspBuilding richwebapplicationsusingasp
Building richwebapplicationsusingasp
Giovanni Javier Jimenez Cadena
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
icubesystem
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
vchircu
 
AI: Mobile Apps That Understands Your Intention When You Typed
AI: Mobile Apps That Understands Your Intention When You TypedAI: Mobile Apps That Understands Your Intention When You Typed
AI: Mobile Apps That Understands Your Intention When You Typed
Marvin Heng
 
Micro services from scratch - Part 1
Micro services from scratch - Part 1Micro services from scratch - Part 1
Micro services from scratch - Part 1
Azrul MADISA
 
Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008
Jonas Follesø
 
16 interacting with user data contacts and appointments
16   interacting with user data contacts and appointments16   interacting with user data contacts and appointments
16 interacting with user data contacts and appointments
WindowsPhoneRocks
 
Android Cloud to Device Messaging Framework at GTUG Stockholm
Android Cloud to Device Messaging Framework at GTUG StockholmAndroid Cloud to Device Messaging Framework at GTUG Stockholm
Android Cloud to Device Messaging Framework at GTUG Stockholm
Johan Nilsson
 
MongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB Stitch Tutorial
MongoDB Stitch Tutorial
MongoDB
 
MongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDBMongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB
 
ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
Mădălin Ștefîrcă
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
Divyam Pateriya
 
Leture5 exercise onactivities
Leture5 exercise onactivitiesLeture5 exercise onactivities
Leture5 exercise onactivities
maamir farooq
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 

What's hot (16)

WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data ServicesWP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
 
Mockito junit
Mockito junitMockito junit
Mockito junit
 
Building richwebapplicationsusingasp
Building richwebapplicationsusingaspBuilding richwebapplicationsusingasp
Building richwebapplicationsusingasp
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
 
AI: Mobile Apps That Understands Your Intention When You Typed
AI: Mobile Apps That Understands Your Intention When You TypedAI: Mobile Apps That Understands Your Intention When You Typed
AI: Mobile Apps That Understands Your Intention When You Typed
 
Micro services from scratch - Part 1
Micro services from scratch - Part 1Micro services from scratch - Part 1
Micro services from scratch - Part 1
 
Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008
 
16 interacting with user data contacts and appointments
16   interacting with user data contacts and appointments16   interacting with user data contacts and appointments
16 interacting with user data contacts and appointments
 
Android Cloud to Device Messaging Framework at GTUG Stockholm
Android Cloud to Device Messaging Framework at GTUG StockholmAndroid Cloud to Device Messaging Framework at GTUG Stockholm
Android Cloud to Device Messaging Framework at GTUG Stockholm
 
MongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB Stitch Tutorial
MongoDB Stitch Tutorial
 
MongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDBMongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDB
 
ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
 
Leture5 exercise onactivities
Leture5 exercise onactivitiesLeture5 exercise onactivities
Leture5 exercise onactivities
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 

Viewers also liked

Demo-BW_Tutorial-USPG_%20Ed_1-3
Demo-BW_Tutorial-USPG_%20Ed_1-3Demo-BW_Tutorial-USPG_%20Ed_1-3
Demo-BW_Tutorial-USPG_%20Ed_1-3
tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
introduction
introductionintroduction
introduction
tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
tutorialsruby
 
tutorial7
tutorial7tutorial7
tutorial7
tutorialsruby
 
XSD%20and%20jCAM%20tutorial
XSD%20and%20jCAM%20tutorialXSD%20and%20jCAM%20tutorial
XSD%20and%20jCAM%20tutorial
tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
tutorialsruby
 
forms
formsforms

Viewers also liked (8)

Demo-BW_Tutorial-USPG_%20Ed_1-3
Demo-BW_Tutorial-USPG_%20Ed_1-3Demo-BW_Tutorial-USPG_%20Ed_1-3
Demo-BW_Tutorial-USPG_%20Ed_1-3
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
introduction
introductionintroduction
introduction
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
tutorial7
tutorial7tutorial7
tutorial7
 
XSD%20and%20jCAM%20tutorial
XSD%20and%20jCAM%20tutorialXSD%20and%20jCAM%20tutorial
XSD%20and%20jCAM%20tutorial
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
 
forms
formsforms
forms
 

Similar to ASPNET_MVC_Tutorial_06_CS

Adding a view
Adding a viewAdding a view
Adding a view
Nhan Do
 
Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_cs
Alfa Gama Omega
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
Ravi Bhadauria
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
Bhavin Shah
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
Stefano Paluello
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
jinaldesailive
 
Secure mvc application saineshwar
Secure mvc application   saineshwarSecure mvc application   saineshwar
Secure mvc application saineshwar
Saineshwar bageri
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
tutorialsruby
 
Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributes
sonia merchant
 
Ways to Set Focus on an Input Field After Rendering in React.pptx
Ways to Set Focus on an Input Field After Rendering in React.pptxWays to Set Focus on an Input Field After Rendering in React.pptx
Ways to Set Focus on an Input Field After Rendering in React.pptx
BOSC Tech Labs
 
Aspnet mvc tutorial_9_cs
Aspnet mvc tutorial_9_csAspnet mvc tutorial_9_cs
Aspnet mvc tutorial_9_cs
Murali G
 
React JS .NET
React JS .NETReact JS .NET
React JS .NET
Jennifer Estrada
 
Server side rendering with React and Symfony
Server side rendering with React and SymfonyServer side rendering with React and Symfony
Server side rendering with React and Symfony
Ignacio Martín
 
React js
React jsReact js
React js
Rajesh Kolla
 
JavaScript
JavaScriptJavaScript
JavaScript
Gulbir Chaudhary
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
IMC Institute
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
mwillmer
 
ASP.net Manual final.pdf
ASP.net Manual final.pdfASP.net Manual final.pdf
ASP.net Manual final.pdf
SwapnilGujar13
 
MVC Training Part 1
MVC Training Part 1MVC Training Part 1
MVC Training Part 1
Lee Englestone
 

Similar to ASPNET_MVC_Tutorial_06_CS (20)

Adding a view
Adding a viewAdding a view
Adding a view
 
Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_cs
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
 
Secure mvc application saineshwar
Secure mvc application   saineshwarSecure mvc application   saineshwar
Secure mvc application saineshwar
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributes
 
Ways to Set Focus on an Input Field After Rendering in React.pptx
Ways to Set Focus on an Input Field After Rendering in React.pptxWays to Set Focus on an Input Field After Rendering in React.pptx
Ways to Set Focus on an Input Field After Rendering in React.pptx
 
Aspnet mvc tutorial_9_cs
Aspnet mvc tutorial_9_csAspnet mvc tutorial_9_cs
Aspnet mvc tutorial_9_cs
 
React JS .NET
React JS .NETReact JS .NET
React JS .NET
 
Server side rendering with React and Symfony
Server side rendering with React and SymfonyServer side rendering with React and Symfony
Server side rendering with React and Symfony
 
React js
React jsReact js
React js
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
ASP.net Manual final.pdf
ASP.net Manual final.pdfASP.net Manual final.pdf
ASP.net Manual final.pdf
 
MVC Training Part 1
MVC Training Part 1MVC Training Part 1
MVC Training Part 1
 

More from tutorialsruby

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
tutorialsruby
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
tutorialsruby
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
tutorialsruby
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
tutorialsruby
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
tutorialsruby
 
CSS
CSSCSS
CSS
CSSCSS
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
tutorialsruby
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
tutorialsruby
 
Winter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20JavascriptWinter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20Javascript
tutorialsruby
 
Winter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20JavascriptWinter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20Javascript
tutorialsruby
 

More from tutorialsruby (20)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
Winter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20JavascriptWinter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20Javascript
 
Winter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20JavascriptWinter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20Javascript
 

Recently uploaded

Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Project Management Semester Long Project - Acuity
Project Management Semester Long Project - AcuityProject Management Semester Long Project - Acuity
Project Management Semester Long Project - Acuity
jpupo2018
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
fredae14
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 

Recently uploaded (20)

Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Project Management Semester Long Project - Acuity
Project Management Semester Long Project - AcuityProject Management Semester Long Project - Acuity
Project Management Semester Long Project - Acuity
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 

ASPNET_MVC_Tutorial_06_CS

  • 1. MVC :: Preventing JavaScript Injection Attacks The goal of this tutorial is to explain how you can prevent JavaScript injection attacks in your ASP.NET MVC applications. This tutorial discusses two approaches to defending your website against a JavaScript injection attack. You learn how to prevent JavaScript injection attacks by encoding the data that you display. You also learn how to prevent JavaScript injection attacks by encoding the data that you accept. What is a JavaScript Injection Attack? Whenever you accept user input and redisplay the user input, you open your website to JavaScript injection attacks. Let’s examine a concrete application that is open to JavaScript injection attacks. Imagine that you have created a customer feedback website (see Figure 1). Customers can visit the website and enter feedback on their experience using your products. When a customer submits their feedback, the feedback is redisplayed on the feedback page.
  • 2. Figure 1 – Customer Feedback Website The customer feedback website uses the controller in Listing 1. This controller contains two actions named Index() and Create(). Listing 1 – HomeController.cs using System; using System.Web.Mvc; using CustomerFeedback.Models; namespace CustomerFeedback.Controllers
  • 3. { [HandleError] public class HomeController : Controller { private FeedbackDataContext db = new FeedbackDataContext(); public ActionResult Index() { return View(db.Feedbacks); } public ActionResult Create(string message) { // Add feedback var newFeedback = new Feedback(); newFeedback.Message = message; newFeedback.EntryDate = DateTime.Now; db.Feedbacks.InsertOnSubmit(newFeedback); db.SubmitChanges(); // Redirect return RedirectToAction("Index"); } } } The Index() method displays the Index view. This method passes all of the previous customer feedback to the Index view by retrieving the feedback from the database (using a LINQ to SQL query). The Create() method creates a new Feedback item and adds it to the database. The message that the customer enters in the form is passed to the Create() method in the message parameter. A Feedback item is created and the message is assigned to the Feedback item’s Message property. The Feedback item is submitted to the database with the DataContext.SubmitChanges() method call. Finally, the visitor is redirected back to the Index view where all of the feedback is displayed. The Index view is contained in Listing 2.
  • 4. Listing 2 – Index.aspx <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="CustomerFeedback.Views.Home.Index" %> <%@ Import Namespace="CustomerFeedback.Models" %> <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server"> <h1>Customer Feedback</h1> <p> Please use the following form to enter feedback about our product. </p> <form method="post" action="/Home/Create"> <label for="message">Message:</label> <br /> <textarea name="message" cols="50" rows="2"></textarea> <br /><br /> <input type="submit" value="Submit Feedback" /> </form> <% foreach (Feedback feedback in ViewData.Model) {%> <p> <%=feedback.EntryDate.ToShortTimeString()%> -- <%=feedback.Message%> </p> <% }%> </asp:Content> The Index view has two sections. The top section contains the actual customer feedback form. The bottom section contains a For..Each loop that loops through all of the previous customer feedback items and displays the EntryDate and Message properties for each feedback item.
  • 5. The customer feedback website is a simple website. Unfortunately, the website is open to JavaScript injection attacks. Imagine that you enter the following text into the customer feedback form: <script>alert(“Boo!”)</script> This text represents a JavaScript script that displays an alert message box. After someone submits this script into the feedback form, the message Boo! will appear whenever anyone visits the customer feedback website in the future (see Figure 2). Figure 2 – JavaScript Injection
  • 6. Now, your initial response to JavaScript injection attacks might be apathy. You might think that JavaScript injection attacks are simply a type of defacement attack. You might believe that no one can do anything truly evil by committing a JavaScript injection attack. Unfortunately, a hacker can do some really, really evil things by injecting JavaScript into a website. You can use a JavaScript injection attack to perform a Cross-Site Scripting (XSS) attack. In a Cross-Site Scripting attack, you steal confidential user information and send the information to another website. For example, a hacker can use a JavaScript injection attack to steal the values of browser cookies from other users. If sensitive information -- such as passwords, credit card numbers, or social security numbers – is stored in the browser cookies, then a hacker can use a JavaScript injection attack to steal this information. Or, if a user enters sensitive information in a form field contained in a page that has been compromised with a JavaScript attack, then the hacker can use the injected JavaScript to grab the form data and send it to another website. Please be scared. Take JavaScript injection attacks seriously and protect your user’s confidential information. In the next two sections, we discuss two techniques that you can use to defend your MVC applications from JavaScript injection attacks. Approach #1: HTML Encode in the View One easy method of preventing JavaScript injection attacks is to HTML encode any data entered by website users when you redisplay the data in a view. The updated Index view in Listing 3 follows this approach. Listing 3 – Index.aspx (HTML Encoded) <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="CustomerFeedback.Views.Home.Index" %> <%@ Import Namespace="CustomerFeedback.Models" %> <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server"> <h1>Customer Feedback</h1> <p> Please use the following form to enter feedback about our product. </p> <form method="post" action="/Home/Create"> <label for="message">Message:</label> <br /> <textarea name="message" cols="50" rows="2"></textarea> <br /><br /> <input type="submit" value="Submit Feedback" />
  • 7. </form> <% foreach (Feedback feedback in ViewData.Model) {%> <p> <%=feedback.EntryDate.ToShortTimeString()%> -- <%=Html.Encode(feedback.Message)%> </p> <% }%> </asp:Content> Notice that the value of feedback.Message is HTML encoded before the value is displayed with the following code: <%=Html.Encode(feedback.Message)%> What does it mean to HTML encode a string? When you HTML encode a string, dangerous characters such as < and > are replaced by HTML entity references such as &lt; and &gt;. So when the string <script>alert("Boo!")</script> is HTML encoded, it gets converted to &lt;script&gt;alert(&quot;Boo!&quot;)&lt;/script&gt;. The encoded string no longer executes as a JavaScript script when interpreted by a browser. Instead, you get the harmless page in Figure 3.
  • 8. Figure 3 – Defeated JavaScript Attack Notice that in the Index view in Listing 3 only the value of feedback.Message is encoded. The value of feedback.EntryDate is not encoded. You only need to encode data entered by a user. Because the value of EntryDate was generated in the controller, you don’t need to HTML encode this value. Approach #2: HTML Encode in the Controller Instead of HTML encoding data when you display the data in a view, you can HTML encode the data just before you submit the data to the database. This second approach is taken in the case of the controller in Listing 4. Listing 4 – HomeController.cs (HTML Encoded) using System; using System.Web.Mvc; using CustomerFeedback.Models; namespace CustomerFeedback.Controllers {
  • 9. [HandleError] public class HomeController : Controller { private FeedbackDataContext db = new FeedbackDataContext(); public ActionResult Index() { return View(db.Feedbacks); } public ActionResult Create(string message) { // Add feedback var newFeedback = new Feedback(); newFeedback.Message = Server.HtmlEncode(message); newFeedback.EntryDate = DateTime.Now; db.Feedbacks.InsertOnSubmit(newFeedback); db.SubmitChanges(); // Redirect return RedirectToAction("Index"); } } } Notice that the value of Message is HTML encoded before the value is submitted to the database within the Create() action. When the Message is redisplayed in the view, the Message is HTML encoded and any JavaScript injected in the Message is not executed. Typically, you should favor the first approach discussed in this tutorial over this second approach. The problem with this second approach is that you end up with HTML encoded data in your database. In other words, your database data is dirtied with funny looking characters. Why is this bad? If you ever need to display the database data in something other than a web page, then you will have problems. For example, you can no longer easily display the data in a Windows Forms application.
  • 10. Summary The purpose of this tutorial was to scare you about the prospect of a JavaScript injection attack. This tutorial discussed two approaches for defending your ASP.NET MVC applications against JavaScript injection attacks: you can either HTML encode user submitted data in the view or you can HTML encode user submitted data in the controller.