SSH via live Github public keys

by dawmail333
5 deployments · 1 still active · last rev. 1 year ago

This 'borrows' from https://www.linode.com/stackscripts/view/10079, but configures it so that authorized keys are fetched at the time of request - instant propagation of additions and removals to your Github public keys. I hardcoded Ubuntu specific paths, but this would probably also work on Debian. Haven't checked. Unsure what happens if Github is currently unavailable - might be worth building a caching system for the keys in future.

Compatible with: Ubuntu 14.04 LTS
						#!/bin/bash
# <UDF name="gh_username" Label="GitHub Username" example="GitHub User account to create with sudo access" />
source <ssinclude StackScriptID=1>

function btr_user_add_sudo {
  USERNAME="$1"
  USERPASS="$2"
  if [ ! -n "$USERNAME" ] || [ ! -n "$USERPASS" ]; then
    echo "No new username and/or password entered"
    return 1;
  fi

  if [ -f /etc/debian_version ]; then
    adduser "$USERNAME" --disabled-password --gecos ""
    echo "$USERNAME:$USERPASS" | chpasswd
    apt-get install -y sudo
    usermod -aG sudo "$USERNAME"
  elif [ -f /etc/redhat-release ]; then
    adduser "$USERNAME" -p "$USERPASS"
    yum install -y sudo
    usermod -aG wheel "$USERNAME"
  fi
}

echo "#################"
echo "########"
echo "########  G I T H U B :"
echo "  ======                $GH_USERNAME"
echo "  ======"
echo ""
echo "Creating user..."
btr_user_add_sudo "$GH_USERNAME" "$(randomString)"
passwd -d "$GH_USERNAME"

echo "Giving user passwordless sudo/su..."
sed -i 's/#\?\s*\(auth\s\+sufficient\s\+pam_wheel.so\s\+trust\)/\1/' /etc/pam.d/su
#sed -i "s/^root:.*/\0,$GH_USERNAME/" /etc/group
#sed -i "s/^wheel:.*/\0,$GH_USERNAME/" /etc/group

if [ -d /etc/sudoers.d ]; then
  SUDOERS="/etc/sudoers.d/$GH_USERNAME"
else
  SUDOERS=/etc/sudoers
fi

echo "$GH_USERNAME ALL=NOPASSWD: ALL" >> "$SUDOERS"
chmod 0440 "$SUDOERS"

echo "Configuring SSH to use Github keys"
echo '#!/bin/bash' > /usr/local/bin/userkeys.sh
echo 'curl -sf https://github.com/$1.keys' >> /usr/local/bin/userkeys.sh
chmod +x /usr/local/bin/userkeys.sh

echo 'AuthorizedKeysCommand      /usr/local/bin/userkeys.sh' >> /etc/ssh/sshd_config
echo 'AuthorizedKeysCommandUser  nobody' >> /etc/ssh/sshd_config

echo "Disabling Root SSH..."
ssh_disable_root

echo "Disabling Root Password..."
passwd -d root

echo "Disabling Root Shell..."
chsh -s $(which nologin) root

echo "Disabling NullOK Pam/Unix Auth for SecureTTYs..."
grep -l nullok_secure /etc/pam.d/* | while read pamf; do sed -i s/nullok_secure// $pamf; done

echo -e "\n\nPasswords have been disabled.\nUse SSH ssh://$GH_USERNAME@$(dnsdomainname -f)" >> /etc/issue
echo "Restarting SSHD"
service sshd restart

echo "Done."
echo ""
echo "  ======"
echo "########"
echo "########"