Search code examples
stringsecuritysshmalware

Find and delete everything and between and including two strings with SSH?


I am struggling to write an ssh command that searches every file on my server that contains

<!--4e530a--> ... malcious code ... <!--/4e530a-->

And then deletes the tags and the javascript inside them.

Also curious to know how the code seems regenerates itself.


Solution

  • Firstly, if the malicious code is being "regenerated," then you have a much bigger problem on your hands than simply removing the malicious code from your files. You have likely been compromised through some means and the attacker has persistent access to your system, or has planted some malware (possibly a root-kit) that is molesting your server. You need to fix this problem!

    There are thousands of possibilities here, but some easy ones to check before you call a professional (you do need to call a pro, but the more info you can provide the cheaper it will be), are new user accounts, unusual user account activity, failed login attempts, unusual traffic loads/patterns, etc.

    As for your actual question, use find to feed the files to grep, and grep to search the files. Something like this:

    grep --color --line-number "malicious code" $(echo $(eval find / -type f))

    If you have a ton of files on your system, you may run into the "too many args" problem. If that happens you'll have to get creative with the script or else run it on subdirectories. If you want you can use a script I wrote on my Github called "findref.sh". This script will make what you're trying to do easy and it compensates for the "too many args" problem and grep.

    As for deleting the contents, that will be pretty tough (but possible) to do automagically with bash/SSH. You may want to write a Python or Perl script for that and SCP it over, then kick it off through SSH. Be careful using scripts to modify your code, especially if it's production code.