Post installation script

In several earlier blog posts I mentioned a few things to do after you set up a new server: Hardening sshd config, enable firewall, etc.

Here’s a compact form of all this as a script, which you can customise and simply run after an installation. It will create a specific user, and only this user is allowed to ssh with public-key authentication (password authentication will be disabled). UFW will be installed and enabled as firewall. Fail2ban installed and enabled as basic brute-force protection. And a classic LAMP stack will be installed. On a debian system you should only have to edit the ‘Options’ section. For other distros you obviously have to adjust the script accordingly.

#!/bin/bash

###### Options

user="SOME_USER"

key="SOME_USERS_SSH_KEY"

aptpackages="vim screen lynx mariadb-server mariadb-client apache2 libapache2-mod-php php" # classic LAMP server

snappackages="certbot" # Have to run 'certbot --apache' manually later

######


# redirect all output to log file
exec >> /root/post_install.log
exec 2>&1


# update base installation
apt-get -y -q update
apt-get -y -q upgrade


# add the main user
adduser --disabled-password --gecos "" $user
mkdir /home/$user/.ssh
chmod 700 /home/$user/.ssh
echo "$key" >> /home/$user/.ssh/authorized_keys
chmod 644 /home/$user/.ssh/authorized_keys
ssh-keygen -t rsa -N '' -f /home/$user/.ssh/id_rsa
chown -R $user:$user /home/$user/.ssh


# harden ssh config
sed -i "s/.*PubkeyAuthentication.*/PubkeyAuthentication yes/g" /etc/ssh/sshd_config
sed -i "s/.*PasswordAuthentication.*/PasswordAuthentication no/g" /etc/ssh/sshd_config
sed -i "s/.*PermitRootLogin.*/PermitRootLogin no/g" /etc/ssh/sshd_config
echo "AllowUsers $user" >> /etc/ssh/sshd_config
echo "$user      ALL=(ALL)       NOPASSWD: ALL" >> /etc/sudoers


# setup firewall
apt-get -y -q install ufw
ufw default deny incoming
ufw allow ssh
ufw allow http
ufw allow https
ufw --force enable


# setup fail2ban
apt-get -y -q install fail2ban
cat <<EOT > /etc/fail2ban/jail.local
[DEFAULT]
bantime = 1h

[sshd]
enabled = true

[apache-auth]
enabled  = true

[apache-badbots]
enabled  = true

[apache-noscript]
enabled  = true

[apache-overflows]
enabled  = true
EOT
systemctl reload fail2ban


# Install additional packages
if [ -n "$aptpackages" ]
then
  apt-get -y -q install $aptpackages
fi


# Install snap packages
if [ -n "$snappackages" ]
then
  apt-get -y -q install snapd
  snap install core
  snap refresh core
  snap install --classic $snappackages
fi