아래 예제 MVC Project를 보면서 쉽게 이해하자.
1. We start by modifying the HomeController / Index method
namespace XssAttackSample.Controllers
{
public class HomeController : Controller
{
public ActionResult Index(string UserName)
{
ViewBag.UserName = UserName;
return View();
}
public ActionResult About()
{
return View();
}
}
}
2. Then we add this information to the home index view,
@{
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!';
$("#welcome-message").html(message).hide().show('slow');
});
</script>
}
3. We tested that with the following url: http://localhost:13810/?UserName=hello. It seems to be OK.
4. But if we tested that with the following http://localhost:13810/?UserName=<script>alert('pwnd')</script>
As you can see, it was detected by request validation:
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:13810/?UserName=Jon\x3cscript\x3e%20alert(\x27pwnd\x27)%20\x3c/script\x3e
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
A. There are two ways to handle this. The simplest is to use the @Ajax.JavaScriptStringEncode helper function
@{
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)!';
$("#welcome-message").html(message).hide().show('slow');
});
</script>
}
B. 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)!';
$("#welcome-message").html(message).hide().show('slow');
});
</script>
}
5. With either of the above two checks in place, the Javascript XSS injection is caught: