Reputation: 10830
I have a MVC 4 application in which i am trying to simulate an XSS attach. I just have a button and text box which will just output the value entered in the text box as below. When i enter <script>alert('xss')</script>
in the text box automatically an exception is showing stating dangerous value was detected from the client. How can I prevent this atleast for learning purposes
Now the exception does not come after following Furqan's advice. However I would expect the alert message box to appear but it does not and instead the script tag appears as a string.
Can somebody explain why it is this way?
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<h2>@ViewBag.Message</h2>
<form method="post" action="/home/index">
<input type ="text" id="text" name="search" value="@ViewBag.Message"/>
<input type="submit" />
</form>
These are my controller actions.
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string search)
{
ViewBag.Message = search;
return View();
}
Upvotes: 0
Views: 519
Reputation: 12599
MSDN has a great article on preventing Cross Site Scripting:How To: Prevent Cross-Site Scripting in ASP.NET.
You may also like to try some security tools such as Netsparker that will test for an array of common, and less common, attack vectors.
Upvotes: 1
Reputation: 49095
You need to use both [ValidateInput(false)]
on Action and @Html.Raw
in the View:
Controller:
[HttpPost]
[ValidateInput(false)]
public ActionResult Index(string search)
{
ViewBag.Message = search;
return View();
}
View:
<h2>@Html.Raw(ViewBag.Message)</h2>
Upvotes: 3