Discover LinuxSecurity Features
A Linux Admin's Getting Started Guide to Improving PHP Security
Running PHP on a Linux web server is a prerequisite for the use of many popular applications such as Wordpress, Joomla and Drupal. Linux administrators and web developers must approach PHP with caution, as new vulnerabilities in poorly written and implemented PHP code are abundant and dangerous.
In a recent security incident, hackers were able to add a backdoor to the PHP source code. Although the backdoor mechanism was discovered before it made it into production, the incident serves as the latest reminder of the importance of prioritizing PHP security.
PHP security is inextricably tied to web server security. Because the popular open-source server-side scripting language is often paired with MySQL, PHP compromise can mean a compromise of the accompanying MySQL database, as well as any web applications running on the web server.
This article will examine how you can configure and run PHP securely to mitigate the risk of attacks and compromise, secure web applications, protect user privacy and maintain a secure and properly functioning Linux web server.
PHP Vulnerabilities Carry Great Risk for Admins
Vulnerabilities in PHP code are a prevalent and serious threat to web server administrators and web application developers. These flaws are often introduced when developers are writing code, either due to a mistake or the inability to anticipate malicious hackers’ ever-evolving techniques. A plethora of vulnerabilities exist in the PHP core - with new security bugs being discovered each month.
On March 28, 2021, hackers breached the internal PHP Git repository and inserted a backdoor into the PHP source code. Luckily, the malicious code was discovered by Michael Voříšek before it made it into production, and the hack led the PHP team to move source code management operations from its internal Git server to its official GitHub account, which will serve as PHP’s official Git repository going forward. In another PHP security incident that occurred less than three years ago and has yet to be explained today, hackers compromised the official PHP PEAR extensions system website and hosted a backdoored version of the PHP PEAR package manager for almost six months.
PHP vulnerabilities can be exploited by attackers to spread malware & take control of hundreds of thousands of web servers in botnets. In one such instance this past year, the infamous hackers-for-hire group DarkCrewFriends resurfaced with a dangerous botnet strategy exploiting an unrestricted file upload vulnerability to compromise PHP servers running websites. In another malicious campaign a year prior, the Neutrino botnet was discovered hijacking servers by taking over other hackers’ PHP and Java web shells to install a cryptocurrency-mining malware.
To help you better understand the threats that your web servers and web applications face, let’s take a look at some of the most notorious types of PHP vulnerabilities.
A Quick Look at the Most Common & Dangerous Types of PHP Vulnerabilities Threatening Your Web Servers
Remote Code Execution (RCE)
In this type of vulnerability, a bug in a PHP application accepts user input and evaluates it as PHP code, enabling an attacker to upload code to a website and execute it. This could, for example, allow a malicious actor to tell the website to create a new file containing code that gives him or her full access to the compromised website. RCE vulnerabilities are very serious because they are easy to exploit and grant an attacker full access when
SQL Injection (SQLi)
SQL injection (SQLi) occurs when a hacker is able to send instructions to a database and the database executes those instructions. This type of vulnerability occurs when a PHP developer takes input from a website visitor and passes it to the database without reviewing it for malicious code. SQLi vulnerabilities are very serious because they are easy to exploit and often grant full access immediately.
Cross-Site Scripting (XSS)
Cross-site scripting (XSS) takes place when an attacker causes malicious code to load in a website visitor’s browser and execute. This code often steals user cookies to grant the attacker administrative level access or performs functions as the user to grant additional access.
Cross-site Request Forgery (CSRF)
Cross-site request forgery (CSRF) describes a scenario in which a user is tricked into issuing a request that is not in his or her best interest. For instance, an attacker may create a link and trick an administrator into clicking on that link, causing the site to take a certain action such as creating a new ‘admin’ user with a known password.
This critical WordPress vulnerability which was fixed in November of 2020 left servers vulnerable to a variety of attacks including cross-site request forgery and cross-site scripting.
This type of vulnerability is introduced through incorrect validation that a site visitor has the access level required to take a certain action. For example, a developer may wrongly use a function called ‘is_admin()’ - which is designed to indicate if someone is viewing an admin page - to try to validate that someone is an administrator, mistakenly granting non-admin users access to features that only administrators should have access to.
PHP Object Injection
PHP object injection is a complex attack that occurs when a PHP application takes user input and passes it to the unserialize() function, which takes a stored object and turns it into an object in memory. This type of vulnerability occurs when a developer allows user input to be used in an unsafe way within a PHP application.
The unserialize() function must be approached with extreme caution, as this function is commonly exploited by attackers. PHP 7 has includes a new filtered unserialize feature designed to mitigate the impact of code injection vulnerabilities by requiring that developers specify classes that are safe to unserialize. However, it is critical to keep in mind that even with this improvement, passing untrusted input to unserialize() is never safe.
Remote File Inclusion (RFI) & Local File Inclusion (LFI)
Remote file inclusion (RFI) and local file inclusion (LFI) take place when a PHP application takes user input and passes it to a function designed to load a file. The inclusion of a remote file in a URL is known as Remote File Inclusion (RFI) while the inclusion of a local file in a URL is known as Local File Inclusion (LFI). LFI is often the method an attacker employs to gain access to a WordPress website’s wp-config.php file.
Source Code Revelation
This type of vulnerability has to do with people being able to see the names and content of files that they shouldn’t be able to view due to the breakdown of a web server’s configuration. The code revealed in this type of vulnerability may list accessible configuration files or contain sensitive information such as database credentials.
Session hijacking occurs when a malicious actor steals a user’s session ID. When a session is set up between a client and a web server, PHP will store the session ID in a cookie on the client side. Sending the ID with the page request provides access to this confidential information, potentially resulting in session hijacking. Session IDs are commonly stolen via XSS attacks, and can also be vulnerable server-side through the use of hosting services that store session information in globally accessible directories.
These vulnerabilities in Apache versions 2.4.33-1 and prior - which have since been fixed upstream - left web servers susceptible to session hijacking and an array of other dangerous exploits.
Directory traversal looks for vulnerable websites and causes files to be accessed that the owner did not plan on making publicly accessible. It is also referred to as the ../ (dot, dot, slash) attack, the climbing attack, or the backtracking attack.
Tracking advisories is critical in preventing all of these prevalent and serious types of PHP vulnerabilities. Subscribing to our weekly Linux Advisory Watch newsletter is an easy, convenient way to stay up-to-date on the latest advisories and updates issues by your Linux distro.
In addition to tracking advisories, we recommend that web server administrators implement the ModSecurity web application firewall (WAF), which can provide another line of defense against the attacks listed above. The open-source, cross platform WAF has a robust event-based programming language and allows for HTTP traffic monitoring, logging and real-time analysis.
Best Practices for Improving PHP Security
The majority of attacks on Linux web servers can be attributed to misconfigurations and poor administration. Thus, it is essential that administrators configure their web servers to be as secure as is practical within the construct of their environment. The Open Web Application Security Project (OWASP), a nonprofit foundation we trust and admire that works to improve the security of software through community-led open-source projects, suggests that administrators and developers implement these secure PHP configuration recommendations to protect their web servers against dangerous PHP vulnerabilities and prevent attacks.
LinuxSecurity.com PHP security experts Brittany Day and Dave Wreski have additional tips and advice for improving PHP security, which we will explore in this section.
Our Top PHP Security Tips & Advice
Update Your PHP Version and Modules Regularly
It is critically important that administrators and developers update their PHP version and modules regularly. With the support of the open-source community behind PHP, patches and bug fixes for vulnerabilities are released frequently, and newer versions of PHP and its modules often contain mitigations for known security issues that can be exploited by malicious hackers. As of January, 2022, the stable release for PHP is version 8.1.1, from December 2021.
It should be noted that when PHP is being used in a hosting environment, users may not be able to update their PHP version number. In such scenarios, users must be especially careful and vigilant. They should also explore potential workarounds and demand that their hosting provider update PHP at the earliest opportunity.
Restrict PHP Information Leakage
The unfortunate reality is that it is common for platforms to leak sensitive information - and PHP is no exception. For example, PHP releases versions and the fact that it is installed on a server through the expose_php directive. To prevent the leakage of this sensitive data, administrators should set this directive to off in /etc/php.d/security.ini.
Control File System Access
PHP can access files by default via the open_basedir directive using functions like fopen(). To control file access and prevent security issues, the open_basedir directive should always be set to the /var/www/html directory.
Disable Remote Code Execution (RCE)
In PHP, remote code execution is enabled by default. The "allow_url_fopen" directive allows functions including require, include, or URL-aware fopen wrappers to obtain direct access to PHP files. Remote access can be obtained using the HTTP and FTP protocols, leaving system defenseless against code injection vulnerabilities. To protect against these types of exploits, administrators should disable remote code execution by setting the "allow_url_fopen" directive to "Off".
Disable Dangerous PHP Functions & Get Rid of Unnecessary Modules
PHP comes with a selection of useful functions, but is also plagued with functions that can be exploited by attackers and should be disabled. To disable these dangerous functions, administrators must edit the php.ini file. In this file, they should find the disable_functions directive and disable the dangerous functions in it using:
PHP also comes with an array of excellent modules; however, not all modules are required for every project. In PHP, all the extension modules found in /etc/php.d/ directory are loaded by default. Administrators should get rid of all modules that are not currently required, as doing so will improve both security and performance. To view available PHP modules, use the command:
Once you have accessed this list, you will be able to get rid of all unnecessary modules. To enable or disable a particular module, simply find the configuration file in the /etc/php.d/ directory and comment the module name.
Scan PHP Scripts & Audit PHP Code for Security Vulnerabilities
Scanning PHP scripts and auditing PHP code is essential in identifying and fixing potential security vulnerabilities before they are exploited by attackers. There is a plethora of excellent free and open-source tools and utilities available to assist Linux users in this process. Here are some of our favorites:
- Phpcs-security-audit is a set of customizable PHP_CodeSniffer rules that identifies security vulnerabilities and weaknesses in PHP code. The tool checks for CVE issues and security adviso
ries related to the CMS/framework, enabling administrators to follow the versioning of components during static code analysis.
- SensioLabs Security Checker is a command line tool that checks if an application uses dependencies with known security vulnerabilities using the Security Check Web service and the Security Advisories Database.
- Suhosin is an advanced security system for PHP installations designed to protect servers and users from known and unknown flaws in PHP applications and the PHP core.
- PHP Malware Finder (PMF) is a self-hosted solution designed to help administrators and developers identify potentially malicious code in files. Detection is performed by crawling the filesystem and t
esting files against a set of YARA rules.
- RIPS is a PHP static code analysis tool that is integrated through the development lifecycle to identify security issues in real-time. The tool supports 15 different types of vulnerabilities, and is able to scan PHP applications very rapidly for PHP-specific vulnerabilities.
- SonarPHP is a static code analyzer that uses pattern matching and data flow techniques to identify vulnerabilities in PHP code. It is used as an extension for the SonarQube platform and features over 200 rules, along with support of custom rules.
- Dependency-check-cli is a great tool from OWASP that uses dependency-check-core to detect publicly disclosed vulnerabilities associated with the scanned project dependencies. The tool will generate a report listing the dependency, any identified Common Platform Enumeration (CPE) identifiers, and the associated Common Vulnerability and Exposure (CVE) entries.
- PHP Secure Configuration Checker is a single file that checks a current PHP configuration for potential security flaws. It is user-friendly and has almost no dependencies.
The Bottom Line
PHP offers web server administrators and web application developers an array of valuable functions and modules paired with robust security inside out - a characteristic that can largely be attributed to the support that PHP receives from the vibrant, global open-source community. However, PHP security is ultimately in the hands of the administrator. He or she must make sure code is written properly, the proper configurations have been made and that the best practices covered in this article are being implemented.
PHP security should be a primary concern for administrators and developers, as it is inextricably tied to the security of a web server as a whole. Sound PHP security can help mitigate the risk of attacks and compromise, secure web applications, protect user privacy and maintain a secure and properly functioning Linux web server.
Do you have questions about PHP security or want to discuss the topic in more depth? Let’s chat!
Connect with us on social media: