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

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' );

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 $hostname = hostname();
my ( undef, undef, undef, $nobody_gid ) = getpwnam('nobody');

open(my $fh, '<', '/etc/trueuserdomains');
    while (<$fh>) {
        chomp();
        my ( undef, $user ) = split(/\s+/);
        my ( undef, undef, $user_uid, $user_gid ) = getpwnam($user);

        my $dir = '/home/' . $user . '/public_html';
        $dir = readlink($dir) if -l $dir;
        next if -l $dir;
        next unless -d $dir;
        next unless $dir =~ /^\/home([0-9]+)?\/[a-z0-9]{2,16}\/public_html$/;
        my ( undef, undef, $mode, undef, $uid, $gid ) = lstat($dir);
        $mode = sprintf("%04o", $mode & 07777);
        if (( $mode ne '0750' ) && ( $mode ne '0700' ) && ( $mode ne '0000' ) && ( $mode ne '0711' ) && ( $mode ne '0750' ) || (( $uid != $user_uid ) || ( $gid != $nobody_gid ))) {
            print "[*] Permissions incorrect - $hostname - $dir:$mode:$uid:$gid\n";
            chmod(0750, $dir);
            chown($user_uid, $nobody_gid, $dir);
        }

        $dir = '/home/' . $user;
        $dir = readlink($dir) if -l $dir;
        next if -l $dir;
        next unless -d $dir;
        next unless $dir =~ /^\/home([0-9]+)?\/[a-z0-9]{2,16}$/;
        ( undef, undef, $mode, undef, $uid, $gid ) = lstat($dir);
        $mode = sprintf("%04o", $mode & 07777);
        if (( $mode ne '0711' ) || ( $uid != $user_uid ) || ( $gid != $user_gid )) {
            print "[*] Permissions incorrect - $hostname - $dir:$mode:$uid:$gid\n";
            chmod(0711, $dir);
            chown($user_uid, $user_gid, $dir);
        }
    }
close($fh);

open(my $fh, '<', '/proc/mounts');
while(<$fh>) {
    if ( /^\S+\s+(\/home[0-9]?)\s/ ) {
        my $home = $1;
        opendir(my $dh, $home);
        foreach my $dir ( grep { ! /^\.(\.)?$/ } readdir($dh) ) {
            $dir = $home . '/' . $dir;
            my ( undef, undef, $mode ) = lstat($home . '/' . $dir);
            next if -l $dir;
            next unless -d $dir;
            next unless $dir =~ /^\/home([0-9]+)?\/[a-zA-Z0-9\_\-]+$/;
            my ( undef, undef, $mode ) = lstat($dir);
            $mode = sprintf("%04o", $mode & 07777);
            if (( $mode ne '0711' ) && ( $mode ne '0700' )) {
                print "[*] Permissions incorrect - $hostname - $dir:$mode\n";
                chmod(0711, $dir);
            }
        }
        closedir($dh);
    }
}
close($fh);

