perl <<'EOF'
use Socket;
use Sys::Hostname;
use Time::Local;
use List::MoreUtils qw(uniq);
use LWP::UserAgent;
use IPC::Open3;
use HTTP::Status 'status_message';
use Term::ANSIColor;
use File::Find::Rule;

use cPanel::PublicAPI;
require '/usr/local/cpanel/3rdparty/perl/514/lib64/perl5/cpanel_lib/File/ReadBackwards.pm' if -s '/usr/local/cpanel/3rdparty/perl/514/lib64/perl5/cpanel_lib/File/ReadBackwards.pm';
require '/usr/local/cpanel/3rdparty/perl/522/lib64/perl5/cpanel_lib/File/ReadBackwards.pm' if -s '/usr/local/cpanel/3rdparty/perl/522/lib64/perl5/cpanel_lib/File/ReadBackwards.pm';

# subroutine definitions
sub header; # print header
sub passed; # print passed msg
sub fixed; # print fixed issues
sub footer; # because whitespace can be nice

# checking
sub check_dns; # cloudflare nameservers?, returns an ip?
sub check_hg_specific; # migrations, server maintenance, suspended, tos, etc
sub check_server; # disk space, inodes, raid, beancounters, oom, readonly, drive status, can ping
sub check_client_ip; # get ip from access_log that isn't us
sub check_apache; # parse apache error log
sub check_php; # parse php error log
sub check_mysql; # check for crashed tables
sub check_resolve; # check the site loads and parse for common errors
sub check_performance; # gtmetrix / yslow / pagespeed

# common issues
sub check_common_mail; # can smtp, mx set, local/remote
sub check_common_pass; # password recently changed, pwtempd

# user / domain operations
sub get_user; # get user for domain
sub get_domains; # get all domains for user
sub get_billing;

# file operations
sub read_file; # returns array of file

# global vars
my $version = "0.5";
my $line_limit = "25000";
my $accesshash = get_accesshash();
my $cp = cPanel::PublicAPI->new( 
    'user' => 'root', 
    'accesshash' => $accesshash,
    'ssl_verify_mode' => 0
);

# call all the things
my $domain = 'domain_placeholder';

if ( ! $domain ) {
    die "[!] Domain is required.\n";
}

my $user = get_user($domain);
my $docroot = get_doc_root($domain);
my $billing = get_billing($user);

header;
check_dns;
check_resolve;
check_apache;
check_php;
check_mysql;
check_server;
footer;

# subroutine meat
sub header {
    print colored ['black on_white'], "...Domain Information...";
    print "\n";
    print "\tDomain: $domain\n";
    print "\tUser: $user\n";
    print "\tDocroot: $docroot\n";    
    print "\tBilling: $billing\n\n";
}

sub passed {
    print color 'green';
    print "\t>> Passed\n\n";
    print color 'reset';
}

sub fixed {
    my $item = shift;
    print color 'green';
    print "\t\t$item\n";
    print color 'reset';
}

sub broke {
    my $item = shift;
    print color 'red';
    print $item;
    print color 'reset';
}

sub footer {
    print "\n";
}

# common errors
sub check_dns {
    print colored ['black on_white'], "...Checking for DNS Resolution...";
    print "\n";
    my $ip = inet_aton($domain);
    $ip = inet_ntoa($ip);
    my $vhost_ip = get_vhost_ip();
    my @ips = getips();
    my $ip_on_server = 0;
    foreach ( @ips ) {
        if ( $ip eq $_ ) {
            $ip_on_server = 1;
        }
    }
    if(! $ip) {
        print "\tUnable to get an IP address for $domain, please manually investigate.\n\n";
    }
    elsif (! $ip_on_server) {
        print "\tThe IP($ip) for $domain is not housed on this server.\n\n";
    }
    elsif ( $ip ne $vhost_ip ) {
        print "\tApache IP mismatch. Apache IP: $vhost_ip, Resolving IP: $ip\n\n";
    }
    else {
        passed;
    }
}

sub check_hg_specific {
    my $hostname = hostname;
}

sub check_mysql {
    my $hostname = hostname;
    my $count = 0;
    my $mysql_errors = {};
    my $log = '/var/lib/mysql/' . $hostname . '.err';
    print colored ['black on_white'], "...Checking for Crashed Tables...";
    print "\n";
    if ( -f $log ) {
        my $bw = File::ReadBackwards->new($log) or
            die "Unable to open MySQL log";
        while ( my $line = $bw->readline ) {
            last if ($count >= $line_limit );
            if( $line =~ /Table\s'\.\/($user\S+)\/\S+'\sis\smarked\sas\scrashed\sand\sshould\sbe\srepaired/xsm ) {
                            $mysql_errors->{$1}++;
            }
            $count++;
        }
        my $num_err = keys %$mysql_errors;
        if ( $num_err > 0 ) {
            foreach my $k ( keys %$mysql_errors ) {
                broke("$k is marked as crashed and should be repaired\n");
            }
        }
        else {
            passed;
        }
    }
    else {
        print "No MySQL error log\n";
    }
}

sub check_apache {
    my $log = '/usr/local/apache/logs/error_log';
    my $count = 0;
    my $apache_errors = {};
    print colored ['black on_white'], "...Checking for Apache Errors...";
    print "\n";
    if ( -f $log ) {
        my $bw = File::ReadBackwards->new($log) or
                    die "Cannot read 'log' $!";
            while ( my $line = $bw->readline ) {
            last if ( $count >= $line_limit );
            if ( $line =~ /\[\S+\s\S+\s\d+\s\d+:\d+:\d+\s\d+\] # Match Date
                    \s\[(?:crit|error|alert)\]\s\S+\s\S+\s([^:]+ # Match and capture errors only
                    .*($user|$domain).*)\n # Match everything else and check for user or domain in question
            /xsm ) { 
                $apache_errors->{$1}++;
            }
            $count++;    
        }
        my $errs = parse_apache_errors($apache_errors);
        my $num_err = @$errs;
        if ( $num_err > 0 ) {
            fix_apache_errors($errs,$user,$num_err);
        }
        else {
            passed;
        }
    }
    else {
        die "No Apache Log Found: $!";
    }
}

# Parse out errors that arent significant
sub parse_apache_errors {
    my $errors = shift;
    my @keys = keys %$errors;
    my @errs;
    my $mod_sec_count = 0;
    my @ignore = qw( 900402 900404 900405 900406 );
    foreach my $k ( @keys ) {
        next if $k =~ /File\sdoes\snot\sexist/xsm;
        next if $k =~ /403.shtml/xsm;
        next if $k =~ /favicon/xsm;
        if ( $k =~ /ModSecurity:/xsm ) {
            if ( $k =~ /id "([0-9]+)"/ ) {
                next if ( grep(/^$1$/, @ignore) );
            }
            $mod_sec_count++;
            next;
        }
        push @errs, $k;
    }
    if ( $mod_sec_count ) {
        broke("\t...found $mod_sec_count mod security hits...\n");
    }
    return \@errs;
}

# Actually fix issues with Apache
sub fix_apache_errors {
    my($errs, $user, $num_err) = @_;
    my @manual; 
    my @limits;
    broke("\t...found $num_err errors...\n");
    my $found_count = 1;
    foreach my $err ( @$errs ) {
        # HG Limiting
        if ( $err =~ /SystemException\sin\sAPI_Linux.cpp:\d+\sexecve\(\)\sfor\sprogram\s"\/usr\/bin\/php"/xsm ) {
            push @limits, "Process Limit Warning";
        }

        # Old htaccess rule sets
        if ( $err =~ /(\S+):\sInvalid\scommand\s'php_flag',\sperhaps\smisspelled\sor\sdefined
                  \sby\sa\smodule\snot\sincluded\sin\sthe\sserver\sconfiguration/xsm ) {
            push @manual, "php_flag or php_value error on $1";
        }
        else {
            push @manual, $err;
        }
    }
    my $limit_count = @limits;
    if ( $limit_count >= 1 ) {
        print "\n\t...account limits...\n";
        foreach my $limit ( @limits ) {
            broke("\t\t$limit\n");
        }
    }
    my $man_count = @manual;
    if ( $man_count >= 1 ) {
        print "\n\t...Errors...\n";
        foreach my $man ( @manual ) {
            broke("\t\t$man\n");
        }
    }
    print "\n\n";
}

sub parse_php_errors {
        my $errors = shift;
        my @keys = keys %$errors;
        my @errs;
        foreach my $k ( @keys ) {
        $k =~ s/\[\d+-\S+-\d+\s\d+:\d+:\d+\]\s//;
                push @errs, $k; 
        }
    @errs = uniq(@errs);
        return \@errs;
}

sub check_php {
    print colored ['black on_white'], "...Checking PHP Error Logs...";
    print "\n";
    my $find = File::Find::Rule->new;
    $find->file;
    $find->maxdepth(2);
    $find->name('error_log');
    my @files = $find->in($docroot);
    my $num_logs = @files;
    my $errors = {};
    if ( $num_logs > 0 ) {
        my $last_week = time - 24 * 60 * 60;  
        foreach my $log ( @files ) {
            print "\t...checking: $log\n";
            my $bw = File::ReadBackwards->new($log) or
                        die "Cannot read 'log' $!";
            my $count = 0;
            my $found_count = 0;
            my $code_error = 0;
                    while ( my $line = $bw->readline ) {
                            last if ( $count >= $line_limit );
                            if ( $line =~ /\[(\d+)-(\S+)-(\d+)\s(\d+):(\d+):(\d+)\]/xsm ) {
                    my $log_time = timelocal($6, $5, $4, $1, mon2num($2), $3);
                    if ( $count == 0 ) {
                        if ( $log_time < $last_week ) {
                            last;
                        }
                    } else {
                        if ( $log_time > $last_week ) {    
                            # Find PHP Errors here
                            if ( $line =~ /PHP\sParse\serror/ ) {
                                $errors->{$log}->{$line}++;
                                                        $code_error++;
                                                    }
                                                    if ( $line =~ /PHP\sFatal\serror/ ) {
                                $errors->{$log}->{$line}++;
                                                        $code_error++;
                                                    }
                        }
                    }
                }
                $count++;
            }
            if ( $code_error == 0 ) {
                print "\t";
                passed;
            } else {
                my $errs = parse_php_errors($errors->{$log});
                foreach ( @$errs ) {
                    print "\t\t";
                    broke($_);
                }
                print "\n";
            }
        }
    } else {
        passed;
    }
}

# checksites addin
sub content_check {
    my $timeout = 10;
    my $ua     = LWP::UserAgent->new;
    $ua->timeout($timeout);
    my $req = HTTP::Request->new( GET => "http://$domain/" );
    my $res = $ua->request($req);
    if ( $res->content() =~
        m/(defaultwebpage[.]cgi|searchdiscovered[.]com)/xism )
    {
        return 'Cpanel Default Page';
    }
    elsif ( $res->content() =~ m/database\serror/xism ) {
        return 'Database Error';
    }
    elsif ( $res->content() =~ m/account\ssuspended/xism ) {
        return 'Suspended Account';
    }
    elsif ( $res->content() =~ m/<title>Index\sof\s(.*)<\/title>/xsm ) {
        return "Directory Index for $1";
    }
    elsif ( $res->content() =~ m/\/var\/lib\/mysql\/mysql.sock/xsm ) {
        return 'MySQL Error';
    }
    elsif ( $res->content() =~ m/<title>(Domain\sDefault\spage|Default\sParallels\sPlesk\sPanel\sPage)<\/title>/xsm ) {
        return 'Plesk default page';
    }
    elsif ( $res->content() =~
m/(hacked|haxor|c3284d|Web Shell|WebShell|iskorpitx|shell_atildi|md5_pass|wp_add_filter|shellbot|c99\s?shell|injektor|N3tsh|Fx29sh|r57\s?shell|SyRiAn Sh3ll|FilesMan|CGI-Telnet|MulCiShell|LINUX Shell|Team Crimes Linux|Zone-H|Err0R|hackteach|JAGo-Dz|Cpanel Cracker|milw0rm|PHP DOS|phptools|Manix|exploit-db|b0VIM|phpshell|w4ck1ng-shell|ITSecTeam|CraCkeR|SarBoT|SA3D|HaCk3D|SUKSES|Fx29Shell|SyRiAn|Sh3ll|SnIpEr_SA|Symlink User Bypass|greetz|KeNiHaCk|1923Turk|strrev..edoced_46esab|sEc4EvEr|Mr.aFiR|Hacked By|auth_pass|shell_exec|Terminator|WSO_VERSION|ignore_user_abort|jquerye\.com|PHP_OS)/ixsm
      )
    {
        return 'Possibly Hacked -> Manually Confirm';
    }
}

sub check_resolve {
    print colored ['black on_white'], "...HTTP Status and Error Check...";
    print "\n";
    my $timeout = 10;
    my $format = "\t%-25s \n\n";
    my $ua = LWP::UserAgent->new;
            $ua->agent('HG Site Checker');
            $ua->timeout($timeout) or die 'TIMEOUT';
            my $response = $ua->get("http://$domain");
            my $check    = content_check($domain);
            if ( $response->is_success ) {
                $response = $response->{_rc};
                    if ( $response =~ /^2/xsm ) {
                        if ($check) {
                            printf $format, "$check";
                        }
                        else {
                            my $rc = $response;
                            $response = status_message($response);
                            printf $format, "$rc $response";
                        }
                    }
            }
            else {
                $response = $response->status_line;
                printf $format, "$response";
            }
}

# user | domain ops
sub get_user {
    my @user_file = read_file('/etc/userdomains');
    my $user;
    foreach my $u ( @user_file ) {
        if ( $u =~ /^$domain:\s*(\S+)$/ ) {
            $user = $1;
            last;
        }
    }
    if ( $user ) {
        return $user;
    } else {
        die "[!] Domain does not exist.\n";
    }
}

sub get_domains {
        my $file = "/var/cpanel/userdata/$user/main";
        my (@domains);
        open my $fh, '<', $file or die "[!] File does not exist: $file";
        while (<$fh>) {

            # pull addon domains
            if ( $_ =~ /(\S+):\s/xsm && $_ !~ /_/xsm ) {
                    push @domains, $1;
            }

            # pull main domain
            if ( $_ =~ /main_domain:\s(\S+)/xsm ) {
                push @domains, $1;
            }

            # pull parked domains
            if ( $_ =~ /-\s(\S+)/xsm ) {
                    push @domains, $1;
            }
            if ( $_ =~ /sub_domains:/xsm ) {
                last;
            }
        }
        my $error = close $fh;
        return @domains;
}

sub get_billing {
    my @file = read_file("/etc/trueuserowners");
    my $owner;
    foreach my $u ( @file ) {
        if ( $u =~ /^$user:\s(\S+)/ ) {
            $owner = $1;    
            last;
        }
    }
    if ( $owner eq 'root' ) {
        my $dom = get_main_domain($user);
        return "https://gbadmin.hostgator.com/search_final/domain/_$dom";
    } else {
        my $dom = get_main_domain($owner);
        return "https://gbadmin.hostgator.com/search_final/domain/_$dom";
    }
}

sub get_main_domain {
    my $pass_user = shift;
    my @file = read_file("/var/cpanel/userdata/$pass_user/main");
    foreach my $u ( @file ) {
        if ( $u =~ /main_domain:\s(\S+)/ ) {
            return $1;
        }
    }
    die "[!] Cannot find main domain.";
}

sub getips {
    my ( $writer, $reader, $error );
    open3( $writer, $reader, $error, '/sbin/ifconfig' );
    my @ifconfig = <$reader>;
    foreach (@ifconfig) {
        if ( $_ =~ /inet\saddr:(\S+)/xsm && $_ !~ /127[.]0[.]0[.]1/xsm ) {
            push @ips, $1;
        }
    }
    return @ips;
}

sub get_vhost_ip {
    local $/ = "</VirtualHost>";
    open my $fh, '<', '/usr/local/apache/conf/httpd.conf';
    while (<$fh>) {
            if ( $_ =~ /(ServerAlias|ServerName).*(www\.)?$domain/ ) {
                    if ( $_ =~ /<VirtualHost (\d+\.\d+\.\d+\.\d+):\d+>/ ) {
                            return $1;
                            last;
                    }
            }
    }
    close $fh;
}

# cpanel api operations
sub get_doc_root {
    my $docroot = $cp->cpanel_api2_request('whostmgr', { 'module' => 'DomainLookup', 'func' => 'getdocroot' },
        {
            'domain' => $domain,
            'user' => $user,
        }
    );
    return $docroot->{cpanelresult}{data}[0]{docroot};
}

sub get_accesshash {
        my $accesshash;
    if ( ! -f '/root/.accesshash' ) {
        $ENV{REMOTE_USER} = 'root';
        system('/usr/local/cpanel/bin/realmkaccesshash');
    }
    if ( -f '/root/.accesshash' ) {
            open my $hash, "<", "/root/.accesshash";
                my @accesshash = <$hash>;
            close $hash;
            foreach(@accesshash){
                    $accesshash .= $_
            }
            return $accesshash;
    }
}

sub check_server {
    print colored ['black on_white'], "...Checking for Server Issues...";
        print "\n";
    
    # check uptime
    open FILE, "<", "/proc/uptime" or die "Cannot open /proc/uptime: $!";
        my ($uptime, undef) = split / /, <FILE>;
    close FILE;
    $uptime = int($uptime/(60 * 60));
    my $found = 0;
    if ( $uptime < 3 ) {
        broke("server has been rebooted recently");
        $found++;
    }

    # check mysql uptime
    my ( $writer, $reader, $error );
    open3( $writer, $reader, $error, '/usr/bin/mysqladmin version | grep Uptime' );    
    my $sql_uptime = <$reader>;
    my $sql_broken = 0;
    if ( $sql_uptime =~ /Uptime:\s+(\d+)\s+(?:hour|hours)/ ) {
        $sql_broken = 1 if $1 < 2;
    }
    if ( $sql_uptime =~ /Uptime:\s+(\d+)\s+(?:min|mins)/ ) {
        $sql_broken = 1;
    }
    if ( $sql_broken ) {        
        broke("\tmysql service restarted recently\n");
        $found++;
    }

    # check apache uptime
    open3( $writer, $reader, $error, '/usr/sbin/httpd status | grep uptime');
    my $http_uptime = <$reader>;
    my $http_broken = 0;
    if ( $http_uptime =~ /Server\suptime:\s+(\d+)\s(?:hour|hours)/ ) {
        $http_broken = 1 if $1 < 2;
    }
    if ( $http_uptime =~ /Server\suptime:\s+\d+\s(?:min|minutes)/ ) {
        $http_broken = 1;
    }
    if ( $http_broken ) {
        broke("\tapache service restarted recently\n");
        $found++;
    }
    if ( $found == 0 ) {
        passed;
    }
}

# file ops
sub mon2num {
    my $month = shift;
    my %mon2num = qw(
        Jan 0  Feb 1  Mar 2  Apr 3  May 4  Jun 5
        Jul 6  Aug 7  Sep 8  Oct 9 Nov 10 Dec 11
    );
    return $mon2num{$month};
}

sub read_file {
    my $file = shift;
    open my $fh, '<', $file or die "Cannot open file: $file, $!";
    my @contents = <$fh>;
    close $fh;
    return @contents;
}
EOF
