#!/usr/bin/perl
use strict;
use warnings;
use Sys::Hostname;
my %homedir_addons;
my %users;
my %seen;
my $hostname = hostname();
$ENV{HOSTNAME} = $hostname; # for secure_docroot
my ( undef, undef, undef, $nobody_gid ) = getpwnam('nobody');
my $mwp = -f '/nfssys/cluster.conf';
my @dotfiles = qw(
    .my.cnf
    .htpasswds
    .attracta.conf
    public_html.zip
    dbconnect-backup.tar

    .permslog
    .viminfo
    .bash_history
    .mysql_history
    .sqlite_history
    .dns
);
push @dotfiles, '.ssh' unless $mwp;

# exclude from MWP pass stripping 'o' perms from homedir contents
my %standard_dirs = map { $_, 1 } qw(
    mail
    tmp
    .htaccess
);

sub getpwnam_cached {
    my ($user) = @_;
    $users{$user} = [getpwnam($user)] unless exists $users{$user};
    return @{$users{$user}};
}

sub fails_paranoid_docroot_check {
    my ($user, $path) = @_;
    my @stat = lstat($path);
    my ( $uid, $gid, $homedir ) = (getpwnam_cached($user))[2,3];
    if (
        $path =~ /\.\./  # relative pathing
        || $path !~ m(^/home\d*/\Q$user\E/)  # doesn't look like path's under user's homedir
        || $path =~ m(^/home\d*/\Q$user\E/mail/?$)  # is for some unspeakable reason the user's mail dir
        || !@stat  # doesn't exist
        || -l $path  # a symlink (redundant)
        || $stat[4] != $uid  # not owned by our user
        || ($stat[5] != $gid && $stat[5] != $nobody_gid)  # not group-owned by user|nobody
    ) {
        #print "[!] Rejected docroot: $path\n";
        return 1
    }
    0
}

sub secure_dotfiles {
    my ($dir) = @_;
    for (@dotfiles) {
        next unless -e "$dir/$_";
        system "/root/bin/secure_private" => "$dir/$_";
    }
}

sub secure_homedir {
    my ($homedir, $user_uid, $user_gid, $user) = @_;
    opendir(my $dh, $homedir) or return;
    $ENV{PERMLOGPATH} = $homedir . '/' . '.permfixlog'; # log for secure_private
    $ENV{PERMLOGUID} = $user_uid;
    $ENV{PERMLOGGID} = $user_gid;
    foreach my $basedir ( grep { ! /^\.(\.)?$/ } readdir($dh) ) {
        next if exists $standard_dirs{$basedir};
        my $dir = $homedir . '/' . $basedir;
        if (-l $dir) {
            my $dest = readlink($dir);
            if (defined($dest) && $dest =~ m,^/local.data\d*/\Q$user\E/\Q$basedir\E/*$,) {
                $dir = $dest;
            } else {
                next
            }
        }
        my ( undef, undef, $mode, undef, $uid ) = lstat($dir);
        next unless $uid == $user_uid;
        if ($mode & 07) { # if any 'other' bits are set...
            system "/root/bin/secure_private" => $dir; # strip them
        }
    }
    delete $ENV{PERMLOGPATH}; # no need to delete other PERMLOG* vars
    closedir($dh);
}

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, </home*/hgtransfer>);
chmod(0700, '/var/log/hgtransfer');
chmod(0660, '/var/log/mysql_queries.log');
chmod(0600, '/etc/shadow');

{
    open(my $fh, '<', '/etc/userdatadomains');
    while (<$fh>) {
        chomp();
        my ($user, $type, $docroot) = (split /: |==/, $_)[1,3,5];
        my ( $user_uid, $user_gid, $homedir ) = (getpwnam_cached($user))[2,3,7];
        if ($docroot =~ m(^/ [^/]+ / [^/]+ /public_html (?:/)?$)x) {
            # worry less about changing the permissions of a public_html
            $homedir_addons{$user}{$docroot}++;
            system "/root/bin/secure_docroot" => $docroot;
        }
        elsif (! exists $homedir_addons{$user}{$docroot} && $user_uid >= 500
                && $docroot !~ m(^/ [^/]+ / [^/]+ /public_html/ [^/]+)x # skip docroots under public_html
                && -d $docroot && ! -l $docroot
                && defined($user_uid) && defined($user_gid) && defined($homedir)) {
            unless (fails_paranoid_docroot_check($user, $docroot)) {
                $homedir_addons{$user}{$docroot}++;
                system "/root/bin/secure_docroot" => $docroot;
            }
        }

        my $dir = '/home/' . $user;
        unless ($seen{$dir}++) {
            $dir = readlink($dir) if -l $dir;
            next if -l $dir;
            next unless -d $dir;
            next unless $dir =~ m(^/home[0-9]*/[a-z0-9]{2,16}$);
            secure_dotfiles($dir);
            secure_homedir($dir, $user_uid, $user_gid, $user) if $mwp;
            my ( 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);
            }
        }

        $dir = '/home/' . $user . '/backups/sak'; 
        unless ($seen{$dir}++) {
            $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}\/backups\/sak$/;
            my ( undef, undef, $mode, undef, $uid, $gid ) = lstat($dir);
            $mode = sprintf("%04o", $mode & 07777);
            if (( $mode ne '0700' ) || ( $uid != $user_uid ) || ( $gid != $user_gid )) {
                print "[*] Permissions incorrect - $hostname - $dir:$mode:$uid:$gid\n";
                chmod(0700, $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;
                next unless $dir =~ /^\/home([0-9]+)?\/[a-zA-Z0-9\_\-]+$/;
                next if -l $dir;
                next unless -d $dir;
                my ( undef, undef, $mode ) = lstat($dir);
                $mode = sprintf("%04o", $mode & 07777);
                if (( $mode ne '0711' ) && ( $mode ne '0700' ) && ( $mode ne '0000')) {
                    print "[*] Permissions incorrect - $hostname - $dir:$mode\n";
                    chmod(0711, $dir);
                }
            }
            closedir($dh);
        }
        elsif (m#^/dev/mapper/vg_dr-lv_backups_(?:root|home\d)\s(/eig_backup(?:/gator\d+.hostgator.com/backup\d)?)#) {
            my $backup_mnt = $1;
            next unless -d $backup_mnt;
            my $mode       = ( stat($backup_mnt) )[2];
            $mode = sprintf( "%04o", $mode & 07777 );
            if ( $mode ne '0700' ) {
                print "[*] Permissions incorrect - $hostname - $backup_mnt:$mode\n";
                chmod( 0700, $backup_mnt );
            }
        }
    }
    close($fh);
}
