Skip to content

Instantly share code, notes, and snippets.

@juliancruzsanchez
Last active December 28, 2024 12:23
Show Gist options
  • Save juliancruzsanchez/943f0a33c6c2378cd0670f143977074e to your computer and use it in GitHub Desktop.
Save juliancruzsanchez/943f0a33c6c2378cd0670f143977074e to your computer and use it in GitHub Desktop.
Gets ZeroTier IP and sets it as the only host able to access SSH
#!/bin/bash
# Make sure you've already setup ZeroTier or this will kick you out
ZTIP=$(ip -4 -o addr show | awk '$2 ~ /^zt*/ {print $2, $4}' | cut -f2 -d' ' | cut -f1 -d'/')
# Check if ZTIP has a value
if [[ -z "$ZTIP" ]]; then
echo "Error: ZeroTier IP address not found. Make sure ZeroTier is installed and running."
exit 1
fi
# Backup the files
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
sudo cp /lib/systemd/system/ssh.socket /lib/systemd/system/ssh.socket.bak
# sshd_config set IP
sudo sed -i "s/^ListenAddress.*/ListenAddress $ZTIP/" /etc/ssh/sshd_config
# /lib/systemd/system/ssh.socket set IP
sudo sed -i "s=^ListenStream.*=ListenStream=$ZTIP:22=" /lib/systemd/system/ssh.socket
sudo dpkg-divert --no-rename --divert /lib/systemd/system/ssh.socket.diverted /lib/systemd/system/ssh.socket
sudo systemctl daemon-reload
sudo systemctl restart ssh.socket
sudo systemctl restart ssh
# Prompt for authentication method
read -p "Do you use SSH keys for authentication? (yes/no) " use_keys
if [[ "$use_keys" == "yes" ]]; then
# Check destination reachability using key-based authentication
if ! ssh -o "BatchMode=yes" -o "ConnectTimeout=5" "$ZTIP" "echo 'OK'"; then
echo "Error: Destination unreachable using key-based authentication. Restoring backups..."
restore_backups
exit 1
else
echo "Destination reachable. SSH configuration updated successfully!"
fi
elif [[ "$use_keys" == "no" ]]; then
# Prompt for password
read -sp "Enter password for $ZTIP: " password
echo
# Check destination reachability using password authentication
if ! sshpass -p "$password" ssh -o "BatchMode=yes" -o "ConnectTimeout=5" "$ZTIP" "echo 'OK'"; then
echo "Error: Destination unreachable using password authentication. Restoring backups..."
restore_backups
exit 1
else
echo "Destination reachable. SSH configuration updated successfully!"
fi
else
echo "Invalid input. Please enter 'yes' or 'no'."
restore_backups
exit 1
fi
# Function to restore backups
restore_backups() {
sudo cp /etc/ssh/sshd_config.bak /etc/ssh/sshd_config
sudo cp /lib/systemd/system/ssh.socket.bak /lib/systemd/system/ssh.socket
sudo dpkg-divert --no-rename --divert /lib/systemd/system/ssh.socket.diverted /lib/systemd/system/ssh.socket
sudo systemctl daemon-reload
sudo systemctl restart ssh.socket
sudo systemctl restart ssh
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment