Site icon Astra Security Blog

A Step-By-Step Guide On PHP Security

As of 2020, over 79% of server-side language was PHP. Most of these are content management systems including eCommerce sites and WordPress. As it is such a widely-used programming language for websites, including Facebook and Wikipedia, it is under continuous threat of attacks and exploitations. PHP security has become very important to keep websites and platforms safe from cyber-attacks and hacks.

Due to the advancement in cyber-attacks and hacking techniques, the risks of attacks have become greater. To add to that, PHP is fragile too. A small bug or coding error can make your PHP website vulnerable and prone to attacks.

After putting in so much effort into building a PHP website getting hacked is the last thing on anyone’s mind. But to really make your PHP tech stack impenetrable and unhackable, you have to ensure rock-solid security.

To help you with that, we have put together this extensive PHP security guide. This guide will help you identify PHP security threats and ways to strengthen your website’s security. It also has some effective security measures that you can follow to keep its security intact.

All that in a minute, but first, let’s look at these PHP hacking statistics.

Some statistics about PHP security

PHP Security threats and fixes

Over the years hackers have invented smart ways to trick and bypass every little feature on a PHP website. Some of the most popular attacks with hackers are:

1. SQL Injection

SQL Injection is a very common form of attack accounting for about two-thirds of all web attacks. With improper or ineffective code leading to a SQL Injection attack, a data breach can occur resulting in the leakage of important details such as credit card details and credentials, to name a few. It can also compromise an entire web server. Below is an example of an insecure code snippet:

Type caption (optional)

An attacker can send in a query that will be executed along with the query, like below:

Type caption (optional)

The above query will modify the code as follows:

Type caption (optional)

By using scripts similar to the above code, attackers can get access to all data tables and sensitive information.

The solution to this is to use parameterized SQL queries and PHP Data Objects (PDO). Using parameterized queries will let the database differentiate between the data and query parts. Thus, it can then treat the two parts separately. PDO is included in PHP version 5.1 and later, and you can use it to execute prepared snippets in your code.

To further protect your website you can do the following:

2. Directory Traversal

In this attack, one can view or execute crucial files and folders that should be inaccessible to everyone but the administrators. These files may reside outside the root folders and with incorrect file permissions or coding error these files may be vulnerable to unauthorized access. The below code sample will allow for queries that can access files:

Type caption (optional)

If an attacker enters “/etc/passwd” as an argument then it will return this file as it is accessible to all. To prevent it you need to apply proper permissions based on the user’s status.

3. Cross-Site Scripting (XSS attacks)

XSS vulnerabilities are very common and this makes this attack widely used. In this attack, client-side scripts are inserted into the output of a webpage and then these scripts are executed on the user’s system. Attackers use this attack to steal information, credentials, or cookies, to name a few. XSS attacks are also common in websites that display external data.

The following vulnerable code snippet can be exploited to launch an XSS attack:

Type caption (optional)

When the attacker passes codes such as <script>alert(“XSS”);</script> to this webpage, it will get executed and display “XSS”. This shows how external malicious codes can be injected and executed to cause damage.

You can prevent such attacks by following the below steps:

4. Cross-site request forgery

Cross-site request forgery attacks are done from the user side and exploit the trust that webpages have on users. Users having higher privileges face the highest threats. This attack is less popular than others and is thus more dangerous. Protecting your website from such attacks is also more complicated as compared to the ones mentioned above. When users log into a website, they receive certain privileges such as accessing pages not available to others. Using these privileges, attackers can design HTTP requests that are then executed by the webpage. Attackers can use this technique to access the database or extract important information.

The below PHP security steps will help you prevent such attacks:

5. Password storage

With the increasing cases of credential theft and data dumping on the dark web, storing credentials such as passwords securely has become much more important. Attackers can leverage vulnerabilities such as SQL Injection or XSS attacks and access passwords stored within the website. In case there is a breach of security, it is important to ensure that attackers are unable to decode the passwords and cause further damage. There are two important ways to securely store passwords, using a hashing algorithm and salt.

The most common hashing algorithm is MD5 and it is the fastest. However, it is easy and fast to crack. You can use the password_hash() function instead of MD5, as it is more secure. This function generates a sixty character hash based on BCRYPT (CRYPT_BLOWFISH algorithm). It accepts three parameters: the password, hashing algorithm (by default uses BCRYPT), and an optional value such as cost. You can verify the hashed password by using password_verify().

Type caption (optional)

Salt is a random string that is added to the password before hashing it. A long and random salt will effectively make cracking methods ineffective. Some more PHP security tips to ensure that passwords are safely stored:

Related Guide – PHP Salts & Password Hashing

6. Session hijacking

Session hijacking attacks are the most common form of session attacks. This attack includes accessing an unsuspecting user’s session and then launch further attacks. Once hijacking is successful the attacker can perform all tasks that the original user had permission for. In case the user’s session was to log into their bank accounts, attackers can make transfers or take over the account entirely. This attack can also provide access to company-wide networks, in case the session belongs to an employer in an organization.

This attack can be done by simply having the session identifier. To prevent session hijacking attacks, websites have to verify a couple of details in the HTTP request and analyze them to identify a genuine session. Attackers trick the website by passing in such information that is then interpreted to be authentic and allows the session to continue. An effective way to stop such attacks is to look for such fields that will be difficult for the attacker to generate. These fields can then be used to verify the authenticity of the session. Fields such as user-agent are difficult to replicate by an attacker. Also, checking for location details and browser information and matching them with historical data can provide some insights as to the current session.

In order to not impact the user experience, if, in doubt, websites can request a password entry to authenticate. Users will appreciate the extra precaution and the system will not lock out a genuine user.

7. Session Fixation

In session fixation, the attacker sends the user a valid session ID and then uses that to get into the website. The attacker creates a session and then waits for a user to use the attacker’s session ID to log into the website. Then the website will consider the session authentic and allow the attacker to use this session without any interruptions.

If a website extracts session IDs from URLs or forms, it is easy for attackers to use this method of attack. In this case, the user only has to click on the link, and the website will then append the attacker’s session ID to the user. This can also be done with cookies by setting it to the attacker’s session ID.There are two major ways to stop such attacks:

Session data exposed

If you use a shared server then your sessions might be stored in a shared session store. If this is the case with your server, then your website’s sessions are vulnerable to unauthorized access. In this, with the below code, attackers can easily access the session stored in the “/tmp” folder by default:

Type caption (optional)

This is a simple PHP query that can use the server privileges to access and read the files. To prevent this, you can use safe_mode directives but as it only works for PHP, attackers can use other languages to do this. A better solution is to avoid using a shared session store. Store the data in a database that has unique access credentials related to your account. To do this, you can use session_set_save_handler() function to replace PHP’s default handling of sessions with your own functions.

Related guide – Clickjacking in PHP

XML Attacks

For this attack, attackers exploit the parsing feature of XML inputs. If XML parser is weakly configured then it will parse an XML input with reference to external sources. There are two major vulnerabilities that can be exploited: XML External Entity and XPath Injection. These attacks form a base for further attacks such as remote file inclusion exploits.XPath Injection is similar to SQL Injection but is applicable to XML documents. As this type of attack is rare, there is comparatively less inbuilt functions and mechanisms to protect against it. You can use a set of whitelisted characters to make sure that unwanted or special characters are not accepted.

Type caption (optional)

PHP security tips and tricks

Security is an essential part of the development and just as attacks have evolved over time, security has to evolve too, to match the pace. Security of a website is not only important to the website owner but also users who risk their information in case of cyber-attacks. We need to understand a few points regarding security to enable us to take proper steps:

As discussed above, PHP security is always under threat but it can be tackled if we implement a few essential security protocols and follow guidelines. Below are some security tips that will help in strengthening PHP security:

Validating inputs

For PHP security, having client-side data validation is not enough. It can be easily broken through, for example, if an attacker removes any JavaScript from the source code of a website and then submits a form without any verification, it will not be detected if there is no server-side validation. This opens up a way for attacks such as SQL Injection, XSS or CSRF attacks. Both the user side and server-side validation is essential for PHP security.

Blacklisting

Blacklisting can be circumvented by attackers through trial and error methods. It does not always protect against malicious inputs but in some cases, it can protect against known or common attack methods. You can blacklist common strings used by attackers or special characters that are known to be dangerous.

Research

In the development phase, researching about bugs or security threats is useful as we come across several methods and solutions. However, copy-pasting those codes is not a good idea. Your website might be different from the one the solution if from. Also, they might be outdated and you will be putting your entire website server at risk. If you copy codes from several sources then there is a change that all code snippets might not work together and linking them will require substantial effort. Research helps in answering a lot of questions, however, using it as a source of understanding is a better option than copying codes.

Strong passwords

This cannot be stressed enough. A major portion of attacks is possible due to weak or easily breakable credentials. A strong password can be alphanumeric with both lower and upper case characters. Another option is to use phrases as it will take considerable time and computational power to crack such passwords. Also, make sure that all default passwords are changed, by both users and admins. Assist your users in using a stronger password by making them aware of its importance and guidelines they can follow.

Multi-factor authentication

Multiple level authentication has become the new security standard. In this case, attackers will be unable to cause any damage if they have the credentials as it will require an additional field such as OTP (One-time passwords) to log in. In 2 Factor Authentication, users will have to enter an additional code after they use their credentials. To get through this, attackers will require the credentials as well as control of the device receiving OTP.

Related Guide – PHP File Permissions

Data filtering

Proper data filtering will protect your website from malicious code snippets and code injection attacks. There are multiple ways to enable effective data filtering. Include method means having a single module dedicated to security that is placed at the beginning of all scripts that are publicly accessible. Multiple security checkpoints and protocols can be included. For filtering data, you can use a whitelist approach and include several combinations of characters and strings.

Using a firewall

A firewall is all-round protection for your website. It filters all unwanted and malicious data and requests from reaching your website. A strong firewall like Astra will offer complete protection from attacks such as SQL Injection, DDoS, and malware, to name a few.

At Astra, we have intelligent & efficient tools and security expertise to offer you complete protection against all cyber threats. Dashboard and reports will keep you updated with everything that goes on with your website.

How Astra Web Application Firewall protects your website

PHP security tips listed in this guide will help you keep your website safe and ensure that data on your website stays safe. Security is dynamic and ever-changing, so staying updated with all the latest developments will help you protect your website from advanced attacks. Using a security service will help you in this without any hassle. Leaving your PHP security to an expert like Astra is probably a good idea. A lot of effort and hard work goes into creating a website, and protecting it is a tough but important task. With proper understanding and accurate information, you can keep attackers at bay.

Exit mobile version