Ingrid_bw.png
Astra saved my website from the dreaded Japanese SEO hack. Have used Astra for my website's security ever since & super happy to see dozens of attacks being stopped & the support I've received Ingrid Kjelling
Owner, IK Photography

The Ultimate Drupal Security Practices and Malware Removal Guide

This Drupal security guide will help you to protect your website from hackers & how you can fix your hacked Drupal website

The Ultimate Drupal Security Practices and Malware Removal Guide

If you own a site, you probably know how distressing it is to lose your precious data overnight. As a crawling malware succeeded in making a hole in your weak Drupal security Structure. So, Astra is back with another useful article to save you from sleepless nights and distressing thoughts. Now, let us move to the scene where a Drupal site has been hacked. Let us understand the types of hacks, their symptoms, the process of Drupal malware removal and the ways to prevent them in the future. With this guide, your Drupal security will improve tenfold. It is everything you need, in case you were wondering how to restore your site after a brutal cyber attack.

Introduction to Drupal Security

Wikipedia defines Drupal as a free and open source content management framework written in PHP. It enjoys the title of being the third most popular content management framework in the market only after WordPress and Joomla. Because of the versatile nature of Drupal, variant sites can work on it efficiently. And thus it is being used by big corporates and enterprises. To name a few famous users of Drupal, we can safely include NASA, Harvard University, Tesla and Nokia.
But, when it comes to the question of Drupal security, these sites seem to live under a cloud. Although, it must be mentioned here that the Drupal security structure is reputed to be a really hardened one. There have been negligible malpractices with its sites till now. The vulnerability of its sites getting infected lies mainly with the cross-site inscription(XSS). Still, it must not be forgotten that no site is completely hacked proof. Thus, this article “Drupal security and Drupal Malware removal guide”.
Coming to the issue of Drupal site getting hacked, you surely need to figure out a way for the Drupal Malware Removal. No worries! Astra is happy to help.

Types of Drupal Hacks

Hacking is a broad area, which makes it an arduous task to classify it into numbers and types. Having said that, we are presenting you a list of only the trending hacking types that are found to be the current craze amongst the hackers.
First things first, before getting into the details of Drupal malware removal and safety guidelines, it is of extreme importance to learn a bit about the hacks on rising in Drupal or other CMS(s). Here is a short list of the hacks and their Drupal Malware Removal process.

Drupal Malware Removal in SEO Spam

For sites with high-quality content and fairly good popularity, there comes unwanted threats and exploits. Drupal surely is one popular website and houses a huge number of other large and important sites. This, invariably, makes it easy prey for the spammers. SEO (search engine optimization) spam is one such hack used primarily to get undeserved visibility in search engines. It is done by manipulating the indexes. Further, it is also used to spread phishing content online.
Moreover, the hacker uses the website as a host to send spam emails, to collect user data and to execute a number of other malpractices. These practices no doubt, have serious consequences. Losing the control of the site, modification or misuse of user database are only a few examples. In addition to the data loss, the reputation of the website is put to stake too. In severe cases, the site also loses its valuable customers.
A similar case was seen when Drupal was infected with the Pharma hack recently, where SEO spammers used its vulnerabilities to redirect users to pages selling viagra and cialis. This SEO spam is known as Black Hat SEO. Another famous example of SEO spam is Japanese SEO Spam. In this spam, the spammers hijacked google search results and displayed Japanese words in the titles and keywords.
Pharma Hack
Japanese SEO Spam

Drupal SEO spam symptoms

To check whether your Drupal website has been attacked, look for the following symptoms:
  • Unusual, slow, or abnormal site behavior
  • Modified files like-page.php, nav.php, etc. index.php, drupal.
  • Added new pages like leftpanelsin.php, cache.php, etc.
  • Edited xmlrpc.php in order to escape detection by webmasters.
  • Usage of base64 encoding to obfuscate code.
  • Files are hidden under /images folder to skip detection.
  • Altered page name as .somefile as an attempt to avoid being seen.
  • A difference in search results of Google, Mozilla, Bing, etc as a result of the spam.
  • Unauthorized new users on the Drupal dashboard.
  • New nodes from an unauthorized user.

Drupal Malware Removal Process

If it is found that your site is behaving in the manner specified above, Follow the next steps vigilantly to undo the damage that has been forced.
  • Scanning: Scan your website with modules like Hacked!, git etc to know the status of the hack. Also, analyze your website with the help of google webmasters tools to check for an unusual web traffic increase. Check out for new, unfamiliar codes in your files. Have a look at the following sample of codes which redirects your website to that of the hacker’s                                       
    <ul id="menu">
    <li><a href= attackerdomain.com">Something1 </a></li>
    Hackers also hide their code in tobase64 avoid detection as the attackerdomain.com looks like: YXR0YWNrZXJkb21haW4uY29t making it hard to detect the attacker domain.
    Similarly, in order to search for base 64 encodings in files the grep command is helpful as following: find . -name "*.php" -exec grep "base64"'{}'\; -print &> b64-detections.txt This piece of code basically searches into the .php files of your choice for base64 encodings. The results of which is saved in b64-deTtections.txt files. You can, finally, use an online resource to decode this and get a clear picture of the misdoings to the site.
  • Cleaning: Malpracticers often leave loopholes in a site to get access repeatedly. The common backdoors are hidden under several PHP files, these include, base64, system. assert, st_rot13, create_function etc. Remove these backdoors manually.

  • Securing: Restore authentic backup files. Update every theme and module of your website. Disable plugins with obsolete modules. Install good copies of modules from the Drupal’s site. This will remove all the loopholes left by the hacker.

Drupal Malware Removal in Admin Hack

Another very problematic hack is named Admin hack. It is exactly how it sounds, a hack where the attacker gets access to the details, passwords, keys, and powers of the admin of the site.
Once getting hold of the powers an admin enjoys, they have the control to Change/delete/manage/reset passwords from there. They can also add unverified members, or send spam emails as an imposter of the admin, modify modules/ core coding of the site.

Drupal Admin Hack symptoms:

  • Unusual, slow, or abnormal site behavior
  • Multiple admin users added to Drupal.
  • Infected and malicious files with uncommon names added to the public_html folder
  • Several files copied to the website
  • A new file called  ext.php added to folder/drupal-admin which gives the power to hackers to upload dangerous PHP files to the ‘drupal-admin directory’.
  • Re-infection of the website almost immediately.
Security warning by the Hacked! Module in Drupal

Drupal Malware Removal Process

  • Scanning: Scan your website with modules like Hacked!, git, etc to know the status of the hack. Check index.php, drupal-admin/index.php to see if they have been modified. Scan for new, unfamiliar files in the server or/drupal-admin folder. The files that you may find are: Marvins.php ,db_.php, 8c18ee, 83965, admin.php, buddy.zip, dm.php
  • Cleaning: Delete unknown Drupal administrator accounts from the user’s page. And also the codes that add malicious admin user(s). Remove all the PHP files from your ‘uploads’ directory. Clean the admin user database manually so as to get rid of the unknown users added.
  • Securing: Restore authentic backup files. Update every theme and module of your website. Disable plugin with obsolete modules. Install good copies of modules from the Drupal’s site. This will remove all the loopholes left by the hacker.

Drupal Malware Removal in Redirection hack:

Redirection hack is something every internet user must have experienced at some point in their surfing history. But, when you are a website owner, to have your users redirect to spam sites is literally a nightmare. In Redirect spam, a spammer redirects visitors of a particular website to spammy and malicious sites.
As for Drupal, it is a popular and growing site, and thus a desired target for the web crawlers. Drupal redirect hack is another convenient yet unscrupulous way for the hackers to use this progressive site as a door to redirect visitors to their sites. These sites usually have little or zero relevance to the search opted for.

Drupal Redirection Hack Symptoms

Admin hack could be identified easily by the following symptoms:
  • An unusual increase in web traffic.
  • Clicking links on your website homepage redirects to spam.
  • Unwanted ads or pages open up on your website as a result of the hack.
  • The Appearance of unknown nodes and files.
  • Spam content in search engine results. Blacklisting by search engines like Google, Bing etc.

Drupal Malware Removal Process

The Drupal Malware removal for this kind of hack can be done as follows:
  • Scanning: Check for alien files added to your website with Drupal modules like Hacked!, git, file integrity, etc. Scan for any new, unverified user entries. Look out for any fishy tables like Sqlmap. To show all the tables simply use the command. show tables;. The attacker might have also created new user entries and gained admin privileges. To check that use: Select * from users as u AND u.created > UNIX_TIMESTAMP(STR_TO_DATE('Oct 15 2018', '%M %d %Y ')); Here, it will display all the users created after 15 October 2018.
  • Cleaning: Remove all the unfamiliar files from your server manually. Clear your cache using the following command: drush cache-rebuild (Drupal 8) or drush cache-clear all (Drupal 7). Also, Edit the .htaccess file as follows: order allow, deny allow from all deny from env = spammer SetEnvIfNoCase Referer ". * (Poker | credit | money). *" Spammer </ Limit> This piece code block users from accessing the pages with links like poker, credit etc based on identifiers (HTTP referrers)
  • Securing: Restore authentic backup files. Update every theme and module of your website. Block access based on its own identifier (HTTP REFERRERS). Rewrite Engine On RewriteBase / # allow referrals from search engines: RewriteCond% {HTTP_REFERER}!. * xyz \ .com /.*$ [NC] RewriteCond% {HTTP_REFERER}! ^ Http: // ([^ /] +) google \ .. * $ [NC] Continue replacing the phrase google with all the search engines like yahoo, bing etc. you wanna allow. # Conditions for don`t wanted referrals RewriteCond% {HTTP_REFERER} ^. * Loans. * $ [OR] Continue replacing the word loan with the spam words like viagra, porn, etc you wanna block.
Note: Know more about Google Blacklist Removal.

Enhancing your Drupal Security

Now that we have applied the Drupal malware Removal, it is time that we guard it against any future mishaps. The following tips will help you in enhancing your Drupal security structure to the maximum level.

Updating:

It is incredible how just updating and resetting your websites and modules reduces its vulnerabilities by a huge extent. New versions are nothing but patched and mended loopholes in your Drupal security structure. It is only prudent to use it for it to possess lessened security threats. The Latest version of Drupal can always be downloaded from Drupal’s official site drupal.org.

Unique Usernames and Passwords:

This is probably the most underrated of the security measures. But, the importance it holds could not be emphasized more. Most people opt for simpler usernames and passwords their memory could retain easily. This is one dangerous practice. Using your own name, word admin as usernames is a big NO. 123456789, or word “password” are way too simple and easy-to-crack passwords. One security loosened is one opportunity provided. Make sure you go for unique and strong usernames and passwords.

Backing up with frequent Backups:

In times, such as a brutal cyber attack, only backups has got your back. Undermining the importance of timely and regular backups will cost you dearly. DO NOT overlook the value and necessity of backups. Drupal’s official site has all the backup related information, you can always take help from there. Backups will prove to be a savior if you lost your valuable data in an unfortunate cyber hack.
Restricting Permissions:

Giving permissions with a vigilant eye is one hack to protect your site against any malware attack. Stopping any bots, pages etc which are extraneous will add to your site’s security majorly.

Using Drupal Modules:

Drupal security modules promise a more secured structure, in fact, its popularity is attributed to its security excellence. Using Drupal modules will work for your benefit. Some modules are as follows:

1. File Permissions:

Since Drupal is an open CFS, anyone can read and write codes in it. But, this allowance should be optimized carefully. To have a secured site, you must check if the permissions for opening, reading and altering these files is reasonable and not too liberal. Again, this module is easily found on the Drupal’s website.

2. Sanitizing output:

In order to prevent XSS infection to your sites, it is necessary to sanitize and filter the HTML outputs. Sanitization can be done with various modules available in Drupal, such as Twig Templates, Javascript(jQuery) and drupal.checkplain(). To learn more about Sanitizing of texts, visit Drupal.

3. File integrity check module:

This Drupal module allows you to scan the website and the modules attached. It periodically checks for any divergence in the current state of the website as compared to the original authentic version you feed into it. It then alarms you, if, modifications or loopholes in different modules or core module is found. You can check this facility on Drupal itself or click on the link https://www.drupal.org/project/file_integrity for direct access.

4. Coder:

The coder command checks your site’s codes against set standards. It suggests the best practices for coding. It also highlights any violations in coding standards done in your site.

5. Captcha:

The captcha module’s sole purpose is to block login attempts by automated bots lurking on the internet sphere. With this module, you are invariably going to increase your Drupal security.

Conclusion

We hope Astra had your queries answered and problems solved to a great extent. Be safe and dodge any cyber attack by keeping your site super secure with this guide. Be smarter than the hackers and apply the recommended steps very carefully.

Drupal 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.

Continue reading

The Ultimate Moodle Security Practices and Malware Removal Guide

This Moodle guide will help you to secure your Moodle website from hackers & how you can fix your hacked website.

The Ultimate Moodle Security Practices and Malware Removal Guide

If you are a teacher or a student then you must have heard about Moodle. It is one of the most popular learning management systems in the world. It has over a hundred million users, which makes it an attractive target for hackers and exploiters. Instances of hacking and defacing Moodle based services are becoming more common now. These incidents call for an awareness regarding Moodle security. By knowing about the various security threats and adopting some basic safety measures, you can easily protect your Moodle platform.

Understanding the security

To understand the security of your web application, you need to understand the various types of users of your Moodle based application. Based on that you can custom fit your Moodle security system.

  • Administrators: Administrators will have all privileges such as for changing all the settings, create and access various courses; modify all language packs and also the users. They can also execute shell and PHP codes. Administrators in Moodle applications can be restricted in certain areas by hardcoding certain settings in the config.php file.

  • Teachers: Teachers are the ones responsible for designing courses, enrolling and teaching students. They will usually require permissions for uploading files and submitting html texts, for creating and managing activities and access information such as grades and personal information of students. Files containing flash, JavaScript and other scripts are generally considered security risks. However, these files are commonly used by teachers and removing them is not possible. There is always a certain amount of risk when considering the privileges the teachers have.

  • Students: Students are the main participants in the courses. They will generally require the following permissions:
    • For posting formatted texts along with inline images and attachments
    • For uploading binary documents (files that contain text and the formatting in binary form)

  • Guests: Unregistered guests can be spammers or hackers trying to find backdoors or insert one into your application. Try to disallow them from uploading any type of files or submit any type of text. Sites having user sign up via email must be careful of spammers and numerous other types of attacks.

What types of attacks are we dealing with?

These are some of the common attacks:

  • Unauthenticated and unauthorized access
  • Cross site request forgery
  • SQL Injection
  • Cross site scripting
  • Data loss
  • Command line injection
  • Session fixation
  • Denial of Service
  • Brute force login
  • Confidential and configuration information leakage
  • Social engineering

The following provides a closer look at a few common attacks

  • SQL Injection: Any attacker can delete all the data in your application using SQL Injection attacks, especially when your code fails to clean the parameters properly. In Moodle 2.0, the concatenation of strings is completely avoided and instead it would pass an array of values to the database with the SQL. To protect your web application from this type of attacks, use higher level dmlib methods, such as get_record, this will eliminate the need for you to create SQL yourself. Use place holders wherever you need to insert values into SQL statements.

  • Cross-Site Scripting: In Moodle, users can type in HTML which in turn is displayed on the website. Thus, if the content has any hidden JavaScript, the user can have full access of everything on the page. Moodle helps in preventing cross site scripting by cleaning the input, dividing the input into various categories and by providing specific JavaScript guidelines for users. When the data comes in, using the optional_param or required_param functions, you can be sure of the input data. Moodle also divides the input into four categories: plain text, labels as plain text, HTML content by any user and HTML content input by trusted users. Depending on the input data type, users can choose the output function to display them. Also, while sending data to JavaScript, users should follow the Java Script guidelines and put the content in an external file. Then, communicate with the file by using $Page->requires->js_function_call or $Page->data_for_js functions. These functions encode all PHP data before passing it to JavaScript.

Past security flaws

Security loopholes in the past let attackers to enter into the system. Developers have patched them since, but they provide useful insights into how attackers exploit the vulnerabilities. Some of these are:

  • The /badges/mybackpack.php file had a vulnerability that allowed setting the URL of badges, while it should be restricted only to the Open Badges backpack URL of Mozilla. There was a possibility of blind SSRF via requests by the page in this vulnerability.
  • The capability named “Managing Groups” earlier was missing the “XSS Risk” flag. This capability was to be available only to trusted users, thus it was assigned to managers and teachers by default.
  • To prevent login cross site request forgery, the login form was not protected by any token. This was a serious risk since this can allow attackers to steal data or change the passwords.
  • During importing “drag and drop into text” questions in quizzes, it was possible to inject and execute PHP code from within the questions. Infected questions or questions from untrusted sources could use this vulnerability to enter and cause harm to the application.

These were a few vulnerabilities in Moodle that were fixed. They are the perfect example to show how attackers can leverage various backdoors and bugs to exploit the system. Being vigilant about such gaps in your Moodle security helps in quickly resolving them and securing them.

An in-depth analysis of an attack

The following is an example of Code Injection through a major vulnerability in Moodle. RIPS Code Analysis detected a vulnerability that allowed users with the role of a Teacher to perform code execution within the application.

The attacker and the attack:

Any user who is assigned the role of a teacher can exploit this vulnerability. One can also escalate their role with the use of any other gap in the security. Any attacker with this knowledge can run arbitrary commands on the operating system running the Moodle’s server.

The vulnerability:

Moodle has a feature that allows teachers to enter mathematical formulas. Moodle then evaluates these formulas with randomized values that prevent students from sharing their answers. After inserting random values in the formula, Moodle calls the eval() function on the formula which evaluates the answer. To prevent eval() from executing harmful codes, the developers have introduced a qtype_calculated_find_formula_errors() function which is a validator function. Moodle evaluates this function before the eval () to detect malicious code.

Moodle security vulnerability

The vulnerability in Moodle

Bypassing the security:

In the following code snippet, line 1939 will allow only specific characters (-+/*%>:^\~ The expression to bypass the security[/caption]

The fix:

On informing Moodle about the vulnerability, they proposed several patches. The first patch was to blacklist any formula that initiates a PHP comment. However, this patch was exploitable with a more sophisticated payload. The second patch was designed to prevent nested placeholders. However, this patch was also unable to completely prevent the malicious formulas from getting through. The third patch combined the ideas of the first two patches. But, in this patch if an attacker targeted the import feature present in the quiz component, then the attacker will be able to reimport a malicious XML file to take control of the $dataset argument. This will let them nullify the placeholders. Thus, this will result in the malicious code getting through like the earlier patches. Fortunately, the fourth patch was release and Moodle claims that this is the fix for this vulnerability.

Moodle security patch

Modifications in the second patch

How to tighten your Moodle Security

Securing your web applications is necessary to protect your web applications from common attacks. There are a few general requirements and safety steps which everyone should follow for stronger Moodle Security.

  • Have a separate administration backend:

    • Along with having a separate backend for administrator, using strong passwords is also a necessary step. Most users keep the default administrator password as “admin”. This lets attackers an easy way into the application. Make sure to use a strong password with a variety of alphanumeric characters. Also, enforcing a password policy will further strength your Moodle security. Moodle offers an option to set password policy which will let users set stronger passwords.
  • Avoid storing any sensitive information in the web application:

    • Storing sensitive information within the application will result in huge loss during an attack. Also, keeping regular backups of all information of the application is a good practice. The backups will let you restore your defaced or damaged application. In case of any infection you restore a fresh copy of all the important files and folders.
  • Prefer encrypted communication by using SSL:

    • Apart from using SSL for communication, using HTTPS for user login will protect the user’s information. It will be difficult for attackers to extract usernames and passwords of your users. You can enable HTTPS login by following some simple steps. In Settings, select Site Administration and within the Security option activate the HTTP security.
  • Try to log all user actions:

    • Tracking user actions helps in inspecting suspicious activities in the application. Along with tracking the actions, setting appropriate folder and file permissions is also important. This will prevent unauthorized users form accessing sensitive files and folders. Avoid configuring permissions with 777; instead using 750 or 755 is more secure.
  • Always keep your Moodle updated:

    • As mentioned above, there might be vulnerabilities that are revealed by developers and users. These vulnerabilities are patched up in the newer versions. Thus, updating your Moodle will help you protect your application. Each new version comes with better security and tools. Using outdated or unsupported versions will put you at a higher risk of attacks.
  • Avoid any 3rd party plugins or browser extensions:

    • Uninstalling unused plugins is a good way to keep your application safe. You can check all the courses which use plugins in Moodle. You can do this by going to Site Administrator, then Plugins, click on Activities, where you will find Manage Activities. Once you find out the plugins you are not using anymore, uninstalling them is a good idea for Moodle Security.

If you need some assistance

Protecting web applications can be tricky sometimes and attackers keep coming up with newer methods to get into the system. Thus, being vigilant will save you a lot of hassle. However, protecting your web application all on your own can distract you from the important stuffs. This is where Astra comes in to assist you in safeguarding your application so that you can concentrate on the more important aspects. With their wide range of security features and tools, Astra can protect your application round the clock from any type of attacks. With their state-of-the-art dashboards and security threat detection systems, you will get all the data regarding any attack on your application. So, if you want the best Moodle security without any hassle, then Astra is the right choice for you.

Moodle 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.

Continue reading

The Ultimate PHP Security Practices and Malware Removal Guide

This PHP security guide will help you protect your PHP based store from hackers & how you can fix your hacked store website.

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);
$stmt->execute();

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';
$stmt->execute();
// insert another row with different values
$txtNam = 'two';
$txtAdd = 'USA';
$txtCit = 'California';
$stmt->execute();
//... 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:
allow_url_include=Off
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 http://example.com/csr-reports
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' https://apis.google.com">

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.

<?php
$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:
display_errors=Off
However, you may still need to check the errors by yourself to fix critical issues. In order to accomplish this, use the following code:
log_errors=On
error_log=/var/log/httpd/php_error.log
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.

Continue reading