#!/usr/local/cpanel/3rdparty/bin/perl

###########
# iskilled
# Checks to see if the account is in any of the kill logs on a shared server.
# Wiki page @ https://confluence.endurance.com/display/HGS/IsKilled 
# Project page @ https://stash.endurance.com/projects/HGADMIN/repos/iskilled/browse
# Dusten Barker (dbarker@hostgator.com)
##########

use strict;
use warnings;
use Cwd;
use POSIX qw(strftime);
use DateTime::Format::Strptime;
use Sys::Hostname;
use Getopt::Long qw(GetOptions);
use DBI;
use autobox;
Getopt::Long::Configure qw(gnu_getopt);

no warnings 'uninitialized';
use constant {
    VERSION      => 20160406,
    SPACING              => 10,
    MYSQL_LOG            => "/var/log/mysql_queries.log",
    LIMITPHP_LOG         => "/opt/hgmods/automated_monitoring/logs/autocpu.log",
    KILLUSAGE_LOG        => "/opt/hgmods/kill_usage.log",
    MYSQLAUTOSUSPEND_LOG => "/opt/hgmods/automated_monitoring/logs/mysql_autosuspend.log",
    CPUTIME_LOG          => "/opt/hgmods/hg_user_cputime.log",
    SQLBAN_LOG           => "/opt/hgmods/automated_monitoring/etc/banned_sqlusers",
    PCOUNT_LOG           => "/opt/hgmods/hg_processcount.log",
    PHISH_LOG            => "/opt/eig_linux/etc/marked_phishing_domains.sqlite",
    KILLIMAP_LOG         => "/opt/hgmods/kill_imap.log",
    PLUS                 => "[\033[34m+\033[0m]",
    DASH                 => "[\033[34m-\033[0m]"
};

our ($timeframe, $opt_list, $opt_listkills);
our $opt_number = 5;
our $opt_time = 24;
my ($opt_help, $opt_user, $user, @opt_logs, $opt_version);

# Create "matches" method for array to grep per element in array; uses autobox module
sub ARRAY::matches {
    grep(/^${_[1]}$/,@{$_[0]})
};

# Output function for kills today. Needs username, number of kills, and verbiage.
sub show_kills_today($$$) {
    my $user    = shift;
    my $kills   = shift;
    my $say     = shift;
    my $colour  = "\033[0m";
    my $SPACING = SPACING;
    if ( defined($kills) && defined($say) ) {
        if ( $kills > 0 ) {
            $colour = "\033[1m";
        }
        printf( "%s %${SPACING}s %s %s%i\033[0m times in past %ihrs.\n", DASH, $user, $say, $colour, $kills, $opt_time );
    }
}

# Output function for kills total. Needs username, number of kills, and verbiage.
sub show_kills_total($$$) {
    my $user    = shift;
    my $kills   = shift;
    my $say     = shift;
    my $SPACING = SPACING;
    if ( defined($kills) && defined($say) ) {
        printf( "%s %${SPACING}s %s %i times.\n", DASH, $user, $say, $kills );
    }
}

# Output function for when killed. Needs username, unixtime, and verbiage.
sub show_when_killed($$$) {
    my $user    = shift;
    my $first   = shift;
    my $say     = shift;
    my $SPACING = SPACING;
    if ( defined($first) && $first > 0 && defined($say) ) {
        printf( "%s %${SPACING}s was %s: %s\n", DASH, $user, $say, localtime($first) . "" );
    }
}

# Output function for limitphp. Needs username and limit; 1=PERM, 2=regular limit
sub show_limitphp($$) {
    my $user    = shift;
    my $limit   = shift;
    my $SPACING = SPACING;
    if ( defined($limit) && $limit > 0 ) {
        if ( $limit == 2 ) {
            printf( "%s %${SPACING}s \033[1mlimit\033[0m exists!\n", DASH, $user );
        }
        elsif ( $limit == 1 ) {
            printf( "%s %${SPACING}s PERM \033[1mlimit\033[0m exists!\n", DASH, $user );
        }
    }
}

# Output function for checking logname. Needs log name.
sub checking($) {
    my $logname = shift;
    printf( "%s Checking \"%s\"\n", PLUS, $logname );
}

# Prints last N number of elements of array. Takes array passed by value, and number of last elements to print.
sub print_matches(\@$$) {
    my $SPACING = SPACING;
    my @last_matches = @{(shift)};
    my $num_matches = shift;
    my $kills_today = shift;
    if ((defined($opt_listkills) && $kills_today>0) || !defined($opt_listkills)) {
        printf( "%s %${SPACING}s Listing last %i entries:\n", DASH, "", $num_matches );
        print(($num_matches>=@last_matches) ? @last_matches : @last_matches[-$num_matches..-1]);
        print "\n";
    }
}

# Check mysql queries log. Needs username.
sub check_mysql($) {
    my $user          = shift;
    my $total_entries = 0;
    my $kills_today   = 0;
    my $first_entry;
    my $last_entry;
    my @last_matches;
    checking(MYSQL_LOG);
    if ( !-e MYSQL_LOG ) {
        return 1;
    }
    open( my $mysql_fh, "<", MYSQL_LOG );
    while ( my $line = <$mysql_fh> ) {
        if ( $line =~ /\ ${user}\_\S+\ \]\ \[\ Query\ \]\ \[\ KILLED\ \]/) {
            my @F = split( /\s+/, $line );
            if ( $F[1] =~ /^\d+$/ ) {
                if ( !defined($first_entry) ) {
                    $first_entry = $F[1];
                }
                if ( $F[1] > ( strftime( "%s", localtime ) - $timeframe ) ) {
                    $kills_today++;
                }
                $last_entry = $F[1];
                $total_entries++;
        if (defined($opt_list)){
                    push(@last_matches,$line);
                }
            }
        }
    }
    close($mysql_fh);
    if ($total_entries) {
        show_kills_total( $user, $total_entries, "killed" );
        show_kills_today( $user, $kills_today, "killed" );
        show_when_killed( $user, $first_entry, "first killed" );
        show_when_killed( $user, $last_entry,  "last killed" );
    if (defined($opt_list)){
        print_matches(@last_matches,$opt_number,$kills_today);
    }
    }
}

# Check the processcount (>25) log. Needs username.
sub check_processcount($) {
    my $user          = shift;
    my $total_entries = 0;
    my $kills_today   = 0;
    my $first_entry;
    my $last_entry;
    my $parse = DateTime::Format::Strptime->new( pattern => '%a %b %d %T %Y', time_zone => 'America/Chicago' );
    my $logfile;
    my $foundfile;
    my @last_matches;
    checking(PCOUNT_LOG);
    for (my $iter = 50; $iter >= 0; $iter-- ) {
        if ($iter == 0) {
            $logfile = PCOUNT_LOG;
        } else {
            $logfile = PCOUNT_LOG . "." . $iter;
        }
        if ( -e $logfile ) {
            $foundfile=1;
            open( my $pcount_fh, "<", $logfile );
            while ( my $line = <$pcount_fh> ) {
                if ( $line =~ /^\[\S{3}\ \S{3}\ \d+ \d{2}\:\d{2}\:\d{2}\ \d{4}\]\ uid\ \d+\ \(${user}\)\ processes\:$/ ) {
                    my @F = split( /[][]/, $line );
                    my $ti = $parse->parse_datetime( $F[1] )->epoch;
                    if ( $ti =~ /^\d+$/ ) {
                        if ( !defined($first_entry) ) {
                            $first_entry = $ti;
                        }
                        if ( $ti > ( strftime( "%s", localtime ) - $timeframe ) ) {
                            $kills_today++;
                        }
                        $last_entry = $ti;
                        $total_entries++;
            if (defined($opt_list)){
                            push(@last_matches,$line);
                        }
                    }
                }
            }
            close($pcount_fh);
        }
    }
    if (defined($foundfile) && $total_entries) {
        show_kills_total( $user, $total_entries, "hit pcount limit" );
        show_kills_today( $user, $kills_today, "hit pcount limit" );
        show_when_killed( $user, $first_entry, "first hit limit" );
        show_when_killed( $user, $last_entry,  "last hit limit" );
        if (defined($opt_list)){
            print_matches(@last_matches,$opt_number,$kills_today);
        }
    }
}

# Check logs for the imap killer. Needs username.
sub check_kill_imap($) {
    my $user          = shift;
    my $total_entries = 0;
    my $kills_today   = 0;
    my $first_entry;
    my $last_entry;
    my @last_matches;
    checking(KILLIMAP_LOG);
    if ( !-e KILLIMAP_LOG ) {
        return 1;
    }
    open( my $killimap_fh, "<", KILLIMAP_LOG );
    while ( my $line = <$killimap_fh> ) {
        if ( $line =~ /^${user}\ \-/ ) {
            my @F = split( /\s+/, $line );
            if ( $F[4] =~ /^\d+$/ ) {
                if ( !defined($first_entry) ) {
                    $first_entry = $F[4];
                }
                if ( $F[4] > ( strftime( "%s", localtime ) - $timeframe ) ) {
                    $kills_today++;
                }
                $last_entry = $F[4];
                $total_entries++;
        if (defined($opt_list)){
                    push(@last_matches,$line);
                }
            }
        }
    }
    close($killimap_fh);
    if ($total_entries) {
        show_kills_total( $user, $total_entries, "hit imap killer" );
        show_kills_today( $user, $kills_today, "hit imap killer" );
        show_when_killed( $user, $first_entry, "first hit imap killer" );
        show_when_killed( $user, $last_entry,  "last hit imap killer" );
        if (defined($opt_list)){
            print_matches(@last_matches,$opt_number,$kills_today);
        }
    }
}

# Check kill usage logs. Needs username.
sub check_killusage($) {
    my $user          = shift;
    my $total_entries = 0;
    my $kills_today   = 0;
    my $first_entry;
    my $last_entry;
    my @last_matches;
    checking(KILLUSAGE_LOG);
    if ( !-e KILLUSAGE_LOG ) {
        return 1;
    }
    open( my $killusage_fh, "<", KILLUSAGE_LOG );
    while ( my $line = <$killusage_fh> ) {
        if ( $line =~ /USR=${user}\,/ ) {
            my @F = split( /[][]/, $line );
            if ( $F[1] =~ /^\d+$/ ) {
                if ( !defined($first_entry) ) {
                    $first_entry = $F[1];
                }
                if ( $F[1] > ( strftime( "%s", localtime ) - $timeframe ) ) {
                    $kills_today++;
                }
                $last_entry = $F[1];
                $total_entries++;
        if (defined($opt_list)){
                    push(@last_matches,$line);
                }
            }
        }
    }
    close($killusage_fh);
    if ($total_entries) {
        show_kills_total( $user, $total_entries, "killed" );
        show_kills_today( $user, $kills_today, "killed" );
        show_when_killed( $user, $first_entry, "first killed" );
        show_when_killed( $user, $last_entry,  "last killed" );
        if (defined($opt_list)){
            print_matches(@last_matches,$opt_number,$kills_today);
        }
    }
}

# Checks the cputime logs. Needs username.
sub check_cputime($) {
    my $user          = shift;
    my $total_entries = 0;
    my $kills_today   = 0;
    my $first_entry;
    my $last_entry;
    my @last_matches;
    checking(CPUTIME_LOG);
    if ( !-e CPUTIME_LOG ) {
        return 1;
    }
    open( my $cputime_fh, "<", CPUTIME_LOG );
    while ( my $line = <$cputime_fh> ) {
        if ( $line =~ /\-\ ${user}\ \-/ ) {
            my @F = split( /[\(\)]/, $line );
            if ( $F[1] =~ /^\d+$/ ) {
                if ( !defined($first_entry) ) {
                    $first_entry = $F[1];
                }
                if ( $F[1] > ( strftime( "%s", localtime ) - $timeframe ) ) {
                    $kills_today++;
                }
                $last_entry = $F[1];
                $total_entries++;
        if (defined($opt_list)){
                    push(@last_matches,$line);
                }
            }
        }
    }
    close($cputime_fh);
    if ($total_entries) {
        show_kills_total( $user, $total_entries, "killed" );
        show_kills_today( $user, $kills_today, "killed" );
        show_when_killed( $user, $first_entry, "first killed" );
        show_when_killed( $user, $last_entry,  "last killed" );
        if (defined($opt_list)){
            print_matches(@last_matches,$opt_number,$kills_today);
        }
    }
}

sub check_phishing($) {
    my $user = shift;
    my $phished;
    checking(PHISH_LOG);
    eval { # suppress errors
        my $p_dbh = DBI->connect("dbi:SQLite:dbname=/opt/eig_linux/etc/marked_phishing_domains.sqlite", undef, undef, { RaiseError => 1, ReadOnly => 1 });
        $phished = $p_dbh->selectall_arrayref("SELECT * FROM domains WHERE user=?", { Slice => {} }, $user);
        $p_dbh->disconnect();
    };
    if (defined $phished) {
        for my $phish (@$phished) {
            printf( "%s %@{[SPACING]}s [%s] suspending marked phishing domain: %s\n", DASH, $user, scalar(localtime($phish->{added})), $phish->{domain});
        }
    }
}

# Checks for current mysql ban. Needs username.
sub check_sqlban($) {
    my $user = shift;
    my $entries;
    my $SPACING = SPACING;
    checking(SQLBAN_LOG);
    if ( !-e SQLBAN_LOG ) {
        return 1;
    }
    open( my $sqlban_fh, "<", SQLBAN_LOG );
    while ( my $line = <$sqlban_fh> ) {
        if ( $line =~ /^${user}$/ ) {
            $entries++;
            last;
        }
    }
    close($sqlban_fh);
    if ( defined($entries) && $entries ) {
        printf( "%s %${SPACING}s had database \033[1mBAN\033[0m.\n", DASH, $user );
    }
}

# Checks for mysql suspensions. Needs username.
sub check_mysql_autosuspend($) {
    my $user          = shift;
    my $total_entries = 0;
    my $kills_today   = 0;
    my $first_entry;
    my $last_entry;
    my @last_matches;
    my $parse = DateTime::Format::Strptime->new( pattern => '%Y/%m/%d %H:%M:%S' );
    my $user8 = substr($user, 0, 8);
    checking(MYSQLAUTOSUSPEND_LOG);
    if ( !-e MYSQLAUTOSUSPEND_LOG ) {
        return 1;
    }
    open( my $mysqlauto_fh, "<", MYSQLAUTOSUSPEND_LOG );
    while ( my $line = <$mysqlauto_fh> ) {
        if ( $line =~ /INFO - Freezing \(${user8}\)/ ) {
            my @F = split( /\s+/, $line );
            my $ti = $parse->parse_datetime( $F[0] . " " . $F[1] )->epoch;
            if ( $ti =~ /^\d+$/ ) {
                if ( !defined($first_entry) ) {
                    $first_entry = $ti;
                }
                if ( $ti > ( strftime( "%s", localtime ) - $timeframe ) ) {
                    $kills_today++;
                }
                $last_entry = $ti;
                $total_entries++;
        if (defined($opt_list)){
                    push(@last_matches,$line);
                }
            }
        }
    }
    close($mysqlauto_fh);
    if ($total_entries) {
        show_kills_total( $user, $total_entries, "froze" );
        show_kills_today( $user, $kills_today, "froze" );
        show_when_killed( $user, $first_entry, "first frozen" );
        show_when_killed( $user, $last_entry,  "last frozen" );
        if (defined($opt_list)){
            print_matches(@last_matches,$opt_number,$kills_today);
        }
    }
}

# Checks the limitphp logs. Needs username.
sub check_limitphp_log($) {
    my $user          = shift;
    my $total_entries = 0;
    my $kills_today   = 0;
    my $first_entry;
    my $last_entry;
    my $last_perm_entry;
    my @last_matches;
    my $SPACING         = SPACING;
    checking(LIMITPHP_LOG);
    if ( !-e LIMITPHP_LOG ) {
        return 1;
    }
    open( my $limitphplog_fh, "<", LIMITPHP_LOG );
    while ( my $line = <$limitphplog_fh> ) {
        if ( $line =~ /\ disable\ .*\-\ ${user}\ / ) {
            my $tt;
            my @F = split( /\s+/, $line );
            if ( $F[0] =~ /^\[/ ) {
                $tt = $F[7];
            }
            elsif ( $F[0] =~ /\// ) {
                $tt = $F[4];
            }
            else {
                $tt = $F[0];
            }
            if ( defined($tt) && $tt =~ /^\d+$/ ) {
                if ( !defined($first_entry) ) {
                    $first_entry = $tt;
                }
                if ( $tt > ( strftime( "%s", localtime ) - $timeframe ) ) {
                    $kills_today++;
                }
                if ( $line =~ /PERM/ ) {
                    $last_perm_entry = $tt;
                }
                $last_entry = $tt;
                $total_entries++;
        if (defined($opt_list)){
                    push(@last_matches,$line);
                }
            }
        }
    }
    close($limitphplog_fh);
    if ($total_entries) {
        show_kills_total( $user, $total_entries, "limited" );
        show_kills_today( $user, $kills_today, "limited" );
        show_when_killed( $user, $first_entry, "first killed" );
        show_when_killed( $user, $last_entry,  "last killed" );
        if ( defined($last_perm_entry) ) {
            printf( "%s %${SPACING}s had last PERM 503 limit on: %s\n", DASH, $user, localtime($last_perm_entry) . "" );
        }
        if (defined($opt_list)){
            print_matches(@last_matches,$opt_number,$kills_today);
        }
    }
}

# Checks for current limit. Needs username.
sub check_limitphp($) {
    my $user  = shift;
    my $uid   = getpwnam($user);
    my $limit = 0;
    checking("/dev/shm/limit");
    if ( -e "/dev/shm/limit/" . $uid ) {
        open( my $limitphp_fh, "<", "/dev/shm/limit/" . $uid );
        while ( my $line = <$limitphp_fh> ) {
            if ( $line =~ /PERM/ ) {
                $limit = 1;
            }
            else {
                $limit = 2;
            }
        }
    }
    show_limitphp( $user, $limit );
}

# Check if a shared or reseller server
sub shared_server{
    if(hostname()=~/\.(hostgator\.(com(\.(tr|br))?|in)|(websitewelcome|webhostsunucusu|ehost(s)?|ideahost|hostclear)\.com|websitedns\.in|prodns\.com\.br)$/){
        return 1;
    } else {
        return 0;
    }
}

# Display help/usage and exit.
sub show_help{
    print("\nWiki page @ https://confluence.endurance.com/display/HGS/IsKilled\n");
    print("Project page @ https://stash.endurance.com/projects/HGADMIN/repos/iskilled/browse\n");
    print("\nUSAGE: iskilled [user|domain] [-hklLntuv] \n");
    print(" -h|--help             Shows this help page and exits\n");
    print(" -k|--kills            Only display entries of kills today|time. Requires -l\n");
    print(" -l|--list             Shows last entries found\n");
    print(" -L|--log=[LOG[,LOG]]  Search only specified LOG\n");
    print(" -n|--number=[NUM]     Show NUM number of entries in list. Requires -l\n");
    print(" -t|--time=[HOURS]     Look back HOURS number of hours.\n");
    print(" -u|--user=[USER]      Specify USER. Not required.\n");
    print(" -v|--version          Display version information and exit.\n");
    print("\nIskilled will search killscript logs for specified username. If domain is specified, it\n");
    print("will attempt to find username from domain name. If no username or domain is provided,\n");
    print("will attempt to use present working directory to find user.\n\n");
}

# Runs the other check_* functions. Needs username.
sub check_allthethings($) {
    my $user = shift;
    if(!@opt_logs||@opt_logs->matches("(/opt/hgmods/automated_monitoring/logs/)?autocpu(\.log)?")){
        check_limitphp($user);
    }
    if(!@opt_logs||@opt_logs->matches("(/opt/hgmods/automated_monitoring/logs/)?autocpu(\.log)?")){
        check_limitphp_log($user);
    }
    if(!@opt_logs||@opt_logs->matches("(/opt/hgmods/)?kill_usage(\.log)?")){
        check_killusage($user);
    }
    if(!@opt_logs||@opt_logs->matches("(/var/log/)?mysql_queries(\.log)?")){
        check_mysql($user);
    }
    if(!@opt_logs||@opt_logs->matches("(/opt/hgmods/automated_monitoring/logs/)?mysql_autosuspend(\.log)?")){
        check_mysql_autosuspend($user);
    }
    if(!@opt_logs||@opt_logs->matches("(/opt/hgmods/)?hg_processcount(\.log)?")){
        check_processcount($user);
    }
    if(!@opt_logs||@opt_logs->matches("(/opt/hgmods/)?kill_imap(\.log)?")){
        check_kill_imap($user);
    }
    if(!@opt_logs||@opt_logs->matches("(/opt/hgmods/automated_monitoring/etc/)?banned_sqlusers")){
        check_sqlban($user);
    }
    if(!@opt_logs||@opt_logs->matches("(/opt/hgmods/)?hg_user_cputime(\.log)?")){
        check_cputime($user);
    }
    if(!@opt_logs||@opt_logs->matches("(/opt/eig_linux/etc/marked_)?phishing(_domains\.sqlite)?")){
        check_phishing($user);
    }
    return;
}

# Gets username from either explicit call on commandline, cwd ('.'), or domain name. Needs command line arg to lookup passed to it.
sub get_user($) {
    my $arg = shift;
    if ($arg) {
        if ( $arg eq '.' ) {
            if ( cwd() =~ /\/home[0-9]?\/APACHE_LOGS\/domlogs\/([^\/]*)\/?/ || cwd() =~ /\/home[0-9]?\/([^\/]*)\/?/ ) {
                return $1;
            }
        }
        elsif ( $arg =~ /\./ ) {
            my $maybeuser;
            open( my $userdomains_fh, "<", "/etc/userdomains" );
            while ( my $line = <$userdomains_fh> ) {
                if ( $line =~ /^${arg}:/ ) {
                    my @F = split( /\s+/, $line );
                    $maybeuser = $F[1];
                    last;
                }
            }
            close($userdomains_fh);
            if ( defined($maybeuser) && -d "/home/" . $maybeuser ) {
                return $maybeuser;
            }
        }
        elsif ( -d "/home/" . $arg ) {
            return $arg;
        }
    }
    elsif ( !$arg ) {
        if ( cwd() =~ /\/home[0-9]?\/APACHE_LOGS\/domlogs\/([^\/]*)\/?/ || cwd() =~ /\/home[0-9]?\/([^\/]*)\/?/ ) {
            return $1;
        }
    }
    print("Could not find user. Pass a valid user or domain.\n");
    exit 2;
}

#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-=#=-
# Main

setpriority( 0, 0, -1 );
GetOptions(
    'help|h' => \$opt_help,
    'user|u=s' => \$opt_user,
    'list|l' => \$opt_list,
    'number|num|n=i' => \$opt_number,
    'kills|k' => \$opt_listkills,
    'time|target|t=i' => \$opt_time,
    'log|L=s' => \@opt_logs,
    'version|v' => \$opt_version
    );

if(defined($opt_help)){
    show_help();
    exit 0;
}
if(defined($opt_version)){
    print(VERSION."\n"); 
    exit 0;
}
@opt_logs = split(/,/,join(",",@opt_logs));
$timeframe = 8600*$opt_time;
if(!defined($opt_user)){
    $opt_user = $ARGV[0];
}
$user = get_user($opt_user);
printf( "\n%s Checking user \"%s\"\n", PLUS, $user );
check_allthethings($user);
print("\n");
exit 0;
