Search file name within file

grepjavascriptregular expressionsedWordpress

Someone put a lot of malicious code onto every single wordpress instance on my server. For the second time. (At least) Every js file has been modified. There is a pattern though, the code always looks like this:

/*[file-name]*/[malicious code]/*file-name*/

is there any way that I could use grep and sed to get rid of those fragments? A previous attack put similar code in the files, which I got rid of using

grep -rnwl './' -e "[/*]d754948f7cc08347e64716505bd652ae[*/].*[/*]d754948f7cc08347e64716505bd652ae[*/]" | xargs sed -i "s/[/*]d754948f7cc08347e64716505bd652ae[*/].*[/*]d754948f7cc08347e64716505bd652ae[*/]//g"

is there any way to modify this exprssion to use each file name instead of a fixed string like "d754948f7cc08347e64716505bd652ae"?

Best Answer

I create final code incrementally, first we find all js files:

find <project_dir> -type f -name '*.js'

Then we iterate these files:

find <project_dir> -type f -name '*.js' | while read file_path; do
    # Code here run once for every file
done

Then we create a pattern by using the file name, and use sed to get rid of malicious code in file:

find <project_dir> -type f -name '*.js' | while read file_path; do
    file_name=$(basename "$file_path")
    pattern="/\*$file_name\*/.*/\*$file_name\*/"
    sed -ri "s:$pattern::g" "$file_path"
done

Some notes:

  • Step zero is backing up your files.
  • In sed command I used "s:$pattern::g" instead of "s/$pattern//g", because our search pattern already have '/' in it, and that makes sed confused.
  • This code handle file name containing space, at least I tried to handle it.
Related Question