Basic Cloud Server Security

Basic security for your SSH-Key Enabled Rackspace Cloud Server

This article provides a script to make web servers more secure. Run the following script for cloud servers running the the Ubuntu operating system to provide more security than the default configuration. While this script helps protect your server, it can't prevent an attack. Ensure that you are writing secure application code.

IMPORTANT: ONLY USE THIS ON VMs BUILT WITH SSH KEYS. Otherwise, you might be locked out of your virtual machine (VM). For information on how to generate public and private key pairs, see
Manage SSH Keypairs for cloud servers with-python-novaclient.

#!/bin/bash

# Exit immediately if a command exits with a non-zero status
set -e

# Variables
NEW_USER="adminuser"
SSH_PORT=22  # Change this if you want to use a non-standard SSH port

# Create a new user and add to sudo group
adduser --disabled-password --gecos "" $NEW_USER
usermod -aG sudo $NEW_USER

# Copy SSH authorized keys from root to the new user
mkdir -p /home/$NEW_USER/.ssh
cp /root/.ssh/authorized_keys /home/$NEW_USER/.ssh/
chown -R $NEW_USER:$NEW_USER /home/$NEW_USER/.ssh
chmod 700 /home/$NEW_USER/.ssh
chmod 600 /home/$NEW_USER/.ssh/authorized_keys

# Disable root SSH login
sed -i 's/^PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config

# Disable password authentication
sed -i 's/^#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sed -i 's/^PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config

# Restart SSH service
systemctl restart sshd

# Install Fail2Ban
apt-get update
apt-get install -y fail2ban

# Enable automatic security updates
apt-get install -y unattended-upgrades
dpkg-reconfigure -plow unattended-upgrades

# Configure UFW firewall
ufw default deny incoming
ufw default allow outgoing
ufw allow $SSH_PORT/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable

echo "Setup complete. Please verify SSH access with the new user before closing your session."

Script Activities

The script performs the following activities:

  1. Creates a new user and add to sudo group

  2. Copies SSH authorized keys from root to the new user

  3. Disables root SSH login

  4. Disables password authentication

  5. Restarts SSH service

  6. Installs Fail2Ban

  7. Enables automatic security updates

  8. Configures UFW firewall to allow the SSH port, port 80, and 443.

Troubleshooting

If SSH, sudo, or iptables are configured incorrectly, you might be locked out of your system. If this occurs, log in to the Rackspace Cloud Control Panel and use the Emergency Console or Rescue Mode to repair the configurations.