#! /bin/bash
# Afrihost - cpanel - africlam_scan
# Popular Script Options:
# -a which can be run in auto mode with -a. Scan trigger is CWD quantity of mail in exim log today
# -cdir to run manually from within public_html 
# Note: Client sites are IP protected with .htaccess allow from rules with known ZA ranges, google, twitter, etc

# africlam_scan --help
#        [-h|--help] 
#        [-a|--automaticlly scan sites which have sent more than 300 mails today according to cwd in exim_mainlog] 
#        [-f|--full (full server public_html dir scan)]
#        [-cdir|--scan the public_html that you are currently in.]
#        [-u|--userlist (scan home dirs of users in /root/africlamusers)
#

#set -uvx # comment out for debbuging

##################################
## setting up logs env          ##
##################################

pscript=$(basename $0)
PWDIR="/var/log/afrilogs/$pscript"
DEDICONTACTFILE="/etc/africlam_contact"
DEDICONTACTEMAIL="$(if [ -f $DEDICONTACTFILE ] ;  then cat "$DEDICONTACTFILE"  ; fi )"

if [ ! -d "$PWDIR" ]; then
                mkdir -p "$PWDIR" ;
fi

serverlog="$PWDIR/users/"
if [ ! -d "$serverlog" ]; then
        mkdir $serverlog
fi

userlogarchive="$PWDIR/userarchive/"
if [ ! -d "$userlogarchive" ]; then
        mkdir $userlogarchive
fi

log2emailarchive="$PWDIR/emailarchive/"
if [ ! -d "$log2emailarchive" ]; then
        mkdir $log2emailarchive
fi

log2email="$PWDIR/`hostname`-clam-infected-`date +"%d%m%Y"`.log"

# Some pre-flight checks 
pre_requ () {
which mail | grep -q mail
if [ $? -eq 1 ]; then
        yum -y install  mail 
        which mail | grep -q mail
                if [ $? -eq 1 ]; then
                       echo " :: YUM ERROR ::mail couldn't be installed"
                       exit 1 
                fi 
fi

which clamscan 
if [ $? -eq 1 ] ; then 
        if /usr/local/cpanel/3rdparty/bin/clamscan -V  ; then  
                ln -s /usr/local/cpanel/3rdparty/bin/clamscan /usr/bin/clamscan  
          else  /usr/local/afribin/maintenance/africlam_install2015  
        fi 
fi

if /usr/local/cpanel/3rdparty/bin/clamscan -V  ; then
                ln -s /usr/local/cpanel/3rdparty/bin/clamscan /usr/bin/clamscan
fi

if ! which maldet | grep  maldet ; then
        sh /usr/local/afribin/configs/maldet/maldet_installer
fi

if ! [ -f /root/.saneinstalled ] ;  then  /usr/local/afribin/configs/clamd_sane.sh ; fi 
}


##################################
## Run Modes                    ##
## run -h for options           ##
## eg: full server scan         ##
## eg: user list                ##
## eg: current directory etc..  ##
##################################
auto_users() {
        grep cwd /var/log/exim_mainlog | 
                grep -v /var/spool | 
                awk -F"cwd=" '{print $2}' | 
                awk '{print $1}' | sort | uniq -c | 
                sort -n  | egrep -v "/root" |  awk '$1>=400 {print $0}' | 
                grep home | sed 's#/u1##'|  
                awk '{print $2}'  | 
                awk  -F "/" '{print $3}' > /root/africlamusers.tmp
                for i in $(find /root/.preports/exim/*.hsb* -mtime 0 ) ; do cat $i ; done | egrep -v "@|/" |awk '($1 > 200 ) {print $2}' | tee -a /root/africlamusers.tmp
                sort /root/africlamusers.tmp | uniq | tee /root/africlamusers ; rm -fv /root/africlamusers.tmp
          userlist=/root/africlamusers
          if ! [[ -s $userlist ]] ; then
                echo -e "$userlist is empty.\n- Please add users to $userlist"
                exit 
          fi
          mode=$(cat /root/africlamusers | sort | uniq)
}

full_users () {
        mode=$(awk -F ": " '{print $2}' /etc/trueuserdomains)
}

user_list () {
        userlist=/root/africlamusers
        if ! [[ -s $userlist ]] ; then
                echo -e "$userlist is empty.\n- Please add users to $userlist"
                exit 
        fi
        mode=$(cat /root/africlamusers | sort | uniq)
}

cd_mode () {
         if [[ $PWD/ = /home/*/public_html/* ]]; then 
                mode=$(echo $PWD  | awk  -F "/home/" '{print $2}' | awk  -F "/" '{print $1}')
         fi
}

user_dirs () {
        userdirs=/root/africlamuser_dirs
        if ! [[ -s $userdirs ]] ; then
                echo -e "$userdirs is empty.\n- Please add paths to $userdirs"
                exit
        fi
        awk  -F "/" '{print $3}' $userdirs > /root/africlamusers
        mode=$(cat /root/africlamusers | sort | uniq) 
}

#########################################
# The scan according to the chosen mode #
#########################################

live_scan () {

echo -e "\n:::: Running Scan on $CPUsER ::::\n"
pdate=$(date +"%Y"-"%m-%d-%R")
echo "Date=$pdate"
pusername="$CPUsER"
echo "Cpuser=$CPUsER"
echo "Scan_path=$LIVESCANPATH"
JOBID=$(shuf -i 1-100000 -n 1)
linkfarmscanfile="/home/"$pusername"/.secscan/lf_scan_"$pusername"_"$pdate"_$JOBID"
#echo "Linkfarm_log=$linkfarmscanfile"
clamscanfile="/home/"$pusername"/.secscan/clam_scan_"$pusername"_"$pdate"_$JOBID"
if [ $(rpm -qa | grep -c imun) -gt 15 ] ; then
        echo "imunfify360 installed"
        # creating logging env
        if [ ! -d /home/"$pusername"/.secscan/ ]; then
                 mkdir -p /home/"$pusername"/.secscan/
        fi
        echo `hostname` > "$linkfarmscanfile"
        echo "$pdate" >> "$linkfarmscanfile"
        echo "$pusername" >> "$linkfarmscanfile"
        echo `hostname` > "$clamscanfile"
        echo "$pdate" >> "$clamscanfile"
        echo "$pusername" >> "$clamscanfile"
        imunify360-agent malware on-demand queue put "$LIVESCANPATH"
        echo "== imunify360 scan initiated - results can be seen in cpanel > imunify360 within an hour."
else
linkfarmscanfile="/home/"$pusername"/.secscan/lf_scan_"$pusername"_"$pdate"_$JOBID"
echo "Linkfarm_log=$linkfarmscanfile"
clamscanfile="/home/"$pusername"/.secscan/clam_scan_"$pusername"_"$pdate"_$JOBID"
echo "Clamscan_log=$clamscanfile"
if echo $LIVESCEMAIL | grep @ ; then
echo REPORT_SEND_TO="$LIVESCEMAIL"
fi

echo -e "\n"

if [ ! -d /home/"$pusername"/.secscan/ ]; then
         mkdir -p /home/"$pusername"/.secscan/ 
fi

echo `hostname` > "$linkfarmscanfile"
echo "$pdate" >> "$linkfarmscanfile"
echo "$pusername" >> "$linkfarmscanfile"

echo `hostname` > "$clamscanfile"
echo "$pdate" >> "$clamscanfile"
echo "$pusername" >> "$clamscanfile"

linkfarmscan --limit=99999 -v $LIVESCANPATH >> "$linkfarmscanfile"
nice `which clamscan` -ir --scan-archive=no $LIVESCANPATH >> "$clamscanfile"
chmod 700 /home/"$pusername"/.secscan/
chmod 600 /home/"$pusername"/.secscan/*
chown -R "$pusername"."$pusername" /home/"$pusername"/.secscan/

if  [ "$LIVESCEMAIL" ] ; then 
echo -e "\n==== LINKFARMSCAN RESPORT ====\n$(cat $linkfarmscanfile) \n==== CLAMSCAN REPORT =====\n$(cat $clamscanfile)\n WE SUGGEST YOU DOWNLOAD YOUR SITE AND USE ADDITIONAL REPUTABLE ANTIVIRUS SCANNER TO SCAN YOUR SITE! " | mail -s "`hostname` Security Scan of $LIVESCANPATH" $LIVESCEMAIL
fi
fi 
}

the_scan () {
# Seeting up the log and quarantine directories.
for pusername in $(echo "$mode") ; do 
        echo -e ":::::: SCANNING $pusername :::::::\n\n"
        USERSDOMAIN=$(grep $pusername /etc/trueuserdomains | awk -F ":" '{print $1}')
        cleanup_queue () {
                service exim stop
                /usr/local/afribin/eximanage --dfrom ".*$pusername.*"
                /usr/local/afribin/eximanage --dfrom ".*$USERSDOMAIN.*"
                /usr/local/afribin/eximanage --dfrom  "<>"
                /usr/local/afribin/eximanage --dfrom  ".*_.*"
		/usr/local/afribin/configs/cpanel_exim_config_ylmf_block
        }
        cleanup_queue
        if [ ! -d "/home/"$pusername"/clam_quarantine" ]; then
          mkdir /home/"$pusername"/clam_quarantine
          touch /home/"$pusername"/clam_quarantine/$pusername-scan-email
          CLIENTABUSEEMAIL="/home/$pusername/clam_quarantine/$pusername-scan-email"
          echo  "Pcheck   ::::::::::::::::::::::::  $CLIENTABUSEEMAIL :::::::::::::::::::::::"
          chown $pusername:$pusername /home/"$pusername"/clam_quarantine
          chmod 750 /home/"$pusername"/clam_quarantine
        fi        
        if [ -f $serverlog/$pusername-clam.log ] ; then
                cp $serverlog/$pusername-clam.log $userlogarchive/$(printf "%06d" $RANDOM)-$pusername-clam.log                 
        fi        

# The scan
        echo -e "Scanning user $pusername"                        
        rm -vf /home/$pusername/clam_quarantine/$pusername-clam.log
        rm -vf $serverlog/$pusername-clam.log
        nice /usr/bin/clamscan -ir --log=$serverlog/$pusername-clam.log --scan-archive=no --move=/home/"$pusername"/clam_quarantine /home/"$pusername"/public_html/ 
        cp $serverlog/$pusername-clam.log /home/"$pusername"/clam_quarantine/
        chown $pusername:$pusername /home/"$pusername"/clam_quarantine/*
        find /home/"$pusername"/public_html/ -maxdepth 1 -type l -exec unlink {} \;
        find /home/"$pusername"/public_html/  -type f  ! -name \*.php  ! -perm 644 -exec chmod  644 {} \;
        find /home/"$pusername"/public_html/ -type f -name \*.php ! -perm 640 -exec chmod 600 {} \;
        find /home/"$pusername"/public_html/ -type d -name \*xBlack_Configs | quarantine 
        cd /home/"$pusername"/public_html/ ; screen -dmS fsecure frob secure
# Condition whether scan found anything or not.
infectedcondition () {
                grep  "Infected files"  /home/$pusername/clam_quarantine/$pusername-clam.log  | awk '$3>0 {print $3}' | grep [1-9]
}
infectedcondition
      
         if [ $? -eq 0 ]; then
                INFECTIONSFOUND=0
                echo "  :: INFECTIONS FOUND ::"
                        else
                INFECTIONSFOUND=1
                echo -e "::::: NO INFECTIONS FOUND, ADIOUS AMIGO ::::::\n\n\n" 
                continue
        fi

# linkfarmscan
africlam_linkfarmscan () {
                 /usr/local/afribin/linkfarmscan --limit=99999 -v /home/$pusername/public_html/ | tee -a /home/$pusername/clam_quarantine/$pusername-lf_scan.log        
                 chown $pusername:$pusername /home/"$pusername"/clam_quarantine/* 
}
africlam_linkfarmscan


# Generate attack info such as file names, IPs, Dates
getinfo () {        
        DOMAINCONTACTEMAIL=$(awk -F "="  '/CONTACTEMAIL/ {print $2}' /var/cpanel/users/$pusername | head -1)

        echo "$DOMAINCONTACTEMAIL" 
 
        DODGEIPS=$(for dodgefile in  $(awk -F "/home/$pusername/public_html/"  '{print $2}' /home/"$pusername"/clam_quarantine/$pusername*.log | 
                        awk -F ":"  '{print $1}'  | 
                        grep . ) ; do grep `date +"%d/%b/%Y"` /home/$pusername/access-logs/* | 
                        grep  $dodgefile  ; done  | 
                        grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' | 
                        sort | 
                        uniq )        
        
        echo "'$DODGEIPS" | tee -a /home/"$pusername"/clam_quarantine/clamips.log
        
        USERSDOMAIN=$(grep $pusername /etc/trueuserdomains | awk -F ":" '{print $1}')
        
        echo "'$USERSDOMAIN"
        
        ALLPOSSIBLEDODGE=$(for dodgefile in  $(awk -F "/home/$pusername/public_html/" '{print $2}' /home/"$pusername"/clam_quarantine/$pusername-clam.log | 
                        awk -F ":"  '{print $1}'  | 
                        grep .) ; do grep $dodgefile /home/$pusername/access-logs/* ; done | 
                        grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' | 
                        sort | 
                        uniq |tail -100 | 
                        xargs -i grep {}  /home/$pusername/access-logs/* | 
                        awk '{print "."$7}' | 
                        sort | 
                        uniq)
        echo "./$ALLPOSSIBLEDODGE"
 
        LFSCAN_RESULT="$(grep "home" /home/$pusername/clam_quarantine/$pusername-lf_scan.log)"

 PROHIBITIPS () {
        for blockip in `echo "$DODGEIPS"` ; 
                do echo "# ips route add prohibit $blockip "
        done
        }
PROHIBITIPS

        cleanup_queue () {
                /usr/local/afribin/eximanage --dfrom ".*$pusername.*"
                /usr/local/afribin/eximanage --dfrom ".*$USERSDOMAIN.*"
                /usr/local/afribin/eximanage --dfrom  "<>"
                /usr/local/afribin/eximanage --dfrom  ".*_.*"
        }
        cleanup_queue
}
getinfo

echo "::::::::::: Got info for report ::::::::::::::"

createreport () {
        touch /home/"$pusername"/clam_quarantine/$pusername-scan-email
        CLIENTABUSEEMAIL="/home/$pusername/clam_quarantine/$pusername-scan-email"
        DOMAINNAME=$(grep $pusername /etc/trueuserdomains|awk -F ":" '{print $1}'|head -1)
        SERVERIP=$(ip addr | egrep 'lo|global'|awk '{print $2}'|grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}'|grep -v 127\.0\.0|head -1)

echo -e "\n\n

Hi There,

Hope this finds you well.

You have received this mail due to an event which triggered a 
virus/malware scan and your domain is infected.

Please attend to this as soon possible and update us with your confirmation
that this has been attended to.

Detection timestamp: `date`
Server IP: $SERVERIP
Hostname: `hostname`

::::::::::::::::::::::::::::::::::::::::::::::::::
::: Recommended steps to resolve this incident :::
::::::::::::::::::::::::::::::::::::::::::::::::::

1. Login to cpanel > file manger and download the following files:

/home/"$pusername"/clam_quarantine/
/home/"$pusername"/clam_quarantine/"$pusername"-clam.log   <-- known malicious virus/malware signatures
/home/"$pusername"/clam_quarantine/"$pusername"-lf_scan.log   <--- highly possible maliciously infected files

########################################################

2. Analyse the results from the provided scan logs and clean, remove or replace any infected 
or highly suspicious files.

Please feel free to access a scanning and patching application called patchman 
to get an idea of what's currently infected and you might be able to clean infected files 
from the patchman interface if this is not possible or cleaning options greyed out 
you will have to physically assess that particular file either clean, remove or replace.

To access patchman > login to cpanel > search for patchman.

2.1 Please also check email forwarders and filters and ensure that no unauthorized access has 
been made to your domains email accounts and no mail interception fraud is being attempted.

https://help.afrihost.com/topic/security/how-to-protect-yourself-from-email-interception-fraud
https://help.afrihost.com/topic/domains-and-hosting/how-to-manage-email-filters-in-cpanel

########################################################

3. look for any files in the report that have been flagged suspicious but have not 
been moved into quarantine. We suggest replacing these files with clean versions from 
the applications maintainers website.

########################################################

4. SECURING YOUR SITE

4.1. Generate a strong password combination [for account, ftp, database etc]

4.2. Don't use the "admin" username, change it to something less common.

4.3. Limit Login Attempts

In the case of a hacker or a bot attempting a brute-force attack to crack your password, 
it can be useful to limit the number of failed login attempts from a single IP address.

    https://wordpress.org/plugins/limit-login-attempts/installation/


4.4. Protect your WordPress/joomla Admin Area

It is important to restrict the access to your WordPress admin area only to people that actually need access to it. 
If your site does not support registration or front-end content creation, your visitors should not be able to access your /wp-admin/ 
folder or the wp-login.php file. The best you can do is to get our home IP address (you can use a site like whatismyip.com for that) and 
add these lines to the .htaccess file in your WordPress admin folder replacing xx.xxx.xxx.xxx with your IP address.

# for wordpress
<Files wp-login.php>
 order deny,allow
 Deny from all
 allow from 169.0.0.0/16
 allow from 127.0.0.1
 allow from xx.xxx.xxx.xxx
</Files>

# for joomla or other aplication admin sections
# In the admin section folder create a .htaccess file if one doesn't exist or
# prepend if does exist the following:

<LIMIT GET POST>
 order deny,allow
 deny from all
 allow from 169.0.0.0/16
 allow from 127.0.0.1
 allow from xxx.xxx.xxx.xxx
</Limit>


4.5. Add additional protection against bot scans etc in the .htaccess file in public_html

# protect against humans scans
<IfModule mod_rewrite.c>
RewriteCond %{QUERY_STRING} http\:\/\/www\.google\.com\/humans\.txt\? [NC]
RewriteRule .* - [F,L]
</IfModule>

# deny POST request using HTTP 0.9 / 1.0
<IfModule mod_rewrite.c>
RewriteCond %{THE_REQUEST} ^POST(.*)HTTP/(0\.9|1\.0)$ [NC]
RewriteRule .* - [F,L]
</IfModule>


4.6. Install web application firewall such as wordfence or rsfirewall


4.7. Password protection

Protect the admin/administration section (normally a folder) with additional
password protect Cpanel offers this control

4.8. If the application is not being used, please remove it entirely. 

4.9. Remove all non-essential and disabled plugins.

Delete the extenstion files of any unnecessary extensions - only disabling an
extension will leave weak files in place.

4.10. Remove all/any old or unused applications ie: old wordpress installation in the public_html.

4.11. Disable unnecessary admin logins

4.12. Change the administration passwords for all administrators of the web applications backend. 

Check that there are no newly created administrator users which you are unaware of.

4.13. Upgrade applications

Upgrade to the current version of the web application(s) or reinstall the web
application if it is already the current version.

4.14. Upgrade all plugins and modules, and if possible reinstall.

4.15. Change the database access password used by your application

4.16. Restrict IP access using htaccess to admin sections and upload sections to trusted IPs only

4.17. IP based acl's

Consider blocking by IP in folder specific htaccess files. eg: sign-up forms,
comments for forums, content management systems, and blogs, as this will
prevent many attacks.

4.18. Mail passwords

Set new passwords for all mail accounts where the length of the current
password is 7 letters or less. (With access to the account one can copy the
encrypted passwords, and decrypt simpler passwords by brute force.)

4.19. Trojans

Remove any modifications made to the web site content (e.g.  additional
administrator accounts, trojan plugins, spam edits to the beginning or the end
of the files, etc.) You can find some of these by looking for files with
recently modified timestamps.

4.20. Browser

Consider using a browser which will resist cross site scripting (XSS) attacks,
especially when doing administrative functions on the site (e.g. up to date
Chrome or Firefox with the NoScript plugin). This is important if the content
of your site has been modified to link to malware.

4.21. Permissions

Use the file manager or FTP to set permissions on the your configuration files
and their parent directory so that these cannot be read (ie. drwx--x--x, 0711).

4.22. Problems with backups

Understand that if you do restore the account from a backup you will restore
the account to its vulnerable state, and you may also reinstate the
modifications made by the intruders. 

4.23. Desktop systems

Examine the desktop systems which are used for administering this site for
malware (viruses, keyloggers) with up to date security software, especially if
it seems that the intruder had access to your administration passwords.

4.24. Think 

Consider that there may be more to this problem than meets the eye: for
example, the offending file or content may be present on desktop systems that
are associated with this account.
 
4.25. Shared passwords, software

The same applications, plugins, themes and passwords that led to the incident
on this account may be in use on other accounts. Please be sure to update not
only this account, but also the other accounts which are similarly vulnerable
to intruders.

4.26 Known-bad software

Check whether any extensions listed on the vulnerable extensions list are in
your installation:

 Joomla : http://vel.joomla.org/

 Wordpress : https://wordpress.org/plugins/tags/vulnerability

########################################################

5. After fixing the problem

Please attend to this as soon possible and update us with your confirmation
that this has been attended to.

We will then review the domain and remove the password protection or ZA IP restrictions.        

Or you are more than welcome to remove the ZA IP restrictions in the htaccess file.

We apologise for the negative impact caused, but this was all carried out to protect 
the reputation of your domain and the server's IP.


########################################################

" | tee "$CLIENTABUSEEMAIL"

}
createreport

echo " ::::::::::: Report created ::::::::::::::"

# Lock out and notification functions (derived from Security and notification functions below) 

frobhacking () {
               echo -e "\n:: Frob HACKING $pusername :: \n REPORT: $CLIENTABUSEEMAIL"
               cd /home/$pusername/public_html 
               chmod 644 /home/$pusername/public_html/.htaccess ; chattr -i /home/$pusername/public_html/.htaccess 
               frobhpass=$(/usr/local/afribin/frob hacking |   awk '{print  $NF}')
               echo "sed -i 's/protectpass/$frobhpass/' "$CLIENTABUSEEMAIL""  | bash
               echo "sed -i 's/yourdomain/$USERSDOMAIN/' "$CLIENTABUSEEMAIL""  | bash
}

only_allow_za () {
                echo -e "\n:: Only allowing ZA IPs to access this site due to infections found :: \n REPORT CAN BE FOUND HERE: $CLIENTABUSEEMAIL"
                cd /home/$pusername/public_html
                chmod 644 /home/$pusername/public_html/.htaccess ; chattr -i /home/$pusername/public_html/.htaccess
                cat /usr/local/afribin/maintenance/.htaccess_joomla_admin_dir_lockdown | tee -a /home/$pusername/public_html/.htaccess
}

# Notification configs
emailcpanelcontact () {
                        cat  "$CLIENTABUSEEMAIL" | 
			mail -s "`hostname` Security alert $USERSDOMAIN - confidential" -b abuse@afrihost.com,paulo@afrihost.com -S from=abuse@afrihost.com "$DOMAINCONTACTEMAIL"
                 if [ $? -eq 0 ]; then
                                continue
                        else
                      cat "$CLIENTABUSEEMAIL" | mail -s "`hostname` Security alert $USERSDOMAIN" "abuse@afrihost.com" "$DOMAINCONTACTEMAIL"
                 fi
                      echo -e "\n::: MAIL SENT TO "$DOMAINCONTACTEMAIL"\n::: Report can be found here: "$CLIENTABUSEEMAIL""

}
emailabuseandreseller  () {
                 cat  $CLIENTABUSEEMAIL
               #  | mail -s ":: `hostname` ClamAV infections found - confidential ::"  paulo@afrihost.com "$DOMAINCONTACTEMAIL" "abuse@afrihost.com"
}
emailabuse  () { 
        if [ ! -f "$DEDICONTACTFILE" ]; then
                        cat "$CLIENTABUSEEMAIL" | mail -s "`hostname` Security alert for $USERSDOMAIN" -S from=abuse@afrihost.com "abuse@afrihost.com"
                        if [ $? -eq 0 ]; then
                                       continue
                               else
                             cat "$CLIENTABUSEEMAIL" | mail -s "`hostname` Security alert for $USERSDOMAIN" "abuse@afrihost.com"
                        fi
                        echo -e "\n::: MAIL SENT TO abuse which in turn gets mailed to the dedicated servers primary contact.\n::: Report can be found here: "$CLIENTABUSEEMAIL""
                else
                        if cat "$DEDICONTACTFILE" | /usr/local/afribin/emailgrep ; then 
                                cat "$CLIENTABUSEEMAIL" | mail -s "`hostname` Security alert on domain $USERSDOMAIN" -S from=noreply@`hostname` "$DEDICONTACTEMAIL"
                        if [ $? -eq 0 ]; then
                                       continue
                               else
                             cat "$CLIENTABUSEEMAIL" | mail -s "`hostname` Security alert for $USERSDOMAIN" "abuse@afrihost.com"
                        fi
                        echo -e "\n::: MAIL SENT TO abuse which in turn gets mailed to the dedicated servers primary contact.\n::: Report can be found here: "$CLIENTABUSEEMAIL""
                        fi
      fi 
}

restart_exim () {
                /scripts/restartsrv_exim ; /scripts/restartsrv_dovecot
		/usr/local/afribin/configs/cpanel_exim_config_ylmf_block
}

restart_exim

# Security/protection allow based on hostname 
server_check()
{
        if    [[ `hostname`  = "daggoth.aserv.co.za" ]] ; then
                echo "This is an IS-Server and we cannot act according to mojo domain status."
                exit 1
        elif    [[ `hostname`  = "kerrigan.aserv.co.za" ]]; then
                echo "This is an IS-Server and we cannot act according to mojo domain status."
                exit 1
        elif    [[ `hostname`  = "amon.aserv.co.za" ]]; then
                echo "This is an IS-Server and we cannot act according to mojo domain status."
                exit 1
        elif    [[ `hostname`  = "*.au" ]]; then
                echo "This is an Ausie server and we cannot act according to mojo domain status."
                exit 1
        elif    [[ `hostname`  = "apache.aserv.co.za" ]]; then
                echo "This is an IS-Server and we cannot act according to mojo domain status."
                exit 1
        elif    [[ `hostname`  = *\.dedicated\.co\.za ]]; then
                echo "This is a dedicated server, frob hacking "
                #frobhacking
                only_allow_za
                emailabuse
                restart_exim
                echo "SCAN and REPORT COMPLETE, Notification Sent"
        elif    [[  `hostname`  = *\.aserv\.co\.za ]]; then
                echo "This is an aserv server, frob hacking and mailing info"
                #frobhacking
                only_allow_za
                emailcpanelcontact
                restart_exim
                echo "SCAN and REPORT COMPLETE, Notification Sent"
        fi
}
server_check        
done
}

infected_stats () {
for i in $(awk '{print $2}' /etc/trueuserdomains) ; do 
        if grep -sq "Infected files: [1-9].*" /home/$i/clam_quarantine/*-clam.log ; then 
                echo -e "$(grep $i /etc/trueuserdomains|awk -F ":" '{print $1}') :: $i :: $(grep -s "Infected files:" /home/$i/clam_quarantine/*-clam.log|grep -v "Infected files: 0") :: Infected File LastModified timestamp: $(ls -1t /home/$i/clam_quarantine/ |egrep -v 'scan-email|*.log'|tail -1|xargs -i stat /home/$i/clam_quarantine/{} |awk '/Modify/ {print $2}') scan_date: $(stat /home/$i/clam_quarantine/*-scan-email*| grep Modify | awk '{print $2}')" 
        fi
done | grep "Infected files:" 
}

nofify_someone () {
if [ -f $log2email ] ; then
       cp $log2email $log2emailarchive/$(printf "%06d" $RANDOM)-`hostname`-clam-infected.log
       echo " " > $log2email
fi

for i in $(grep -i -s  infected $serverlog/*  | grep  -v "Infected files: 0"  |  awk -F ":" '{print $1}') ; do 
        echo -e "\n\n\n\n$i  `cat  $i` \n\n\n "  | tee -a $log2email
done

#grep FOUND "$log2email"
#if [ $? -eq 0 ]; then
#                cat $log2email | mail -s "`hostname` ClamAV infections found"  paulo@afrihost.com
#fi
}

r1soft_backup_check () {
        if  [ -f /usr/sbin/hcp ] ; then 
                 if  hcp -l  | grep -q "Time" ; then 
                        echo "[ R1-backup Running - clamscan will cause to much load ]"
                        echo "[ Please try again later ]"
                        exit
                fi
        fi
}
        
usage_short() {
cat <<EOF

echo -e "Usage:
africlamscan 
        [-h|--help] 
        [-a|--automaticlly scan sites which have sent more than 300 mails today according to cwd in exim_mainlog] 
        [-f|--full (full server public_html dir scan)]
        [-cdir|--scan the public_html that you are currently in.]
        [-u|--userlist (scan home dirs of users in /root/africlamusers)
        [-udir|--userdirs ]
        [-stats] (shows stats of infected sites)
        [-livescan] (shows stats of infected sites)

NOTE ::: Custom email address can be specified in /etc/africlam_contact"
EOF
}


if [ -z "$1" ]; then
        usage_short
else
 while [ -n "$1" ]; do
 case "$1" in
        -a|--auto)
               if [ "$2" != "--force" ] ; then r1soft_backup_check ; fi 
               pre_requ
               auto_users
               the_scan
        ;;
        -f|--full)
               if [ "$2" != "--force" ] ; then r1soft_backup_check ; fi 
                pre_requ
                full_users
                the_scan
        ;;
        -u|--userlist)
               if [ "$2" != "--force" ] ; then r1soft_backup_check ; fi 
                pre_requ
                user_list
                the_scan
        ;;
        -cdir|--currentdirectory)
               if [ "$2" != "--force" ] ; then r1soft_backup_check ; fi 
                pre_requ
                cd_mode
                the_scan
        ;;
        -udirs|--userdirs)
               if [ "$2" != "--force" ] ; then r1soft_backup_check ; fi 
                pre_requ
                user_dirs
                the_scan
        ;;
        -stats)
               if [ "$2" != "--force" ] ; then r1soft_backup_check ; fi 
                infected_stats
        ;;
        -livescan)
                if ! [ "$2" ] ; then
                                echo "live_scan 2nd option requires abolute path to scan eg: /home/username/sitepath/"
                                echo "eg: africlamscan -livescan /home/username/sitepath/"
                                echo "Optional 3rd option is email address to email a report to"
                                echo "eg: africlamscan -livescan /home/username/sitepath/"
                                exit 1
                                else
                                LIVESCANDIRTMP="$2"
                                LIVESCEMAILtmp="$3"
                                if echo $LIVESCEMAILtmp | grep @ ; then LIVESCEMAIL=$3 ; fi
                                CPUsER=$(echo $LIVESCANDIRTMP | awk  -F "/home/" '{print $2}' | awk  -F "/" '{print $1}')
                                        if grep -q "$CPUsER"  /etc/trueuserdomains ; then
                                                LIVESCANPATH=$2
                                              else
                                                echo -e "\nProvided path NOT within /home/user\n"
                                                echo "\neg:  africlamscan -livescan /home/username/sitepath/\n"
                                                exit
                                        fi
                fi
                live_scan
                exit
        ;;
        -h|--help)
                usage_short
        ;;
        *)
                usage_short
        esac
        shift
        done
fi
exit
