From your code it is not clear where your controlId
, type
and post
variables are coming from.
return String.Format(CultureInfo.InvariantCulture, "<input type=\"hidden\" id=\"{0}\" post=\"True\" type=\"{1}\" value=\"{2}\" />", controlId,type,post)
Unless they are set by yourself (e.g. type = "hidden";
) you should assume that they are unsafe (even if they are from your own database). Now unsafe doesn't mean inherently unsafe, it means unsafe for the context that they are output (HTML in this case).
e.g. If they entered " /><script>alert('foo');</script><
in one of your variables, it would cause the JavaScript to be executed. This is because your code would render the following in HTML if post
was changed:
<input type="hidden" id="bar" post="True" type="hidden" value="" /><script>alert('foo');</script>"< />
To make them safe for HTML, you must use the Server.HtmlEncode()
function. The safe version of your code is:
return String.Format(CultureInfo.InvariantCulture, "<input type=\"hidden\" id=\"{0}\" post=\"True\" type=\"{1}\" value=\"{2}\" />", Server.HtmlEncode(controlId), Server.HtmlEncode(type) , Server.HtmlEncode(post))
This will prevent anyone entering the "
character in any of the variables and breaking out of your HTML string (it will become "
and will be rendered by the browser as "
).
@Vineet Verma's answer deals with Cross Site Request Forgery (XSRF), which is completely different to Cross Site Scripting (XSS).
@akirilov's answer suggests to encode inputs. In my opinion this is wrong because input is only unsafe when output. Outputting to JSON for example requires completely different encoding to HTML. This is why you should generally allow any input into your application, but encode when output. Check out the XSS (Cross Site Scripting) Prevention Cheat Sheet and follow their guidelines when outputting to different contexts.
Input validation only makes sense for things that you can easily validate (like a social security number). It is much harder to validate that an input does not contain harmful JavaScript code. This is why it is better to encode when output which will make your application safe from XSS.