Skip to content

Instantly share code, notes, and snippets.

@anthonynsimon
Last active January 11, 2025 03:04
Show Gist options
  • Save anthonynsimon/3487c7f6069aa00611011c2696059cbe to your computer and use it in GitHub Desktop.
Save anthonynsimon/3487c7f6069aa00611011c2696059cbe to your computer and use it in GitHub Desktop.
setup.sh: secure an Ubuntu server for Kamal. More details: https://getdeploying.com/guides/secure-ubuntu-server
#!/usr/bin/env bash
# Applies common security measures for Ubuntu servers. Run it before doing the inital deploy with basecamp/kamal
#
# Afterwards, you'll only be able to SSH into the server as 'nonroot', eg. nonroot@1.2.3.4
#
# So add this to your Kamal deploy.yml:
# ```
# ssh:
# user: nonroot
# ```
#
# MIT LICENSE:
#
# Copyright (c) 2024 Anthony Simon
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
set -e # Exit script on any command failure
# ---------------------------------------------------------
# Step 1: Update and upgrade system packages
# ---------------------------------------------------------
apt update -y
apt upgrade -y
apt install -y vim curl htop
# Configure 'needrestart' for auto-restart of services after upgrades
sed -i "/#\$nrconf{restart} = 'i';/s/.*/\$nrconf{restart} = 'a';/" /etc/needrestart/needrestart.conf
sed -i "s/#\$nrconf{kernelhints} = -1;/\$nrconf{kernelhints} = -1;/g" /etc/needrestart/needrestart.conf
# ---------------------------------------------------------
# Step 2: Install Docker and Docker Compose
# ---------------------------------------------------------
# Update package list and install prerequisites
apt update -y
apt install -y ca-certificates curl gnupg
# Add Docker's official GPG key and set up repository
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg
echo "deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
# Install Docker and Docker Compose plugins
apt update -y
apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
# ---------------------------------------------------------
# Step 3: Configure Virtual Memory Overcommit
# ---------------------------------------------------------
sysctl vm.overcommit_memory=1
echo 'vm.overcommit_memory = 1' >> /etc/sysctl.conf
# ---------------------------------------------------------
# Step 4: Configure UFW Firewall
# ---------------------------------------------------------
# Allow essential traffic for SSH, HTTP, and HTTPS
ufw allow ssh
ufw allow http
ufw allow https
# Uncomment to allow Redis and PostgreSQL traffic if needed
# ufw allow redis
# ufw allow postgres
# Enable UFW
ufw enable
# ---------------------------------------------------------
# Step 5: Secure SSH Configuration
# ---------------------------------------------------------
# Enable public key authentication, disable password-based login, and enforce other security settings
sed -i -e '/^\(#\|\)PasswordAuthentication/s/^.*$/PasswordAuthentication no/' /etc/ssh/sshd_config
sed -i -e '/^\(#\|\)PubkeyAuthentication/s/^.*$/PubkeyAuthentication yes/' /etc/ssh/sshd_config
sed -i -e '/^\(#\|\)PermitEmptyPasswords/s/^.*$/PermitEmptyPasswords no/' /etc/ssh/sshd_config
if ! grep -q "^ChallengeResponseAuthentication" /etc/ssh/sshd_config; then
echo 'ChallengeResponseAuthentication no' >> /etc/ssh/sshd_config
else
sed -i -e '/^\(#\|\)ChallengeResponseAuthentication/s/^.*$/ChallengeResponseAuthentication no/' /etc/ssh/sshd_config
fi
# Reload SSH service to apply configuration changes
echo 'Reloading ssh agent'
systemctl reload ssh
# ---------------------------------------------------------
# Step 6: Create Non-Root User with Sudo and Docker Access
# ---------------------------------------------------------
# Create a non-root user with sudo access
echo "Setup non-root user"
adduser --disabled-password --gecos "" nonroot
echo "nonroot ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers
# Configure SSH key authentication for the new user
AUTHORIZED_KEYS=$(cat ~/.ssh/authorized_keys)
sudo -H -u nonroot bash -c '
mkdir ~/.ssh
chmod 700 ~/.ssh
touch ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
'
sudo -H -u nonroot bash -c "echo '$AUTHORIZED_KEYS' >> ~/.ssh/authorized_keys"
# Add new user to Docker group
usermod -aG docker nonroot
# ---------------------------------------------------------
# Step 7: Install and Configure fail2ban
# ---------------------------------------------------------
# Install fail2ban to protect against brute-force attacks
echo "Setup fail2ban"
apt install -y fail2ban
# Configure fail2ban settings for SSH
cat <<EOF > /etc/fail2ban/jail.local
[sshd]
enabled = true
port = ssh
filter = sshd
maxretry = 5
findtime = 600
bantime = 600
ignoreip = 127.0.0.1/8
logpath = /var/log/auth.log
EOF
# Restart fail2ban to apply configuration
systemctl restart fail2ban
# ---------------------------------------------------------
# Step 8: Secure Shared Memory
# ---------------------------------------------------------
echo "Secure shared memory"
echo "tmpfs /run/shm tmpfs defaults,noexec,nosuid 0 0" >> /etc/fstab
# ---------------------------------------------------------
# Step 9: Disable Root User Login
# ---------------------------------------------------------
# Disable root login over SSH
echo "Disable root user login"
sed -i -e '/^\(#\|\)PermitRootLogin/s/^.*$/PermitRootLogin no/' /etc/ssh/sshd_config
# Reload SSH to apply root login restrictions
systemctl reload ssh
# ---------------------------------------------------------
# Step 10: Reboot to Apply Changes
# ---------------------------------------------------------
echo "Rebooting so changes can take effect"
reboot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment