#!/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];
use Tie::File;
use Digest::MD5 qw(md5_hex);
use DBI;

my ( $type, $action, $target, $ticket,$no_customer_notification, $quiet ) = @ARGV;
if ($quiet eq '--quiet') {
    open STDERR, '>', '/dev/null';
    open STDOUT, '>', '/dev/null';
}
my $now = time();
my $hostname = hostname();

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

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

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

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;
my $docroot;

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

if (( ! $domain ) || ( ! $user ) || ( ! $docroot )) {
    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 ("exim")   {
   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:

* Make all your email passwords more complex and more secure
* 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." ;
                        }

         case("cpanel")  {
   return "Dear Customer,

   We have scanned your domain, and found some malicious files within your cPanel account under the domain $domain.

To ensure performance and stability of the other accounts in the same Shared Hosting environment, we have suspended your access to your cPanel account. Please reach out to our Support team for help in unsuspension of your account. We also request you to adhere to the following points to prevent a similar suspension in the future:

* Make all your email passwords more complex and more secure
* If you are using an email client like Outlook or Thunderbird, please scan your entire laptop/desktop for malware or viruses
* Please scan every file that you are uploading to your cPanel using a trusted antivirus software
* If you are using a CMS such as WordPress or Drupal, please update your plugins, themes and CMS versions to the latest supported versions. Additionally, please make your CMS password more complex and more secure
* Check your email scripts for bugs or loopholes. Hackers could exploit these
* 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." ;
         }

       case("email")  {
   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 the IP address intact, we have temporarily suspended your access to your webmail for the cPanel account $domain.

Before you place a request for the unsuspension of your account, we would request you to run through the following checklist and take necessary action wherever applicable:

* Make all your email passwords more complex and more secure
* If you are using an email client like Outlook or Thunderbird, please scan your entire laptop/desktop for malware or viruses
* If you are using a CMS such as WordPress or Drupal, please update your plugins, themes and CMS versions to the latest supported versions. Additionally, please make your CMS password more complex and more secure
* Check your email scripts for bugs or loopholes. Hackers could exploit these
* 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." ;

                }

      case("http")    {
   return "Dear Customer,

   As a provider of Shared Hosting services, we monitor the usage of all our customers to ensure that our Quality of Service is not adversely affected. Our goal is to ensure that one customer should not affect all the other customers on the same server.

As part of our routine monitoring, we have observed that the domain $domain is involved in violation of our AUP(s).

Hence, considering the gravity of the issue, we have suspended the services associated with the reported domain name $domain.

In order to get the services activated, we request you to kindly provide us with a confirmation that one of the following precautions shall be taken:

* Enable Cloudflare service for your domain.
* Check traffic on your website using AWstats in cPanel. Block malicious traffic from particular IPs based on these statistics
* If you are expecting many unique views on your domain, kindly upgrade your Hosting package to VPS/Dedi server.
* Check and remove the listings for the domain name from major RBLs like Spamhaus, VirusTotal, SURBL, etc.

Once we get an appropriate response from your side, we shall be activating the services from our end.

If you have any queries, please feel free to contact our Support team.

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


      }
    case("script")    {
  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 the IP address intact, we have temporarily suspended your ability to run scripts in the cPanel account $domain.

Before you place a request for the unsuspension of your account, we would request you to run through the following checklist and take necessary action wherever applicable:

* Make all your email passwords more complex and more secure
* If you are using an email client like Outlook or Thunderbird, please scan your entire laptop/desktop for malware or viruses
* If you are using a CMS such as WordPress or Drupal, please update your plugins, themes and CMS versions to the latest supported versions. Additionally, please make your CMS password more complex and more secure
* Check your email scripts for bugs or loopholes. Hackers could exploit these
* 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." ;

    }
     case("cron")    {
  return "Dear Customer,

  We have observed unusual cron activity in your cPanel account under the domain $domain.

In order to prevent further damage to our infrastructure and maintain the stability and performance of other accounts in the same Shared environment, we have suspended your ability to run crons in the cPanel account $domain.

Please reach out to our Support team for help in unsuspension of your account. We also request you to adhere to the following points to prevent a similar suspension in the future:

* Make all your email passwords more complex and more secure
* If you are using an email client like Outlook or Thunderbird, please scan your entire laptop/desktop for malware or viruses
* If you are using a CMS such as WordPress or Drupal, please update your plugins, themes and CMS versions to the latest supported versions. Additionally, please make your CMS password more complex and more secure
* Check your email scripts for bugs or loopholes. Hackers could exploit these
* 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." ;

  }
  } #End of switch

}# End of mail_template

sub mail_this {
  my ($host,$Sender,$To_Email_ID,$mail_body,$Subject,$bcc) = @_;
  my $message = MIME::Lite->new(
                  From    => "$Sender",
                  To      => $To_Email_ID,
                  Bcc     => $bcc,
                  Subject => $Subject,
                  Data    =>  $mail_body
  );
  $message->send('smtp', $host);
  if ( $? ) {
      print "[!] Email not successfully sent. \n";
  } else {
      print "Email send successfully from  $Sender to $To_Email_ID .\n";
  }

}

sub notify_APAC_customers {
    return 1 if  ( defined($no_customer_notification));
    my $service_type = shift;
    my $Subject = 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);
    open(my $DAT, '<', '/etc/trueuserdomains');
        while(<$DAT>) {
          if ( /^([a-zA-Z0-9\-\.]+):\s$user$/ ) {
             $domain = $1;
             print "Corrected Domain to Primary Domain $domain\n";
          }
        }
    close($DAT);
    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
    if ($service_type eq "exim" ) {
       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 @Mail_Attachment = `exigrep $domain /var/log/exim_mainlog`;
       mail_this("spamtrac.india.endurance.com","SwVpWNhBSBqB2WWhdKs2","$user\@$domain",\@Mail_Attachment,$Subject);
     }
    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,$Subject,"apac-abuse-reports\@endurance.com" );
}

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);
            notify_APAC_customers("cpanel","Subject: cPanel suspension for $domain");
        }
    }
}

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);
            notify_APAC_customers("email","Subject: Webmail suspension due to abuse for $domain");

        }
    }
}


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);
            notify_APAC_customers("http","Subject: $domain | Suspended due to HTTP abuse");

        }
    }
}

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","Subject: Email suspension due to abuse for $domain");

                    }
          }
}

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);
            notify_APAC_customers("script","Subject: Script suspension due to abuse for $domain");
        }
    }
}

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);
            notify_APAC_customers("cron","Subject: Cronjob  suspension for $domain");

        }
    }
}

my $warningtop = <<'EOF';
# -- BEGIN SECURITY HEADER - added attackpage warning due to report
RewriteCond %{HTTP_COOKIE} !attackwarning_CODE=1
RewriteRule ^ - [R=416,L]
# -- END SECURITY HEADER - relies on security footer at bottom of file
EOF
my $warningbot = <<'EOF';
# -- BEGIN SECURITY FOOTER - relies on security header at top of file
SetEnvIf Host ^ suppress-error-charset
ErrorDocument 416 "<html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>Suspected Phishing Site</title><style>body{background:white;color:red;margin:40px auto;max-width:650px;line-height:1.6;font-size:18px;padding:0 10px}h1,h2,h3{line-height:1.2}p{color:#444;}</style></head><body><div id=\"langen\" lang=\"en\"><h1>Suspected Phishing Site</h1><h2>Site forgies have been reported on this website.</h2><p>A page at the site you're attempting to access has been reported to be a phishing page. These are attempts to acquire your personal information (passwords, credit card information) by pretending to be a site you're already comfortable sharing this information with.</p><p>Avoid downloading executables or rich text documents (Word, Excel, PDF) from this site, as they could contain malware.</p><p><em>If you own this site</em> please contact your webhost to resolve this matter so that this warning can be removed.</p><p><input value=\"Take me back to safety!\" type=\"button\" onclick=\"window.history.back()\"> <input value=\"Proceed to website with caution\" type=\"button\" onclick=\"dismiss()\"></p></div><div id=\"langpt\" lang=\"pt-BR\"><h1>Site suspeito de phishing</h1><h2>Conteúdo malicioso foi relatado neste site.</h2><p>Uma página do site que você está tentando acessar foi considerada uma página de phishing. Essas são tentativas de adquirir suas informações pessoais (senhas, informações de cartão de crédito) fingindo ser um site com o qual você já se sente confortável em compartilhar essas informações.</p><p>Evite baixar executáveis ou documentos de texto rico (Word, Excel, PDF) deste site, pois eles podem conter malware.</p><p><em>Se você é o proprietário deste site</em>, entre em contato com o seu host da web para resolver o problema para que este aviso possa ser removido. </p><p><input value=\"Leve-me de volta para a segurança!\" type=\"button\" onclick=\"window.history.back()\"> <input value=\"Vá para o site com cuidado\" type=\"button\" onclick=\"dismiss()\"></p></div></body><script>function dismiss() { var now = new Date();now.setTime(now.getTime() + 1000*60*60*24);document.cookie = \"attackwarning_CODE=1;expires=\"+now.toUTCString()+\";path=/\"; window.location.reload(true) } if (navigator.language.startsWith(\"pt\")) { langen.parentNode.removeChild(langen) } else { langpt.parentNode.removeChild(langpt) }</script>"
# -- END SECURITY FOOTER
EOF

sub warningpage {
    module_load ('LWP::UserAgent') or die "Failed to load LWP::UserAgent - can't report suspensions";
    my $htaccess = "$docroot/.htaccess";
    my $tmp = "$htaccess.$now.tmp";
    if (-f $htaccess) {
        system cp => -p => $htaccess, $tmp
            and die "[!] Unable to copy $htaccess => $tmp";
    }
    tie my @ht, 'Tie::File', $tmp or do { unlink $tmp; die "[!] Unable to open $tmp : $!" };
    switch($action) {
        case 'apply' {
            if (@ht && $ht[0] =~ /BEGIN SECURITY HEADER/ && $ht[$#ht] =~ /END SECURITY FOOTER/) {
                untie @ht;
                unlink $tmp;
                die "[!] Warning Page already found in $htaccess\n";
            }
            my $cookie = int(rand(1e5));
            $warningtop =~ s/CODE/$cookie/;
            $warningbot =~ s/CODE/$cookie/;
            unshift @ht, $warningtop;
            push @ht, $warningbot;
            untie @ht;
            system chown => -h => $user.':', $tmp
                and die "[!] Unable to chown $tmp";
            system cp => -p => $htaccess, "$docroot/.htaccess.security.$now.bak"
                and die "[!] Unable to backup $htaccess";
            rename $tmp, $htaccess or die "Failed to rename $tmp => $htaccess";
            print "[*] Added attack warning page to $htaccess\n";
            logit($action, $type, $user, $ticket);
            dbit($action, $user, $ticket, $domain, $docroot);
            repit($domain, $action) unless $ticket eq 'SIR-5350';
            # placeholder - needs email text
            #notify_APAC_customers("warningpage","Subject: $domain | Attack warning page set due to HTTP abuse report")
        }
        case 'remove' {
            if (@ht > 6
                    && $ht[0] =~ /BEGIN SECURITY HEADER/
                    && $ht[1] =~ /attackwarning_/
                    && $ht[2] =~ /R=416/
                    && $ht[3] =~ /END SECURITY HEADER/
                    && $ht[$#ht] =~ /END SECURITY FOOTER/
                    && $ht[$#ht-1] =~ /attackwarning_/
                    && $ht[$#ht-3] =~ /BEGIN SECURITY FOOTER/) {
                shift @ht;
                shift @ht;
                shift @ht;
                shift @ht;
                pop @ht;
                pop @ht;
                pop @ht;
                untie @ht;
                system chown => -h => $user.':', $tmp
                    and die "[!] Unable to chown $tmp";
                system cp => -p => $htaccess, "$docroot/.htaccess.security.$now.bak"
                and die "[!] Unable to backup $htaccess";
                rename $tmp, $htaccess or die "Failed to rename $tmp => $htaccess";
                print "[*] Removed attack warning page from $htaccess\n";
                logit($action, $type, $user, $ticket);
                dbit($action, $user, $ticket, $domain, $docroot);
                repit($domain, $action);
            } else {
                untie @ht;
                unlink $tmp;
                die "[!] No action taken: $htaccess doesn't look like it has an attack warning page";
            }
        }
    }
}

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

my $dbsql = <<'SQL';
CREATE TABLE IF NOT EXISTS active (
        time INT NOT NULL,
        user TEXT NOT NULL,
        ticket TEXT NOT NULL,
        domain TEXT NOT NULL,
        path TEXT NOT NULL,
        UNIQUE (path)
);
SQL

sub dbit {
    my ( $action, $user, $ticket, $domain, $docroot ) = @_;
    my $dbh = DBI->connect("dbi:SQLite:dbname=/opt/eig_linux/etc/attackpage.sqlite", undef, undef, { RaiseError => 1 });
    $dbh->do($dbsql);
    switch($action) {
        case 'apply' {
            $dbh->do('INSERT INTO active VALUES (?, ?, ?, ?, ?)', {}, $now, $user, $ticket, $domain, $docroot);
        }
        case 'remove' {
            $dbh->do('DELETE FROM active WHERE path=?', {}, $docroot);
        }
    }
    $dbh->disconnect();
}

sub repit {
    my ( $domain, $action ) = @_;
    my $ua = LWP::UserAgent->new;
    $ua->agent('domains-potteryreporter');
    $ua->ssl_opts(verify_hostname => 0);
    my $who = defined($ENV{RUSER}) ? $ENV{RUSER} : 'support';
    my $key = md5_hex("$hostname:-AFJ/.sdfkjoi34PO");
    my $res = $ua->post('https://scripts.hostgator.com/~sec/reporting/localattackpage.nim?host='.$hostname.'&domain='.$domain.'&action='.$action.'&who='.$who.'&key='.$key);
    unless ($res->is_success) {
        warn "[!] failed to report action to warningpages console.";
    }
}

$actions{$type}->();

