CheckHomeDirPermissions

19th March 2015 at 11:06pm
CodeSnippets

If you need other people to be able to poke around in your home directory still, but you're just a little bit paranoid about various permissions ever going a little wrong ever, just cron something crude like this to keep the essentials in check.

#!/bin/bash

PROG="${0##*/}"
exec > >(2>&-;logger -s -t "$PROG[$$]" -p user.info 2>&1) 2> >(logger -s -t "$PROG[$$]" -p user.error)

# Find things to update if you wish using the following command:
#   find ~ -maxdepth 1 -type d -printf "%m %u %g %p\n"

# User, group and path is hard-coded for paranoia
cat <<EOT |
755 nicolaw staff /home/nicolaw/
600 nicolaw staff /home/nicolaw/.screenrc
600 nicolaw staff /home/nicolaw/.viminfo
600 nicolaw staff /home/nicolaw/.bash_history
755 nicolaw staff /home/nicolaw/www
755 nicolaw staff /home/nicolaw/tmp
710 nicolaw staff /home/nicolaw/Desktop
710 nicolaw staff /home/nicolaw/etc
700 nicolaw staff /home/nicolaw/log/
700 nicolaw staff /home/nicolaw/backup/
700 nicolaw staff /home/nicolaw/ssl/
700 nicolaw staff /home/nicolaw/.ssh/
700 nicolaw staff /home/nicolaw/.mozilla
700 nicolaw staff /home/nicolaw/.purple
700 nicolaw staff /home/nicolaw/.config
700 nicolaw staff /home/nicolaw/.gconf
700 nicolaw staff /home/nicolaw/.pki
700 nicolaw staff /home/nicolaw/.cache
710 nicolaw staff /home/nicolaw/Templates
710 nicolaw staff /home/nicolaw/Documents
710 nicolaw staff /home/nicolaw/Downloads
710 nicolaw staff /home/nicolaw/Videos
710 nicolaw staff /home/nicolaw/Music
710 nicolaw staff /home/nicolaw/Pictures
710 nicolaw staff /home/nicolaw/.vim
700 nicolaw staff /home/nicolaw/.gnupg
EOT

while read perms user group path ; do
    if [ -z "$path" ] || ! [ -e "$path" ] ; then
        >&2 echo "Empty or non-existent path '$path'; skipping!"
    else
        read ActualPerms ActualUser ActualGroup ActualPath < <(stat -c '%a %U %G %n' "$path")

        if [ -z "$user" ] || [ -z "$ActualUser" ] ; then
            >&2 echo "Skipping failed user ownership comparisson; required='$user', actual='$ActualUser'"
        else
            if [ "$user" != "$ActualUser" ] ; then
                chown -v "$user" "$path"
            fi
        fi

        if [ -z "$group" ] || [ -z "$ActualGroup" ] ; then
            >&2 echo "Skipping failed group ownership comparisson; required='$group', actual='$ActualGroup'"
        else
            if [ "$group" != "$ActualGroup" ] ; then
                chgrp -v "$group" "$path"
            fi
        fi

        if [ -z "$perms" ] || [ -z "$ActualPerms" ] ; then
            >&2 echo "Skipping failed permissions comparisson; required='$perms', actual='$ActualPerms'"
        else
            if [ "$perms" != "$ActualPerms" ] ; then
                chmod -v $perms "$path"
            fi
        fi
    fi
done