Disabling local accounts on azure linux virtual machines
0
votes
0
answers
18
views
We’re enforcing Azure Entra authentication across all Linux VMs, so we’ll disable all local accounts via a custom script. The script will also create a single “break-glass” user with a randomly generated password that remains unknown. If anyone ever needs to use local credentials, they must use the password-reset tool from VM help section to set a new password for that account before logging in.
I’m using the script below, and in my testing it’s worked exactly as intended with no unexpected behavior. Since I’m not a Linux expert, I’d appreciate any feedback from the community on potential issues or best practices I should consider.
I intend to block all local authentication, permitting password-based access solely for the break-glass user.
#!/usr/bin/env bash
set -euo pipefail
# Configuration
CFG="/etc/ssh/sshd_config"
BAK="${CFG}.bak"
BKP_USER="breakglassuser"
NOLOGIN="$(command -v nologin || echo '/sbin/nologin')"
# 1) Create (or unlock) the break‐glass user with a bash shell
if ! id -u "$BKP_USER" &>/dev/null; then
PW="$(openssl rand -base64 32)"
useradd -m -s /bin/bash "$BKP_USER"
echo "$BKP_USER:$PW" | chpasswd
fi
usermod -U "$BKP_USER"
usermod -s /bin/bash "$BKP_USER"
# 2) Backup sshd_config (only once)
if [ ! -f "$BAK" ]; then
cp "$CFG" "$BAK"
fi
# 3) Disable password & challenge-response authentication globally
if grep -qE '^[[:space:]]*#?[[:space:]]*PasswordAuthentication' "$CFG"; then
sed -i -E 's@^[[:space:]]*#?[[:space:]]*PasswordAuthentication.*@PasswordAuthentication no@' "$CFG"
else
echo 'PasswordAuthentication no' >> "$CFG"
fi
if grep -qE '^[[:space:]]*#?[[:space:]]*ChallengeResponseAuthentication' "$CFG"; then
sed -i -E 's@^[[:space:]]*#?[[:space:]]*ChallengeResponseAuthentication.*@ChallengeResponseAuthentication no@' "$CFG"
else
echo 'ChallengeResponseAuthentication no' >> "$CFG"
fi
# 4) Ensure only bkupadmin can use password auth
# Remove any old exception block and append the new one
sed -i '/^Match User bkupadmin/,$d' "$CFG"
cat >> "$CFG" /dev/null; then
systemctl restart sshd || systemctl restart ssh
else
service ssh restart || service sshd restart
fi
# 6) Lock & nologin all other local accounts (UID 1000–59999) except bkupadmin
awk -F: -v skip="$BKP_USER" '($3>=1000 && $3<60000 && $1!=skip){print $1}' /etc/passwd | while read -r user; do
passwd -l "$user"
Asked by Dev Reddy
(21 rep)
May 23, 2025, 07:29 PM