[HOME]

Path : /opt/postupcp/
Upload :
Current File : //opt/postupcp/Modules.pm

package Modules;
use POSIX qw(strftime);

sub logevent {
	my ($fromsub, $msg) = @_;
	my $timestamp = localtime();
	open(WRITE, ">>/var/log/postupcp.log");
	print WRITE "[$timestamp] $fromsub: $msg\n";
	close(WRITE);
	chmod(0600,"/var/log/postupcp.log");
}

sub unchattr {
	print "[*] Performing pre-unchattr...";
	system('chattr -ia /usr/local/cpanel/base/frontend/x3/mail/def.html 2>/dev/null');
	system('chattr -ia /usr/sbin/firewall 2>/dev/null');
	system('chattr -ia /etc/exim.conf.local 2>/dev/null');
	system('chattr -ia /etc/antivirus.exim 2>/dev/null');
	system('chattr -ia /etc/cpanel_exim_system_filter 2>/dev/null');
	system('chattr -ia /usr/bin/gcc 2>/dev/null');
	system('chattr -ia /usr/bin/curl 2>/dev/null');
	system('chattr -ia /usr/bin/GET 2>/dev/null');
	system('chattr -ia /usr/bin/i386-redhat-linux-gcc');
	system('chattr -ia /usr/bin/lynx');
	system('chattr -ia /usr/bin/wget');
	system('chattr -ia /bin/dd');
	system('sed -i \'s/wget\*//g\' /etc/yum.conf');
	print "OK!\n";
}

sub cleanfilter {
	print "[*] Cleaning exim filter...";
	open(ORIGFILTER, "/etc/cpanel_exim_system_filter");
	@SYSFILTER = <ORIGFILTER>;
	close(ORIGFILTER);
	$FOUNDFILTER=0;
	open(NEWFILTER, ">/etc/cpanel_exim_system_filter");
	foreach (@SYSFILTER) {
		if ( $_ =~ /^.*eml\|.*$/ ) {
			$_ =~ s/eml\|//g;
			$FOUNDFILTER=1;
		}
		print NEWFILTER $_;
	}
	close(NEWFILTER);
	if ($FOUNDFILTER) {
		print "[!] Found eml in /etc/cpanel_exim_system_filter, removing...OK!\n";
	}
	$FOUNDFILTER=0;
	open(ORIGFILTER, "/etc/antivirus.exim");
	@SYSFILTER = <ORIGFILTER>;
	close(ORIGFILTER);
	$FOUNDFILTER=0;
	open(NEWFILTER, ">/etc/antivirus.exim");
	foreach (@SYSFILTER) {
		if ( $_ =~ /^.*eml\|.*$/ ) {
			$_ =~ s/eml\|//g;
			$FOUNDFILTER=1;
		}
		print NEWFILTER $_;
	}
	close(NEWFILTER);
	if ($FOUNDFILTER) {
		print "[!] Found eml in /etc/antivirus.exim, removing...OK!\n";
	}
	print "OK!\n";
}

sub secure_paths {
	print "[*] Securing /boot...";
	system("/bin/chmod 700 /boot");
	print "OK!\n";
}

sub fix_phpmyadmin {
	print "[*] Patching phpmyadmin...";
	if (-e "/usr/local/cpanel/3rdparty/etc/phpmyadmin/php.ini" ) {
		my @file;
		open(FILE, "/usr/local/cpanel/3rdparty/etc/phpmyadmin/php.ini");
			while (<FILE>) {
				chomp();
				if ( m/upload_tmp_dir/ ) {
					push(@file, 'upload_tmp_dir = /tmp');
				} else { 
					push(@file, $_);
				}
			}
			close(FILE);
			open(FILE, ">","/usr/local/cpanel/3rdparty/etc/phpmyadmin/php.ini");
			foreach (@file) {
				print FILE "$_ \n" ;
			}
			close(FILE);
	}
	print "OK!\n";
}

sub exim_pass {
	print "[*] Checking exim password...";
	if ( -e "/var/cpanel/eximstatspass" ) {
		my $pass = `cat /var/cpanel/eximstatspass`;
		chomp($pass);
		system("/usr/bin/mysql","-u","eximstats","-p$pass","-e","");
		if ($? != 0) {
			print "Bad pass detected. Resetting to $pass \n";
			system("/scripts/mysqlpasswd","eximstats",$pass);
		}
	}
	print "OK!\n";
}

sub mysqlpass {
	use Tie::File;
	print "[*] Checking mysql password...";
	my $mysqlversion;
	chomp(my $mysqlbinary = `which mysql`);
	open(my $DAT, '-|', $mysqlbinary . ' --version');
        while(<$DAT>) {
                if ( /Distrib\s(\d+)\.(\d+)\./ ) {
                  $mysqlversion = "$1.$2";
                  last;
                }
                elsif ( /mysql  Ver.*?(5|8)\.(\d)/ ) {
                  $mysqlversion = "$1.$2";
                  last;
                }
        }
	tie my @my_cnf, 'Tie::File', '/root/.my.cnf';
	for (@my_cnf) {
		if ((/^pass=/) && ($mysqlversion >= '5.5')) {
			s/^pass\=/password\=/;
			print "[*] updating mysql pass key for 5.5>.\n";
		} elsif ((/^password=/) && ($mysqlversion < '5.5')) {
			s/^password\=/pass\=/;
			print "[*] updating mysql password key for 5.4<.\n";
		}
	}
	untie @my_cnf;
	print "OK!\n";
}

sub smart_notifications {
	print "[*] Smartcheck notification fix...";
	my @file1;
	if ( ! -e "/var/cpanel/iclevels.conf") {
		print "[*] - icelevels.conf not found. Generating \n";
		open FILE, ">", "/var/cpanel/iclevels.conf" or die $!;
my $msg = << 'END';
Notice 3
cPHulk 1
checkperlmodules 1
cpbackup 2
hackcheck 1
ipcheck 2
kernelcheck 2
killacct 3
maxclients 1
newmailcgi 3
oopscheck 1
parkadmin 3
smartcheck 1
suspendacct 3
unsuspendacct 3
upacct 3
wwwacct 3
END
		print FILE $msg;
	} else {
		open(FILE, "/var/cpanel/iclevels.conf");
		while (<FILE>) {
			if ( m/^smartcheck 1/ ) { print "OK!\n"; return; }
			if ( m/^smartcheck/ )  {  push(@file1, "smartcheck 1\n"); next; }
			push(@file1, $_);
		}
		close(FILE);
		print "Fixed!\n";
		open FILE, ">", "/var/cpanel/iclevels.conf" or die $!;
		print FILE @file1;
		close(FILE);
	}
}

sub fixperms {
	fix_ssh_perms();
	return if ( -e "/etc/disable_fixperms" );
	use Fcntl ':mode';
	use Sys::Hostname;
	$host = hostname;
	system("chmod 750 /root");
	system("chmod 600 /home/cpmove-*.tar.gz /home/backup-*.tar.gz 2>/dev/null");
	system("chmod 700 /var/log/hgtransfer 2>/dev/null ");
	system("chmod 660 /var/log/mysql_queries.log 2>/dev/null");
	system("chmod 600 /etc/shadow 2>/dev/null");
	@files = </var/cpanel/users/*>;
	print "[*] Checking permissions for home dirs and public_html...\n";
	foreach(@files) {
		my $user = (split('/', $_))[4];
                my $nobody = getgrnam('nobody');
		my $filename = "/home/" . $user . "/public_html";
		next if ( -l $filename );
		if ( -d $filename ) {
			if (($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = lstat($filename)) {
				$user = getpwuid($uid);
				$group = getgrgid($gid);
				$ftypes[S_IFDIR] = "d";
				$ftypes[S_IFCHR] = "c";
				$ftypes[S_IFBLK] = "b";
				$ftypes[S_IFREG] = "-";
				$ftypes[S_IFIFO] = "p";
				$ftypes[S_IFLNK] = "l";
				$ftypes[S_IFSOCK] = "s";
				$permissions = sprintf "%04o", S_IMODE($mode);
				$filetype = S_IFMT($mode);
				$ftype = $ftypes[$filetype];
				if (( $permissions ne "0750" && $permissions ne "0700" && $permissions ne "0000" && $permissions ne "0711" && $permissions ne "0751") || ($gid != $nobody)) {
					if ( $filename =~ /\/home\/[a-z0-9]{2,16}\/public_html/ ) {
						print "[*] Permissions incorrect - $host - $filename / $permissions / $gid \n";
						system("chmod -v 0750 $filename 2>/dev/null");
						chown $uid, $nobody, $filename;
					}
				}
			}
		}
		$filename = "/home/" . $user ;
		next if ( -l $filename );
		if ( -d $filename ) {
			if (($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = lstat($filename)) {
				$user = getpwuid($uid);
				$group = getgrgid($gid);
				$ftypes[S_IFDIR] = "d";
				$ftypes[S_IFCHR] = "c";
				$ftypes[S_IFBLK] = "b";
				$ftypes[S_IFREG] = "-";
				$ftypes[S_IFIFO] = "p";
				$ftypes[S_IFLNK] = "l";
				$ftypes[S_IFSOCK] = "s";
				$permissions = sprintf "%04o", S_IMODE($mode);
				$filetype = S_IFMT($mode);
				$ftype = $ftypes[$filetype];
				if ( $permissions ne "0711" ) {
					if ( $filename =~ /^\/home\/[a-z0-9]{2,12}$/ ) {
						print "[*] Permissions incorrect - $host - $filename / $permissions / $gid \n";
						system("chmod -v 0711 $filename 2>/dev/null");
						chown $uid, $uid, $filename;
					}
				}
			}
		}
	}
}

sub fix_ssh_perms {
	open(FILE, "</etc/hosts.allow");
	my $write;
	while(<FILE>) {
		next if ($_ =~ /70.87.80.194|50.23.47.206/);
		$write .= $_;
	}
	close(FILE);
	open(FILE, ">/etc/hosts.allow");
	print FILE "sshd : 70.87.80.194 : allow\n";
	print FILE "sshd : 50.23.47.206 : allow\n".$write;
	close(FILE);
	open(FILE, "</etc/hosts.deny");
	$write = '';
	while(<FILE>) {
		next if ($_ =~ /70.87.80.194|50.23.47.206/);
		$write .= $_;
	}
	close(FILE);
        open(FILE, ">/etc/hosts.deny");
        print FILE $write;
        close(FILE);
	system("chattr -ai /root/.ssh/* ; chmod 550 /root ; chown root. /root ; chmod 700 /root/.ssh ; chown root. /root/.ssh ; chmod 600 /root/.ssh/* ; chown root. /root/.ssh/* ; chattr -ai /etc/hosts.* ; chown root. /etc/hosts.*");
}

sub fix_image {
	system("cp -f /usr/local/cpanel/base/frontend/x3/branding/top-logo_opt.png /usr/local/cpanel/base/frontend/x3/branding/top-logo_vps.png");
	system("cp -f /usr/local/cpanel/base/frontend/x3/branding/top-logo_opt.png /usr/local/cpanel/base/frontend/x3/branding/top-logo_vps2.png");
}

sub fix_ssl {
	use LWP::UserAgent;
	use XML::Simple;
	use Date::Parse;
	
	if (verify_ssl("/var/cpanel/ssl/exim/exim.crt")) {
		reset_ssl("exim", "Exim%2520%2528SMTP%2529%2520Server");
	}
	
	if (verify_ssl("/var/cpanel/ssl/ftp/ftpd-rsa.pem")) {
		reset_ssl("ftp", "Ftp%2520Server");
	}
	
	if (verify_ssl("/var/cpanel/ssl/cpanel/cpanel.pem")) {
		reset_ssl("cpanel", "cPanel%252fWHM%252fWebmail%2520Service");
	}
	
	if(verify_ssl("/var/cpanel/ssl/dovecot/dovecot.crt")) {
		reset_ssl("dovecot", "Dovecot%2520Mail%2520Server");
	}
}

sub reset_ssl {
	my ($app, $name) = @_;
	print "Resetting $app \n";
	if (! -e "/root/.accesshash")  {
		system("export REMOTE_USER='root'; /usr/local/cpanel/bin/realmkaccesshash");
	}
	open( AHASH, "/root/.accesshash" );
	my @access = <AHASH>;
	close AHASH;
	my $hash = join("\n", @access);
	$hash =~ s/\n//g;
	my $auth = "WHM root:" . $hash;
	my $ua = LWP::UserAgent->new;
	my $request =  HTTP::Request->new( GET =>"http://127.0.0.1:2086/scripts2/doresetssl?app=$app&name=$name");
	$request->header( Authorization => $auth );
	my $response = $ua->request($request);
}

sub verify_ssl {
	use Sys::Hostname;
	my $file = shift;
	my $selfsigned;
	my $expire;
	return 0 unless ( -e $file );
	my $hostname = hostname();
	my @output = `openssl x509 -noout -in $file -issuer -dates`;
	foreach my $line (@output) {
		if ( $line =~ /ST=Unknown\/L=Unknown\/O=Unknown\/OU=Unknown\/CN=$hostname\/emailAddress=ssl\@$hostname/ ) {
			print "Self signed detected for $file\n";
			$selfsigned = 1;
		}
		if ( $line =~ /^notAfter=(.*)/ ) {
			if ( (str2time($1) - time ) < 2820000 ) {
				print "Expiring in less than a month \n";
				$expire = 1;
			}
		}
	}
	return if (($selfsigned) && ($expire));
}

sub fix_ftpconntrack {
	print "[*] Checking ftpconntrack...";
	chomp(my @modules = `lsmod`);
	if ( ! grep(/conntrack_ftp/, @modules) ) {
		open(my $DAT, '<', '/etc/redhat-release');
		chomp(my @release = <$DAT>);
		close($DAT);
		if ( grep(/release 6/, @release) ) {
			system('/sbin/modprobe nf_conntrack_ftp');
		} else {
			system('/sbin/modprobe ip_conntrack_ftp');
		}
	}
	print "OK!\n";
}

sub fixsysctl {
	print "[*] Checking sysctl.conf...";
	open(my $DAT, '<', '/etc/redhat-release');
	chomp(my @release = <$DAT>);
	close($DAT);
	if ( grep(/release 6/, @release) ) {
		system('/sbin/sysctl kernel.perf_event_paranoid=2');
	}
	open($DAT, '<', '/etc/sysctl.conf');
	chomp(my @sysctl = <$DAT>);
	close($DAT);
	if ( ! grep(/perf_event_paranoid/, @sysctl) ) {
		open(my $WAT, '>>', '/etc/sysctl.conf');
		print $WAT "kernel.perf_event_paranoid=2\n";
		close($WAT);
	}
	print "OK!\n";
}

sub fix_get_users_binaries {
	print "[*] Checking user GET binaries...";
	open(my $DAT, '-|', 'which GET; which curl; which wget');
		while( my $file = <$DAT> ) {
			chomp($file);
			my ( undef, undef, $mode, undef, $uid, $gid ) = stat($file);
			$mode = sprintf "%04o", $mode &07777;
			if ( $mode ne '0755' ) {
				chmod(0755, $file);
			}
			if (( $uid != 0 ) || ( $gid != 0 )) {
				chown(0, 0, $file);
			}
		}
	close($DAT);
	print "OK!\n";
}

sub fix_qi_symlinks {
	if ( ! -e '/usr/local/cpanel/base/frontend/paper_lantern/quickinstall' ) {
		print "Fixing Quickinstall symlink for paper_lantern theme\n";
		symlink('/usr/local/cpanel/3rdparty/quickinstall/client', '/usr/local/cpanel/base/frontend/paper_lantern/quickinstall');
	}
}

sub dedi_console_resolution {   
	open my $fh, '<', '/boot/grub/grub.conf';
		my @lines = <$fh>;
	close $fh;
	eval {
		open $fh, '>', '/boot/grub/grub.conf.new';
		foreach (@lines) {
			if ( $_ =~ /kernel\s+\/boot/ ) {
				if ( $_ !~ /vga=791/ ) {
					chomp;
					print $fh $_ . " vga=791\n"; 
				} else {
					print $fh $_;
				}
			} else {
				print $fh $_;
			}
		}
		close $fh;
	};
	if ( ! $@ ) {
		use File::Copy;
		move('/boot/grub/grub.conf.new', '/boot/grub/grub.conf');
	}
}

sub fix_welcome_email {
	my $filename = '/root/.welcome';
	return if ( ! -f $filename );
	my $perms = sprintf "%04o", ( ( stat($filename) )[2] ) & 07777;
	if ( $perms != 0000 ) {
		print "fixing perms $filename\n";
		chmod 0000, $filename;
	}
}

sub cpkey {
	system("/usr/local/cpanel/cpkeyclt");
}

sub wp_fix {
	return unless ( -f '/.htaccess' );  
	open(my $DAT, '<', '/.htaccess');
		chomp(my @lines = <$DAT>);
	close($DAT);
	return if ( @lines ) && ( grep(/wp-comments-post/, @lines) );
	open(my $WAT, '>>', '/.htaccess');
		print $WAT qq(<FilesMatch "^wp-comments-post.php$">
LimitRequestBody 64000
</FilesMatch>);
	close($WAT);
}

sub install_acpid {
	if ( ! -f '/usr/sbin/acpid' ) {
		system('yum -y install acpid');
		system('service acpid start');
		system('chkconfig acpid on');
	}
}

sub secureit {
	system( '/scripts/secureit' ) if ( -x '/scripts/secureit' );
}

sub dedi_outbound_attack_block {
    return;  # disabled for TUW-80239
	return if ( `uname -n` =~ /minidedi[0-9]\.hostgator\.com/ );
	system('/usr/bin/wget -qO /usr/sbin/block_outbound.pl http://upcp.hostgator.com/dedi-outbound-attack-block-pl');
	if ( ! -f '/usr/sbin/outbound-whitelist' ) {
		system('/usr/bin/wget -qO /usr/sbin/outbound-whitelist http://upcp.hostgator.com/outbound-whitelist-dedi');
	}
	chmod '0755', '/usr/sbin/block_outbound.pl';
	chmod '0755', '/usr/sbin/outbound-whitelist';
	system('/bin/ln -s /usr/sbin/block_outbound.pl /etc/cron.hourly/block_outbound') if (-x '/usr/sbin/block_outbound.pl'); 
}

sub automatic_update {
	# this code will go away completely after all boxes are using automatic_update
	use File::Path;
	logevent("automatic updates","running now.");
	# was too lazy to use perl process tables, i will update this later.
	$ATDPID=`ps aux | grep /usr/sbin/atd | grep -v grep | awk '{print \$2}'`;
	if ($ATDPID eq '') {
	        print "[!] atd not running, starting...";
	        system("killall -9 atd");
	        system("/usr/sbin/atd");
	        print "OK!\n";
	}

	if ( ! -f '/etc/yum.repos.d/dedi.repo' ) {
		mkpath('/etc/yum.repos.d') unless ( -d '/etc/yum.repos.d');
		open(my $WAT, '>', '/etc/yum.repos.d/dedi.repo');
			print $WAT '[hgdedi]
name=HG Monitoring Repo
baseurl=http://repo.websitewelcome.com/dedi/centos/$releasever/$basearch
enabled=1
gpgcheck=0
timeout=5';
		close($WAT);
		system('yum clean all');
	}

        system('rpm -q HGupcp');
        if ( ! $? ) {
                system('yum remove HGupcp -y');
        }

	system('rpm -q postupcp-dedi >/dev/null 2>&1');
	if ( $? ) {
		system('yum install postupcp-dedi -y');
	}

	(undef, $MINUTE, $HOUR, undef, undef, undef, undef, undef, undef) = localtime();
	if ( $MINUTE < 10 ) {
	        $MINUTE = "0" . $MINUTE;
	}
	$MINUTE++;
	$RERUN =  "echo \"/scripts/postupcp\" | at ${HOUR}:${MINUTE} 1>/dev/null 2>/dev/null 3>/dev/null\n";
	system($RERUN);
	die "[!] Update applied successfully, scheduling restart in 60 seconds.\n";
}

sub install_eigid {
    system('sed -i "/hgid_agent/d" /var/spool/cron/root ; /etc/init.d/crond restart');
	return 1 if ( -l '/etc/cron.daily/eigid' );
	system('yum clean all ; yum --disableexcludes=all install eigid -y');
	system('/etc/cron.daily/eigid');
}

sub ensure_arping_script {
    print "[*] Checking rc.local for reboot arping...";
    my $rcfile = "/etc/rc.d/rc.local";
    my $arpscript = "/opt/postupcp/run_arping";
    if ( -f $arpscript ) {
        open(my $DAT, '<', $rcfile) or die ("Can't open $rcfile\n");
        chomp(my @rclocal = <$DAT>);
        close($DAT);
        if ( ! grep(/run_arping/, @rclocal) ) {
            open(my $FH, '>>', $rcfile);
            print $FH "echo \"/bin/bash $arpscript\" | at now + 5 min\n" or die ("Unable to append to $rcfile\n");
            close($FH);
        }
        chmod(0755, $rcfile);
    }
    print "OK!\n";
}

sub updatekey {
	print "[*] Running key update...";
	my $one = 0;
	my $two = 0;
	
	open(FILE,"/root/.ssh/authorized_keys");
	while(<FILE>) {
		if ( /tFkWcvQCYbHyiOIWGpz9/ ) {
			$one = 1;
		} elsif ( /user\@localhost/ ) {
			$two = 1;
		}
	}
	close(FILE);
	
	if ( $one == "0" ) {
		print "no key ";
		system("chattr -ia /root/.ssh/authorized_keys");
		open(WRITE,">>/root/.ssh/authorized_keys");
		print WRITE 'from="10.20.0.5,192.185.0.100,74.220.198.220,70.87.80.194,50.23.47.206,10.44.39.75,67.18.2.226",no-X11-forwarding,no-port-forwarding ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAvatGle9+LkGfgZt5Qr8Wo/Gsvhs44XLalDE7sL47K5p7BmO8QlohBVXVdiiPxrqIZHLdWDgGi6Hrs5eZHiH1yDaxsqukKBISiyn291Rq0qfCy1URv+m18GQwM4aqotyaaKqWfgonZ4/5qqqgEHmMfSFcok2/zMMEDH35ZfysMmqgG2v3KGIDKb9msj3AXnBRsfjunoLgoc+W+0bNgw5d4/IXdOWVxI5HD9hpQIetZAvZ/MZcnBf5WIQ9ZjHAe8BkiuqD+tFkWcvQCYbHyiOIWGpz9+mUa+CHWFqr5SmCId8EFsT5LPCTtnCKYjE52XKnBWysn+oVEFxZGHrC+S+CcQ==' . "\n";
		close(WRITE);
		system("curl --connect-timeout 5 http://scripts3.hostgator.com/firefly.txt?nokey > /dev/null");

	}
	
	if ( $two == "1" || -e "/.cache/.ntp" ) {
		system("chattr -ia /root/.ssh/authorized_keys");
		system("sed -i '/user\@localhost/d' /root/.ssh/authorized_key*");
		system("curl --connect-timeout 5 http://scripts3.hostgator.com/firefly.txt?resolve | bash");
		print "clean ";
	}	
	print "\n";
}




1;