We figured out that the .htaccess files were getting hacked about every 71 minutes, with a few random exceptions. We could not keep running my automated script every hour so I made a bash script from the command line and set up a cron job to run the script once every minute. If it found any differences between the .htaccess file and the .htaccess.bak file then it would overwrite the changes immediately, and send us an email.
Well, the hack was back. All our hard work for nothing. I knew we needed an automated repair to clean the infected .htaccess files with one click. So I wrote this quick little PHP script to clean all the infections out for us (see picture above). It was a good start but we obviously still had a vulnerability on our server and needed to figure out where it was.
Some of our domains started coming up as Infected in Google's search results. So we started looking on the server and found that most of the domains on our BlueHost account had a new .htaccess file. Even domains that had not had one at all before had a new one.
Upon inspection we discovered that each of these new .htaccess files had new rules that invoked a 301 redirect to another infected server when a user came to our sites from a search engine, or if there was an error on the page (404, 500, etc.) the user would also be redirected.
One of the tell-tail signs that these line in the .htaccess files were malicious was that they were heavily indented, You might not even see anything when you open the file unless you have line-wrap on or have it open on a high resolution screen in a wide window. You can see in the screenshot above how the code starts far to the right of the screen and wraps many time.
We manually removed th infected lines of code and replaced missing lines in each of these files. Believing that we had fixed it we decided to take a closer look later to figure out how the hack was planted.