#!/bin/bash

### Not actually intended to be primary line of defense against malware.
### Get some real endpoint protection and use MalwareBytes when you need a good clean.
### This is really a quick automated way to get low-hanging fruit.
### This can run as a Munki postflight script or an Outset boot-every or an Offset logout-every
### Functions based on code from http://stackoverflow.com/a/6364244

# Define log location
LogLocation='/Library/Logs/MalwareRemoval.log'

# Terms to search for are just examples. Obviously, tweak as you see fit.
MalwareTerms=(
   "zeobits"
   "mackeeper"
   "MacKeeper"
   "MegaBackup"
)

# See what the last user was
LastUser=$(/usr/bin/defaults read /Library/Preferences/com.apple.loginwindow.plist lastUserName)

# Define a function that checks for a wildcard and then deletes it if it's found
function CheckAndRemoveLaunchD(){
   if ls "$3"/Library/"$1"/*"$2"* 1> /dev/null 2>&1; then
       echo "$(/bin/date) - $2 exists in $1. Deleting." >> "$LogLocation"
       # Delete them
       /bin/rm "$3"/Library/"$1"/*"$2"*
    else
       /bin/echo "$(/bin/date) - $2 does not exist in $1. Yay!" >>  "$LogLocation"
   fi   
}

# Define a function that checks for an application and then deletes it if it's found
function CheckAndRemoveApplication(){
   if [ -d "/Applications/$1" ]; then
       echo "$(/bin/date) - $1 exists. Deleting." >>  "$LogLocation"
       # Delete them
       /bin/rm -rf /Applications/"$1"
    else
       /bin/echo "$(/bin/date) - $1 does not exist. Yay!" >>  "$LogLocation"
   fi   
}

# Check there is a user who last logged in
if [ ! -z "$LastUser" ]; then

   # Define the directory to look for
   LastUserDir="/Users/$LastUser"

   # Check the directory for the user exists... a bit imprecise... technically the shortname doesn't have to match the home directory name
   # That's why we're checking the directory exists first
   if [ -d "$LastUserDir" ]; then

      for MalwareTerm in "${MalwareTerms[@]}"
         do
            # Remove user-specific launch agents
            CheckAndRemoveLaunchD "LaunchAgents" "$MalwareTerm" "$LastUserDir"
         done

   # End checking directory exists
   fi

# End checking last logged in user exists
fi

## Future possible tweak--make an array to go through in a loop instead of specifying individual values

# Remove launch agents
for MalwareTerm in "${MalwareTerms[@]}"
   do
      CheckAndRemoveLaunchD "LaunchAgents" "$MalwareTerm" ""
   done

# Remove launch daemons
for MalwareTerm in "${MalwareTerms[@]}"
   do
      CheckAndRemoveLaunchD "LaunchDaemons" "$MalwareTerm" ""
   done

# Also remove /Applications folder items
for MalwareTerm in "${MalwareTerms[@]}"
   do
      CheckAndRemoveApplication "$MalwareTerm.app"
   done
