#!/usr/bin/env perl
#################################################################
# security.pl - Michael Karr
# The Mechanical Security Administrator
# Investigates source of, and cleans found shells and malware.
#
# Git: http://git.toolbox.hostgator.com/security
# Installer: http://git.hgfix.net/security/dev/install_security.sh
# Wiki: https://gatorwiki.hostgator.com/Security/SecurityScript
# 
# Please submit all bug reports at http://bugs.hostgator.com
#
# (c) 2012 - HostGator.com, LLC.
#################################################################

# Check for dependencies (non-core modules only) before anything..

eval {
  require DateTime::TimeZone;
  require JSON;
  require YAML::Syck;
};
if ( $@ ) {
  my $hostname = hostname();
  if ($hostname =~ /.*\.(hostgator\.(com(\.(tr|br))?|in)|(websitewelcome|webhostsunucusu|ehost(s)?|ideahost|hostclear)\.com|websitedns\.in|prodns\.com\.br)$/) {
    print "[!] We're missing required perl modules. Please contact an L2 or Supervisor.\n";
    exit();
  } else {
    print "[!] Missing some perl modules. Installing...\n";
    do_modules();
  }
  # re-eval and import to avoid bailout/script rerun
  eval {
    require DateTime::TimeZone;
    require JSON;
    require YAML::Syck;
  };
  if ( $@ ) {
    print "[!] Could not autoresolve dependencies. Please contact support.\n";
    exit;
  } else {
      import DateTime::TimeZone;
      import JSON;
      import YAML::Syck;
      print "[*] Modules have been installed and loaded. Proceeding...\n";
    }
  } else {
      import DateTime::TimeZone;
      import JSON;
      import YAML::Syck;
}

BEGIN { # begin package Security::Config
package Security::Config;

use strict;
use warnings;

# utilities we need to run

our $utilities = { 
    nscan => ['/root/bin/autoclean', 'http://git.hgfix.net/autoclean/autoclean'],
    scan => ['/root/bin/scan','http://scripts.hostgator.com/~sec/scan'],
    vdetect => ['/root/bin/vdetect','http://git.hgfix.net/vdetect/vdetect'],
};

1;
} # end package Security::Config


{ # begin package main
package main;

use strict;
use warnings;

use Getopt::Long;

use Cwd;
use FileHandle;
use File::stat;
use File::Find;
use File::Path qw/mkpath/;
use File::Basename qw/dirname/;
use Sys::Hostname;

# globals

my %userlogs; # will store the file handles for the user logs
my %userlogsn; # will store the filenames for the user logs
my %userstatslogs; # will store the file handles for the stats logs
my %backupdir; # stores the current backup dir for the user
my %args; # stores provided arguments
my $dirty; # used to trigger process termination on dirty accounts

# grab arguments

GetOptions (
    'list|l' => \$args{list},
    'user|u=s' => \$args{user},
    'debug' => \$args{debug},
    'reseller|r=s' => \$args{reseller},
    'noclean|n' => \$args{noclean},
    'nobackup|b' => \$args{nobackup},
    'killpids|k' => \$args{killpids},
);

# main routine

## LOCkE Test :: Ensuring  tabula rasa
    my $lockuser;
    if (defined($args{reseller})) {
        $lockuser=$args{reseller};
    } elsif (defined($args{user})) {
        $lockuser=$args{user};
    } elsif (my $user = dir_to_user(cwd())) {
        $lockuser=$user;
    }
        if (defined($args{nobackup})) {
        my $BACKUPLOCK = File::Spec->catdir(user_to_homedir($lockuser), "/.skip_next_hg_backup");
        sysopen(my $fh, $BACKUPLOCK, O_CREAT | O_EXCL | O_RDWR, 0600);
        close $fh;
        $BACKUPLOCK = File::Spec->catdir(user_to_homedir($lockuser), "/.skip_next_db_backup");
        sysopen($fh, $BACKUPLOCK, O_CREAT | O_EXCL | O_RDWR, 0600);
        close $fh;
        loguser($lockuser,"Backups disabled for next backup cycle.\n");
    }
    loguser($lockuser,'');
    my $PROGRAM = 'security';
    my $LOCKDIR = File::Spec->catdir(user_to_homedir($lockuser), ".security");
    my $LOCKFILE = "$LOCKDIR/$PROGRAM.lock";
    loguser($lockuser,'');
    # use a lockfile to prevent spawning duplicate processes
    unless ( sysopen(my $fh, $LOCKFILE, O_CREAT | O_EXCL | O_RDWR, 0600) )
        {
            close $fh;
        # the lockfile already exists
        print "Lockfile $LOCKFILE aready exists.\nChecking for running $PROGRAM process...\n";
        # sleep for a couple of seconds to make sure we don't race
        # by this time the process should be in the process table
        sleep 2;
        my @ps = grep{ m/(\d+).*?security/ } `ps --no-headers axo pid,args`;
        # we expect 1 copy (us) running
        die "\nThere is already a copy of $PROGRAM running!\n" if @ps > 1;
    }
    $SIG{INT} = $SIG{TERM} = sub {
        unlink $LOCKFILE or warn "Could not unlink $LOCKFILE for $PROGRAM\n";
        syswrite(STDERR, "Caught ^C or KILL. Exiting after lockfile removal.\n", 55 );
        exit;
    };


if (defined($args{list})) {
    if (exists $ARGV[0]) {
        procfile($ARGV[0]); # use the file were were given
    } else {
        procfile("-"); # use stdin if we were provided with nothing else
    }
} else {
    if (defined($args{reseller})) {
        scanreseller($args{reseller});
    } elsif (defined($args{user})) {
        scanuser($args{user});
    } elsif (my $user = dir_to_user(cwd())) {
        scanuser($user);
    } else {
        print "No user given, and I do not appear to be in a home directory.\n";
        print "Please use '-u' to specify a user or '-l' to specify a list of files.\n";
    }
}

cleanup();

exit;

# end main routine

# autoresolve module deps
sub do_modules {
my @modules=(
	'JSON',
	'YAML::Syck'
);
if ( -d "/var/cpanel" ) {
    foreach (@modules) {
      print "[+] Installing module: $_\n";
      my $cmd = "/scripts/perlinstaller $_";
      `$cmd`;
    }
  } elsif ( -d "/usr/local/psa" ) {
      unless (`rpm -qa epel-release` =~ /epel/m) {
        my $cmd = '[[ "$(grep ^\'CentOS release 5\.\' /etc/redhat-release)" ]] && c=5 || { [[ "$(grep ^\'CentOS release 6\.\' /etc/redhat-release)" ]] && c=6;};[[ "$c" ]] && rpm -Uhv `/usr/bin/lynx --dump http://dl.fedoraproject.org/pub/epel/${c}/x86_64/|grep -oP \'http://.*epel-release.*.noarch.rpm$\'`';
        `$cmd 2>/dev/null 1>/dev/null`;
        die "[!] Failed to install EPEL." unless (`rpm -qa epel-release` =~ /epel/m);
      }
      my $pkgstr = '';
      foreach (@modules) {
        $_ =~ s/::/\-/;
        $pkgstr = "$pkgstr perl-$_"
      }
      `yum -y install $pkgstr 2>/dev/null 1>/dev/null;rpm -ev --nodeps epel-release 2>/dev/null 1>/dev/null`;
  } else {
     print "[!] No supported control panel was detected. Exiting.\n";
     exit(1);
  }
}

sub cleanup {
    # clean up opened log files
        
    for my $user (keys %userlogs) {
        if (defined($userlogs{$user})) {
            $userlogs{$user}->close();
        }
    }
    
    for my $user (keys %userstatslogs) {
        if (defined($userlogs{$user})) {
            $userlogs{$user}->close();
        }
    }
    unlink $LOCKFILE;
}

sub scanuser {
    my ($user) = @_;
    
    init();
    
    loguser($user, "Scanning for shell scripts on user '$user'.\n\n");
    
    my $files_r = scan($user);
    
    if (scalar(@{$files_r})) {
        loguser($user, "Shells found.\n\n");
    } else {
        loguser($user, "No shells found.\n\n");
    }
    
    procuser($user, $files_r);
}

sub scanreseller {
    my ($reseller) = @_;
    my $users_r = MK::Utility::cPanel::ownerusers($reseller);
    
    if (scalar(@{$users_r})) {
        
        for my $user (sort {$a cmp $b} @{$users_r}) {
            scanuser($user);
            cleanup();
        }
    } else {
        print "No sub-acccounts found for the given user. Is it actually a reseller?\n";
    }
}

sub procfile {
    my ($file) = @_;
    
    init();
    
    if (defined(my $fh = FileHandle->new("<$file"))) {
        my %malware; # hash of arrays, user -> list of malware files
        
        while (my $line = <$fh>) {
            chomp $line;
            
            if (my $user = dir_to_user($line)) {                
                if (-f $line) { # make sure the file exists
                    push(@{$malware{$user}}, $line);
                }
            }
        }
        
        $fh->close();
        
        for my $user (keys %malware) {
            procuser($user, \@{$malware{$user}});
        }
    } else {
        print STDERR "Opening '$file' for reading failed!\n";
    }
}

sub procuser {
    my ($user, $list_r) = @_;
    $dirty = 0; 
    loguser($user, "Processing user '$user': \n");

    if ($args{noclean}) {
        loguser($user, "No clean mode enabled.\n");
    }

    loguser($user, "\n");

    # check for enabled modsec rules
    unless (-d "/usr/local/psa") {
      loguser($user, "Checking for enabled mod_security rules.\n\n", 1);
      checkmodsec($user);
    }
    
    # push file stats into array for later
        
    my @file_stat = map {
        my $fs = stat($_);
        {
            file => $_,
            size => $fs->size,
            ctime => $fs->ctime,
            mtime => $fs->mtime,
        };
    } @{$list_r};
        
    # if we don't have a list of files, don't bother doing anything associated with it
    
    if (scalar(@{$list_r}) > 0) {
	$dirty = 1;
        loguser($user, "Shells found under user '$user': \n\n");
            
        for my $file (@{$list_r}) {
            loguser($user, "$file\n");
        }
    
        loguser($user, "\n");
        
        # remove the list of files
        
        unless($args{noclean}) {
            loguser($user, "Removing shells from account.\n\n", 1);
            removefiles($user, $list_r);
        }   
    }
    
    # run autoclean on the account
    
    loguser($user, "Scanning for malware.\n\n", 1);
    my $malware = autoclean($user);
    
    # add autoclean malware stats to list
    
    @file_stat = (@file_stat, @{$malware});
    
    # dump the stats list
    
    for my $file (@file_stat) {
        dumpstat($user, $file->{file}, $file->{ctime}, $file->{mtime})
    }

    # re-run clamav scan on files detected with autoclean

    loguser($user, "Rechecking detected files for shells.\n\n", 1);
    my $newshells_r = scanfiles($user, $malware);

    if (scalar(@{$newshells_r}) > 0) {
        loguser($user, "Shells found under user '$user': \n\n");
            
        for my $file (@{$newshells_r}) {
            loguser($user, "$file\n");
        }
    
        loguser($user, "\n");
        
        # remove the list of files

        unless($args{noclean}) {
            loguser($user, "Removing shells from account.\n\n", 1);
            removefiles($user, $newshells_r);
        }
    }

    # terminate user processes if shells/malware was found

    if ((scalar($dirty) > "0") && (defined($args{killpids}))) {
      my @process_list = `ps -u $user --no-headers -o "%p:|:%a"`;
      if ($#process_list > 0) {
        loguser($user, "Terminating processes...\n");
	foreach (@process_list) {
          my @pid = split(/:\|:/,$_);
	  chomp $pid[0];
	  $pid[0] =~ s/^\s+//;
	  chomp $pid[1];
          loguser($user, "Terminating pid $pid[0]: $pid[1]\n");
          `kill -9 $pid[0]`;
        }
        loguser($user, "\n");
      }
    }
    loguser($user, "Searching for outdated software.\n\n", 1);
    vdetect($user);
    
}

sub loguser {
    my ($user, $msg, $debug) = @_;
    
    if ($debug) {
        return unless $args{debug};        
    }
    
    if ($args{debug}) {
        $msg = time.': '.$msg;
    }
    
    print $msg; # output to standard out too
    
    my $secdir = File::Spec->catdir(user_to_homedir($user), ".security");
    
    unless (-d $secdir) {
        mkpath($secdir);
    }
    
    unless (exists($userlogs{$user})) { # if we do not have a log opened for the user, open it
        $userlogsn{$user} = File::Spec->catfile($secdir, "securitylog.".time);
        $userlogs{$user} = FileHandle->new(">$userlogsn{$user}");
        
        unless (defined($userlogs{$user})) {
            print STDERR "Failed to open log file in home directory for user '$user'.\n";
            $userlogs{$user} = undef; # we want to continue anyway and will just forgo writing to the log
        }
    }
    
    if (defined($userlogs{$user})) { # don't bother writing to an undefined file handle
        print {$userlogs{$user}} $msg;
    }
}

sub removefiles {
    my ($user, $files_r) = @_;
    
    for my $file (@{$files_r}) {
        if (-f $file) { # make sure it exists. first
            if (backupfile($user, $file) == 0) {
                if ($file =~ /^.*?\/(index|main|default|header|define_[^\.]*|application_(top|bottom))\.([a-z]?html?|php[0-9]?)$/) { # if the file is on the whitelist, just blank it
                    if (my $fh = FileHandle->new(">$file")) {
                        print $fh "\n"; # just output a single newline
                        $fh->close();
                        loguser($user, "Cleared malicious file: $file\n");
                    } else {
                        loguser($user, "Failed to clear file: $file\n");
                    }
                } else { 
                    if (unlink($file)) {
                        loguser($user, "Removed malicious file: $file\n");
                    } else {
                        loguser($user, "Failed to remove file: $file\n");
                    }
                }
            } else {
                loguser($user, "Failed to backup file '$file'. Aborting removal.\n");
            }
        }
    }

    loguser($user, "\n");
}

sub backupfile {
    my ($user, $file) = @_;
  
    unless (defined ($backupdir{$user})) {
        my $secdir = File::Spec->catdir(user_to_homedir($user), ".security");
        
        unless (-d $secdir) {
            mkpath($secdir);
        }
        
        $backupdir{$user} = File::Spec->catdir($secdir, "securitybkup.".time);
        mkpath($backupdir{$user});
    }
    
    my $destfile = File::Spec->catfile($backupdir{$user}, $file);
    my $path = dirname($destfile);

    unless (-d $path) {
        mkpath($path);
    }
    
    return system("cp", "-a", $file, $destfile);
}

sub getdomains {
    my ($user) = @_;
    my $userpath = "/etc/userdomains";
    my %domains; # hash domains for the given user

    if (defined(my $fh = FileHandle->new("</etc/userdomains"))) {  
        while (my $line = <$fh>) {
            chomp($line); # Kill trailing whitespace/newline
            my @temp = split(": ", $line); # userdomains format is "domain.com: user"
            
            if ($temp[1] eq $user) { # if it's our user, add it
                $domains{$temp[0]} = undef;
            }
        }
        $fh->close();
    } else {
        print STDERR "Opening '/etc/userdomains' for reading failed!\n";
    }
    
    return \%domains;
}

sub checkmodsec {
    my ($user) = @_;
    
    my %secrules = %{getmodsec($user)}; # grab modsec rules for user's domains
    
    if (scalar(keys %secrules) > 0) {
        loguser($user, "Whitelisted mod_security rules detected.\n\n");
        
        for my $domain (keys %secrules) {
            loguser($user, "$domain:\n");
            
            for my $rule (@{$secrules{$domain}}) {
                loguser($user, "\t$rule\n");
            }
        }
        
        loguser($user, "\n");
    }
}
sub getmodsec {
    my ($user) = @_;
    my %domains = %{getdomains($user)};
    my %rules; # domain -> rules map
    
    if (defined(my $fh = FileHandle->new("</opt/mod_security/whitelist.conf"))) {  
        while (my $line = <$fh>) {
            if ($line =~ /^SecRule\sSERVER_NAME\s\"([^\"]*)"\s.*?ruleRemoveByID=([0-9]+)/) {
                if (exists($domains{$1})) {
                    push (@{$rules{$1}}, $2);
                }
            }
        }
        $fh->close();
    } else {
        print STDERR "Opening '/opt/mod_security/whitelist.conf' for reading failed!\n";
    }
    
    return \%rules;
}

sub init {
    my ($sane,$ac_bad) = 1;
    
    # check to ensure that all needed utilities are present
    
    for my $utility (keys %{$Security::Config::utilities}) {
        if (!(-f ${$Security::Config::utilities->{$utility}}[0])) {
            print STDERR "Utility $utility not found.\n";
            $sane = 0;
        }
    }
    
    if (!$sane) {
        print STDERR "Environment not sane. Exiting\n";
        exit;
    }

   # autoclean/py27 sanity check (to avoid errors due to bad/incomplete install later with autoclean/vdetect subroutines)

   my @watac = `${$Security::Config::utilities->{nscan}}[0] -h`;
   foreach (@watac) {
     $ac_bad = '0' if ($_ =~ /^[U|u]sage/);
   }
   if ($ac_bad) {
     print STDERR "Could not validate autoclean. Exiting\n";
     exit 1;
   }
}

sub autoclean {
    my ($user) = @_;
    
    # normal run
    
    loguser($user, "Scanning via Autoclean for normal malware.\n", 1);
    
    my $command_n;

    if ($args{noclean}) {
        $command_n = ${$Security::Config::utilities->{nscan}}[0]." -S -q -d ".user_to_homedir($user);
    } else {    
        $command_n = ${$Security::Config::utilities->{nscan}}[0]." -S -q -c -d ".user_to_homedir($user);
    }

    my @out_n = `$command_n`;
    my $ac_out_n;
    
    for my $line (@out_n) {
        if ($line =~ /^\{.*\}$/) { # we only want valid json, or things will blow up
            $ac_out_n = decode_json($line);
            last;
        }
    }

    my @matches_n = map {{
        file => $_,
        ctime => $ac_out_n->{$_}->{ctime},
        mtime => $ac_out_n->{$_}->{mtime},
        size => $ac_out_n->{$_}->{size},
    }} keys %{$ac_out_n};
    
    # htaccess run
    
    loguser($user, "Scanning via Autoclean for .htaccess malware.\n", 1);
    
    my $command_ht;

    if ($args{noclean}) {
        $command_ht = ${$Security::Config::utilities->{nscan}}[0]." -S -q -l htaccess -d ".user_to_homedir($user);
    } else {
        $command_ht = ${$Security::Config::utilities->{nscan}}[0]." -S -q -c -l htaccess -d ".user_to_homedir($user);
    }

    my @out_ht = `$command_ht`;
    my $ac_out_ht;
    
    for my $line (@out_ht) {
        if ($line =~ /^\{.*\}$/) { # we only want valid json, or things will blow up
            $ac_out_ht = decode_json($line);;
            last;
        }
    }
    
    my @matches_ht = map {{
        file => $_,
        ctime => $ac_out_ht->{$_}->{ctime},
        mtime => $ac_out_ht->{$_}->{mtime},
        size => $ac_out_ht->{$_}->{size},
    }} keys %{$ac_out_ht};
    
    # combine the two
    
    my @matches = (@matches_n, @matches_ht);
    
    if (scalar(@matches) > 0) {
	$dirty = 1; 
        if ($args{noclean}) {
            loguser($user, "Malware has been detected:\n\n");
        } else {
            loguser($user, "Malware has been detected and cleaned in files:\n\n");
        }

        for my $match (@matches) {
            loguser($user, $match->{file}."\n");
        }
        
        loguser($user, "\n");
    }
    
    return \@matches;
}

sub scan {
    my ($user) = @_;
    
    my $command = ${$Security::Config::utilities->{scan}}[0]." -s $user";
    my @matches = map {/(^.*?):\s.*?FOUND$/ ? $1 : ()} `$command`;
    
    return \@matches;
}

sub scanfiles {
    my ($user, $malware) = @_;

    # ensure .security dir exists

    my $secdir = File::Spec->catdir(user_to_homedir($user), ".security");        
    unless (-d $secdir) {
        mkpath($secdir);
    }

    my $tmpfile = File::Spec->catfile($secdir, "scanfiles.tmp".time);
    my $tfh = FileHandle->new(">$tmpfile");

    unless (defined($tfh)) {
        loguser($user, "Failed to open temporary file for clamav scan.\n\n");
        return [];
    }

    for my $file (@{$malware}) {
        print $tfh $file->{file}."\n";
    }

    my $command = ${$Security::Config::utilities->{scan}}[0]." -l $tmpfile";
    my @matches = map {/(^.*?):\s.*?FOUND$/ ? $1 : ()} `$command`;
    
    return \@matches;
}

sub vdetect {
    my ($user) = @_;

    my $command = ${$Security::Config::utilities->{vdetect}}[0]." --maxdepth 9 --plain --json --user $user";
    my $apps = decode_json(`$command`);
    my @vmatches = sort {${$a}[1] cmp ${$b}[1]} @{$apps};
    
    my %seen;
    my @outdated;
    
    for my $match (@vmatches) {
        my ($severity, $script, $location, $version) = @{$match};
        
        if (($severity > 1 || $severity < 0) && !(exists($seen{$location}))) { # filter based on severity
            $seen{$location} = undef;
            push(@outdated, $match);
        }
    }
    

    if (scalar(@outdated) > 0) {
        loguser($user, "Outdated software has been detected:\n\n");
    
        for my $match (@outdated) {
            my ($severity, $script, $location, $version) = @{$match};
            
            loguser($user, sprintf(" % -16s :: % 8s :: % -60s\n",$script,$version,$location));
        }
    
        loguser($user, "\n");
        
    } else {
        loguser($user, "No outdated software has been detected:\n\n");
    }
}

sub dumpstat {
    my ($user, $path, $ctime, $mtime) = @_;
    
    my $secdir = File::Spec->catdir(user_to_homedir($user), ".security");
    
    unless (-d $secdir) {
        mkpath($secdir);
    }

    unless (exists($userstatslogs{$user})) { # if we do not have a log opened for the user, open it
        my $file = File::Spec->catfile($secdir, "statlog.".time);
        $userstatslogs{$user} = FileHandle->new(">$file");
        
        unless (defined($userstatslogs{$user})) {
            print STDERR "Failed to open stat log file in home directory for user '$user'.\n";
            $userstatslogs{$user} = undef; # we want to continue anyway and will just forgo writing to the log
        }
    }
    
    if (defined($userstatslogs{$user})) { # don't bother writing to an undefined file handle
        my $tz = DateTime::TimeZone->new(name =>'local');

        my $dctime = DateTime->from_epoch(epoch => $ctime);
        $dctime->set_time_zone($tz);
    
        my $dmtime = DateTime->from_epoch(epoch => $mtime);
        $dmtime->set_time_zone($tz);

        print {$userstatslogs{$user}} "File: $path\nChange Time: ".$dctime->strftime("%m/%d/%Y %T %z")." ($ctime)\nModify Time: ".$dmtime->strftime("%m/%d/%Y %T %z")." ($mtime)\n";
    }
}

sub dir_to_user {
    my ($dir) = @_;
    my %home_dirs;
  if ($dir =~ m/\/home[0-9]?\/virtfs/) { (my $thome = $dir) =~ s/\/virtfs.*//; print "[!] Cannot run from $dir. Try $thome instead\n";exit }; # added for HL-1464  
  if ( -d "/var/cpanel" ) { 
    while(my @ent = getpwent()) {
        $home_dirs{File::Spec->canonpath($ent[7])} = $ent[0];
    }
    
    endpwent();
    
    my @dp = File::Spec->splitdir($dir);
    
    while (scalar(@dp)) {
        my $nd = File::Spec->canonpath(File::Spec->catdir(@dp));
        
        if (exists($home_dirs{$nd})) {
            if (-e '/var/cpanel/users/'.$home_dirs{$nd}) {
                return $home_dirs{$nd};
            }
        }
        
        pop(@dp);
    }
  } elsif ( -d "/usr/local/psa" ) {
      return (getpwuid(stat("$dir")->[4]))[0];
  }
  return undef;
}

sub user_to_homedir {
    my ($user) = @_;
    my @pwd = getpwnam($user);
    return $pwd[7];    
}

} # end package main


BEGIN { # start package MK::Utility::cPanel
package MK::Utility::cPanel;

use strict;
use warnings;
use Carp;

# module subroutines

sub get_docroot {
    my ($domain) = @_;
    
    # normalize domain
    
    $domain = lc $domain;
    $domain =~ s/(?:^\s+)|(?:\s+$)//g; # trim whitespace
    $domain =~ s/(?:^www\.)//; # remove preceeding 'www.'
    
    if (my $username = MK::Utility::Regex::regex_file_match('/etc/userdomains', '^'.$domain.':\s(\w+)$')) {
        my ($userdata_ref, $maindata_ref) = load_userdata($username, $domain);
        
        if ($userdata_ref) {
            return $userdata_ref->{documentroot};
        } else {
            return undef;
        }
    } else {
        return undef;
    }
}

sub load_userdata {
    my ($user, $domain) = @_;    
    my $real_domain;
    
    my $mainpath = '/var/cpanel/userdata/'.$user.'/main';
    my $main_ref =  LoadFile($mainpath);
    
    # if we are a sub/addon domain, load the associated subdomain file
    
    if ((ref($main_ref->{addon_domains}) eq 'HASH') && $main_ref->{addon_domains}->{$domain}) {
        $real_domain = $main_ref->{addon_domains}->{$domain};
    } elsif ((ref($main_ref->{sub_domains}) eq 'ARRAY') && (grep {$_ eq $domain} @{$main_ref->{sub_domains}})) {
        $real_domain = $domain;
    } else {
        $real_domain = $main_ref->{main_domain};
    }
    
    my $userpath = '/var/cpanel/userdata/'.$user.'/'.$real_domain;
    my $userdata_ref = LoadFile($userpath);
    
    return $userdata_ref, $main_ref;
}

sub ownerusers {
    my ($owner) = @_;
    my @users;
    
    open(my $fh, '/etc/trueuserowners') or die "Failed to open '/etc/trueuserowners': $!";
    
    while (my $line = <$fh>) {
        if ($line =~ /^([^:]+):\s$owner$/) {
            push(@users, $1);
        }
    }
    
    close($fh);
    
    return \@users;
}


1;    
} # end package MK::Utility::cPanel


BEGIN { # start package MK::Utility::Regex
package MK::Utility::Regex;

use strict;
use warnings;
use Carp;

use FileHandle; 

# module subroutines

sub regex_file_match {
    my ($file, $rex) = @_;
    my $fh;
    
    if ($file =~ /^.*?\.gz$/) {
        open($fh, "-|", "zcat " . $file); # total hack, but super fast
    } else {
        $fh = FileHandle->new("<$file");
    }
    
    if ($fh) {
        my @matches;
        
        while(my $line = <$fh>) {
            if ($line =~ /$rex/) {
                push (@matches, $1);
                
                unless (wantarray()) {
                    last;
                }
            }       
        }
        
        $fh->close();
        
        if (wantarray()) {
            return @matches;
        } else {
            return shift @matches;
        }
    } else {
        return undef;
    }
}

1;    
} # end package MK::Utility::Regex
