Merikanto

一簫一劍平生意,負盡狂名十五年

Initial Server Setup - Ubuntu 18.04

When we first create a new Ubuntu 18.04 server, there are a few configuration steps that we should take early on as part of the basic setup. This will increase the security and usability of the server and will give us a solid foundation for subsequent actions.

Note: If you wish to get up and running more quickly, please see the initial server setup script in the last section.


Logging in as Root

To log into your server, you will need to know your server’s public IP address. You will also need the password or, if you installed an SSH key for authentication, the private key for the root user’s account. If you have not already logged into your server, you may want to follow our guide on how to connect to your Droplet with SSH, which covers this process in detail.

If you are not already connected to your server, go ahead and log in as the root user using the following command (substitute the highlighted portion of the command with your server’s public IP address):

1
ssh root@your_server_ip

Accept the warning about host authenticity if it appears. If you are using password authentication, provide your root password to log in. If you are using an SSH key that is passphrase protected, you may be prompted to enter the passphrase the first time you use the key each session. If this is your first time logging into the server with a password, you may also be prompted to change the root password.


About Root

The root user is the administrative user in a Linux environment that has very broad privileges. Because of the heightened privileges of the root account, you are discouraged from using it on a regular basis. This is because part of the power inherent with the root account is the ability to make very destructive changes, even by accident.

The next step is to set up an alternative user account with a reduced scope of influence for day-to-day work. We’ll teach you how to gain increased privileges during the times when you need them.


Creating a New User

Once you are logged in as root, we’re prepared to add the new user account that we will use to log in from now on.

1
adduser merikanto

You will be asked a few questions, starting with the account password.

Enter a strong password and, optionally, fill in any of the additional information if you would like. This is not required and you can just hit ENTER in any field you wish to skip.


Granting Administrative Privileges

Now, we have a new user account with regular account privileges. However, we may sometimes need to do administrative tasks.

To avoid having to log out of our normal user and log back in as the root account, we can set up what is known as “superuser” or root privileges for our normal account. This will allow our normal user to run commands with administrative privileges by putting the word sudo before each command.

To add these privileges to our new user, we need to add the new user to the sudo group. By default, on Ubuntu 18.04, users who belong to the sudo group are allowed to use the sudo command.

As root, run this command to add your new user to the sudo group (substitute the highlighted word with your new user):

1
usermod -aG sudo merikanto

Now, when logged in as your regular user, you can type sudo before commands to perform actions with superuser privileges.


Setting Up a Basic Firewall

Ubuntu 18.04 servers can use the UFW firewall to make sure only connections to certain services are allowed. We can set up a basic firewall very easily using this application.

Different applications can register their profiles with UFW upon installation. These profiles allow UFW to manage these applications by name. OpenSSH, the service allowing us to connect to our server now, has a profile registered with UFW.

You can see this by typing:

1
ufw app list
1
2
3
# Output
Available applications:
OpenSSH

We need to make sure that the firewall allows SSH connections so that we can log back in next time. We can allow these connections by typing:

1
ufw allow OpenSSH

Afterwards, we can enable the firewall by typing:

1
ufw enable

Type “y” and press ENTER to proceed. You can see that SSH connections are still allowed by typing:

1
ufw status
1
2
3
4
5
6
7
# Output

Status: active
To Action From
-- ------ ----
OpenSSH ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)

As the firewall is currently blocking all connections except for SSH, if you install and configure additional services, you will need to adjust the firewall settings to allow acceptable traffic in. You can learn some common UFW operations in this guide.


Enabling External Access for Your Regular User

Now that we have a regular user for daily use, we need to make sure we can SSH into the account directly.

Note: Until verifying that you can log in and use sudo with your new user, we recommend staying logged in as root. This way, if you have problems, you can troubleshoot and make any necessary changes as root.

The process for configuring SSH access for your new user depends on whether your server’s root account uses a password or SSH keys for authentication.


Root Account Uses Password Authentication

If you logged in to your root account using a password, then password authentication is enabled for SSH. You can SSH to your new user account by opening up a new terminal session and using SSH with your new username:

1
ssh merikanto@your_server_ip

After entering your regular user’s password, you will be logged in. Remember, if you need to run a command with administrative privileges, type sudo before it like this:

1
sudo command_to_run

You will be prompted for your regular user password when using sudo for the first time each session (and periodically afterwards).

To enhance your server’s security, we strongly recommend setting up SSH keys instead of using password authentication. Follow our guide on setting up SSH keys on Ubuntu 18.04 to learn how to configure key-based authentication.


Root Account Uses SSH Key Authentication

If you logged in to your root account using SSH keys, then password authentication is disabled for SSH. You will need to add a copy of your local public key to the new user’s ~/.ssh/authorized_keys file to log in successfully.

Since your public key is already in the root account’s ~/.ssh/authorized_keys file on the server, we can copy that file and directory structure to our new user account in our existing session.

The simplest way to copy the files with the correct ownership and permissions is with the rsync command. This will copy the root user’s .ssh directory, preserve the permissions, and modify the file owners, all in a single command. Make sure to change the highlighted portions of the command below to match your regular user’s name:


Note:

The rsync command treats sources and destinations that end with a trailing slash differently than those without a trailing slash. When using rsync below, be sure that the source directory (~/.ssh) does not include a trailing slash (check to make sure you are not using ~/.ssh/).

If you accidentally add a trailing slash to the command, rsync will copy the contents of the root account’s ~/.ssh directory to the sudo user’s home directory instead of copying the entire ~/.ssh directory structure. The files will be in the wrong location and SSH will not be able to find and use them.

1
rsync --archive --chown=merikanto:merikanto ~/.ssh /home/merikanto

Now, open up a new terminal session and using SSH with your new username:

1
ssh merikanto@your_server_ip

You should be logged in to the new user account without using a password. Remember, if you need to run a command with administrative privileges, type sudo before it like this:

1
sudo command_to_run

You will be prompted for your regular user password when using sudo for the first time each session (and periodically afterwards).


Setup Script

Notice

This script is an alternative to manually running through the procedure outlined above. The following variables affect how the script is run, and please update these variables as needed before running the script:

  • USERNAME: The name of the regular user account to create and grant sudo privileges to.
  • COPY_AUTHORIZED_KEYS_FROM_ROOT: Whether to copy the SSH key assets from the root account to the new sudo account.
  • OTHER_PUBLIC_KEYS_TO_ADD: An array of strings representing other public keys to add to the sudo-enabled account. This can optionally be used in addition to or instead of copying the keys from the root account.

When the script runs, the following actions are performed:

  • Create a regular user account with sudo privileges using the name specified by the USERNAME variable.
  • Configure the initial password state for the new account:
    • If the server was configured for password authentication, the original, generated administrative password is moved from the root account to the new sudo account. The password for the root account is then locked.
    • If the server was configured for SSH key authentication, a blank password is set for the sudo account.
  • The sudo user’s password is marked as expired so that it must be changed upon first login.
  • The authorized_keys file from the root account is copied over to the sudo user if COPY_AUTHORIZED_KEYS_FROM_ROOT is set to true.
  • Any keys defined in OTHER_PUBLIC_KEYS_TO_ADD are added to the sudo user’s authorized_keys file.
  • Password-based SSH authentication is disabled for the root user.
  • The UFW firewall is enabled with SSH connections permitted.

Usage

The script can be run in two ways:


If you do not want to use user data, you can also run the script manually over SSH once the server is booted up.

If you have downloaded the script to your local computer, you can pass the script directly to SSH by typing:

1
ssh root@servers_public_IP "bash -s" -- < /path/to/script/file

You should now be able to log in using your sudo account for any further configuration.


If you do not have the script downloaded to your local computer, start by logging into the root account on your server:

1
ssh root@servers_public_IP

Next, download the raw script to the server:

1
curl -L <SCRIPT_LINK> -o /tmp/initial_setup.sh

Inspect the script to ensure that it downloaded properly and update any variables that you wish to change:

1
vim /tmp/initial_setup.sh

Once satisfied, run the script manually using bash:

1
bash /tmp/initial_setup.sh

You should be able to log in using the sudo-enabled user to complete any further configuration.


The Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/bin/bash
set -euo pipefail

# ==================== #
# SCRIPT VARIABLES #
# ==================== #

# Name of the user to create and grant sudo privileges
USERNAME=merikanto

# Whether to copy over the root user's `authorized_keys` file to the new sudo
# user.
COPY_AUTHORIZED_KEYS_FROM_ROOT=true

# Additional public keys to add to the new sudo user
# OTHER_PUBLIC_KEYS_TO_ADD=(
# "ssh-rsa AAAAB..."
# "ssh-rsa AAAAB..."
# )
OTHER_PUBLIC_KEYS_TO_ADD=(
)

# ==================== #
# SCRIPT LOGIC #
# ==================== #

# Add sudo user and grant privileges
useradd --create-home --shell "/bin/bash" --groups sudo "${USERNAME}"

# Check whether the root account has a real password set
encrypted_root_pw="$(grep root /etc/shadow | cut --delimiter=: --fields=2)"

if [ "${encrypted_root_pw}" != "*" ]; then

# Transfer auto-generated root password to user if present
# and lock the root account to password-based access
echo "${USERNAME}:${encrypted_root_pw}" | chpasswd --encrypted
passwd --lock root

else

# Delete invalid password for user if using keys so that a new password
# can be set without providing a previous value
passwd --delete "${USERNAME}"
fi

# Expire the sudo user's password immediately to force a change
chage --lastday 0 "${USERNAME}"

# Create SSH directory for sudo user
home_directory="$(eval echo ~${USERNAME})"
mkdir --parents "${home_directory}/.ssh"

# Copy `authorized_keys` file from root if requested
if [ "${COPY_AUTHORIZED_KEYS_FROM_ROOT}" = true ]; then
cp /root/.ssh/authorized_keys "${home_directory}/.ssh"
fi

# Add additional provided public keys
for pub_key in "${OTHER_PUBLIC_KEYS_TO_ADD[@]}"; do
echo "${pub_key}" >> "${home_directory}/.ssh/authorized_keys"
done

# Adjust SSH configuration ownership and permissions
chmod 0700 "${home_directory}/.ssh"
chmod 0600 "${home_directory}/.ssh/authorized_keys"
chown --recursive "${USERNAME}":"${USERNAME}" "${home_directory}/.ssh"

# Disable root SSH login with password
sed --in-place 's/^PermitRootLogin.*/PermitRootLogin prohibit-password/g' /etc/ssh/sshd_config
if sshd -t -q; then
systemctl restart sshd
fi

# Add exception for SSH and then enable UFW firewall
ufw allow OpenSSH
ufw --force enable