The Ultimate PHP Security Practices and Malware Removal Guide

PHP is a widely used language in almost every CMS powered by the open source community. Even commercial sites like Facebook use PHP which clearly shows its widespread popularity. However, the downside is that PHP web apps are also among one of the most targeted by attackers on the internet. Unfortunately, writing secure code is not as widespread as it should be. It invariably gives hackers a gold mine to exploit. Multiple sites have been compromised in the past due to lax PHP security. Therefore, this guide aims to guard you against PHP malware infections and teach you how to do Custom PHP, PHP Security & PHP hack removal techniques.

How to do custom PHP to improve PHP Security?

A good PHP developer should never trust user input and therefore all functionalities should be designed around this. Writing secure code is a habit which comes a long way in making web applications more convenient for the end users. If you are a self-help person who loves to build a PHP application on your own then, some safe coding practices must be followed. These practices are applicable for developers to increase the PHP security.

PHP Security: Preventing Cross-Site Scripting

XSS if fairly common with not only PHP but every other kind of web pages. The prime cause for such common vulnerabilities like XSS and SQLi is developers trusting user input. Developers should remember never to trust user input while coding. This fact alone can secure the majority of the code. XSS can be used by the attacker to manipulate the users through JavaScript. Attacks can range from phishing pages to defacing the site! To prevent an XSS vulnerability, use htmlspecialchars() function of PHP while coding. Moreover, ENT_QUOTES flag of this function can deal with both, the single and double quotes entered by the user. An example code snippet of a search query is given below for reference.

$search = htmlspecialchars($search, ENT_QUOTES, 'UTF-8');
echo 'Search results for '.$search;
Also, to prevent DOM-based XSS avoid using URI fragments at all. Moreover, do not use the following properties and functions of the native API:

  • innerHTML
  • outerHTML
  • document.write

PHP Security: Preventing SQL Injection

SQL injection is another example of trusting user-supplied input in PHP pages. SQLi can have devastating consequences for the database of your site. This attack gives the database access to an attacker. In some cases, the attacker can only read the sensitive info from tables like passwords. Whereas in other cases, the attacker may even manipulate the database and upload reverse shells on the web server.

To prevent SQLi attacks, using already prepared statements while building the web pages is a must. Apart from improving security, already prepared statements can also save time for a developer as the SQL query needs to be parsed at once. However, it can be run many times with the same or different parameters. The following is an example of implementing prepared statements is PHP.

$stmt = $dbh->prepare("INSERT INTO Users (Uname,Address,City)
VALUES (:nam, :add, :cit)");
$stmt->bindParam(':nam', $txtNam);
$stmt->bindParam(':add', $txtAdd);
$stmt->bindParam(':cit', $txtCit);

Now, the same prepared statement could be used for repeated inserts i.e. to add multiple rows into the table, add the following code below the code snippet given above.
// inserting one row
$txtNam = 'one';
$txtAdd = 'India';
$txtCit = 'Delhi';
// insert another row with different values
$txtNam = 'two';
$txtAdd = 'USA';
$txtCit = 'California';
//... and so on!
Also, make sure to encrypt the sensitive contents of the database like passwords. The password_hash() function of PHP could be used to encrypt the data. Whereas the function password_verify() helps in confirming that the given value corresponds to the hash stored in the table.

PHP Security: Preventing Cross-Site Request Forgery

CSRF vulnerability in your PHP application can potentially allow an attacker to manipulate users into performing unwanted actions. These include deleting a page or updating user password without the consent of the end user. To protect your users from CSRF attacks, use random tokens. These token would be unique for each user. Therefore, when a user clicks on a malicious link which tries to perform a CSRF attack, the request will not be processed automatically due to an invalid token. Make sure it is random otherwise, the attacker could figure out the pattern. A simple implementation is given below.
$randomtoken = md5(uniqid(rand(), true));
Also, if you experience problems with the HTML layout, use Base64 encoding. This can be implemented by the following command:
$randomtoken = base64_encode( openssl_random_pseudo_bytes(32));
After CSRF protection token is generated, make sure to add this to the session variables i.e. ’ />
Also, ensure that every form contains a security token and it would be better if there is a different token for each form. However, it is noteworthy here that implementing multiple tokens in multiple forms can be problematic at times when a user opens multiple forms simultaneously. Therefore, try to use open source PHP classes and libraries for CSRF protection token implementation.

PHP Security: Preventing Session Hijacking

Session hijacking allows an attacker to take over the identity of verified users. There are multiple attacks like XSS, Network eavesdropping which allow an attacker to steal the session info. The transparent session ID feature in PHP further aids this type of attack. Firstly, ensure that the directivesini_set() are at the beginning of every script. This is to override any global settings which may be present. Add the following lines of code to your php.ini file:
ini_set( 'session.use_only_cookies', TRUE );
ini_set( 'session.use_trans_sid', FALSE );
In the first line of code, session.use_only_cookies prevents info leakage by the transparent session ID feature in PHP. This feature forces PHP to manage the session ID using a cookie thus disabling the $_GET['PHPSESSID']. Also, the second line of code turns off thesession.use_trans_sid Thereby avoiding leakages of session ID in all URIs returned. However, it is noteworthy here that the users may still be vulnerable to DNS and proxy attacks. It is also necessary to add a cookie timeout and generate a unique random session ID for each session. The timeout can be set by,
setcookie("myCookie", $value, time() + 3600);
This code ensures that the cookie expires in the browser within an hour. Alternatively, you can set a cookie to expire as soon the browser closes. Also, avoid using cookies to store serialized data. As it can be used by attackers to add variables to your scope. Remember to use the session_regenerate_id() of PHP function to regenerate a new user session id whenever a user logs out or changes status.

PHP Security: Preventing File Inclusion Attacks

Remote File Inclusion (RFI) and Local File Inclusion (LFI) attacks are widespread on the PHP web apps, which is a threat to PHP security. These vulnerabilities are also related to unsanitized user input, which allows an attacker to execute code. The prime cause behind these attacks is the failure of code to securely parse “include” statements. Thus, the web app itself builds a path to malicious executable code. This is later on loaded and run based on an attacker-controlled variable which could be a malicious cookie or a vulnerable request parameter. Most of the time, LFI and RFI attacks are used to deface sites, however, they can also be used for data exfiltration and DOS attacks.

Therefore, it is advised to the developers to avoid improper use of PHP functions like include, include_once, require, require_once, etc. When the include function takes a request parameter as input, without verifying input, the attacker can provide any file parameter and it will be executed. This could be an IP address, port number or even a filename. The best practice to remove LFI and RFI vulnerabilities is to not allow remote file includes via specifying a URL instead of a local file path. However, this option is disabled by default. Simply change the following flag to OFF in your .htaccess file to eliminate RFI attacks:
Now, in order to mitigate the risk of LFI attacks, disallow input provided by the user from getting ahead and on to any file system or framework API in your PHP web app for execution. According to OWASP, maintain a whitelist of acceptable filenames. Thereafter, use an identifier other than the actual file name to access that particular file. This would eliminate the risk of file inclusion attacks and boost PHP security.

PHP Security: Implementing The Content Security Policy

PHP Security: Implementing The Content Security Policy
Most of the browsers today have a security feature known as The Content-Security Policies. This means that the browsers will obey the author of the web page as to where from the JavaScript and other resources can be loaded and executed. Majority of attacks like XSS and JavaScript Injection use the web page to run their own malicious code. The attacker injects script or HTML tabs somewhere to load malicious code from their own domains. Therefore, a content security policy in the header ensures that the browsers don’t execute such malicious requests. To enable content security policy in your Apache server, add this code to the .htaccess file:
Content-Security-Policy-Report-Only: script-src 'self'; report-uri
This script-src ‘self’ tells the browser to block code execution from other domains. Also, the report-uri directive will inform you about a policy violation rather than blocking it. This means you can double check before blocking so that there are no more of such scripts.
Content security policy can be enabled for other servers too by various methods. You can also use web pages to implement the content security policy. This can be done via a tag in the element of the page. See the code snippet given below for reference.
content="script-src 'self'">

PHP Security: Safe Practices for Administrators

Web admins are the custodian of their PHP security. Therefore, the administrators should ensure that the site is compliant to security practices. Small practices like never using the default passwords or keeping site updated can prevent the hassle of PHP hack removal after an infection. Some key takeaways for the administrators to increase PHP security are:

Use Secure Socket Layer(SSL)

SSL encrypts the communication between your PHP site and the customers. This means that the end users are protected from eavesdropping attacks. Moreover, most of the customers today look for a valid security certificate before visiting a site. Therefore, get a valid certificate from a certificate authority to boost PHP security. Also, after implementing SSL on your PHP site, ensure that the site always forces the users to HTTPS. This can be done by adding the following code to your .htaccess file.
# Redirect HTTP to HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Set Permission

Setting permission for PHP file means authorizing users to read, write or execute a PHP file. This security setting can be implemented using the chmod() function of the PHP. This function takes two inputs. One is the name of the file whose permissions need to be set and second is the three-digit number which defines those permissions. Out of this three digit number:
  • Primary digit denotes permissions granted to the owner of the file.
  • The second digit denotes permissions granted to the owner group of the file.
  • And the third digit denotes permissions granted to everyone else.

To further clarify, look at the code snippet given below.

$fn = './test.txt';
chmod($fn, 0644);
Here, the chmod defines permission as 644. The digit 0 before 644 indicates PHP to interpret this as an octal no. Now, the digit 6 means the owner can read as well as write to the PHP file. While the rest of two digits written as 44 indicate that the group owner, as well as everyone else, can only read the PHP file.

Disable Dangerous Functions

Some PHP functions need to be avoided to maintain PHP security. These functions were originally designed for legitimate purposes which are now widely exploited by the attackers. The functions can also provide root access to the attackers, therefore, avoid using functions like assert(), shell_exec(), system(), passthru(), show_source(), highlight_file(), proc_open(), and pcntl_exec(). These dangerous functions can be easily blocked. Simply open the php.ini file and search for find disable_functions, then replace it with the following command:
disable_functions = “apache_child_terminate, apache_setenv, define_syslog_variables, escapeshellarg, escapeshellcmd, eval, exec, fp, fput, ftp_connect, ftp_exec, ftp_get, ftp_login, ftp_nb_fput, ftp_put, ftp_raw, ftp_rawlist, highlight_file, ini_alter, ini_get_all, ini_restore, inject_code, mysql_pconnect, openlog, passthru, php_uname, phpAds_remoteInfo, phpAds_XmlRpc, phpAds_xmlrpcDecode, phpAds_xmlrpcEncode, popen, posix_getpwuid, posix_kill, posix_mkfifo, posix_setpgid, posix_setsid, posix_setuid, posix_setuid, posix_uname, proc_close, proc_get_status, proc_nice, proc_open, proc_terminate, shell_exec, syslog, system, xmlrpc_entity_decode”
This command would cover almost all such dangerous functions. Don’t forget to restart the server in order to let these changes take place.

Turn Off Error Reporting

Errors can leak sensitive info about your server. This could range from software version to file locations!. Therefore, it is advisable to turn off the error reporting of your PHP website for end users. In order to do this, add the following code to your php.ini file:
However, you may still need to check the errors by yourself to fix critical issues. In order to accomplish this, use the following code:
The second line of code here would save the errors to a specific file i.e. php_error.log in this case. Similarly, change the path and name of the file where errors are to be saved.

How to do PHP Hack Removal?

PHP Hack Removal: Database Cleanup

The database is often targeted to breach PHP security. Remember to take a complete backup of the database before starting the cleanup process. In case something goes wrong, it would be used to rollback the changes. Begin the comprehensive database cleanup by searching for malware keywords. For instance, the PHP/apiword malware contains a signature in the form of a variable called wp_cd_code. Similarly, other malware strains would contain similar signatures which need to be searched for. Manually it may become cumbersome, therefore, use phpMyAdmin for PHP hack removal. Multiple such keywords can be searched for using this freeware.

Thereafter, delete the malicious contents from infected tables. Also, remove any new software or script which may have had access to the database in the recent past. Don’t forget to verify if the site is functional after database changes.

PHP Hack Removal: Identifying Infected PHP Files

Before starting file cleanup to boost your PHP security, it would be necessary to check for infected files. It is highly likely that the PHP files which have been modified by the attacker in the recent past have been used to inject malware into the site. To search for any recent PHP file modifications, log in to your SSH. Now via command line execute the following:
$ find ./ -name "*.php" -type f -mtime -2
This commands here would list all the PHP files modified in the past two days. Alternatively, an FTP client could also be used to list the file modifications column separately. Most of the popular CMSes which use PHP contain some core files which affect the functionality of the platform. These files generally need no modification and are crucial for PHP website security. A modification of the core files is an indication of infection. To check for any such issue, first, download a copy of the CMS on your local machine. Thereafter, use the diff command to compare the freshly downloaded files to the ones present on your server by executing the command:
diff -r InfectedDir OriginalDir

PHP Hack Removal: Cleaning infected files

This command here recursively compares the two directories. No core file modification is a sign of accep PHP: Cleaning Infected PHP Files
Malware detection may be tricky for average web admins. At times the infection may be hidden in core files or obfuscated. In an attempt to clean up the infection, Web admin may break the site. Therefore, first and foremost it is crucial to take a complete backup of the site. Thereafter, delete or comment out the suspicious code. Attackers tend to use various techniques to hide the code from average human eyes. The malware may be using some kind of encoding like the base64 to look gibberish to average humans and thus evade detection. Such code can be detected using the following command:
find . -name "*.php" -exec grep "base64"'{}'; -print &> output.txt
This command would scan all the PHP files for base64 encoded code. This code would be saved inside the output.txt which can be later analyzed for malware. Base64 encoded code inside the PHP files can be decoded using online services. Also, the web admins need to search for the keywords like “Obfuscation provided by FOPO – Free Online PHP Obfuscator”. This here is an indication that the PHP malware is a FOPO variant which can be de-obfuscated using online tools for analysis. However, it is noteworthy here that some addon/extension/plugin developers may be using FOPO for genuine purposes. There is an exhaustive list of PHP malware signatures which cannot be summarised in this one article. Therefore, in case the infection is reoccurring or you are unable to determine the cause of infection, seek professional guidance.

PHP Hack Removal: Dealing with Hidden Backdoors and Infections

The intent of attackers to inflict maximum damage to the PHP web applications. Therefore, once the server is compromised, attackers modify the PHP files and inject backdoors. These backdoors are basically a malicious code which can provide unrestricted access to the attacker in the future thereby defeating the whole concept of PHP security. Such backdoors are not easy to spot owing to the complex nature of the code.

Therefore, it is advisable to use a security solution like Astra for automatic malware and backdoor removal. Astra firewall would ward off any infections in the future while its cleanup engine would ensure that no backdoors are left behind. With Astra experience your PHP website security on steroids.

Take an Astra Demo now!

Magento Security Suite

"Excellent service, I am sleeping like a baby since I got it."

Excellent service, always responding super fast when I need them, and never had any problem with hackers since I'm with Astra.