#!/usr/bin/perl
use strict;
use Fcntl ':mode';
use Sys::Hostname;

open(my $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";
	print $FILE $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.*');

exit if ( -e '/etc/disable_fixperms' );

my $host = hostname();
chmod(0750, '/root');
chmod(0600, </home/cpmove-*.tar.gz>);
chmod(0600, </home/backup-*.tar.gz>);
chmod(0700, '/var/log/hgtransfer');
chmod(0660, '/var/log/mysql_queries.log');
chmod(0600, '/etc/shadow');
my @ftypes;
$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";
foreach (</var/cpanel/users/*>) {
	my $user = (split('/', $_))[4];
	my $filename = '/home/' . $user . '/public_html';
	next if ( -l $filename );
	if ( -d $filename ) {
		if (my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = lstat($filename)) {
			my $user = getpwuid($uid);
			my $group = getgrgid($gid);
			my $permissions = sprintf "%04o", S_IMODE($mode);
			my $filetype = S_IFMT($mode);
			my $ftype = $ftypes[$filetype];
			if (( $permissions ne "0750" && $permissions ne "0700" && $permissions ne "0000" && $permissions ne "0711" && $permissions ne "0751") || ($gid != 99)) {
				if ( $filename =~ /\/home\/[a-z0-9]{2,16}\/public_html/ ) {
					print "[*] Permissions incorrect - $host - $filename / $permissions / $gid \n";
					chmod(0750, $filename);
					chown $uid, 99, $filename;
				}
			}
		}
	}
	$filename = "/home/" . $user;
	next if ( -l $filename );
	if ( -d $filename ) {
		if (my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = lstat($filename)) {
			my $user = getpwuid($uid);
			my $group = getgrgid($gid);
			my $permissions = sprintf "%04o", S_IMODE($mode);
			my $filetype = S_IFMT($mode);
			my $ftype = $ftypes[$filetype];
			if ( $permissions ne "0711" ) {
				if ( $filename =~ /^\/home\/[a-z0-9]{2,12}$/ ) {
					print "[*] Permissions incorrect - $host - $filename / $permissions / $gid \n";
					chmod(0711, $filename);
					chown $uid, $uid, $filename;
				}
			}
		}
	}
}
