@Tom they're upset about bits of it: Where people actually want to let some HTML through. In your case, you don't, so you don't need to worry about that particular problem.
–
George Stocker♦Sep 27 '12 at 13:00

3

@GeorgeStocker Are you still planning to update your answer? Cheers
–
TomOct 1 '12 at 11:41

For output encoding, Server.HtmlEncode(p.message) should do the trick (so what you have currently in your example will work, don't need to do the Regex replace if you don't want to. The output encoding will prevent XSS). Here I am assuming you want to do HTML encoding and not Url encoding or the like.

Looks like you are using the .NET MVC framework. You could use DataAnnotations to preform white-list validation (allow only safe characters) versus black-listing. I would look at using the RegularExpressionAttribute. For example:

To protect against the web's security shortcomings:

Try to mitigate damage. Use antiforgery tokens, ensure that you only accept ssl for certain actions. Ensure that cookies are appropriately secured. Overall, minimize the attack surface and put roadblocks to make it harder.

To protect against users input:

Parametrize user input, if you can't parametrize, encode, but be very careful with encoding, many many exploits have been caused by improper encoding. Encoding also depends upon where and how the input is going to be used.
Constrain and validate user input, ensure that server only accepts certain domains of input. And as before, understand all the ways the input is going to be used.

Handling response from the web server:

Ensure that you got an OK status from the web server. If you didn't, handle each response appropriately. Generally jquery.ajax gives you the option to handle all the responses with done, fail, always, and statusCode, refernce jquery documentation about how to do this properly.