How to Find Malware in Your Server Files

Ciprian on Friday, May 18, 2018 in Blog

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

This script will run and display all potential malware files in your selected directory path. Make a backup before deleting any files and note that the script will also find legitimate files (false positives).

Add the code below to your server root. Change the directory path in find_files('path') and add a pattern to look for in the check_files() function. See below for a list of possible patterns.

The code below is set up to look for the 'js_escape' string in the /wp-content/ directory, in all .php, .js and .txt files.

<?php
ini_set('max_execution_time', 0);
ini_set('set_time_limit', 0);

find_files('wp-content');

function find_files($seed) {
    if (!is_dir($seed)) {
        return false;
    }

    $files = array();
    $dirs = array($seed);

    while (null !== ($dir = array_pop($dirs))) {
        if ($dh = opendir($dir)) {
            while (false !== ($file = readdir($dh))) {
                if ($file == '.' || $file == '..') {
                    continue;
                }

                $path = $dir . '/' . $file;
                if (is_dir($path)) {
                    $dirs[] = $path;
                } else {
                    if (preg_match('/^.*\.(php[\d]?|js|txt)$/i', $path)) {
                        check_files($path);
                    }
                }
            }

            closedir($dh);
        }
    }
}

function check_files($this_file) {
    /*
     * Possible patterns:
     * passthru, shell_exec, system, phpinfo, base64_decode, popen, exec,
     * proc_open, pcntl_exec, python_eval, fopen, fclose, readfile, js_escape
     */
    $str_to_find = 'js_escape'; // the string(code/text) to search for

    if (!($content = file_get_contents($this_file))) {
        echo '<p>Could not check ' . $this_file . '</p>';
    } else {
        if (stristr($content, $str_to_find)) {
            echo '<p>' . $this_file . ' -> contains ' . $str_to_find . '</p>';
        }
    }

    unset($content);
}

Possible patterns include:

passthru, shell_exec, system, phpinfo, base64_decode, popen, exec, proc_open, pcntl_exec, python_eval, fopen, fclose, readfile, js_escape.

Photo by Markus Spiske on Unsplash

Related posts

Leave a Reply

You have to agree to the comment policy.