Security Tips To Protect Your PHP Application
PHP is a lightweight yet very powerful backend programming language. It powers around 80% of the global web applications, making it one of the most commonly used languages in the development world.
The reason for its popularity and wide usage is its easy coding structure and developer-friendly functions. There are a lot of CMS and frameworks built on top of PHP and thousands of known developers from all around the world are a regular part of its community.
One great example is WordPress.
When PHP applications are deployed on live servers, it may face several instances of hacking and web attacks, which makes its site data extremely vulnerable to get stolen. It is one of the most debated topics in the community, that how to build a completely secure application, keeping in check all the core objectives of the project.
Despite their best efforts, developers always stay wary of the hidden loopholes that go unnoticed while developing an application. These loopholes can seriously compromise the protection of vital site data on any web hosting for PHP MySQL apps, leaving them vulnerable for hacking attempts.
So, this article is all about some useful PHP security tips that you could use wisely in your projects. Using these little tips, you can make sure that your application always stands high on security checks and never gets compromised by any external web attacks.
Cross-Site Scripting (XSS)
Cross-Site Scripting is one of the most dangerous external attacks performed by injecting any malicious code or script into the website. It can affect the cores of your application, as the hacker can inject any type of code into your application without even giving you a hint. This attack mostly occurs in those websites that admit and submit user data.
In an XSS attack, the injected code replaces the original code of your website, yet works as an actual code disrupting site performance and often stealing the data. The hackers bypass the access control of your application, getting access to your cookies, sessions, history, and other vital functions.
You can counter this attack by using HTML special chars & ENT_QUOTES in your application codes. Using ENT_QUOTES, you can remove single and double quote options, that allows you to purge out any possibility of the cross-site scripting attack.
Cross-Site Request Forgery (CSRF)
CSRF hands out complete application control to the hackers to perform any undesirable action. With complete control, hackers can carry out malicious operations by transferring infected code to your website, resulting in data theft, functional modifications, etc. The attack forces the users to change the conventional requests to the altered destructive ones, like transferring funds unknowingly, deleting the entire database without any notification, etc.
The CSRF attack can only be initiated once you click on the disguised malicious link sent by the hacker. This means that if you are smart enough to figure out the infected hidden scripts, you can easily rule out any potential CSRF attack. Meanwhile, you can also use two protective measures to fortify your app security, i.e. by using the GET requests in your URL and ensuring the non-GET requests only generate from your client-side code.
Session Hijacking
Session hijacking is an attack through which the hacker steals your session ID to gain access to the intended account. Using that session ID, the hacker can validate your session by sending a request to the server, where a $_SESSION array validates its uptime without keeping in your knowledge. It can be performed through an XSS attack or by accessing the data where the session data is stored.
To prevent session hijacking, always bind your sessions to your actual IP address. This practice helps you to invalidate sessions whenever an unknown violation occurs, immediately letting you know that someone is trying to bypass your session to get the access control of the application. And always remember, not to expose IDs under any circumstances, as it can later compromise your identity with another attack.
Prevent SQL Injection Attacks
The database is one of the key components of an application that mostly gets targeted by hackers via an SQL injection attack. It is a type of attack in which the hacker uses particular URL parameters to get access to the database. The attack can also be made by using web form fields, where the hacker can alter data that you are passing through queries. By altering those fields and queries, the hacker can get control of your database and can perform several disastrous manipulations, including deleting the entire application database.
To prevent SQL injection attacks, it is always advised to use parameterised queries. This PDO queries properly substitute the arguments before running the SQL query, effectively ruling out any possibility of a SQL injection attack. This practice not only helps you to secure your SQL queries but also makes them structured for efficient processing.
Always Use SSL Certificates
To get end-to-end secured data transmission over the internet, always use SSL certificates in your applications. It is a globally recognized standard protocol known as Hypertext Transfer Protocol (HTTPS) to transmit data between the servers securely. Using an SSL certificate, your application gets the secure data transfer pathway, which almost makes it impossible for hackers to intrude on your servers.
All the major web browsers like Google Chrome, Safari, Firefox, Opera, and others recommend using an SSL certificate, as it provides an encrypted protocol to transmit, receive, and decrypt data over the internet.
Hide Files from the Browser
There is a specific directory structure in the micro PHP frameworks, which ensures the storage of important framework files like controllers, models, the configuration file (.yaml), etc.
Most of the time, these files aren’t processed by the browser, yet they are kept being seen in the browser for a longer period, building a security breach for the application.
So, always store your files in a public folder, rather than keeping them in the root directory. This will make them less accessible in the browser and will hide the functionalities from any potential attacker.
Validation
To guarantee your PHP application security, never rely solely on client-side user data validation as it can be easily bypassed. For instance, an attacker can disable/remove any JavaScript from the source code of a page and submit a form without any validation. If the script that accepts input does not have any server-side validation, it is possible that web application security issues such as SQL Injection (SQLi), Cross-site Scripting (XSS), or Cross-site Request Forgery (CSRF) can be exploited. A combination of both server/client-side validation is ideal to protect your web pages against malicious JavaScript or rogue SQL queries.
Blacklisting
There are numerous ways to make the same request or action. In most cases, blacklisting can be circumvented and sometimes it is very difficult to include every possible forbidden input. Blacklisting should never be used as the only security measure. However, there are cases when blacklisting can be useful. For example, having a list of strings that are commonly used in attacks can help block automated bots/scripts.
Software Update
This cannot be stressed enough. Not only in PHP security, keeping software up to date is critical. Updates commonly include security fixes that patch various vulnerabilities (publicly known or not). This relates to all the elements that form a web application: the operating system, web server software, PHP software, as well as any open-source solutions based on PHP such as WordPress. Many companies have critical servers and services running on outdated software. Reasons for this include application compatibility issues, security ignorance, or lack of policies. This, however, leaves their systems and services open to attacks.
Research
It is very common for developers to search online to find answers/solutions to problems that they are facing with their code or projects. This is perfectly normal and it is one of the powerful characteristics of the Internet. However, it is also common for people to copy whatever piece of code they find online into their PHP files just because it has a lot of votes or because it appears to be working. This is wrong for many reasons. There are numerous sources that have insecure or outdated code snippets. By using them, you put your entire site or web server at risk.
Another reason for which you should never blindly copy ready-made PHP code is that at some point you end up having a web application with different code blocks from different people and you have no idea how it works, why it works that way, and if it’s working as it should. It is very important to spend time to study and understand the mechanics behind various functions or technologies that you are interested in. Not only will you be able to identify insecure or buggy code, but you will also write your own scripts in your own style. It is much easier to troubleshoot your own code than somebody else’s.
Rate Limit and Lockout
If you are building a web application that uses a login system or shows dynamic content based on user input, you should consider implementing rate limiting. The rate limit is when a system is configured to allow only a certain number of requests to be processed/served within a time window. For instance, to allow 10 requests to be made in 20 seconds. Depending on the case, if the limit is exceeded requests can be dropped, blocked, or queued. This can be particularly useful against brute-force attacks on login forms where a very large number of requests is required to crack a password. It can also be useful to protect against other attacks as it will significantly slow down automated scanners, crawlers, or bots that initiate hundreds or thousands of requests to identify vulnerabilities.
Slowing down an attacker can help. However, they might have all the time in the world to complete their attack. This is where a lockout comes in. In case of a login form, if an account has N unsuccessful login attempts, it should be blocked for a period of M. Combined with a notification system to alert an admin, this can effectively mitigate various attacks.
Strong Password Enforcement
In the third part of this series, we talked about the importance of password storage in web applications. It is equally important to use strong passwords – both for administrators and regular end users. A web application should not allow users to define a weak password for their account as this would make cracking easier. Even with a rate limit or lockout mechanism in place, if a password is extremely common or easy, it might be guessed within the allowed fail/rate limit.
Weak Passwords
A password can be qualified as weak if it fits into one or more of the following categories:
- It is too short (<6 characters), for example, passme
- It consists of only numbers, for example, 181759
- It consists of only lowercase characters, for example, mypassword
- It consists of only uppercase characters, for example, MYPASSWORD
- It contains dictionary terms and/or common words, for example, football, house, dog, car
- It is the software default, for example, admin, root, password
- It has letters or numbers in a sequence, for example, qwerty123
- It contains the username, for example, vinay1234 (where the username is vinay)
Strong Passwords
A strong password should
- Be more than 8-10 characters long
- Contain a combination of uppercase characters, lowercase characters, numbers, and symbols in a random order
- Not have repeated characters or a pattern
- Not include common or dictionary words
Example of a strong password: 8a<:7],)>En1C$M{JH>08hv!s
Multi-Factor Authentication (MFA)
MFA refers to the process in which a user must be authenticated against a system using more than one method. The first and most common method of authentication is a password. However, passwords can be cracked/leaked or stolen. With MFA applied, the user needs to provide additional methods of authentication such as verification via email, telephone (SMS or voice call), or token devices. This ensures that even if the user’s password is leaked, their account will not be compromised (unless the attacker has access to all the authentication methods that the victim has set up). It is very easy to implement and it should be considered when building a web application.
Logging
Logs are an extremely important part of a system. They can be used to troubleshoot errors, gather statistics, and provide admin information regarding the health and security of an application. Monitoring the logs can be useful to understand what, when, and why happened. It is recommended to keep daily logs of critical systems and applications and have them analysed to identify malicious activities. Ideally, they should be backed up to a remote location to avoid tampering by an attacker in case the system is compromised. Avoid storing logs in publicly accessible directories and make sure that they have correct permissions.
Leave a Reply
You must be logged in to post a comment.