Fix Drupal Files/Directories permissions by PHP after hacked

Fix Drupal Files/Directories permissions by PHP after hacked

Posted on Wed, 08/08/2018 - 08:48 by zhilevan

Last night one of our former company's customer called me and need help to recover their hacked website, 

First of all, I install the Hacked module, and check the changed files and recover them, then looking and cleansing some backdoor files which their job is to inject codes for external codes(most of the time, js files to traffic hijacking) to the website.

 

Then I saw wow, there are a lot of files and directories with  777 permission !!! the most dangerous file/directory permission. their host was CPANEL and we don't have ssh access to files and changing the permission of files/directories manually seems to be waste and need a long time.

 

I tried to use exec PHP function with the following snippet (to better understand the Drupal files/directories permission Read Securing file permissions and ownership )

 

<?php

exec('find . -type f | xargs chmod 644');

exec('find . -type d | xargs chmod 755');

?>

But no achievement. in some Hosts for security reasons exec and shell_exec are disabled. So I tried to write custom PHP code to change the permission recursively by PHP.

 

<?php
fix_file_directory_permission(dirname(__FILE__));

function fix_file_directory_permission($dir, $nomask = array('.', '..')) {
  if (is_dir($dir)) {
     // Try to fix directories permission
     if (@chmod($dir, 0755)) {
       echo "<p>Permission Fixed for : " . $dir . "</p>";
     }
  }
  if (is_dir($dir) && $handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
      if (!in_array($file, $nomask) && $file[0] != '.') {
        if (is_dir("$dir/$file")) {
          // Recurse into subdirectories
          fix_file_directory_permission("$dir/$file", $nomask);
        }
        else {
          $filename = "$dir/$file";
            // Try to fix files permission
            if (@chmod($filename, 0644)) {
              echo "<p>Permission Fixed for : " . $filename . "</p>";
            }
        }
      }
    }
    closedir($handle);
  }
}
?>

and the all permission fixed easily.

please keep your Drupal Modules and Core update, especially when you have critical updates.

 

This code is available on my GitHub in a gist file with the title "Fix Files Directories Permissions by PHP code"