0

I'm currently reading up on .net MVC and have just reached the security chapter of the book. I've known about xss, and I never trust any user input without sanitizing it first (usually with html encoding or even something like php's strip_tags). Up until this point I was not familiar with Javascript encoding strings for protection. One of the examples in the book had a user pass in a string like:

\x3cscript\x3e%20alert(\x27test\x27)\x3c/script\x3e

So naturally when I learn something new I want to test it. I created this:

public ActionResult Index()
    {
        ViewBag.test = "\x3cscript\x3e%20alert(\x27test\x27)\x3c/script\x3e";
        return View("index");
    }

and this view code that prints out the test string on the page:

@ViewBag.test

However, I cannot get this alert box to show at all. When I view source on the page I get

<script>%20alert('test')</script>

I've tried playing with it a few different ways

  1. Passing the @ViewBag from a query string
  2. putting the viewbag print inside of existing script code (this is how the book had it)
  3. Replacing the %20 with actual spaces
  4. Using jquery to replace html with ViewBag.test:
    $('#inject_here').html('@ViewBag.test');

Nothing I try will execute this code (which I guess is a good thing?). Now I know there wouldn't be a portion of this book dedicated to something that didn't work in the first place, so the problem must be on my end. I just don't know what it is. Any one have any ideas?

0

1 Answer 1

1

asp.net MVC tries to take care of this issue for you. It automatically encodes output. You must go out of your way to print out a string without html encoding it.

@Html.Raw(ViewBag.test)

There are places where you will end up doing this in an application. Ideally you would have templates that models are rendered into. But, in some cases you'll have sections of HTML that are dynamic and need to be printed as is. In those cases you'll use the Html.Raw and just need to be aware that you must validate the sanity of the content.

Sign up to request clarification or add additional context in comments.

1 Comment

You're right. turns out this portion of the book was only showing conceptual examples of xss, not working code. Guess I skipped over that part :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.