Skip to content

Instantly share code, notes, and snippets.

@ribasco
Last active September 28, 2021 07:48
Show Gist options
  • Save ribasco/c0f70e1b45f7c20e86d2d8e5b88d0b60 to your computer and use it in GitHub Desktop.
Save ribasco/c0f70e1b45f7c20e86d2d8e5b88d0b60 to your computer and use it in GitHub Desktop.
Simple bash script to fix the SSH Permissions of a user (in case you encounter Bad Ownership errors)
#!/bin/bash
set -e
if [[ $UID != 0 ]]; then
echo "Please run this script with sudo"
exit 1
fi
HOME_USER=$1
if [ -z "$HOME_USER" ]; then
echo "usage: $0 <user>"
exit 1;
fi
function print_cval() {
local path=$1
local value=$(stat --format '%a' $path)
echo "$path = $value"
}
HOME_DIR_PATH=/home/${HOME_USER}
SSH_DIR_PATH=${HOME_DIR_PATH}/.ssh
if [ ! -d $HOME_DIR_PATH ]; then
echo "Home ${HOME_DIR_PATH} does not exists"
exit 1;
fi
if [ ! -d $SSH_DIR_PATH ]; then
echo "The SSH directory of user '${HOME_USER}' does not exist '${SSH_DIR_PATH}'"
exit 1;
fi
echo "Fixing ssh file/directory permissions.."
chown -v ${HOME_USER}:${HOME_USER} ${HOME_DIR_PATH}
chown -vR ${HOME_USER}:${HOME_USER} ${SSH_DIR_PATH}
chmod -v 755 $HOME_DIR_PATH
chmod -v 700 $SSH_DIR_PATH
chmod -v 600 $SSH_DIR_PATH/authorized_keys
chmod -v 600 $SSH_DIR_PATH/id_*
chmod -v 644 $SSH_DIR_PATH/known_hosts
for f in $SSH_DIR_PATH/*
do
if [[ ! "${f}" =~ id\_.* ]]; then
continue;
fi
echo "Updating chmod for '${f}' to 600"
chmod -v 600 $f
done
print_cval ${HOME_DIR_PATH}
print_cval ${SSH_DIR_PATH}
print_cval $SSH_DIR_PATH/authorized_keys
print_cval $SSH_DIR_PATH/id_*
print_cval $SSH_DIR_PATH/known_hosts
echo "Done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment