This article provides a convenient Bash script to automate permissions policy requirements for Key-Based Authentication.
Bash Script to Automate Permissions Policy Requirements for Key-Based Authentication.
Here's a Bash script that will automatically update file and directory permissions to ensure key-based SSH authentication works properly. It adjusts permissions for:
- The SSH directory (
~/.ssh/) - The
authorized_keysfile - The user's home directory (if necessary)
This script ensures that permissions are correctly set to prevent SSH from rejecting key-based authentication due to security concerns.
Script: fix_ssh_permissions.sh
#!/bin/bash
# Define the user whose SSH settings need to be fixed
USER_HOME="$HOME"
SSH_DIR="$USER_HOME/.ssh"
AUTHORIZED_KEYS="$SSH_DIR/authorized_keys"
echo "Fixing SSH permissions for user: $(whoami)"
# Ensure the home directory has secure permissions
chmod 700 "$USER_HOME"
echo "Set home directory permissions to 700"
# Ensure .ssh directory exists and has the correct permissions
if [ ! -d "$SSH_DIR" ]; then
echo "Creating .ssh directory..."
mkdir -p "$SSH_DIR"
fi
chmod 700 "$SSH_DIR"
echo "Set .ssh directory permissions to 700"
# Ensure authorized_keys file exists and has the correct permissions
if [ -f "$AUTHORIZED_KEYS" ]; then
chmod 600 "$AUTHORIZED_KEYS"
echo "Set authorized_keys file permissions to 600"
else
echo "No authorized_keys file found. If you are using key-based authentication, ensure this file is created."
fi
# Ensure SSH config file permissions are correct if it exists
SSH_CONFIG="$SSH_DIR/config"
if [ -f "$SSH_CONFIG" ]; then
chmod 600 "$SSH_CONFIG"
echo "Set SSH config file permissions to 600"
fi
# Ensure proper ownership (run as root if fixing another user's SSH access)
chown -R "$(whoami)":"$(whoami)" "$SSH_DIR"
echo "Set ownership of .ssh directory and contents to $(whoami)"
echo "SSH permissions have been successfully updated."
How to Use the Script
To simplify this process, we've setup a GitHub repository to manage this script. This will allow us the luxury of running a single command for deployment. From your SSH client, run the following command:
cd ~ && wget https://raw.githubusercontent.com/sclaeys/fix_ssh_permissions/refs/heads/master/fix_ssh_permissions.sh && chmod +x fix_ssh_permissions.sh && ./fix_ssh_permissions.sh
What This Script Does
- Ensures the home directory has
700permissions. - Ensures the
~/.ssh/directory exists and is set to700. - Ensures the
authorized_keysfile (if it exists) is set to600. - Fixes the SSH config file permissions (if present).
- Sets the correct ownership for all files in
~/.ssh/.
This setup ensures SSH authentication works properly while maintaining security best practices.
Conclusion
You now have access to a Bash script to automate permissions policy requirements for Key-Based Authentication.

👀 Choose SSD-powered VPS servers for increased speed, power, and security! Now 50% off- starting from only $3.19/mo.