Preventing Javascript Encoding XSS attacks in ASP.NET MVC

I just posted about cross-site scripting, or XSS attacks, in ASP.NET  - take a quick look at that post for some background on XSS attacks. I wanted to take a deeper look at Javascript Encoding XSS attacks. They're a particularly tricky form of XSS, since Javascript encoded values are valid HTML and will pass through default HTML encoding. Here's an example - let's assume we want to add a special welcome message to our home page if a UserName parameter is present so we can send out personalized links to the site in an e-mail promotion. We start by modifying the HomeController / Index method:

public ActionResult Index(string UserName)
    ViewBag.UserName = UserName;
    return View();

Then we add this information to the home index view, using Javascript so that we can make sure our users notice it:

Warning: Do not use this code - it's got an XSS vulnerability.

    ViewBag.Title = "Home Page";
<h2 id="welcome-message">Welcome to our website</h2>

@if(!string.IsNullOrWhiteSpace(ViewBag.UserName)) {
<script type="text/javascript">
    $(function () {
        var message = 'Welcome, @ViewBag.UserName!';

Sadly, we've just exposed our end users to an XSS vulnerability. Nonsense, you say! We tested that with the following url: http://localhost:58570/?UserName=<script>alert('pwnd')</script>

As you can see, it was detected by request validation:

2011-04-28 11h03_54

But since this value is being rendered via Javascript, it's vulnerable to Javascript encoding, which won't be picked up by the ASP.NET encoder. Try this url: http://localhost:58570/?UserName=Jon\x3cscript\x3e%20alert(\x27pwnd\x27)%20\x3c/script\x3e

2011-04-28 11h09_15

Note: Remember that we're using an alert here for demonstration purposes, but a real XSS attack will do something more sinister, designed so end users will never notice.

Fixing the Javascript encoding XSS vulnerability

There are two ways to handle this. The simplest is to use the @Ajax.JavaScriptStringEncode helper function, like this:

    ViewBag.Title = "Home Page";
<h2 id="welcome-message">Welcome to our website</h2>

@if(!string.IsNullOrWhiteSpace(ViewBag.UserName)) {
<script type="text/javascript">
    $(function () {
        var message = 'Welcome, @Ajax.JavaScriptStringEncode(ViewBag.UserName)!';

If we've included the AntiXSS library in our project, we can bring in the namespace with a @using Microsoft.Security.Application statement and call into the AntiXSS library's JavaScriptStringEncode function, which follows a whitelist approach to screen out alternate encodings and character sets.

@using Microsoft.Security.Application

    ViewBag.Title = "Home Page";
<h2 id="welcome-message">Welcome to our website</h2>

@if(!string.IsNullOrWhiteSpace(ViewBag.UserName)) {
<script type="text/javascript">
    $(function () {
        var message = 'Welcome, @Encoder.JavaScriptEncode(ViewBag.UserName, false)!';

Note: By default, the AntiXSS JavaScriptEncode function wraps the value in single quotes. With AntiXSS 4.1, there's an optional second parameter which allows turning that behavior off by passing in false, as shown above.

With either of the above two checks in place, the Javascript XSS injection is caught:

2011-04-28 11h22_21


  • thanks for shareing

  • Jon\x3cscript\x3e%20alert(\x27pwnd\x27)%20\x3c/script\x3e

  • @kkrasinski You had to try it, didn't you. ;-)

  • AntiXSS library is nice, but average application wanna accept things like ? and maybe other characters. Not having //00xx in the middle of
    the screen. And string.replace feels wrong, the weakest link rule kinda applies on this matter.

    So how do you fix this?

  • Hello to every body, itÂ’s my first pay a visit of
    this web site; this website carries amazing and genuinely
    fine information in favor of visitors.
    Around the globe, Online surfers seek ways to remain confidential
    to the Web pages many people go to. Those same users are already looking for
    strategies to access to well-liked Sites which can be clogged by overall sets of customers.
    Individuals have got used the anonymizer and also Website proxies companies to live secret or get
    at on the net TV, Xbox live Reside, Hulu, along with
    key information internet sites from around the globe.

    The favored Ruskies anonymizer vendor HideME.
    ru provides as a final point developed a good Uk Internet site
    with regard to their products and services referred
    to as InCloak.internet. “Our providers allow for people to modify his or her
    real Ip to some presented mysterious Ip address that
    permits these to surf the Web safely and securely devoid of making a brief history along with obtain 100-percent access
    to in the past obstructed Sites,” claimed a strong InCloak.

    net consultant.

    The actual wide web anonymizer makes it possible for the person to create a hosting server nation
    with origin, pick virtually any obtainable IP address, filtration system malevolent
    pieces of software, lower ad banners and include favorite and sometimes went to Web sites towards
    programÂ’s alexa toolbar. Although the anonymizer works for a special preferred method, the
    vendor supplies a electronic Non-public Circle (VPN) known
    as OpenVPN. The VPN customer assistance presents greatest anonymity as well
    as to safeguard all of programs that will use the Online through the
    subscriber’s computer system. “The major VPN edge on every proxy as well as anonymizer is
    definitely the method it offers privacy plus
    to safeguard the complete personal computer immediately,” said the

    InCloak.internet provides Web page instruments such as World-wide-web proxies, proxy listing, Checker and even more
    for as few as $0.2005 on a daily basis or even VPN access
    at as low as $0.11 per day by using one-year dues.

    Further blueprints include each day, month-to-month as
    well as two-year subscriptions. Your advanced access system
    gives total accessibility anonymizer (and also VPN,
    if the value is usually bought with this alternative) with out restrictions
    with use. A number of more features are also provided.

  • performers for individuals ambitions not caring to tbeneficiaries

  • Hi there, I read your blogs on a regular basis.
    Your humoristic style is witty, keep up the
    good work!

  • In fact no matter if someone doesn't understand then its up to other visitors that they will assist, so here it happens.

  • The write-up offers established beneficial to myself.
    It’s really educational and you're simply certainly quite experienced in this region. You possess exposed my own eye for you to different opinion of this specific matter using interesting and reliable content.

  • Once the game is 80% complete you will need to work on the sound. they simply need to learn that you will not be able to appease everyone of your player-base. Next Jim Deacove developed a few of his own board games based on the principles of cooperation, group strategy and joint problem solving.

  • Wonderful article! That is the type of info that are supposed to be shared across the internet.

    Shame on the search engines for no longer positioning this submit upper!
    Come on over and discuss with my site . Thanks =)

  • Your should see something similar to the illustration above.
    If you already have your Facebook fan or business page created you will need to have
    25 fans or "LIKES" in order to create a custom URL. It allows you to see their picture and decide if
    you should add them to your friends.

  • Multiplayer versions is more exciting as in this, you'll be able to team up or even contend with other participants to defeat the enemies. While having a passion for playing games is important, getting a rewarding career in game design will require students to be a cut above the competition. It can go as far as ruining their experience since it is the last interaction they have with a game.

  • In most cases they are, but when it comes to updates,
    patches, etc to the mmorpgs. If you don’t have much skill in programming, but
    still think that creating and developing games is the most suitable for you, there are special courses that will
    give you training in graphic designing, game development, and computer animation.
    As ever we strive to help our customers make informed decisions and understand where their r4 cards are coming from.

  • Much like Safari, the Camera app, the App Store and i -
    Pod, Game Center has no option to be deleted when editing your apps.
    It should come as no surprise that i - Tunes is loaded full of pirate apps for i - Phone, i - Pod Touch, and i - Pad.
    Are you a Kansas City Chiefs or Pittsburgh Steelers fan.

  • Webcams can do a lot of things, such as video conferencing, virtual advertising, workplace or home surveillance, event broadcast, and
    many other functions. On the bright side,
    the actual functionality of the integration is perfect.

    Up to five profiles can be stored on the gameboard at once and macros can be created while actually
    gaming real time.

  • Hi I am so glad I found your website, I really found you by error,
    while I was researching on Yahoo for something else, Regardless I
    am here now and would just like to say cheers for
    a tremendous post and a all round thrilling blog
    (I also love the theme/design), I don’t have time to read it all
    at the minute but I have book-marked it and also added
    in your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the excellent

  • Psychological Help, Tips and Advice, learn how to get
    your Ex Boyfriend, Girlfriend, husband, wife or spouse back.
    These are reaching thousands of people at a time who
    recognize the self help benefits and pass them on to friends who
    do the same and they become viral. Remember fall in
    love poems should say the exact thing you feel without
    hesitation and fear of being embarrassed, either you
    write fall in love poems yourself or choose from the famous fall
    in love poems.

  • May I simply say what a relief to discover somebody who truly understands what they're talking about over the internet. You definitely understand how to bring a problem to light and make it important. More and more people have to read this and understand this side of your story. I was surprised that you aren't more popular
    since you certainly have the gift.

  • How often have you bought headsets but discarded them after some time, once
    they didn. Which means that you will only end up spending $47 on this unit.
    Another great aspect of this remote is that it comes with a
    recharging dock.

  • This has led to an explosion of new radio stations and new ways
    to access existing radio stations with new facilities.
    One thing about conventional radio that’s gotten quite annoying over
    the years is that the networks have switched around trying to find programming so often that you don’t even know where to go for your
    musical preference anymore. One of the very best reasons to include internet radio as
    part of your online marketing plan is because of the search engine optimization opportunities.

  • Inject some personality and colour into her eyewear with these Wayfarer sunglasses from Ray-ban. Made with impact resistant, optical precision lenses designed to be worn in moderate sunshine, these are great all year round. The recognisable branding adds a touch of classic appeal, whilst the pop of colour keeps them youthfu

  • Having read this I believed it was very informative. I appreciate
    you finding the time and energy to put this content
    together. I once again find myself spending a significant
    amount of time both reading and commenting. But so what, it was still worth it!

  • With internet radio, you get pretty much what you want, when you
    want. The table top radio connects to the internet using Wi-Fi or Ethernet cable, and
    searches for stations by country, genre or call letters.
    Many think that having thoughts of supposed happiness that will never come
    is futile and that they are only giving false hopes to those
    who need them the most.

  • With internet radio, you get pretty much what you want, when you
    want. The table top radio connects to the internet using Wi-Fi or Ethernet cable, and
    searches for stations by country, genre or call letters.
    Many think that having thoughts of supposed happiness that will never come
    is futile and that they are only giving false hopes to those
    who need them the most.

  • This article is really a fastidious one it helps new web
    users, who are wishing for blogging.

Comments have been disabled for this content.