#!/usr/bin/perl
use strict;
use Switch;
use File::Path;
use File::Touch;
use Sys::Hostname;
use Module::Load;
use Module::Load::Conditional qw[can_load  requires];


my ( $type, $action, $target, $ticket ) = @ARGV;

sub usage {
    die "[!] Usage: $0 <cpanel|email|http|exim|script|cron> <enable|disable> <domain|account|email> <ticket-id>\n";
}

usage() unless (
    ( $type =~ /^(cpanel|email|http|exim|script|cron)$/ ) &&
    ( $action =~ /^(enable|disable)$/ ) &&
    ( $target ) &&
    ( $ticket )
);

my %actions = (
    cpanel => \&cpanel,
    email => \&email,
    http => \&http,
    exim => \&exim,
    script => \&script,
    cron => \&cron
);

if ( ! -f '/root/bin/rebuild_http_suspension' ) {
    die "[!] Required script [/root/bin/rebuild_http_suspension] not found!\n";
}

my @confs;
open(my $fh, '<', '/usr/local/apache/conf/includes/pre_main_global.conf');
	while(<$fh>) {
		push(@confs, $_);
	}
close($fh);
open($fh, '<', '/usr/local/apache/conf/bluehost.conf');
	while(<$fh>) {
		push(@confs, $_);
	}
close($fh);

if ( ! grep(/^Include(?:Optional)? \S+\/disable_user_httpd\.con(?:\[f\]|f)"?$/, @confs) ) {
	die("[!!] Server does not support abusetool. Please escalate this.\n");
}
@confs = ();

my $domain;
my $user;

if ( $target =~ /@/ ) {
    ( undef, $domain ) = split('@', $target);
    open(my $DAT, '<', '/etc/userdomains');
        while(<$DAT>) {
            if ( /^$domain:\s([a-zA-Z0-9]+)$/ ) {
                $user = $1;
            }
        }
    close($DAT);
} else {
    open(my $DAT, '<', '/etc/userdomains');
        while(<$DAT>) {
            if ( /^$target:\s([a-zA-Z0-9]+)$/ ) {
                ( $domain, $user ) = ( $target, $1 );
            } elsif ( /^([a-zA-Z0-9\-\.]+):\s$target$/ ) {
                ( $domain, $user ) = ( $1, $target );
            }
        }
    close($DAT);
}

if (( ! $domain ) || ( ! $user )) {
    die "[!] Could not find an account associated with input!\n";
}

sub module_load {
    my $module = shift;
    my $module_list = {
        $module => undef,
    };
    if (can_load(modules => $module_list)) {
       load $module;
       $module->import;
       return 1;
    }
    else {
          print "$Module::Load::Conditional::ERROR\n";
          return 0;
        }
}

sub mail_template {
  my $service_type = shift;
  my $BU_Name = shift;
  switch ($service_type) {
        case ($service_type)   {
   return "Dear Customer,

We have observed unusual email activity from one of your email accounts $user under the domain $domain.


In order to prevent further damage to our infrastructure and keep the reputation of IP address intact, we have temporarily suspended the outgoing email funtionality (SMTP service) for the email account $user. Please note that you will still be able to receive emails. Only the outgoing email (SMTP service) has been suspended.

Before you request for unsuspension, we ask you to run through the following checklist and take necessary action wherever applicable:

* Reset the password for email accounts with more complex and secure passwords.
* If a mail client is being used to send/receive emails (Outlook, Thunderbird etc), please scan the entire PC where the email account is setup. The PC may be infected with malware operated by spambots.
* If a CMS (Wordpress,Joomla etc.) is involved, please check for vulnerable plugins and upgrade the plugins/CMSs as soon as possible. Also, it is recommended to change the admin password of the CMS.
* Recheck the email script, fix the loopholes in the script.
* Setup captcha for your email form.
* Refrain from sending bulk emails via scripts.


For any further clarifications, unsuspension requests, please contact our Support helpdesk.

Regards,
$BU_Name
Disclaimer: This is an auto-generated email sent by our monitoring system. Please contact our Support helpdesk for further information." ;
                        }

                      }

                    }

sub mail_this {

  my ($host,$Sender,$To_Email_ID,$mail_body) = @_;
  my $message = MIME::Lite->new(
                  From    => "$Sender",
                  To      => $To_Email_ID,
                  Subject => "Subject: High amount of SPAM originating from account $user ($domain).",
                  Data    =>  $mail_body
  );
  $message->send('smtp', $host);
  if ( $? ) {
      my $now = time();
      print "[!] Email not successfully sent. \n";
  } else {
      print "Email send successfully from  $Sender to $To_Email_ID .\n";
  }

}

sub notify_APAC_customers {
    my $service_type = shift;
    module_load ('YAML::Syck') or return 1;
    my $yaml = eval { LoadFile("/opt/eig_linux/etc/account_pl.yaml") }  ;
    my $organization = $yaml->{organization} if (ref($yaml) eq "HASH") ;
    unless ($organization) {
        $yaml = eval { LoadFile("/opt/eig_linux/etc/account_pl_apac_legacy.yaml") } or return 1 ;
        $organization = $yaml->{organization} if (ref($yaml) eq "HASH") ;
        return 1 unless ($organization);
      }
    return 1  unless ($organization eq "DIRECTI" );
    my $location = $yaml->{location};
    module_load ('LWP::Simple') or return 1;
    module_load ('MIME::Lite') or return 1;
    my ($cust_reseller_email,$BU_Name,$BU_Email,$value);
    my $hostname = hostname();
    print "Notifying the customer of $domain on  the server $hostname about Abuse and Adding to Spamtrac also \n";
    ## spamtrac looks it works only with curl command
    qx(curl -k "https://spamtrac.india.endurance.com/linuxapi/add?emailid=$user\@$domain&hostname=$hostname&method=8&action=Blacklisted&colo=$location" >out 2>&1);
    my @bll_return =  get("http://bll-1.webhostbox.net:8082/montro-bll/details.xml?domainname=$domain&hostname=$hostname");

    foreach (@bll_return) {
       chomp $_;
       if ($_ =~ /abuseEmailAddress>(.*)</) {
          $cust_reseller_email = $1 ;
           }
       if ($_ =~ /bizBranding>(.*)</) {
           $BU_Name = $1 ;
               }
      if ($_ =~ /bizFromEmail>(.*)</) {
        $value = $1;
        $value =~ s/hosting-review\@supportnation.com/help\@supportnation.com/;
        $value =~ s/hosting-review\@/support\@/;
        $value =~ s/.*@/noreply@/;
        $BU_Email = $value ;
                       }
       }
    unless  ($cust_reseller_email or $BU_Name or $BU_Email) {
             print  "Unable to get Domain details from BLL\n";
             return 1;
              }

  my $mail_body = mail_template($service_type,$BU_Name);
  print  "Sending mail to $cust_reseller_email, for primary domain $domain as $BU_Name <$BU_Email>\n";
  mail_this("localhost","$BU_Name <$BU_Email>",$cust_reseller_email,$mail_body );
  my @Mail_Attachment = `exigrep $domain /var/log/exim_mainlog`;
  mail_this("spamtrac.india.endurance.com","SwVpWNhBSBqB2WWhdKs2","$user\@$domain",\@Mail_Attachment);

}

sub cpanel {
    switch($action) {
        case 'enable' {
            open(my $fh, '<', '/etc/shadow');
                while(<$fh>) {
                    if ( /^$user:/ ) {
                        my ( undef, $hash ) = split(':', $_);
                        if ( $hash !~ /^!!/ ) {
                            die "[!] The $user account is not currently locked\n";
                        } else {
                            last;
                        }
                    }
                }
            close($fh);
            system('passwd -u ' . $user);
	    unlink("/opt/eig_linux/var/suspended/cpanel.$user");
            logit($action, $type, $user, $ticket);
        }
        case 'disable' {
            open(my $fh, '<', '/etc/shadow');
                while(<$fh>) {
                    if ( /^$user:/ ) {
                        my ( undef, $hash ) = split(':', $_);
                        if ( $hash =~ /^!!/ ) {
                            die "[!] The $user account is already locked\n";
                        } else {
                            last;
                        }
                    }
                }
            close($fh);
            system('passwd -l ' . $user);
	    open(my $WAT, '>', "/opt/eig_linux/var/suspended/cpanel.$user");
	    print $WAT $ticket;
	    close($WAT);
            logit($action, $type, $user, $ticket);
        }
    }
}

sub email {
    switch($action) {
        case 'enable' {
            system('chattr -ia /home/' . $user . '/etc/' . $domain . '/shadow');
            system('/root/bin/pwtemp -d setmail ' . $target . ' >/dev/null 2>&1');
            print "[*] $target email unlocked\n";
	    unlink("/opt/eig_linux/var/suspended/email.$user");
            logit($action, $type, $user, $ticket);
        }
        case 'disable' {
            system('/root/bin/pwtemp -d setmail ' . $target . ' >/dev/null 2>&1');
            system('chattr -ia /home/' . $user . '/etc/' . $domain . '/shadow');
            print "[*] $target email locked\n";
	    open(my $WAT, '>', "/opt/eig_linux/var/suspended/email.$user");
	    print $WAT $target.":".$ticket;
	    close($WAT);
            logit($action, $type, $user, $ticket);
        }
    }
}


sub http {
    switch($action) {
        case 'enable' {
            if ( ! -f "/opt/eig_linux/var/suspended/$user" ) {
                die "[!] $user is not currently disabled in apache.\n";
            }
            unlink("/opt/eig_linux/var/suspended/$user");
            system('/root/bin/rebuild_http_suspension >/dev/null 2>&1');
            print "[*] All sites for $user have been enabled in apache.\n";
            logit($action, $type, $user, $ticket);
        }
        case 'disable' {
            if ( -f "/opt/eig_linux/var/suspended/$user" ) {
                die "[!] $user is already disabled in apache.\n";
            }
            if ( ! -d '/opt/eig_linux/var/suspended' ) {
                mkpath('/opt/eig_linux/var/suspended');
            }
            open(my $WAT, '>', "/opt/eig_linux/var/suspended/$user");
                print $WAT $ticket;
            close($WAT);
            system('/root/bin/rebuild_http_suspension >/dev/null 2>&1');
            print "[*] All sites for $user have been disabled in apache.\n";
            logit($action, $type, $user, $ticket);
        }
    }
}

sub exim {
    my @conf;
    open(my $fh, '<', '/etc/exim.pl.local');
    push(@conf, $_) while(<$fh>);
    close($fh);
    my $disabled_users = (grep(/\/opt\/eig_linux\/var\/exim_suspended/,@conf)) ? '/etc/eximdisabledusers' : '/etc/outgoing_mail_suspended_users';
    @conf = ();
    switch($action) {
        case 'enable' {
            open(my $DAT, '<', $disabled_users);
                chomp(my @current = <$DAT>);
            close($DAT);
            if ( ! grep(/^$user$/, @current) ) {
                die "[!] $user is not currently disabled in exim.\n";
            }
            open(my $WAT, '>', $disabled_users);
                print $WAT map { if ( $_ ne $user ) { $_ } } @current;
            close($WAT);
            if ( -f "/opt/eig_linux/var/exim_suspended/$user" ) {
                unlink("/opt/eig_linux/var/exim_suspended/$user");
            }
            print "[*] All e-mail accounts for $user have been enabled in exim.\n";
            logit($action, $type, $user, $ticket);
        }
        case 'disable' {
            if ( ! -d '/opt/eig_linux/var/exim_suspended' ) {
                mkpath('/opt/eig_linux/var/exim_suspended');
            }
            open(my $DAT, '<', $disabled_users);
                chomp(my @current = <$DAT>);
            close($DAT);
            if ( grep(/^$user$/, @current) ) {
                die "[!] $user is already disabled in exim.\n";
            }
            push(@current, $user);
            open(my $WAT, '>', $disabled_users);
                print $WAT map { $_ . "\n" } @current;
            close($WAT);
            open($WAT, '>', "/opt/eig_linux/var/exim_suspended/$user");
                print $WAT $ticket;
            close($WAT);
            print "[*] All e-mail accounts for $user have been disabled in exim.\n";
            logit($action, $type, $user, $ticket);
            notify_APAC_customers("exim");
                    }
          }
}

sub script {
    my @conf;
    open(my $fh, '<', '/etc/exim.pl.local');
    push(@conf, $_) while(<$fh>);
    close($fh);
    if (!grep(/\/opt\/eig_linux\/var\/script_mail_suspended/,@conf)) {
        die("[!!] Server does not support script disable. Try 'exim disable' instead.\n");
    }
    @conf = ();
    switch($action) {
        case 'enable' {
            if ( ! -f "/opt/eig_linux/var/script_mail_suspended/$user" ) {
                die "[!] $user is not currently disabled from using scripts.\n";
            }
            unlink("/opt/eig_linux/var/script_mail_suspended/$user");
            print "[*] $user scripts have been enabled.\n";
            logit($action, $type, $user, $ticket);
        }
        case 'disable' {
            if ( ! -d "/opt/eig_linux/var/script_mail_suspended" ) {
                mkpath("/opt/eig_linux/var/script_mail_suspended");
            }
            if ( -f "/opt/eig_linux/var/script_mail_suspended" ) {
                die "[!] User scripts have already been disabled.\n";
            }
            open(my $WAT, '>', "/opt/eig_linux/var/script_mail_suspended/$user" );
                print $WAT $ticket;
            close($WAT);
            print "[*] $user scripts have been disabled.\n";
            logit($action, $type, $user, $ticket);
        }
    }
}

sub cron {
    # User being suspended changes how we handle crontab
    my $whm_suspended = 0;
    $whm_suspended = 1 if -f "/var/cpanel/suspended/$user";
    my $ecron = '/var/spool/cron';
    my $dcron = '/var/spool/cron.suspended';
    my $tcron = '/opt/eig_linux/var/cron_suspended';
    switch($action) {
        case 'enable' {
            die "[!] ${user}'s crons are already enabled.\n" unless -f "$tcron/$user";
            # Remove immutable - enable crontab if WHM active - no clobbering unless 0 size
            die "[!] ${user} already has active crontab, investigate manually.\n" if ( -f "$ecron/$user" && ! -z "$ecron/$user" );
            if ($whm_suspended) {
                system("chattr -i $dcron/$user >/dev/null 2>&1");
            } else {
                system("chattr -i $dcron/$user >/dev/null 2>&1");
                rename("$dcron/$user", "$ecron/$user");
            }
            # Remove user from cron.deny
            open(my $DAT, '<', '/etc/cron.deny');
            chomp(my @current = <$DAT>);
            close($DAT);
            if ( grep(/^$user$/, @current) ) {
                open(my $WAT, '>', '/etc/cron.deny');
                print $WAT map { if ( $_ ne $user ) { $_ . "\n" } } @current;
                close($WAT);
            }
            unlink("$tcron/$user");
            print "[*] ${user}'s crons have been enabled.\n";
            logit($action, $type, $user, $ticket);
        }
        case 'disable' {
	    die "[!] $user has no crontab.\n" if (! -f "${ecron}/${user}" && ! -f "${tcron}/${user}" && ! -f "${dcron}/${user}");
            die "[!] ${user}'s crons are already disabled.\n" if -f "$tcron/$user";
            mkpath("$tcron") unless -d $tcron;
            # Add immutable - disable crontab if WHM active - no clobbering
            if ($whm_suspended) {
                system("chattr +i $dcron/$user >/dev/null 2>&1");
            } elsif ( -f "$ecron/$user" ) {
                die "[!] ${user} not suspended, but has disabled crontab, investigate manually.\n" if ( -f "$dcron/$user" && ! -z "$dcron/$user" );
                mkpath($dcron, 0, 0700) unless -d $dcron;
                rename("$ecron/$user", "$dcron/$user");
                system("chattr +i $dcron/$user >/dev/null 2>&1");
            }
            # Add user to cron.deny
            open(my $DAT, '<', '/etc/cron.deny');
            chomp(my @current = <$DAT>);
            close($DAT);
            unless ( grep(/^$user$/, @current) ) {
                push(@current, $user);
                open(my $WAT, '>', '/etc/cron.deny');
                print $WAT map { $_ . "\n" } @current;
                close($WAT);
            }
            open(my $WAT, '>', "$tcron/$user" );
            print $WAT "$ticket\n";
            close($WAT);
            print "[*] ${user}'s crons have been disabled.\n";
            logit($action, $type, $user, $ticket);
        }
    }
}

sub logit {
    my ( $action, $type, $user, $ticket ) = @_;
    open(my $WAT, '>>', '/var/log/abusetool.log');
    print $WAT time() . ":$type:$action:$user:$ticket\n";
    close($WAT);
}

$actions{$type}->();

